From 5f03ded7ff351f58ec293671e612d54a773a3a2f Mon Sep 17 00:00:00 2001 From: aitbc Date: Thu, 30 Apr 2026 08:36:55 +0200 Subject: [PATCH] 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) --- aitbc/api_utils.py | 8 +-- aitbc/data_layer.py | 4 +- aitbc/events.py | 8 +-- aitbc/queue_manager.py | 12 ++--- aitbc/security.py | 6 +-- aitbc/state.py | 4 +- aitbc/testing.py | 14 ++--- .../src/app/ai/advanced_ai.py | 20 +++---- .../src/app/ai/realtime_learning.py | 12 ++--- .../src/app/auth/jwt_handler.py | 16 +++--- .../app/consensus/distributed_consensus.py | 26 ++++----- apps/agent-coordinator/src/app/exceptions.py | 6 +-- .../src/app/monitoring/alerting.py | 20 +++---- .../src/app/protocols/communication.py | 6 +-- .../src/app/protocols/message_types.py | 18 +++---- .../src/app/routers/agents.py | 10 ++-- .../src/app/routers/alerts.py | 6 +-- .../src/app/routers/consensus.py | 4 +- .../src/app/routers/health.py | 4 +- .../src/app/routers/messages.py | 14 ++--- .../src/app/routers/monitoring.py | 6 +-- .../src/app/routers/tasks.py | 6 +-- .../src/app/routing/agent_discovery.py | 24 ++++----- .../src/app/routing/load_balancer.py | 14 ++--- .../tests/test_communication.py | 6 +-- .../agent-bridge/src/integration_layer.py | 8 +-- .../agent-compliance/src/compliance_agent.py | 4 +- .../agent-coordinator/src/coordinator.py | 4 +- .../agent-protocols/src/message_protocol.py | 8 +-- .../agent-protocols/src/task_manager.py | 12 ++--- apps/agent-services/agent-registry/src/app.py | 4 +- apps/ai-engine/src/ai_service.py | 20 +++---- .../tests/test_edge_cases_ai_engine.py | 6 +-- .../tests/test_integration_ai_engine.py | 6 +-- apps/blockchain-node/create_genesis.py | 4 +- apps/blockchain-node/fix_accounts.py | 4 +- .../scripts/unified_genesis.py | 4 +- .../src/aitbc_chain/consensus/poa.py | 10 ++-- .../contracts/agent_wallet_security.py | 12 ++--- .../contracts/guardian_contract.py | 22 ++++---- .../contracts/persistent_spending_tracker.py | 18 +++---- .../src/aitbc_chain/cross_chain.py | 6 +-- .../blockchain-node/src/aitbc_chain/logger.py | 4 +- .../src/aitbc_chain/rpc/router.py | 12 ++--- .../src/aitbc_chain/state/state_transition.py | 4 +- apps/blockchain-node/src/aitbc_chain/sync.py | 6 +-- apps/blockchain-node/tests/test_consensus.py | 22 ++++---- .../tests/test_guardian_contract.py | 8 +-- apps/blockchain-node/tests/test_sync.py | 26 ++++----- apps/compliance-service/main.py | 30 +++++------ .../test_edge_cases_compliance_service.py | 6 +-- .../test_integration_compliance_service.py | 6 +-- .../tests/test_unit_compliance_service.py | 10 ++-- .../examples/agent_identity_sdk_example.py | 6 +-- .../scripts/production_deployment.py | 4 +- .../scripts/system_maintenance.py | 4 +- .../src/app/agent_identity/core.py | 30 +++++------ .../src/app/agent_identity/manager.py | 14 ++--- .../src/app/agent_identity/registry.py | 18 +++---- .../src/app/agent_identity/wallet_adapter.py | 14 ++--- .../agent_identity/wallet_adapter_enhanced.py | 14 ++--- .../src/app/domain/agent_performance.py | 4 +- .../src/app/domain/agent_portfolio.py | 6 +-- apps/coordinator-api/src/app/domain/amm.py | 12 ++--- .../src/app/domain/cross_chain_bridge.py | 8 +-- .../src/app/domain/pricing_strategies.py | 4 +- apps/coordinator-api/src/app/exceptions.py | 4 +- .../src/app/middleware/tenant_context.py | 6 +-- .../src/app/repositories/confidential.py | 10 ++-- .../src/app/reputation/aggregator.py | 24 ++++----- .../src/app/reputation/engine.py | 26 ++++----- .../app/routers/adaptive_learning_health.py | 10 ++-- apps/coordinator-api/src/app/routers/admin.py | 18 +++---- .../src/app/routers/agent_identity.py | 10 ++-- .../src/app/routers/agent_performance.py | 8 +-- .../src/app/routers/agent_router.py | 16 +++--- .../src/app/routers/agent_security_router.py | 2 +- .../src/app/routers/analytics.py | 4 +- .../coordinator-api/src/app/routers/bounty.py | 12 ++--- .../src/app/routers/certification.py | 4 +- .../coordinator-api/src/app/routers/client.py | 10 ++-- .../src/app/routers/confidential.py | 20 +++---- .../app/routers/cross_chain_integration.py | 8 +-- .../src/app/routers/developer_platform.py | 8 +-- .../src/app/routers/dynamic_pricing.py | 16 +++--- .../src/app/routers/ecosystem_dashboard.py | 8 +-- .../src/app/routers/exchange.py | 12 ++--- .../src/app/routers/global_marketplace.py | 6 +-- .../routers/global_marketplace_integration.py | 18 +++---- .../src/app/routers/governance_enhanced.py | 10 ++-- .../src/app/routers/gpu_multimodal_health.py | 10 ++-- .../routers/marketplace_enhanced_health.py | 10 ++-- .../src/app/routers/marketplace_gpu.py | 22 ++++---- apps/coordinator-api/src/app/routers/miner.py | 4 +- .../routers/modality_optimization_health.py | 10 ++-- .../src/app/routers/monitoring_dashboard.py | 28 +++++----- .../src/app/routers/multimodal_health.py | 10 ++-- .../src/app/routers/openclaw_enhanced_app.py | 4 +- .../app/routers/openclaw_enhanced_health.py | 10 ++-- .../src/app/routers/partners.py | 6 +-- .../src/app/routers/reputation.py | 24 ++++----- .../src/app/routers/rewards.py | 10 ++-- .../src/app/routers/staking.py | 4 +- .../src/app/routers/trading.py | 6 +-- apps/coordinator-api/src/app/routers/users.py | 16 +++--- .../src/app/routers/zk_applications.py | 12 ++--- .../src/app/sdk/enterprise_client.py | 6 +-- .../src/app/services/access_control.py | 24 ++++----- .../src/app/services/adaptive_learning.py | 16 +++--- .../src/app/services/advanced_ai_service.py | 16 +++--- .../src/app/services/advanced_learning.py | 46 ++++++++-------- .../advanced_reinforcement_learning.py | 6 +-- .../src/app/services/agent_communication.py | 28 +++++----- .../src/app/services/agent_integration.py | 12 ++--- .../src/app/services/agent_orchestrator.py | 14 ++--- .../app/services/agent_performance_service.py | 20 +++---- .../app/services/agent_portfolio_manager.py | 32 +++++------ .../src/app/services/agent_security.py | 18 +++---- .../src/app/services/agent_service.py | 44 +++++++-------- .../app/services/agent_service_marketplace.py | 30 +++++------ .../src/app/services/amm_service.py | 36 ++++++------- .../src/app/services/analytics_service.py | 20 +++---- .../src/app/services/atomic_swap_service.py | 14 ++--- .../src/app/services/audit_logging.py | 18 +++---- .../src/app/services/bid_strategy_engine.py | 14 ++--- .../src/app/services/bounty_service.py | 30 +++++------ .../src/app/services/certification_service.py | 24 ++++----- .../src/app/services/community_service.py | 8 +-- .../src/app/services/compliance_engine.py | 42 +++++++-------- .../src/app/services/confidential_service.py | 4 +- .../src/app/services/cross_chain_bridge.py | 24 ++++----- .../services/cross_chain_bridge_enhanced.py | 38 ++++++------- .../app/services/cross_chain_reputation.py | 34 ++++++------ .../app/services/dao_governance_service.py | 8 +-- .../services/developer_platform_service.py | 16 +++--- .../src/app/services/distributed_framework.py | 4 +- .../app/services/dynamic_pricing_engine.py | 16 +++--- .../src/app/services/ecosystem_service.py | 54 +++++++++---------- .../src/app/services/encryption.py | 4 +- .../app/services/enterprise_api_gateway.py | 30 +++++------ .../app/services/enterprise_integration.py | 20 +++---- .../app/services/enterprise_load_balancer.py | 24 ++++----- .../src/app/services/enterprise_security.py | 10 ++-- .../src/app/services/federated_learning.py | 4 +- .../src/app/services/global_cdn.py | 36 ++++++------- .../src/app/services/global_marketplace.py | 10 ++-- .../global_marketplace_integration.py | 14 ++--- .../src/app/services/governance_service.py | 10 ++-- .../src/app/services/gpu_multimodal.py | 8 +-- .../src/app/services/hsm_key_manager.py | 14 ++--- .../src/app/services/ipfs_storage_service.py | 8 +-- apps/coordinator-api/src/app/services/jobs.py | 8 +-- .../src/app/services/key_management.py | 14 ++--- .../src/app/services/market_data_collector.py | 34 ++++++------ .../services/marketplace_cache_optimizer.py | 4 +- .../src/app/services/marketplace_enhanced.py | 14 ++--- .../services/marketplace_enhanced_simple.py | 12 ++--- .../app/services/marketplace_gpu_optimizer.py | 6 +-- .../src/app/services/marketplace_monitor.py | 18 +++---- .../src/app/services/marketplace_scaler.py | 8 +-- .../src/app/services/memory_manager.py | 18 +++---- .../src/app/services/miners.py | 10 ++-- .../src/app/services/modality_optimization.py | 22 ++++---- .../multi_chain_transaction_manager.py | 36 ++++++------- .../services/multi_language/api_endpoints.py | 6 +-- .../src/app/services/multi_modal_fusion.py | 4 +- .../src/app/services/multimodal_agent.py | 10 ++-- .../src/app/services/openclaw_enhanced.py | 6 +-- .../app/services/openclaw_enhanced_simple.py | 4 +- .../src/app/services/payments.py | 36 ++++++------- .../app/services/performance_monitoring.py | 22 ++++---- .../src/app/services/quota_enforcement.py | 18 +++---- .../src/app/services/receipts.py | 6 +-- .../src/app/services/reputation_service.py | 30 +++++------ .../src/app/services/reward_service.py | 42 +++++++-------- .../src/app/services/secure_wallet_service.py | 20 +++---- .../src/app/services/staking_service.py | 48 ++++++++--------- .../src/app/services/task_decomposition.py | 8 +-- .../src/app/services/tenant_management.py | 32 +++++------ .../src/app/services/trading_service.py | 30 +++++------ .../src/app/services/usage_tracking.py | 20 +++---- .../src/app/settlement/bridges/base.py | 8 +-- .../src/app/settlement/hooks.py | 4 +- .../src/app/settlement/manager.py | 6 +-- .../src/app/settlement/storage.py | 16 +++--- apps/coordinator-api/src/app/storage/db_pg.py | 6 +-- .../coordinator-api/src/app/utils/alerting.py | 12 ++--- apps/coordinator-api/src/app/utils/metrics.py | 10 ++-- .../tests/test_agent_identity_sdk.py | 24 ++++----- apps/coordinator-api/tests/test_billing.py | 22 ++++---- apps/exchange-integration/main.py | 22 ++++---- apps/exchange/exchange_api.py | 8 +-- apps/exchange/real_exchange_integration.py | 6 +-- apps/exchange/scripts/seed_market.py | 4 +- apps/exchange/simple_exchange_api.py | 6 +-- apps/exchange/simple_exchange_api_pg.py | 4 +- .../tests/test_edge_cases_exchange.py | 12 ++--- apps/exchange/tests/test_unit_exchange.py | 14 ++--- apps/global-ai-agents/main.py | 46 ++++++++-------- .../tests/test_edge_cases_global_ai_agents.py | 10 ++-- .../test_integration_global_ai_agents.py | 30 +++++------ .../tests/test_unit_global_ai_agents.py | 18 +++---- apps/global-infrastructure/main.py | 38 ++++++------- .../test_edge_cases_global_infrastructure.py | 4 +- .../test_integration_global_infrastructure.py | 6 +-- .../tests/test_unit_global_infrastructure.py | 4 +- apps/miner/production_miner.py | 6 +-- apps/miner/production_miner_fixed.py | 6 +-- apps/multi-region-load-balancer/main.py | 36 ++++++------- ...t_edge_cases_multi_region_load_balancer.py | 10 ++-- ..._integration_multi_region_load_balancer.py | 6 +-- .../test_unit_multi_region_load_balancer.py | 8 +-- apps/plugin-analytics/main.py | 38 ++++++------- .../tests/test_edge_cases_plugin_analytics.py | 12 ++--- .../test_integration_plugin_analytics.py | 16 +++--- .../tests/test_unit_plugin_analytics.py | 16 +++--- apps/plugin-marketplace/main.py | 38 ++++++------- apps/plugin-registry/main.py | 30 +++++------ .../tests/test_edge_cases_plugin_registry.py | 16 +++--- .../tests/test_integration_plugin_registry.py | 12 ++--- .../tests/test_unit_plugin_registry.py | 6 +-- apps/plugin-security/main.py | 28 +++++----- .../tests/test_unit_plugin_security.py | 4 +- .../src/app/registry/miner_registry.py | 8 +-- apps/pool-hub/src/app/routers/health.py | 6 +-- apps/pool-hub/src/app/routers/jobs.py | 4 +- .../src/app/scoring/scoring_engine.py | 12 ++--- apps/pool-hub/src/poolhub/app/routers/sla.py | 10 ++-- .../repositories/feedback_repository.py | 2 +- .../poolhub/repositories/match_repository.py | 4 +- .../poolhub/repositories/miner_repository.py | 8 +-- .../poolhub/services/billing_integration.py | 6 +-- .../src/poolhub/services/sla_collector.py | 16 +++--- .../tests/test_billing_integration.py | 8 +-- .../tests/test_integration_coordinator.py | 8 +-- apps/pool-hub/tests/test_sla_collector.py | 4 +- apps/pool-hub/tests/test_sla_endpoints.py | 6 +-- apps/trading-engine/main.py | 28 +++++----- .../tests/test_edge_cases_trading_engine.py | 18 +++---- .../tests/test_integration_trading_engine.py | 14 ++--- .../tests/test_unit_trading_engine.py | 8 +-- .../src/app/keystore/persistent_service.py | 8 +-- cli/aitbc_cli/commands/exchange.py | 10 ++-- cli/aitbc_cli/commands/wallet.py | 10 ++-- cli/build/lib/aitbc_cli/commands/wallet.py | 10 ++-- cli/commands/blockchain_event_bridge.py | 4 +- cli/commands/exchange.py | 10 ++-- cli/commands/genesis_protection.py | 16 +++--- cli/commands/global_infrastructure.py | 6 +-- cli/commands/market_maker.py | 20 +++---- cli/commands/multisig.py | 16 +++--- cli/commands/oracle.py | 14 ++--- cli/commands/plugin_marketplace.py | 4 +- cli/commands/plugin_registry.py | 10 ++-- cli/commands/production_deploy.py | 14 ++--- cli/commands/transfer_control.py | 36 ++++++------- cli/commands/wallet.py | 22 ++++---- cli/examples/miner.py | 4 +- cli/utils/secure_audit.py | 10 ++-- .../aitbc_cache/gpu_marketplace_cache.py | 12 ++--- dev/gpu/gpu_miner_host.py | 6 +-- dev/gpu/gpu_registry_demo.py | 8 +-- dev/onboarding/auto-onboard.py | 20 +++---- dev/onboarding/onboarding-monitor.py | 4 +- dev/scripts/patches/patch_poa_genesis.py | 4 +- .../patches/patch_poa_genesis_fixed.py | 2 +- docs/agent-sdk/examples/oracle_agent.py | 12 ++--- infra/scripts/chaos_orchestrator.py | 8 +-- infra/scripts/chaos_test_coordinator.py | 10 ++-- infra/scripts/chaos_test_database.py | 10 ++-- infra/scripts/chaos_test_network.py | 10 ++-- .../aitbc-agent-sdk/src/aitbc_agent/agent.py | 6 +-- .../src/aitbc_agent/compute_provider.py | 6 +-- .../src/aitbc_agent/swarm_coordinator.py | 14 ++--- scripts/monitoring/monitor-prs.py | 8 +-- scripts/security/security_audit.py | 4 +- scripts/services/gpu/gpu_miner_host.py | 6 +-- scripts/services/gpu/gpu_registry_demo.py | 8 +-- scripts/testing/generate_staking_test_data.py | 20 +++---- scripts/testing/qa-cycle.py | 6 +-- scripts/utils/claim-task.py | 6 +-- scripts/utils/fix_gpu_release.py | 4 +- scripts/utils/generate-api-keys.py | 6 +-- scripts/utils/keystore.py | 6 +-- .../phase3/test_decision_framework.py | 18 +++---- .../phase4/test_autonomous_decision_making.py | 10 ++-- .../phase5/test_vision_integration.py | 26 ++++----- tests/fixtures/staking_fixtures.py | 44 +++++++-------- tests/integration/test_staking_lifecycle.py | 8 +-- tests/load/locustfile.py | 6 +-- .../test_confidential_transactions.py | 22 ++++---- tests/services/test_staking_service.py | 16 +++--- tests/verification/test_block_import.py | 4 +- .../test_cross_node_blockchain.py | 4 +- 294 files changed, 1997 insertions(+), 1997 deletions(-) diff --git a/aitbc/api_utils.py b/aitbc/api_utils.py index 0427610f..1bffc350 100644 --- a/aitbc/api_utils.py +++ b/aitbc/api_utils.py @@ -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() } diff --git a/aitbc/data_layer.py b/aitbc/data_layer.py index 92d86643..8c56321b 100644 --- a/aitbc/data_layer.py +++ b/aitbc/data_layer.py @@ -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 diff --git a/aitbc/events.py b/aitbc/events.py index f11026f5..14f21db1 100644 --- a/aitbc/events.py +++ b/aitbc/events.py @@ -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 = [] diff --git a/aitbc/queue_manager.py b/aitbc/queue_manager.py index 267e5acc..0f761291 100644 --- a/aitbc/queue_manager.py +++ b/aitbc/queue_manager.py @@ -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 diff --git a/aitbc/security.py b/aitbc/security.py index 29050e3c..c88ee26a 100644 --- a/aitbc/security.py +++ b/aitbc/security.py @@ -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() diff --git a/aitbc/state.py b/aitbc/state.py index 9d4b4c1a..d84c1e68 100644 --- a/aitbc/state.py +++ b/aitbc/state.py @@ -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""" diff --git a/aitbc/testing.py b/aitbc/testing.py index 910ab6df..664fa7b7 100644 --- a/aitbc/testing.py +++ b/aitbc/testing.py @@ -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) diff --git a/apps/agent-coordinator/src/app/ai/advanced_ai.py b/apps/agent-coordinator/src/app/ai/advanced_ai.py index 48c1384e..88943c5a 100644 --- a/apps/agent-coordinator/src/app/ai/advanced_ai.py +++ b/apps/agent-coordinator/src/app/ai/advanced_ai.py @@ -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: diff --git a/apps/agent-coordinator/src/app/ai/realtime_learning.py b/apps/agent-coordinator/src/app/ai/realtime_learning.py index d466cd84..40d954eb 100644 --- a/apps/agent-coordinator/src/app/ai/realtime_learning.py +++ b/apps/agent-coordinator/src/app/ai/realtime_learning.py @@ -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""" diff --git a/apps/agent-coordinator/src/app/auth/jwt_handler.py b/apps/agent-coordinator/src/app/auth/jwt_handler.py index 88d68499..5e68bc6c 100644 --- a/apps/agent-coordinator/src/app/auth/jwt_handler.py +++ b/apps/agent-coordinator/src/app/auth/jwt_handler.py @@ -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 { diff --git a/apps/agent-coordinator/src/app/consensus/distributed_consensus.py b/apps/agent-coordinator/src/app/consensus/distributed_consensus.py index 4cf82fea..931a9c80 100644 --- a/apps/agent-coordinator/src/app/consensus/distributed_consensus.py +++ b/apps/agent-coordinator/src/app/consensus/distributed_consensus.py @@ -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: diff --git a/apps/agent-coordinator/src/app/exceptions.py b/apps/agent-coordinator/src/app/exceptions.py index ea3b280d..447eebec 100644 --- a/apps/agent-coordinator/src/app/exceptions.py +++ b/apps/agent-coordinator/src/app/exceptions.py @@ -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(), }, ) diff --git a/apps/agent-coordinator/src/app/monitoring/alerting.py b/apps/agent-coordinator/src/app/monitoring/alerting.py index c9229e63..34ebec11 100644 --- a/apps/agent-coordinator/src/app/monitoring/alerting.py +++ b/apps/agent-coordinator/src/app/monitoring/alerting.py @@ -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()} diff --git a/apps/agent-coordinator/src/app/protocols/communication.py b/apps/agent-coordinator/src/app/protocols/communication.py index 2ab6a4f4..e5355606 100644 --- a/apps/agent-coordinator/src/app/protocols/communication.py +++ b/apps/agent-coordinator/src/app/protocols/communication.py @@ -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 diff --git a/apps/agent-coordinator/src/app/protocols/message_types.py b/apps/agent-coordinator/src/app/protocols/message_types.py index 689abb1b..3a41c0a3 100644 --- a/apps/agent-coordinator/src/app/protocols/message_types.py +++ b/apps/agent-coordinator/src/app/protocols/message_types.py @@ -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 diff --git a/apps/agent-coordinator/src/app/routers/agents.py b/apps/agent-coordinator/src/app/routers/agents.py index 064a8407..d273a4b3 100644 --- a/apps/agent-coordinator/src/app/routers/agents.py +++ b/apps/agent-coordinator/src/app/routers/agents.py @@ -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") diff --git a/apps/agent-coordinator/src/app/routers/alerts.py b/apps/agent-coordinator/src/app/routers/alerts.py index f96dcb1a..d62f651e 100644 --- a/apps/agent-coordinator/src/app/routers/alerts.py +++ b/apps/agent-coordinator/src/app/routers/alerts.py @@ -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 diff --git a/apps/agent-coordinator/src/app/routers/consensus.py b/apps/agent-coordinator/src/app/routers/consensus.py index b26e99da..feead8db 100644 --- a/apps/agent-coordinator/src/app/routers/consensus.py +++ b/apps/agent-coordinator/src/app/routers/consensus.py @@ -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", diff --git a/apps/agent-coordinator/src/app/routers/health.py b/apps/agent-coordinator/src/app/routers/health.py index db33de9a..b50a5651 100644 --- a/apps/agent-coordinator/src/app/routers/health.py +++ b/apps/agent-coordinator/src/app/routers/health.py @@ -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" } diff --git a/apps/agent-coordinator/src/app/routers/messages.py b/apps/agent-coordinator/src/app/routers/messages.py index d51fc819..85d20a64 100644 --- a/apps/agent-coordinator/src/app/routers/messages.py +++ b/apps/agent-coordinator/src/app/routers/messages.py @@ -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: diff --git a/apps/agent-coordinator/src/app/routers/monitoring.py b/apps/agent-coordinator/src/app/routers/monitoring.py index 8cce7f6e..f38933a3 100644 --- a/apps/agent-coordinator/src/app/routers/monitoring.py +++ b/apps/agent-coordinator/src/app/routers/monitoring.py @@ -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 { diff --git a/apps/agent-coordinator/src/app/routers/tasks.py b/apps/agent-coordinator/src/app/routers/tasks.py index e7d71f2a..b7ad8ca7 100644 --- a/apps/agent-coordinator/src/app/routers/tasks.py +++ b/apps/agent-coordinator/src/app/routers/tasks.py @@ -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: diff --git a/apps/agent-coordinator/src/app/routing/agent_discovery.py b/apps/agent-coordinator/src/app/routing/agent_discovery.py index 02b3ec70..15dc7f06 100644 --- a/apps/agent-coordinator/src/app/routing/agent_discovery.py +++ b/apps/agent-coordinator/src/app/routing/agent_discovery.py @@ -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 diff --git a/apps/agent-coordinator/src/app/routing/load_balancer.py b/apps/agent-coordinator/src/app/routing/load_balancer.py index a938c269..82aedf33 100644 --- a/apps/agent-coordinator/src/app/routing/load_balancer.py +++ b/apps/agent-coordinator/src/app/routing/load_balancer.py @@ -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 diff --git a/apps/agent-coordinator/tests/test_communication.py b/apps/agent-coordinator/tests/test_communication.py index 70af7156..46035681 100644 --- a/apps/agent-coordinator/tests/test_communication.py +++ b/apps/agent-coordinator/tests/test_communication.py @@ -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: diff --git a/apps/agent-services/agent-bridge/src/integration_layer.py b/apps/agent-services/agent-bridge/src/integration_layer.py index ef48a671..2cbf9542 100644 --- a/apps/agent-services/agent-bridge/src/integration_layer.py +++ b/apps/agent-services/agent-bridge/src/integration_layer.py @@ -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} diff --git a/apps/agent-services/agent-compliance/src/compliance_agent.py b/apps/agent-services/agent-compliance/src/compliance_agent.py index 0b593c78..f4e66ec8 100644 --- a/apps/agent-services/agent-compliance/src/compliance_agent.py +++ b/apps/agent-services/agent-compliance/src/compliance_agent.py @@ -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 diff --git a/apps/agent-services/agent-coordinator/src/coordinator.py b/apps/agent-services/agent-coordinator/src/coordinator.py index ce39c3cc..48151bcb 100644 --- a/apps/agent-services/agent-coordinator/src/coordinator.py +++ b/apps/agent-services/agent-coordinator/src/coordinator.py @@ -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 diff --git a/apps/agent-services/agent-protocols/src/message_protocol.py b/apps/agent-services/agent-protocols/src/message_protocol.py index 48289d6b..17ddeefc 100644 --- a/apps/agent-services/agent-protocols/src/message_protocol.py +++ b/apps/agent-services/agent-protocols/src/message_protocol.py @@ -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 diff --git a/apps/agent-services/agent-protocols/src/task_manager.py b/apps/agent-services/agent-protocols/src/task_manager.py index af680c99..4679cb54 100644 --- a/apps/agent-services/agent-protocols/src/task_manager.py +++ b/apps/agent-services/agent-protocols/src/task_manager.py @@ -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 diff --git a/apps/agent-services/agent-registry/src/app.py b/apps/agent-services/agent-registry/src/app.py index 70eb95f7..9d340a4d 100644 --- a/apps/agent-services/agent-registry/src/app.py +++ b/apps/agent-services/agent-registry/src/app.py @@ -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 diff --git a/apps/ai-engine/src/ai_service.py b/apps/ai-engine/src/ai_service.py index 46b7dde6..3e9e417f 100644 --- a/apps/ai-engine/src/ai_service.py +++ b/apps/ai-engine/src/ai_service.py @@ -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 diff --git a/apps/ai-engine/tests/test_edge_cases_ai_engine.py b/apps/ai-engine/tests/test_edge_cases_ai_engine.py index 141d77cf..92d4b26d 100644 --- a/apps/ai-engine/tests/test_edge_cases_ai_engine.py +++ b/apps/ai-engine/tests/test_edge_cases_ai_engine.py @@ -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') diff --git a/apps/ai-engine/tests/test_integration_ai_engine.py b/apps/ai-engine/tests/test_integration_ai_engine.py index 23430119..34192806 100644 --- a/apps/ai-engine/tests/test_integration_ai_engine.py +++ b/apps/ai-engine/tests/test_integration_ai_engine.py @@ -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") diff --git a/apps/blockchain-node/create_genesis.py b/apps/blockchain-node/create_genesis.py index 2fb69187..26066836 100755 --- a/apps/blockchain-node/create_genesis.py +++ b/apps/blockchain-node/create_genesis.py @@ -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, diff --git a/apps/blockchain-node/fix_accounts.py b/apps/blockchain-node/fix_accounts.py index 08a9cc91..cbfb9413 100644 --- a/apps/blockchain-node/fix_accounts.py +++ b/apps/blockchain-node/fix_accounts.py @@ -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") diff --git a/apps/blockchain-node/scripts/unified_genesis.py b/apps/blockchain-node/scripts/unified_genesis.py index 8960e836..4279482c 100644 --- a/apps/blockchain-node/scripts/unified_genesis.py +++ b/apps/blockchain-node/scripts/unified_genesis.py @@ -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() ) ) diff --git a/apps/blockchain-node/src/aitbc_chain/consensus/poa.py b/apps/blockchain-node/src/aitbc_chain/consensus/poa.py index ecea0063..d8a9956e 100755 --- a/apps/blockchain-node/src/aitbc_chain/consensus/poa.py +++ b/apps/blockchain-node/src/aitbc_chain/consensus/poa.py @@ -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 diff --git a/apps/blockchain-node/src/aitbc_chain/contracts/agent_wallet_security.py b/apps/blockchain-node/src/aitbc_chain/contracts/agent_wallet_security.py index 969c01c6..4fbfe29e 100755 --- a/apps/blockchain-node/src/aitbc_chain/contracts/agent_wallet_security.py +++ b/apps/blockchain-node/src/aitbc_chain/contracts/agent_wallet_security.py @@ -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() } diff --git a/apps/blockchain-node/src/aitbc_chain/contracts/guardian_contract.py b/apps/blockchain-node/src/aitbc_chain/contracts/guardian_contract.py index 6174c27a..fe3c44ee 100755 --- a/apps/blockchain-node/src/aitbc_chain/contracts/guardian_contract.py +++ b/apps/blockchain-node/src/aitbc_chain/contracts/guardian_contract.py @@ -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, diff --git a/apps/blockchain-node/src/aitbc_chain/contracts/persistent_spending_tracker.py b/apps/blockchain-node/src/aitbc_chain/contracts/persistent_spending_tracker.py index 7544e8fd..84d87eae 100755 --- a/apps/blockchain-node/src/aitbc_chain/contracts/persistent_spending_tracker.py +++ b/apps/blockchain-node/src/aitbc_chain/contracts/persistent_spending_tracker.py @@ -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 = { diff --git a/apps/blockchain-node/src/aitbc_chain/cross_chain.py b/apps/blockchain-node/src/aitbc_chain/cross_chain.py index d3814a02..447feece 100644 --- a/apps/blockchain-node/src/aitbc_chain/cross_chain.py +++ b/apps/blockchain-node/src/aitbc_chain/cross_chain.py @@ -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(), } diff --git a/apps/blockchain-node/src/aitbc_chain/logger.py b/apps/blockchain-node/src/aitbc_chain/logger.py index 5bcf8508..d0054376 100755 --- a/apps/blockchain-node/src/aitbc_chain/logger.py +++ b/apps/blockchain-node/src/aitbc_chain/logger.py @@ -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() diff --git a/apps/blockchain-node/src/aitbc_chain/rpc/router.py b/apps/blockchain-node/src/aitbc_chain/rpc/router.py index c30ba851..6ee7496b 100755 --- a/apps/blockchain-node/src/aitbc_chain/rpc/router.py +++ b/apps/blockchain-node/src/aitbc_chain/rpc/router.py @@ -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"], diff --git a/apps/blockchain-node/src/aitbc_chain/state/state_transition.py b/apps/blockchain-node/src/aitbc_chain/state/state_transition.py index bd577d8b..3a48fddf 100644 --- a/apps/blockchain-node/src/aitbc_chain/state/state_transition.py +++ b/apps/blockchain-node/src/aitbc_chain/state/state_transition.py @@ -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( diff --git a/apps/blockchain-node/src/aitbc_chain/sync.py b/apps/blockchain-node/src/aitbc_chain/sync.py index 09dfffb2..9c5a2551 100755 --- a/apps/blockchain-node/src/aitbc_chain/sync.py +++ b/apps/blockchain-node/src/aitbc_chain/sync.py @@ -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: diff --git a/apps/blockchain-node/tests/test_consensus.py b/apps/blockchain-node/tests/test_consensus.py index f61f6ca6..e74bec9d 100644 --- a/apps/blockchain-node/tests/test_consensus.py +++ b/apps/blockchain-node/tests/test_consensus.py @@ -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) diff --git a/apps/blockchain-node/tests/test_guardian_contract.py b/apps/blockchain-node/tests/test_guardian_contract.py index bcce9d75..961a4073 100644 --- a/apps/blockchain-node/tests/test_guardian_contract.py +++ b/apps/blockchain-node/tests/test_guardian_contract.py @@ -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", diff --git a/apps/blockchain-node/tests/test_sync.py b/apps/blockchain-node/tests/test_sync.py index 3ba242aa..10c087e1 100755 --- a/apps/blockchain-node/tests/test_sync.py +++ b/apps/blockchain-node/tests/test_sync.py @@ -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", diff --git a/apps/compliance-service/main.py b/apps/compliance-service/main.py index 7b2cc645..4ea6afe3 100755 --- a/apps/compliance-service/main.py +++ b/apps/compliance-service/main.py @@ -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"]) diff --git a/apps/compliance-service/tests/test_edge_cases_compliance_service.py b/apps/compliance-service/tests/test_edge_cases_compliance_service.py index 0a8541c8..6eda77a4 100644 --- a/apps/compliance-service/tests/test_edge_cases_compliance_service.py +++ b/apps/compliance-service/tests/test_edge_cases_compliance_service.py @@ -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 diff --git a/apps/compliance-service/tests/test_integration_compliance_service.py b/apps/compliance-service/tests/test_integration_compliance_service.py index 9716033c..b4ca9005 100644 --- a/apps/compliance-service/tests/test_integration_compliance_service.py +++ b/apps/compliance-service/tests/test_integration_compliance_service.py @@ -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 diff --git a/apps/compliance-service/tests/test_unit_compliance_service.py b/apps/compliance-service/tests/test_unit_compliance_service.py index 50b92e86..10bb826e 100644 --- a/apps/compliance-service/tests/test_unit_compliance_service.py +++ b/apps/compliance-service/tests/test_unit_compliance_service.py @@ -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 diff --git a/apps/coordinator-api/examples/agent_identity_sdk_example.py b/apps/coordinator-api/examples/agent_identity_sdk_example.py index 24d8d025..b7d6560f 100755 --- a/apps/coordinator-api/examples/agent_identity_sdk_example.py +++ b/apps/coordinator-api/examples/agent_identity_sdk_example.py @@ -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"] } diff --git a/apps/coordinator-api/scripts/production_deployment.py b/apps/coordinator-api/scripts/production_deployment.py index 6b36a389..5a1167e6 100755 --- a/apps/coordinator-api/scripts/production_deployment.py +++ b/apps/coordinator-api/scripts/production_deployment.py @@ -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": [], diff --git a/apps/coordinator-api/scripts/system_maintenance.py b/apps/coordinator-api/scripts/system_maintenance.py index 2e44aca3..a6205cb6 100755 --- a/apps/coordinator-api/scripts/system_maintenance.py +++ b/apps/coordinator-api/scripts/system_maintenance.py @@ -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": [], diff --git a/apps/coordinator-api/src/app/agent_identity/core.py b/apps/coordinator-api/src/app/agent_identity/core.py index 4afbf49e..5466bb59 100755 --- a/apps/coordinator-api/src/app/agent_identity/core.py +++ b/apps/coordinator-api/src/app/agent_identity/core.py @@ -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(), } diff --git a/apps/coordinator-api/src/app/agent_identity/manager.py b/apps/coordinator-api/src/app/agent_identity/manager.py index 712a1ae9..b3b5febf 100755 --- a/apps/coordinator-api/src/app/agent_identity/manager.py +++ b/apps/coordinator-api/src/app/agent_identity/manager.py @@ -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: diff --git a/apps/coordinator-api/src/app/agent_identity/registry.py b/apps/coordinator-api/src/app/agent_identity/registry.py index ce2bf60b..3cc682d6 100755 --- a/apps/coordinator-api/src/app/agent_identity/registry.py +++ b/apps/coordinator-api/src/app/agent_identity/registry.py @@ -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) diff --git a/apps/coordinator-api/src/app/agent_identity/wallet_adapter.py b/apps/coordinator-api/src/app/agent_identity/wallet_adapter.py index eb5fe918..e6ac11ef 100755 --- a/apps/coordinator-api/src/app/agent_identity/wallet_adapter.py +++ b/apps/coordinator-api/src/app/agent_identity/wallet_adapter.py @@ -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() diff --git a/apps/coordinator-api/src/app/agent_identity/wallet_adapter_enhanced.py b/apps/coordinator-api/src/app/agent_identity/wallet_adapter_enhanced.py index 26468ba7..9f18bd7c 100755 --- a/apps/coordinator-api/src/app/agent_identity/wallet_adapter_enhanced.py +++ b/apps/coordinator-api/src/app/agent_identity/wallet_adapter_enhanced.py @@ -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 diff --git a/apps/coordinator-api/src/app/domain/agent_performance.py b/apps/coordinator-api/src/app/domain/agent_performance.py index a8f0749b..17cf9e99 100755 --- a/apps/coordinator-api/src/app/domain/agent_performance.py +++ b/apps/coordinator-api/src/app/domain/agent_performance.py @@ -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)) diff --git a/apps/coordinator-api/src/app/domain/agent_portfolio.py b/apps/coordinator-api/src/app/domain/agent_portfolio.py index 8be547ad..40babe21 100755 --- a/apps/coordinator-api/src/app/domain/agent_portfolio.py +++ b/apps/coordinator-api/src/app/domain/agent_portfolio.py @@ -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)) diff --git a/apps/coordinator-api/src/app/domain/amm.py b/apps/coordinator-api/src/app/domain/amm.py index 14501879..c925010a 100755 --- a/apps/coordinator-api/src/app/domain/amm.py +++ b/apps/coordinator-api/src/app/domain/amm.py @@ -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)) diff --git a/apps/coordinator-api/src/app/domain/cross_chain_bridge.py b/apps/coordinator-api/src/app/domain/cross_chain_bridge.py index 90896023..84f9d3c9 100755 --- a/apps/coordinator-api/src/app/domain/cross_chain_bridge.py +++ b/apps/coordinator-api/src/app/domain/cross_chain_bridge.py @@ -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): diff --git a/apps/coordinator-api/src/app/domain/pricing_strategies.py b/apps/coordinator-api/src/app/domain/pricing_strategies.py index ca66366c..a09f1992 100755 --- a/apps/coordinator-api/src/app/domain/pricing_strategies.py +++ b/apps/coordinator-api/src/app/domain/pricing_strategies.py @@ -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) diff --git a/apps/coordinator-api/src/app/exceptions.py b/apps/coordinator-api/src/app/exceptions.py index 6d455112..40c6e200 100755 --- a/apps/coordinator-api/src/app/exceptions.py +++ b/apps/coordinator-api/src/app/exceptions.py @@ -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: diff --git a/apps/coordinator-api/src/app/middleware/tenant_context.py b/apps/coordinator-api/src/app/middleware/tenant_context.py index 924b646b..9e625cb5 100755 --- a/apps/coordinator-api/src/app/middleware/tenant_context.py +++ b/apps/coordinator-api/src/app/middleware/tenant_context.py @@ -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 diff --git a/apps/coordinator-api/src/app/repositories/confidential.py b/apps/coordinator-api/src/app/repositories/confidential.py index 26361944..c79da946 100755 --- a/apps/coordinator-api/src/app/repositories/confidential.py +++ b/apps/coordinator-api/src/app/repositories/confidential.py @@ -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() diff --git a/apps/coordinator-api/src/app/reputation/aggregator.py b/apps/coordinator-api/src/app/reputation/aggregator.py index 0c1a2424..9a41820a 100755 --- a/apps/coordinator-api/src/app/reputation/aggregator.py +++ b/apps/coordinator-api/src/app/reputation/aggregator.py @@ -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) diff --git a/apps/coordinator-api/src/app/reputation/engine.py b/apps/coordinator-api/src/app/reputation/engine.py index 69333e4e..749e5433 100755 --- a/apps/coordinator-api/src/app/reputation/engine.py +++ b/apps/coordinator-api/src/app/reputation/engine.py @@ -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, diff --git a/apps/coordinator-api/src/app/routers/adaptive_learning_health.py b/apps/coordinator-api/src/app/routers/adaptive_learning_health.py index 54f16fd0..73dacc81 100755 --- a/apps/coordinator-api/src/app/routers/adaptive_learning_health.py +++ b/apps/coordinator-api/src/app/routers/adaptive_learning_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/admin.py b/apps/coordinator-api/src/app/routers/admin.py index 0d538e6b..120a4b6c 100755 --- a/apps/coordinator-api/src/app/routers/admin.py +++ b/apps/coordinator-api/src/app/routers/admin.py @@ -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", diff --git a/apps/coordinator-api/src/app/routers/agent_identity.py b/apps/coordinator-api/src/app/routers/agent_identity.py index 21c79c8f..7d158154 100755 --- a/apps/coordinator-api/src/app/routers/agent_identity.py +++ b/apps/coordinator-api/src/app/routers/agent_identity.py @@ -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") diff --git a/apps/coordinator-api/src/app/routers/agent_performance.py b/apps/coordinator-api/src/app/routers/agent_performance.py index 915f2374..25011f34 100755 --- a/apps/coordinator-api/src/app/routers/agent_performance.py +++ b/apps/coordinator-api/src/app/routers/agent_performance.py @@ -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", diff --git a/apps/coordinator-api/src/app/routers/agent_router.py b/apps/coordinator-api/src/app/routers/agent_router.py index d37cf112..821e6e7a 100755 --- a/apps/coordinator-api/src/app/routers/agent_router.py +++ b/apps/coordinator-api/src/app/routers/agent_router.py @@ -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", diff --git a/apps/coordinator-api/src/app/routers/agent_security_router.py b/apps/coordinator-api/src/app/routers/agent_security_router.py index ffe689dd..f10515de 100755 --- a/apps/coordinator-api/src/app/routers/agent_security_router.py +++ b/apps/coordinator-api/src/app/routers/agent_security_router.py @@ -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) diff --git a/apps/coordinator-api/src/app/routers/analytics.py b/apps/coordinator-api/src/app/routers/analytics.py index 8868b48e..f1c38586 100755 --- a/apps/coordinator-api/src/app/routers/analytics.py +++ b/apps/coordinator-api/src/app/routers/analytics.py @@ -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) diff --git a/apps/coordinator-api/src/app/routers/bounty.py b/apps/coordinator-api/src/app/routers/bounty.py index 1c971fce..0b77dca8 100755 --- a/apps/coordinator-api/src/app/routers/bounty.py +++ b/apps/coordinator-api/src/app/routers/bounty.py @@ -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 diff --git a/apps/coordinator-api/src/app/routers/certification.py b/apps/coordinator-api/src/app/routers/certification.py index 24fe2a2d..79ed74f1 100755 --- a/apps/coordinator-api/src/app/routers/certification.py +++ b/apps/coordinator-api/src/app/routers/certification.py @@ -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: diff --git a/apps/coordinator-api/src/app/routers/client.py b/apps/coordinator-api/src/app/routers/client.py index c81f65c2..1e7f691c 100755 --- a/apps/coordinator-api/src/app/routers/client.py +++ b/apps/coordinator-api/src/app/routers/client.py @@ -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", diff --git a/apps/coordinator-api/src/app/routers/confidential.py b/apps/coordinator-api/src/app/routers/confidential.py index d032e309..31c96b28 100755 --- a/apps/coordinator-api/src/app/routers/confidential.py +++ b/apps/coordinator-api/src/app/routers/confidential.py @@ -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}") diff --git a/apps/coordinator-api/src/app/routers/cross_chain_integration.py b/apps/coordinator-api/src/app/routers/cross_chain_integration.py index 7d268ffe..cb3a50be 100755 --- a/apps/coordinator-api/src/app/routers/cross_chain_integration.py +++ b/apps/coordinator-api/src/app/routers/cross_chain_integration.py @@ -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: diff --git a/apps/coordinator-api/src/app/routers/developer_platform.py b/apps/coordinator-api/src/app/routers/developer_platform.py index 794b0d5e..5aa1290d 100755 --- a/apps/coordinator-api/src/app/routers/developer_platform.py +++ b/apps/coordinator-api/src/app/routers/developer_platform.py @@ -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: diff --git a/apps/coordinator-api/src/app/routers/dynamic_pricing.py b/apps/coordinator-api/src/app/routers/dynamic_pricing.py index 9fe01c62..34bf198d 100755 --- a/apps/coordinator-api/src/app/routers/dynamic_pricing.py +++ b/apps/coordinator-api/src/app/routers/dynamic_pricing.py @@ -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"} diff --git a/apps/coordinator-api/src/app/routers/ecosystem_dashboard.py b/apps/coordinator-api/src/app/routers/ecosystem_dashboard.py index 36be8716..54b27905 100755 --- a/apps/coordinator-api/src/app/routers/ecosystem_dashboard.py +++ b/apps/coordinator-api/src/app/routers/ecosystem_dashboard.py @@ -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 } diff --git a/apps/coordinator-api/src/app/routers/exchange.py b/apps/coordinator-api/src/app/routers/exchange.py index 7a7d37b7..0b5ca9d6 100755 --- a/apps/coordinator-api/src/app/routers/exchange.py +++ b/apps/coordinator-api/src/app/routers/exchange.py @@ -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", diff --git a/apps/coordinator-api/src/app/routers/global_marketplace.py b/apps/coordinator-api/src/app/routers/global_marketplace.py index e7be1259..dfd7d1ce 100755 --- a/apps/coordinator-api/src/app/routers/global_marketplace.py +++ b/apps/coordinator-api/src/app/routers/global_marketplace.py @@ -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: diff --git a/apps/coordinator-api/src/app/routers/global_marketplace_integration.py b/apps/coordinator-api/src/app/routers/global_marketplace_integration.py index 5d21164d..700b9aa6 100755 --- a/apps/coordinator-api/src/app/routers/global_marketplace_integration.py +++ b/apps/coordinator-api/src/app/routers/global_marketplace_integration.py @@ -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 diff --git a/apps/coordinator-api/src/app/routers/governance_enhanced.py b/apps/coordinator-api/src/app/routers/governance_enhanced.py index e1ae38b5..939939ab 100755 --- a/apps/coordinator-api/src/app/routers/governance_enhanced.py +++ b/apps/coordinator-api/src/app/routers/governance_enhanced.py @@ -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 diff --git a/apps/coordinator-api/src/app/routers/gpu_multimodal_health.py b/apps/coordinator-api/src/app/routers/gpu_multimodal_health.py index bd9d7270..ffb1ce6d 100755 --- a/apps/coordinator-api/src/app/routers/gpu_multimodal_health.py +++ b/apps/coordinator-api/src/app/routers/gpu_multimodal_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/marketplace_enhanced_health.py b/apps/coordinator-api/src/app/routers/marketplace_enhanced_health.py index 3ec7a38c..ab4a541d 100755 --- a/apps/coordinator-api/src/app/routers/marketplace_enhanced_health.py +++ b/apps/coordinator-api/src/app/routers/marketplace_enhanced_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/marketplace_gpu.py b/apps/coordinator-api/src/app/routers/marketplace_gpu.py index b2de9a25..ab1fea0a 100755 --- a/apps/coordinator-api/src/app/routers/marketplace_gpu.py +++ b/apps/coordinator-api/src/app/routers/marketplace_gpu.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/miner.py b/apps/coordinator-api/src/app/routers/miner.py index b57331e5..4193fa46 100755 --- a/apps/coordinator-api/src/app/routers/miner.py +++ b/apps/coordinator-api/src/app/routers/miner.py @@ -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) diff --git a/apps/coordinator-api/src/app/routers/modality_optimization_health.py b/apps/coordinator-api/src/app/routers/modality_optimization_health.py index db74ac8a..54f5c9fd 100755 --- a/apps/coordinator-api/src/app/routers/modality_optimization_health.py +++ b/apps/coordinator-api/src/app/routers/modality_optimization_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/monitoring_dashboard.py b/apps/coordinator-api/src/app/routers/monitoring_dashboard.py index 9ad9ced9..9ff8f0e2 100755 --- a/apps/coordinator-api/src/app/routers/monitoring_dashboard.py +++ b/apps/coordinator-api/src/app/routers/monitoring_dashboard.py @@ -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]: diff --git a/apps/coordinator-api/src/app/routers/multimodal_health.py b/apps/coordinator-api/src/app/routers/multimodal_health.py index bd393da3..ff0a9ebb 100755 --- a/apps/coordinator-api/src/app/routers/multimodal_health.py +++ b/apps/coordinator-api/src/app/routers/multimodal_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/openclaw_enhanced_app.py b/apps/coordinator-api/src/app/routers/openclaw_enhanced_app.py index 47c124b6..eed2451d 100755 --- a/apps/coordinator-api/src/app/routers/openclaw_enhanced_app.py +++ b/apps/coordinator-api/src/app/routers/openclaw_enhanced_app.py @@ -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(), diff --git a/apps/coordinator-api/src/app/routers/openclaw_enhanced_health.py b/apps/coordinator-api/src/app/routers/openclaw_enhanced_health.py index 08ec9a55..4db3088e 100755 --- a/apps/coordinator-api/src/app/routers/openclaw_enhanced_health.py +++ b/apps/coordinator-api/src/app/routers/openclaw_enhanced_health.py @@ -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", } diff --git a/apps/coordinator-api/src/app/routers/partners.py b/apps/coordinator-api/src/app/routers/partners.py index fbd05776..40ad9484 100755 --- a/apps/coordinator-api/src/app/routers/partners.py +++ b/apps/coordinator-api/src/app/routers/partners.py @@ -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( diff --git a/apps/coordinator-api/src/app/routers/reputation.py b/apps/coordinator-api/src/app/routers/reputation.py index 13a336fd..54829466 100755 --- a/apps/coordinator-api/src/app/routers/reputation.py +++ b/apps/coordinator-api/src/app/routers/reputation.py @@ -7,7 +7,7 @@ Reputation Management API Endpoints REST API for agent reputation, trust scores, and economic profiles """ -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 @@ -272,7 +272,7 @@ async def get_trust_score_breakdown( security_score=security_score, economic_score=economic_score, reputation_level=reputation_level.value, - calculated_at=datetime.utcnow().isoformat() + calculated_at=datetime.now(datetime.UTC).isoformat() ) except Exception as e: @@ -348,7 +348,7 @@ async def get_reputation_metrics( ] # Recent activity (last 24 hours) - recent_cutoff = datetime.utcnow() - timedelta(days=1) + recent_cutoff = datetime.now(datetime.UTC) - timedelta(days=1) recent_events = session.execute( select(func.count(ReputationEvent.id)).where( ReputationEvent.occurred_at >= recent_cutoff @@ -474,7 +474,7 @@ async def update_specialization( raise HTTPException(status_code=404, detail="Reputation profile not found") reputation.specialization_tags = specialization_tags - reputation.updated_at = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) session.commit() session.refresh(reputation) @@ -510,7 +510,7 @@ async def update_region( raise HTTPException(status_code=404, detail="Reputation profile not found") reputation.geographic_region = region - reputation.updated_at = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) session.commit() session.refresh(reputation) @@ -568,7 +568,7 @@ async def get_cross_chain_reputation( "last_updated": reputation.updated_at.isoformat() } }, - "last_updated": datetime.utcnow().isoformat() + "last_updated": datetime.now(datetime.UTC).isoformat() } except HTTPException: @@ -601,7 +601,7 @@ async def sync_cross_chain_reputation( "agent_id": agent_id, "sync_status": "completed", "chains_synced": [1], - "sync_timestamp": datetime.utcnow().isoformat(), + "sync_timestamp": datetime.now(datetime.UTC).isoformat(), "message": "Cross-chain reputation synchronized successfully" } @@ -651,7 +651,7 @@ async def get_cross_chain_leaderboard( "total_count": len(agents), "limit": limit, "min_score": min_score, - "last_updated": datetime.utcnow().isoformat() + "last_updated": datetime.now(datetime.UTC).isoformat() } except Exception as e: @@ -691,7 +691,7 @@ async def submit_cross_chain_event( new_score = max(0, min(1000, old_score + (impact * 1000))) reputation.trust_score = new_score - reputation.updated_at = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) # Update reputation level if needed if new_score >= 900: @@ -708,13 +708,13 @@ async def submit_cross_chain_event( session.commit() return { - "event_id": f"event_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}", + "event_id": f"event_{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}", "agent_id": agent_id, "event_type": event_data['event_type'], "impact_score": impact, "old_score": old_score / 1000.0, "new_score": new_score / 1000.0, - "processed_at": datetime.utcnow().isoformat() + "processed_at": datetime.now(datetime.UTC).isoformat() } except HTTPException: @@ -785,7 +785,7 @@ async def get_cross_chain_analytics( "average_consistency_score": 1.0, "chain_diversity_score": 0.0 # No cross-chain diversity yet }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } except Exception as e: diff --git a/apps/coordinator-api/src/app/routers/rewards.py b/apps/coordinator-api/src/app/routers/rewards.py index 61b7635f..cc83485a 100755 --- a/apps/coordinator-api/src/app/routers/rewards.py +++ b/apps/coordinator-api/src/app/routers/rewards.py @@ -7,7 +7,7 @@ Reward System API Endpoints REST API for agent rewards, incentives, and performance-based earnings """ -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 @@ -368,13 +368,13 @@ async def get_reward_leaderboard( try: # Calculate date range based on period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(days=7) + start_date = datetime.now(datetime.UTC) - timedelta(days=7) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=7) + start_date = datetime.now(datetime.UTC) - timedelta(days=7) # Query reward profiles query = select(AgentRewardProfile).where( diff --git a/apps/coordinator-api/src/app/routers/staking.py b/apps/coordinator-api/src/app/routers/staking.py index a0609c3f..cf668034 100755 --- a/apps/coordinator-api/src/app/routers/staking.py +++ b/apps/coordinator-api/src/app/routers/staking.py @@ -5,7 +5,7 @@ Staking Management API REST API for AI agent staking system with reputation-based yield farming """ -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 @@ -303,7 +303,7 @@ async def unbond_stake( if stake.status != StakeStatus.ACTIVE: raise HTTPException(status_code=400, detail="Stake is not active") - if datetime.utcnow() < stake.end_time: + if datetime.now(datetime.UTC) < stake.end_time: raise HTTPException(status_code=400, detail="Lock period has not ended") # Initiate unbonding diff --git a/apps/coordinator-api/src/app/routers/trading.py b/apps/coordinator-api/src/app/routers/trading.py index a639d366..6c5895cf 100755 --- a/apps/coordinator-api/src/app/routers/trading.py +++ b/apps/coordinator-api/src/app/routers/trading.py @@ -7,7 +7,7 @@ P2P Trading Protocol API Endpoints REST API for agent-to-agent trading, matching, negotiation, and settlement """ -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 @@ -634,9 +634,9 @@ async def get_trading_analytics( end_dt = datetime.fromisoformat(end_date) if not start_dt: - start_dt = datetime.utcnow() - timedelta(days=30) + start_dt = datetime.now(datetime.UTC) - timedelta(days=30) if not end_dt: - end_dt = datetime.utcnow() + end_dt = datetime.now(datetime.UTC) # Get analytics data (mock implementation) # In real implementation, this would query TradingAnalytics table diff --git a/apps/coordinator-api/src/app/routers/users.py b/apps/coordinator-api/src/app/routers/users.py index 5fbc383f..4549b5a6 100755 --- a/apps/coordinator-api/src/app/routers/users.py +++ b/apps/coordinator-api/src/app/routers/users.py @@ -9,7 +9,7 @@ User Management Router for AITBC import hashlib import time import uuid -from datetime import datetime +from datetime import datetime, UTC from typing import Any from fastapi import APIRouter, Depends, HTTPException, status @@ -70,8 +70,8 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen id=str(uuid.uuid4()), email=user_data.email, username=user_data.username, - created_at=datetime.utcnow(), - last_login=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + last_login=datetime.now(datetime.UTC), ) session.add(user) @@ -79,7 +79,7 @@ async def register_user(user_data: UserCreate, session: Annotated[Session, Depen session.refresh(user) # Create wallet for user - wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.utcnow()) + wallet = Wallet(user_id=user.id, address=f"aitbc_{user.id[:8]}", balance=0.0, created_at=datetime.now(datetime.UTC)) session.add(wallet) session.commit() @@ -112,8 +112,8 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends( id=str(uuid.uuid4()), email=f"{login_data.wallet_address}@aitbc.local", username=f"user_{login_data.wallet_address[-8:]}_{str(uuid.uuid4())[:8]}", - created_at=datetime.utcnow(), - last_login=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + last_login=datetime.now(datetime.UTC), ) session.add(user) @@ -121,14 +121,14 @@ async def login_user(login_data: UserLogin, session: Annotated[Session, Depends( session.refresh(user) # Create wallet - wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.utcnow()) + wallet = Wallet(user_id=user.id, address=login_data.wallet_address, balance=0.0, created_at=datetime.now(datetime.UTC)) session.add(wallet) session.commit() else: # Update last login user = session.execute(select(User).where(User.id == wallet.user_id)).first() - user.last_login = datetime.utcnow() + user.last_login = datetime.now(datetime.UTC) session.commit() # Create session token diff --git a/apps/coordinator-api/src/app/routers/zk_applications.py b/apps/coordinator-api/src/app/routers/zk_applications.py index bc7371fb..2576f4de 100755 --- a/apps/coordinator-api/src/app/routers/zk_applications.py +++ b/apps/coordinator-api/src/app/routers/zk_applications.py @@ -8,7 +8,7 @@ ZK Applications Router - Privacy-preserving features for AITBC import hashlib import secrets -from datetime import datetime +from datetime import datetime, UTC from typing import Any from fastapi import APIRouter, Depends, HTTPException @@ -67,7 +67,7 @@ async def create_identity_commitment( commitment_input = f"{user.email}:{salt}" commitment = hashlib.sha256(commitment_input.encode()).hexdigest() - return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.utcnow().isoformat()} + return {"commitment": commitment, "salt": salt, "user_id": user.user_id, "created_at": datetime.now(datetime.UTC).isoformat()} @router.post("/zk/membership/verify") @@ -104,7 +104,7 @@ async def verify_group_membership( "group_id": request.group_id, "verified": True, "nullifier": request.nullifier, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -127,7 +127,7 @@ async def submit_private_bid(request: PrivateBidRequest, session: Annotated[Sess "auction_id": request.auction_id, "commitment": request.bid_commitment, "status": "submitted", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -172,7 +172,7 @@ async def verify_computation_proof( "result_hash": request.result_hash, "public_inputs": request.public_inputs, "verification_key": "demo_vk_12345", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } return verification_result @@ -197,7 +197,7 @@ async def create_private_receipt( "user_address": user_address, "commitment": commitment, "privacy_level": privacy_level, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "verified": True, } diff --git a/apps/coordinator-api/src/app/sdk/enterprise_client.py b/apps/coordinator-api/src/app/sdk/enterprise_client.py index bba58e2e..ea7531e5 100755 --- a/apps/coordinator-api/src/app/sdk/enterprise_client.py +++ b/apps/coordinator-api/src/app/sdk/enterprise_client.py @@ -6,7 +6,7 @@ Python SDK for enterprise clients to integrate with AITBC platform import hashlib import secrets from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -162,7 +162,7 @@ class EnterpriseClient: # Store tokens self.access_token = auth_data["access_token"] self.refresh_token = auth_data.get("refresh_token") - self.token_expires_at = datetime.utcnow() + timedelta(seconds=auth_data["expires_in"]) + self.token_expires_at = datetime.now(datetime.UTC) + timedelta(seconds=auth_data["expires_in"]) # Update session headers self.session.headers["Authorization"] = f"Bearer {self.access_token}" @@ -175,7 +175,7 @@ class EnterpriseClient: async def _ensure_valid_token(self): """Ensure we have a valid access token""" - if not self.access_token or (self.token_expires_at and datetime.utcnow() >= self.token_expires_at): + if not self.access_token or (self.token_expires_at and datetime.now(datetime.UTC) >= self.token_expires_at): await self.authenticate() async def create_integration(self, integration_config: IntegrationConfig) -> APIResponse: diff --git a/apps/coordinator-api/src/app/services/access_control.py b/apps/coordinator-api/src/app/services/access_control.py index 6c393b68..24b15959 100755 --- a/apps/coordinator-api/src/app/services/access_control.py +++ b/apps/coordinator-api/src/app/services/access_control.py @@ -2,7 +2,7 @@ Access control service for confidential transactions """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -216,7 +216,7 @@ class AccessController: def _is_business_hours(self) -> bool: """Check if current time is within business hours""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) # Monday-Friday, 9 AM - 5 PM UTC if now.weekday() >= 5: # Weekend @@ -229,7 +229,7 @@ class AccessController: def _check_retention_period(self, transaction: dict, role: str | None) -> bool: """Check if data is within retention period for role""" - transaction_date = transaction.get("timestamp", datetime.utcnow()) + transaction_date = transaction.get("timestamp", datetime.now(datetime.UTC)) # Different retention periods for different roles if role == "regulator": @@ -243,7 +243,7 @@ class AccessController: expiry_date = transaction_date + timedelta(days=retention_days) - return datetime.utcnow() <= expiry_date + return datetime.now(datetime.UTC) <= expiry_date def _get_participant_info(self, participant_id: str) -> dict | None: """Get participant information""" @@ -274,8 +274,8 @@ class AccessController: "transaction_miner_id": "miner-789", "miner_id": "miner-789", "purpose": "settlement", - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(hours=1)).isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(), "metadata": {"job_id": "job-123", "amount": "1000", "currency": "AITBC"}, } if transaction_id.startswith("ctx-"): @@ -286,8 +286,8 @@ class AccessController: "transaction_miner_id": "miner-456", "miner_id": "miner-456", "purpose": "settlement", - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(hours=1)).isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(), "metadata": {"job_id": "job-456", "amount": "1000", "currency": "AITBC"}, } else: @@ -301,7 +301,7 @@ class AccessController: """Get cached access result""" if cache_key in self._access_cache: cached = self._access_cache[cache_key] - if datetime.utcnow() - cached["timestamp"] < self._cache_ttl: + if datetime.now(datetime.UTC) - cached["timestamp"] < self._cache_ttl: return cached else: del self._access_cache[cache_key] @@ -309,20 +309,20 @@ class AccessController: def _cache_result(self, cache_key: str, allowed: bool): """Cache access result""" - self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.utcnow()} + self._access_cache[cache_key] = {"allowed": allowed, "timestamp": datetime.now(datetime.UTC)} def create_access_policy( self, name: str, participants: list[str], conditions: dict[str, Any], access_level: AccessLevel ) -> str: """Create a new access policy""" - policy_id = f"policy_{datetime.utcnow().timestamp()}" + policy_id = f"policy_{datetime.now(datetime.UTC).timestamp()}" policy = { "participants": participants, "conditions": conditions, "access_level": access_level, "time_restrictions": conditions.get("time_restrictions"), - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } self.policy_store.add_policy(policy_id, policy) diff --git a/apps/coordinator-api/src/app/services/adaptive_learning.py b/apps/coordinator-api/src/app/services/adaptive_learning.py index 064174bf..bc34dba2 100755 --- a/apps/coordinator-api/src/app/services/adaptive_learning.py +++ b/apps/coordinator-api/src/app/services/adaptive_learning.py @@ -11,7 +11,7 @@ Reinforcement learning frameworks for agent self-improvement from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any @@ -380,7 +380,7 @@ class AdaptiveLearningService: "action_space_size": len(environment.action_space), "safety_constraints": len(environment.safety_constraints), "max_episodes": environment.max_episodes, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -403,7 +403,7 @@ class AdaptiveLearningService: "discount_factor": agent.discount_factor, "exploration_rate": agent.exploration_rate, "status": "created", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -427,7 +427,7 @@ class AdaptiveLearningService: self.training_sessions[session_id] = { "agent_id": agent_id, "environment_id": environment_id, - "start_time": datetime.utcnow(), + "start_time": datetime.now(datetime.UTC), "config": training_config, "status": "running", } @@ -438,7 +438,7 @@ class AdaptiveLearningService: # Update session self.training_sessions[session_id].update( - {"status": "completed", "end_time": datetime.utcnow(), "results": training_results} + {"status": "completed", "end_time": datetime.now(datetime.UTC), "results": training_results} ) return { @@ -626,7 +626,7 @@ class AdaptiveLearningService: "performance_metrics": agent.performance_metrics, "current_exploration_rate": agent.exploration_rate, "policy_size": len(agent.q_table) if hasattr(agent, "q_table") else "neural_network", - "last_updated": datetime.utcnow().isoformat(), + "last_updated": datetime.now(datetime.UTC).isoformat(), } async def evaluate_agent(self, agent_id: str, environment_id: str, evaluation_config: dict[str, Any]) -> dict[str, Any]: @@ -678,7 +678,7 @@ class AdaptiveLearningService: "min_reward": float(min(evaluation_rewards)), "average_episode_length": float(np.mean(evaluation_lengths)), "success_rate": sum(1 for r in evaluation_rewards if r > 0) / len(evaluation_rewards), - "evaluation_timestamp": datetime.utcnow().isoformat(), + "evaluation_timestamp": datetime.now(datetime.UTC).isoformat(), } async def create_reward_function(self, reward_id: str, reward_type: RewardType, config: dict[str, Any]) -> dict[str, Any]: @@ -690,7 +690,7 @@ class AdaptiveLearningService: "config": config, "parameters": config.get("parameters", {}), "weights": config.get("weights", {}), - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } self.reward_functions[reward_id] = reward_function diff --git a/apps/coordinator-api/src/app/services/advanced_ai_service.py b/apps/coordinator-api/src/app/services/advanced_ai_service.py index 02dad71a..92be81a8 100755 --- a/apps/coordinator-api/src/app/services/advanced_ai_service.py +++ b/apps/coordinator-api/src/app/services/advanced_ai_service.py @@ -7,7 +7,7 @@ Port: 8009 """ import uuid -from datetime import datetime +from datetime import datetime, UTC from typing import Any import numpy as np @@ -120,7 +120,7 @@ async def health_check(): """Health check endpoint""" return { "status": "healthy", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "gpu_available": torch.cuda.is_available(), "services": {"rl_engine": "operational", "fusion_engine": "operational", "advanced_learning": "operational"}, } @@ -193,7 +193,7 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest): """Process multi-modal fusion""" try: - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate database session @@ -213,13 +213,13 @@ async def process_multi_modal_fusion(request: MultiModalFusionRequest): modal_data=request.modal_data, performance_requirements=request.fusion_config or {} ) - processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000 + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() * 1000 return { "fusion_result": result, "processing_time_ms": processing_time, "strategy_used": request.fusion_strategy, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -243,7 +243,7 @@ async def optimize_gpu_processing(request: GPUOptimizationRequest): modality_features=request.modality_features, attention_config=request.attention_config ) - return {"optimization_result": result, "timestamp": datetime.utcnow().isoformat()} + return {"optimization_result": result, "timestamp": datetime.now(datetime.UTC).isoformat()} except Exception as e: logger.error(f"GPU optimization failed: {e}") @@ -255,7 +255,7 @@ async def advanced_ai_processing(request: AdvancedAIRequest): """Unified advanced AI processing endpoint""" try: - datetime.utcnow() + datetime.now(datetime.UTC) if request.request_type == "rl_training": # Convert to RL training request @@ -335,7 +335,7 @@ async def get_performance_metrics(): } return { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "gpu_metrics": gpu_metrics, "service_metrics": service_metrics, "system_health": "operational", diff --git a/apps/coordinator-api/src/app/services/advanced_learning.py b/apps/coordinator-api/src/app/services/advanced_learning.py index 5244e15b..8cfde794 100755 --- a/apps/coordinator-api/src/app/services/advanced_learning.py +++ b/apps/coordinator-api/src/app/services/advanced_learning.py @@ -10,7 +10,7 @@ from aitbc import get_logger logger = get_logger(__name__) import json from dataclasses import asdict, dataclass -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any @@ -231,8 +231,8 @@ class AdvancedLearningService: performance_metrics={}, training_data_size=0, validation_data_size=0, - created_at=datetime.utcnow(), - last_updated=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + last_updated=datetime.now(datetime.UTC), status=LearningStatus.INITIALIZING, ) @@ -251,7 +251,7 @@ class AdvancedLearningService: computation_efficiency=0.0, learning_rate=self.default_learning_rate, convergence_speed=0.0, - last_evaluation=datetime.utcnow(), + last_evaluation=datetime.now(datetime.UTC), ) logger.info(f"Model created: {model_id} for agent {agent_id}") @@ -298,7 +298,7 @@ class AdvancedLearningService: model_id=model_id, agent_id=model.agent_id, learning_type=model.learning_type, - start_time=datetime.utcnow(), + start_time=datetime.now(datetime.UTC), end_time=None, status=LearningStatus.INITIALIZING, training_data=training_data, @@ -316,7 +316,7 @@ class AdvancedLearningService: # Update model status model.status = LearningStatus.TRAINING - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) # Start training asyncio.create_task(self._execute_learning_session(session_id)) @@ -349,7 +349,7 @@ class AdvancedLearningService: model_id=model.id, agent_id=agent_id, learning_type=LearningType.META_LEARNING, - start_time=datetime.utcnow(), + start_time=datetime.now(datetime.UTC), end_time=None, status=LearningStatus.TRAINING, training_data=meta_data["training"], @@ -400,7 +400,7 @@ class AdvancedLearningService: model_id=model_id, agent_id="federated", learning_type=LearningType.FEDERATED, - start_time=datetime.utcnow(), + start_time=datetime.now(datetime.UTC), end_time=None, status=LearningStatus.TRAINING, training_data=[], @@ -443,16 +443,16 @@ class AdvancedLearningService: if model.status != LearningStatus.ACTIVE: raise ValueError(f"Model {model_id} not active") - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate inference prediction = await self._simulate_inference(model, input_data) # Update analytics - inference_time = (datetime.utcnow() - start_time).total_seconds() + inference_time = (datetime.now(datetime.UTC) - start_time).total_seconds() analytics = self.learning_analytics[model_id] analytics.total_inference_time += inference_time - analytics.last_evaluation = datetime.utcnow() + analytics.last_evaluation = datetime.now(datetime.UTC) logger.info(f"Prediction made with model {model_id}") return prediction @@ -480,7 +480,7 @@ class AdvancedLearningService: # Update model performance model.accuracy = adaptation_results.get("accuracy", model.accuracy) - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) # Update analytics analytics = self.learning_analytics[model_id] @@ -573,7 +573,7 @@ class AdvancedLearningService: # Update model model.accuracy = optimization_results.get("accuracy", model.accuracy) model.inference_time = optimization_results.get("inference_time", model.inference_time) - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) logger.info(f"Model optimized: {model_id}") return True @@ -625,12 +625,12 @@ class AdvancedLearningService: model.recall = np.random.uniform(0.7, 0.95) model.f1_score = np.random.uniform(0.7, 0.95) model.loss = session.results.get(f"epoch_{session.iterations}", {}).get("loss", 0.1) - model.training_time = (datetime.utcnow() - session.start_time).total_seconds() + model.training_time = (datetime.now(datetime.UTC) - session.start_time).total_seconds() model.inference_time = np.random.uniform(0.01, 0.1) model.status = LearningStatus.ACTIVE - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) - session.end_time = datetime.utcnow() + session.end_time = datetime.now(datetime.UTC) session.status = LearningStatus.COMPLETED # Update analytics @@ -673,9 +673,9 @@ class AdvancedLearningService: # Update model with meta-learning results model.accuracy = np.random.uniform(0.8, 0.98) model.status = LearningStatus.ACTIVE - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) - session.end_time = datetime.utcnow() + session.end_time = datetime.now(datetime.UTC) session.status = LearningStatus.COMPLETED logger.info(f"Meta-learning completed: {session_id}") @@ -713,9 +713,9 @@ class AdvancedLearningService: # Update model model.accuracy = np.random.uniform(0.75, 0.92) model.status = LearningStatus.ACTIVE - model.last_updated = datetime.utcnow() + model.last_updated = datetime.now(datetime.UTC) - session.end_time = datetime.utcnow() + session.end_time = datetime.now(datetime.UTC) session.status = LearningStatus.COMPLETED logger.info(f"Federated learning completed: {session_id}") @@ -811,7 +811,7 @@ class AdvancedLearningService: while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) for session_id, session in self.learning_sessions.items(): if session.status == LearningStatus.TRAINING: @@ -862,7 +862,7 @@ class AdvancedLearningService: while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) inactive_sessions = [] for session_id, session in self.learning_sessions.items(): @@ -905,7 +905,7 @@ class AdvancedLearningService: "models": {k: asdict(v) for k, v in self.models.items()}, "sessions": {k: asdict(v) for k, v in self.learning_sessions.items()}, "analytics": {k: asdict(v) for k, v in self.learning_analytics.items()}, - "export_timestamp": datetime.utcnow().isoformat(), + "export_timestamp": datetime.now(datetime.UTC).isoformat(), } if format.lower() == "json": diff --git a/apps/coordinator-api/src/app/services/advanced_reinforcement_learning.py b/apps/coordinator-api/src/app/services/advanced_reinforcement_learning.py index 76908ab9..0c9a66e2 100755 --- a/apps/coordinator-api/src/app/services/advanced_reinforcement_learning.py +++ b/apps/coordinator-api/src/app/services/advanced_reinforcement_learning.py @@ -5,7 +5,7 @@ Phase 5.1: Advanced AI Capabilities Enhancement """ import asyncio -from datetime import datetime +from datetime import datetime, UTC from typing import Any from uuid import uuid4 @@ -616,7 +616,7 @@ class AdvancedReinforcementLearningEngine: rl_config.success_rate_history = training_results["success_rate_history"] rl_config.convergence_episode = training_results["convergence_episode"] rl_config.status = "ready" - rl_config.trained_at = datetime.utcnow() + rl_config.trained_at = datetime.now(datetime.UTC) rl_config.training_progress = 1.0 session.commit() @@ -1329,7 +1329,7 @@ class MarketplaceStrategyOptimizer: rl_config.deployment_performance = deployment_performance rl_config.deployment_count += 1 rl_config.status = "deployed" - rl_config.deployed_at = datetime.utcnow() + rl_config.deployed_at = datetime.now(datetime.UTC) session.commit() diff --git a/apps/coordinator-api/src/app/services/agent_communication.py b/apps/coordinator-api/src/app/services/agent_communication.py index 9c9ac064..f8dc0bcc 100755 --- a/apps/coordinator-api/src/app/services/agent_communication.py +++ b/apps/coordinator-api/src/app/services/agent_communication.py @@ -11,7 +11,7 @@ logger = get_logger(__name__) import hashlib import json from dataclasses import asdict, dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -199,7 +199,7 @@ class AgentCommunicationService: messages_sent=0, messages_received=0, active_channels=0, - last_activity=datetime.utcnow(), + last_activity=datetime.now(datetime.UTC), average_response_time=0.0, delivery_rate=0.0, ) @@ -346,11 +346,11 @@ class AgentCommunicationService: encryption_key=encryption_key, encryption_type=encryption_type, size=len(content_bytes), - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), status=MessageStatus.PENDING, price=price, metadata=metadata or {}, - expires_at=datetime.utcnow() + timedelta(seconds=self.message_timeout), + expires_at=datetime.now(datetime.UTC) + timedelta(seconds=self.message_timeout), reply_to=reply_to, thread_id=thread_id, ) @@ -395,7 +395,7 @@ class AgentCommunicationService: raise ValueError(f"Message {message_id} not pending") message.status = MessageStatus.DELIVERED - message.delivery_timestamp = datetime.utcnow() + message.delivery_timestamp = datetime.now(datetime.UTC) # Update stats await self._update_message_stats(message.sender, message.recipient, "delivered") @@ -426,7 +426,7 @@ class AgentCommunicationService: # Mark as read message.status = MessageStatus.READ - message.read_timestamp = datetime.utcnow() + message.read_timestamp = datetime.now(datetime.UTC) # Update stats await self._update_message_stats(message.sender, message.recipient, "read") @@ -495,8 +495,8 @@ class AgentCommunicationService: agent2=agent2, channel_type=channel_type, is_active=True, - created_timestamp=datetime.utcnow(), - last_activity=datetime.utcnow(), + created_timestamp=datetime.now(datetime.UTC), + last_activity=datetime.now(datetime.UTC), message_count=0, participants=[agent1, agent2], encryption_enabled=encryption_enabled, @@ -814,17 +814,17 @@ class AgentCommunicationService: if sender in self.communication_stats: self.communication_stats[sender].total_messages += 1 self.communication_stats[sender].messages_sent += 1 - self.communication_stats[sender].last_activity = datetime.utcnow() + self.communication_stats[sender].last_activity = datetime.now(datetime.UTC) elif action == "delivered": if recipient in self.communication_stats: self.communication_stats[recipient].total_messages += 1 self.communication_stats[recipient].messages_received += 1 - self.communication_stats[recipient].last_activity = datetime.utcnow() + self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC) elif action == "read": if recipient in self.communication_stats: - self.communication_stats[recipient].last_activity = datetime.utcnow() + self.communication_stats[recipient].last_activity = datetime.now(datetime.UTC) async def _process_message_queue(self): """Process message queue for delivery""" @@ -848,7 +848,7 @@ class AgentCommunicationService: while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) expired_messages = [] for message_id, message in self.messages.items(): @@ -875,7 +875,7 @@ class AgentCommunicationService: while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) inactive_channels = [] for channel_id, channel in self.channels.items(): @@ -958,7 +958,7 @@ class AgentCommunicationService: "messages": {k: asdict(v) for k, v in self.messages.items()}, "channels": {k: asdict(v) for k, v in self.channels.items()}, "templates": {k: asdict(v) for k, v in self.message_templates.items()}, - "export_timestamp": datetime.utcnow().isoformat(), + "export_timestamp": datetime.now(datetime.UTC).isoformat(), } if format.lower() == "json": diff --git a/apps/coordinator-api/src/app/services/agent_integration.py b/apps/coordinator-api/src/app/services/agent_integration.py index 91846bde..39cd126f 100755 --- a/apps/coordinator-api/src/app/services/agent_integration.py +++ b/apps/coordinator-api/src/app/services/agent_integration.py @@ -6,7 +6,7 @@ Integrates agent orchestration with existing ML ZK proof system and provides dep from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any from uuid import uuid4 @@ -380,7 +380,7 @@ class AgentDeploymentManager: # Update deployment status config.status = DeploymentStatus.DEPLOYING - config.deployment_time = datetime.utcnow() + config.deployment_time = datetime.now(datetime.UTC) self.session.commit() deployment_result = { @@ -469,7 +469,7 @@ class AgentDeploymentManager: instance.status = DeploymentStatus.DEPLOYED instance.health_status = "healthy" instance.endpoint_url = f"http://localhost:{instance.port}" - instance.last_health_check = datetime.utcnow() + instance.last_health_check = datetime.now(datetime.UTC) self.session.commit() @@ -554,11 +554,11 @@ class AgentDeploymentManager: # Update instance health status instance.health_status = health_status - instance.last_health_check = datetime.utcnow() + instance.last_health_check = datetime.now(datetime.UTC) # Add to health check history health_check_record = { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "status": health_status, "response_time": response_time, } @@ -582,7 +582,7 @@ class AgentDeploymentManager: # Mark as unhealthy instance.health_status = "unhealthy" - instance.last_health_check = datetime.utcnow() + instance.last_health_check = datetime.now(datetime.UTC) instance.consecutive_failures += 1 self.session.commit() diff --git a/apps/coordinator-api/src/app/services/agent_orchestrator.py b/apps/coordinator-api/src/app/services/agent_orchestrator.py index 1dd8c395..492503a6 100755 --- a/apps/coordinator-api/src/app/services/agent_orchestrator.py +++ b/apps/coordinator-api/src/app/services/agent_orchestrator.py @@ -9,7 +9,7 @@ from aitbc import get_logger logger = get_logger(__name__) from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -360,7 +360,7 @@ class AgentOrchestrator: # Process each execution stage for stage_idx, stage_sub_tasks in enumerate(decomposition.execution_plan): - stage_start = datetime.utcnow() + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage + stage_start = datetime.now(datetime.UTC) + timedelta(hours=stage_idx * 2) # Estimate 2 hours per stage for sub_task_id in stage_sub_tasks: # Find sub-task @@ -368,7 +368,7 @@ class AgentOrchestrator: # Create assignment (will be filled during execution) assignment = AgentAssignment( - sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.utcnow() # Will be assigned during execution + sub_task_id=sub_task_id, agent_id="", assigned_at=datetime.now(datetime.UTC) # Will be assigned during execution ) assignments.append(assignment) @@ -469,7 +469,7 @@ class AgentOrchestrator: sub_task_id=sub_task_id, resource_type=ResourceType.GPU, allocated_amount=1, - allocated_at=datetime.utcnow(), + allocated_at=datetime.now(datetime.UTC), expected_duration=requirements.estimated_duration, ) allocations.append(gpu_allocation) @@ -480,7 +480,7 @@ class AgentOrchestrator: sub_task_id=sub_task_id, resource_type=ResourceType.MEMORY, allocated_amount=requirements.memory_requirement, - allocated_at=datetime.utcnow(), + allocated_at=datetime.now(datetime.UTC), expected_duration=requirements.estimated_duration, ) allocations.append(memory_allocation) @@ -568,7 +568,7 @@ class AgentOrchestrator: # For now, assume agents are healthy if they have recent updates capability = self.agent_capabilities[agent_id] - time_since_update = datetime.utcnow() - capability.last_updated + time_since_update = datetime.now(datetime.UTC) - capability.last_updated if time_since_update > timedelta(minutes=5): if self.agent_status[agent_id] != AgentStatus.OFFLINE: @@ -619,7 +619,7 @@ class AgentOrchestrator: # Adjust for deadline if deadline: - time_to_deadline = (deadline - datetime.utcnow()).total_seconds() / 3600 + time_to_deadline = (deadline - datetime.now(datetime.UTC)).total_seconds() / 3600 if time_to_deadline < decomposition.estimated_total_duration: confidence *= 0.6 diff --git a/apps/coordinator-api/src/app/services/agent_performance_service.py b/apps/coordinator-api/src/app/services/agent_performance_service.py index 23af3996..e7e083a4 100755 --- a/apps/coordinator-api/src/app/services/agent_performance_service.py +++ b/apps/coordinator-api/src/app/services/agent_performance_service.py @@ -4,7 +4,7 @@ Implements meta-learning, resource optimization, and performance enhancement for """ import asyncio -from datetime import datetime +from datetime import datetime, UTC from typing import Any from uuid import uuid4 @@ -109,7 +109,7 @@ class MetaLearningEngine: model.training_time = training_results["training_time"] model.computational_cost = training_results["computational_cost"] model.status = "ready" - model.trained_at = datetime.utcnow() + model.trained_at = datetime.now(datetime.UTC) session.commit() @@ -351,7 +351,7 @@ class ResourceManager: network_bandwidth=optimized_allocation[ResourceType.NETWORK], optimization_target=optimization_target, status="allocated", - allocated_at=datetime.utcnow(), + allocated_at=datetime.now(datetime.UTC), ) session.add(allocation) @@ -601,7 +601,7 @@ class PerformanceOptimizer: optimization.convergence_achieved = optimization_results["converged"] optimization.optimization_applied = True optimization.status = "completed" - optimization.completed_at = datetime.utcnow() + optimization.completed_at = datetime.now(datetime.UTC) session.commit() @@ -619,7 +619,7 @@ class PerformanceOptimizer: ) -> dict[str, Any]: """Run comprehensive optimization process""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Step 1: Analyze current performance analysis_results = self.analyze_current_performance(current_performance, target_metric) @@ -636,7 +636,7 @@ class PerformanceOptimizer: # Step 5: Calculate improvements improvements = self.calculate_improvements(current_performance, applied_performance) - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) duration = (end_time - start_time).total_seconds() return { @@ -865,7 +865,7 @@ class AgentPerformanceService: expertise_levels={}, performance_history=[], benchmark_scores={}, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(profile) @@ -892,7 +892,7 @@ class AgentPerformanceService: profile.performance_metrics.update(new_metrics) # Add to performance history - history_entry = {"timestamp": datetime.utcnow().isoformat(), "metrics": new_metrics, "context": task_context or {}} + history_entry = {"timestamp": datetime.now(datetime.UTC).isoformat(), "metrics": new_metrics, "context": task_context or {}} profile.performance_history.append(history_entry) # Calculate overall score @@ -901,8 +901,8 @@ class AgentPerformanceService: # Update trends profile.improvement_trends = self.calculate_improvement_trends(profile.performance_history) - profile.updated_at = datetime.utcnow() - profile.last_assessed = datetime.utcnow() + profile.updated_at = datetime.now(datetime.UTC) + profile.last_assessed = datetime.now(datetime.UTC) self.session.commit() diff --git a/apps/coordinator-api/src/app/services/agent_portfolio_manager.py b/apps/coordinator-api/src/app/services/agent_portfolio_manager.py index da396481..1eb0407f 100755 --- a/apps/coordinator-api/src/app/services/agent_portfolio_manager.py +++ b/apps/coordinator-api/src/app/services/agent_portfolio_manager.py @@ -7,7 +7,7 @@ Provides portfolio creation, rebalancing, risk assessment, and trading strategy from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -86,8 +86,8 @@ class AgentPortfolioManager: initial_capital=portfolio_data.initial_capital, risk_tolerance=portfolio_data.risk_tolerance, is_active=True, - created_at=datetime.utcnow(), - last_rebalance=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + last_rebalance=datetime.now(datetime.UTC), ) self.session.add(portfolio) @@ -154,7 +154,7 @@ class AgentPortfolioManager: price=trade_result.price, status=TradeStatus.EXECUTED, transaction_hash=trade_result.transaction_hash, - executed_at=datetime.utcnow(), + executed_at=datetime.now(datetime.UTC), ) self.session.add(trade) @@ -213,7 +213,7 @@ class AgentPortfolioManager: continue # Update portfolio rebalance timestamp - portfolio.last_rebalance = datetime.utcnow() + portfolio.last_rebalance = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Rebalanced portfolio {portfolio.id} with {len(executed_trades)} trades") @@ -250,10 +250,10 @@ class AgentPortfolioManager: existing_metrics.sharpe_ratio = risk_metrics.sharpe_ratio existing_metrics.var_95 = risk_metrics.var_95 existing_metrics.risk_level = risk_metrics.risk_level - existing_metrics.updated_at = datetime.utcnow() + existing_metrics.updated_at = datetime.now(datetime.UTC) else: risk_metrics.portfolio_id = portfolio.id - risk_metrics.updated_at = datetime.utcnow() + risk_metrics.updated_at = datetime.now(datetime.UTC) self.session.add(risk_metrics) # Update portfolio risk score @@ -301,7 +301,7 @@ class AgentPortfolioManager: max_drawdown=strategy_data.max_drawdown, rebalance_frequency=strategy_data.rebalance_frequency, is_active=True, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(strategy) @@ -343,7 +343,7 @@ class AgentPortfolioManager: target_allocation=allocation, current_allocation=0.0, balance=0, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(asset) @@ -412,7 +412,7 @@ class AgentPortfolioManager: if sell_asset: sell_asset.balance -= trade.sell_amount - sell_asset.updated_at = datetime.utcnow() + sell_asset.updated_at = datetime.now(datetime.UTC) # Update buy asset buy_asset = self.session.execute( @@ -423,7 +423,7 @@ class AgentPortfolioManager: if buy_asset: buy_asset.balance += trade.buy_amount - buy_asset.updated_at = datetime.utcnow() + buy_asset.updated_at = datetime.now(datetime.UTC) else: # Create new asset if it doesn't exist new_asset = PortfolioAsset( @@ -432,7 +432,7 @@ class AgentPortfolioManager: target_allocation=0.0, current_allocation=0.0, balance=trade.buy_amount, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(new_asset) @@ -449,10 +449,10 @@ class AgentPortfolioManager: price = await self.price_service.get_price(asset.token_symbol) asset_value = asset.balance * price asset.current_allocation = (asset_value / portfolio_value) * 100 - asset.updated_at = datetime.utcnow() + asset.updated_at = datetime.now(datetime.UTC) portfolio.total_value = portfolio_value - portfolio.updated_at = datetime.utcnow() + portfolio.updated_at = datetime.now(datetime.UTC) async def _calculate_portfolio_value(self, portfolio: AgentPortfolio) -> float: """Calculate total portfolio value""" @@ -475,7 +475,7 @@ class AgentPortfolioManager: if not strategy: return False - time_since_rebalance = datetime.utcnow() - portfolio.last_rebalance + time_since_rebalance = datetime.now(datetime.UTC) - portfolio.last_rebalance if time_since_rebalance > timedelta(seconds=strategy.rebalance_frequency): return True @@ -548,7 +548,7 @@ class AgentPortfolioManager: "current_value": current_value, "initial_value": initial_value, "total_trades": len(trades), - "last_updated": datetime.utcnow().isoformat(), + "last_updated": datetime.now(datetime.UTC).isoformat(), } diff --git a/apps/coordinator-api/src/app/services/agent_security.py b/apps/coordinator-api/src/app/services/agent_security.py index 9b705466..4612387c 100755 --- a/apps/coordinator-api/src/app/services/agent_security.py +++ b/apps/coordinator-api/src/app/services/agent_security.py @@ -9,7 +9,7 @@ import json from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any from uuid import uuid4 @@ -425,13 +425,13 @@ class AgentTrustManager: if security_violation: trust_score.security_violations += 1 - trust_score.last_violation = datetime.utcnow() - trust_score.violation_history.append({"timestamp": datetime.utcnow().isoformat(), "type": "security_violation"}) + trust_score.last_violation = datetime.now(datetime.UTC) + trust_score.violation_history.append({"timestamp": datetime.now(datetime.UTC).isoformat(), "type": "security_violation"}) if policy_violation: trust_score.policy_violations += 1 - trust_score.last_violation = datetime.utcnow() - trust_score.violation_history.append({"timestamp": datetime.utcnow().isoformat(), "type": "policy_violation"}) + trust_score.last_violation = datetime.now(datetime.UTC) + trust_score.violation_history.append({"timestamp": datetime.now(datetime.UTC).isoformat(), "type": "policy_violation"}) # Calculate scores trust_score.trust_score = self._calculate_trust_score(trust_score) @@ -449,8 +449,8 @@ class AgentTrustManager: trust_score.average_execution_time * (trust_score.total_executions - 1) + execution_time ) / trust_score.total_executions - trust_score.last_execution = datetime.utcnow() - trust_score.updated_at = datetime.utcnow() + trust_score.last_execution = datetime.now(datetime.UTC) + trust_score.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(trust_score) @@ -477,7 +477,7 @@ class AgentTrustManager: # Recency bonus (recent successful executions) if trust_score.last_execution: - days_since_last = (datetime.utcnow() - trust_score.last_execution).days + days_since_last = (datetime.now(datetime.UTC) - trust_score.last_execution).days if days_since_last < 7: base_score += 5 # Recent activity bonus elif days_since_last > 30: @@ -736,7 +736,7 @@ class AgentSandboxManager: if sandbox: # Mark as inactive sandbox.is_active = False - sandbox.updated_at = datetime.utcnow() + sandbox.updated_at = datetime.now(datetime.UTC) self.session.commit() # Sandbox cleanup requires integration with: diff --git a/apps/coordinator-api/src/app/services/agent_service.py b/apps/coordinator-api/src/app/services/agent_service.py index 3df63be6..b6d5e2af 100755 --- a/apps/coordinator-api/src/app/services/agent_service.py +++ b/apps/coordinator-api/src/app/services/agent_service.py @@ -4,7 +4,7 @@ Implements core orchestration logic and state management for AI agent workflows """ import asyncio -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from aitbc import get_logger @@ -60,7 +60,7 @@ class AgentStateManager: stmt = ( update(AgentExecution) .where(AgentExecution.id == execution_id) - .values(status=status, updated_at=datetime.utcnow(), **kwargs) + .values(status=status, updated_at=datetime.now(datetime.UTC), **kwargs) ) self.session.execute(stmt) @@ -101,7 +101,7 @@ class AgentStateManager: stmt = ( update(AgentStepExecution) .where(AgentStepExecution.id == step_execution_id) - .values(updated_at=datetime.utcnow(), **kwargs) + .values(updated_at=datetime.now(datetime.UTC), **kwargs) ) self.session.execute(stmt) @@ -148,7 +148,7 @@ class AgentVerifier: async def _basic_verify_step(self, step_execution: AgentStepExecution) -> dict[str, Any]: """Basic verification of step execution""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Basic checks: execution completed, has output, no errors verified = ( @@ -157,7 +157,7 @@ class AgentVerifier: and step_execution.error_message is None ) - verification_time = (datetime.utcnow() - start_time).total_seconds() + verification_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "verified": verified, @@ -169,7 +169,7 @@ class AgentVerifier: async def _full_verify_step(self, step_execution: AgentStepExecution) -> dict[str, Any]: """Full verification with additional checks""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Basic verification first basic_result = await self._basic_verify_step(step_execution) @@ -190,7 +190,7 @@ class AgentVerifier: if step_execution.memory_usage and step_execution.memory_usage < 8192: # < 8GB additional_checks.append("reasonable_memory_usage") - verification_time = (datetime.utcnow() - start_time).total_seconds() + verification_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "verified": basic_result["verified"], @@ -209,7 +209,7 @@ class AgentVerifier: 2. Verify proof against public parameters 3. Return verification result with proof hash """ - datetime.utcnow() + datetime.now(datetime.UTC) # For now, fall back to full verification # ZK proof generation and verification requires specialized cryptographic libraries @@ -245,7 +245,7 @@ class AIAgentOrchestrator: try: # Start execution await self.state_manager.update_execution_status( - execution.id, status=AgentStatus.RUNNING, started_at=datetime.utcnow(), total_steps=len(workflow.steps) + execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(datetime.UTC), total_steps=len(workflow.steps) ) # Execute steps asynchronously @@ -340,7 +340,7 @@ class AIAgentOrchestrator: try: # Update step status to running await self.state_manager.update_step_execution( - step_execution.id, status=AgentStatus.RUNNING, started_at=datetime.utcnow(), input_data=inputs + step_execution.id, status=AgentStatus.RUNNING, started_at=datetime.now(datetime.UTC), input_data=inputs ) # Execute the step based on type @@ -357,7 +357,7 @@ class AIAgentOrchestrator: await self.state_manager.update_step_execution( step_execution.id, status=AgentStatus.COMPLETED, - completed_at=datetime.utcnow(), + completed_at=datetime.now(datetime.UTC), output_data=result.get("output"), execution_time=result.get("execution_time", 0.0), gpu_accelerated=result.get("gpu_accelerated", False), @@ -379,7 +379,7 @@ class AIAgentOrchestrator: except Exception as e: # Mark step as failed await self.state_manager.update_step_execution( - step_execution.id, status=AgentStatus.FAILED, completed_at=datetime.utcnow(), error_message=str(e) + step_execution.id, status=AgentStatus.FAILED, completed_at=datetime.now(datetime.UTC), error_message=str(e) ) raise @@ -393,12 +393,12 @@ class AIAgentOrchestrator: 4. Output postprocessing Currently using simulated inference for testing purposes. """ - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate processing time await asyncio.sleep(0.1) - execution_time = (datetime.utcnow() - start_time).total_seconds() + execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "output": {"prediction": "simulated_result", "confidence": 0.95}, @@ -417,12 +417,12 @@ class AIAgentOrchestrator: 4. Model checkpointing and validation Currently using simulated training for testing purposes. """ - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate training time await asyncio.sleep(0.5) - execution_time = (datetime.utcnow() - start_time).total_seconds() + execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "output": {"model_updated": True, "training_loss": 0.123}, @@ -434,12 +434,12 @@ class AIAgentOrchestrator: async def _execute_data_processing_step(self, step: AgentStep, inputs: dict[str, Any]) -> dict[str, Any]: """Execute data processing step""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate processing time await asyncio.sleep(0.05) - execution_time = (datetime.utcnow() - start_time).total_seconds() + execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "output": {"processed_records": 1000, "data_validated": True}, @@ -451,12 +451,12 @@ class AIAgentOrchestrator: async def _execute_custom_step(self, step: AgentStep, inputs: dict[str, Any]) -> dict[str, Any]: """Execute custom step""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simulate custom processing await asyncio.sleep(0.2) - execution_time = (datetime.utcnow() - start_time).total_seconds() + execution_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "output": {"custom_result": "completed", "metadata": inputs}, @@ -494,7 +494,7 @@ class AIAgentOrchestrator: async def _complete_execution(self, execution_id: str, step_results: dict[str, Any]) -> None: """Mark execution as completed""" - completed_at = datetime.utcnow() + completed_at = datetime.now(datetime.UTC) execution = await self.state_manager.get_execution(execution_id) total_execution_time = (completed_at - execution.started_at).total_seconds() if execution.started_at else 0.0 @@ -511,7 +511,7 @@ class AIAgentOrchestrator: """Handle execution failure""" await self.state_manager.update_execution_status( - execution_id, status=AgentStatus.FAILED, completed_at=datetime.utcnow(), error_message=str(error) + execution_id, status=AgentStatus.FAILED, completed_at=datetime.now(datetime.UTC), error_message=str(error) ) def _estimate_completion(self, execution: AgentExecution) -> datetime | None: diff --git a/apps/coordinator-api/src/app/services/agent_service_marketplace.py b/apps/coordinator-api/src/app/services/agent_service_marketplace.py index 6800f67f..89c09e25 100755 --- a/apps/coordinator-api/src/app/services/agent_service_marketplace.py +++ b/apps/coordinator-api/src/app/services/agent_service_marketplace.py @@ -11,7 +11,7 @@ logger = get_logger(__name__) import hashlib import json from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -265,8 +265,8 @@ class AgentServiceMarketplace: completed_jobs=0, average_rating=0.0, rating_count=0, - listed_at=datetime.utcnow(), - last_updated=datetime.utcnow(), + listed_at=datetime.now(datetime.UTC), + last_updated=datetime.now(datetime.UTC), tags=tags, capabilities=capabilities, requirements=requirements, @@ -332,10 +332,10 @@ class AgentServiceMarketplace: if budget < service.base_price: raise ValueError(f"Budget below service price: {service.base_price}") - if deadline <= datetime.utcnow(): + if deadline <= datetime.now(datetime.UTC): raise ValueError("Invalid deadline") - if deadline > datetime.utcnow() + timedelta(days=365): + if deadline > datetime.now(datetime.UTC) + timedelta(days=365): raise ValueError("Deadline too far in future") # Generate request ID @@ -390,13 +390,13 @@ class AgentServiceMarketplace: if service.agent_id != agent_id: raise ValueError("Not service provider") - if datetime.utcnow() > request.deadline: + if datetime.now(datetime.UTC) > request.deadline: raise ValueError("Request expired") # Update request request.status = RequestStatus.ACCEPTED request.assigned_agent = agent_id - request.accepted_at = datetime.utcnow() + request.accepted_at = datetime.now(datetime.UTC) # Calculate dynamic price final_price = await self._calculate_dynamic_price(request.service_id, request.budget) @@ -425,12 +425,12 @@ class AgentServiceMarketplace: if request.assigned_agent != agent_id: raise ValueError("Not assigned agent") - if datetime.utcnow() > request.deadline: + if datetime.now(datetime.UTC) > request.deadline: raise ValueError("Request expired") # Update request request.status = RequestStatus.COMPLETED - request.completed_at = datetime.utcnow() + request.completed_at = datetime.now(datetime.UTC) request.results_hash = hashlib.sha256(json.dumps(results, sort_keys=True).encode()).hexdigest() # Calculate payment @@ -441,7 +441,7 @@ class AgentServiceMarketplace: # Update service stats service.total_earnings += agent_payment service.completed_jobs += 1 - service.last_updated = datetime.utcnow() + service.last_updated = datetime.now(datetime.UTC) # Update category if service.service_type.value in self.categories: @@ -479,7 +479,7 @@ class AgentServiceMarketplace: if rating < 1 or rating > 5: raise ValueError("Invalid rating") - if datetime.utcnow() > request.deadline + timedelta(days=30): + if datetime.now(datetime.UTC) > request.deadline + timedelta(days=30): raise ValueError("Rating period expired") # Update request @@ -539,7 +539,7 @@ class AgentServiceMarketplace: total_earnings=0.0, reputation=founder_reputation, status=GuildStatus.ACTIVE, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), requirements=requirements, benefits=benefits, guild_rules=guild_rules, @@ -547,7 +547,7 @@ class AgentServiceMarketplace: # Add founder as member guild.members[founder_id] = { - "joined_at": datetime.utcnow(), + "joined_at": datetime.now(datetime.UTC), "reputation": founder_reputation, "role": "founder", "contributions": 0, @@ -592,7 +592,7 @@ class AgentServiceMarketplace: # Add member guild.members[agent_id] = { - "joined_at": datetime.utcnow(), + "joined_at": datetime.now(datetime.UTC), "reputation": agent_reputation, "role": "member", "contributions": 0, @@ -842,7 +842,7 @@ class AgentServiceMarketplace: while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) for request in self.service_requests.values(): if request.status == RequestStatus.PENDING and current_time > request.deadline: diff --git a/apps/coordinator-api/src/app/services/amm_service.py b/apps/coordinator-api/src/app/services/amm_service.py index b8fe8124..b6485aad 100755 --- a/apps/coordinator-api/src/app/services/amm_service.py +++ b/apps/coordinator-api/src/app/services/amm_service.py @@ -7,7 +7,7 @@ Provides liquidity pool management, token swapping, and dynamic fee adjustment. from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -83,7 +83,7 @@ class AMMService: reserve_a=0.0, reserve_b=0.0, is_active=True, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), created_by=creator_address, ) @@ -138,7 +138,7 @@ class AMMService: pool.reserve_a += liquidity_request.amount_a pool.reserve_b += liquidity_request.amount_b pool.total_liquidity += liquidity_result.liquidity_received - pool.updated_at = datetime.utcnow() + pool.updated_at = datetime.now(datetime.UTC) # Update or create liquidity position position = self.session.execute( @@ -150,15 +150,15 @@ class AMMService: if position: position.liquidity_amount += liquidity_result.liquidity_received position.shares_owned = (position.liquidity_amount / pool.total_liquidity) * 100 - position.last_deposit = datetime.utcnow() + position.last_deposit = datetime.now(datetime.UTC) else: position = LiquidityPosition( pool_id=pool.id, provider_address=provider_address, liquidity_amount=liquidity_result.liquidity_received, shares_owned=(liquidity_result.liquidity_received / pool.total_liquidity) * 100, - last_deposit=datetime.utcnow(), - created_at=datetime.utcnow(), + last_deposit=datetime.now(datetime.UTC), + created_at=datetime.now(datetime.UTC), ) self.session.add(position) @@ -213,12 +213,12 @@ class AMMService: pool.reserve_a -= removal_result.amount_a pool.reserve_b -= removal_result.amount_b pool.total_liquidity -= liquidity_request.liquidity_amount - pool.updated_at = datetime.utcnow() + pool.updated_at = datetime.now(datetime.UTC) # Update liquidity position position.liquidity_amount -= liquidity_request.liquidity_amount position.shares_owned = (position.liquidity_amount / pool.total_liquidity) * 100 if pool.total_liquidity > 0 else 0 - position.last_withdrawal = datetime.utcnow() + position.last_withdrawal = datetime.now(datetime.UTC) # Remove position if empty if position.liquidity_amount == 0: @@ -285,7 +285,7 @@ class AMMService: pool.reserve_b += swap_request.amount_in pool.reserve_a -= swap_result.amount_out - pool.updated_at = datetime.utcnow() + pool.updated_at = datetime.now(datetime.UTC) # Record swap transaction swap_transaction = SwapTransaction( @@ -298,7 +298,7 @@ class AMMService: price=swap_result.price, fee_amount=swap_result.fee_amount, transaction_hash=swap_result.transaction_hash, - executed_at=datetime.utcnow(), + executed_at=datetime.now(datetime.UTC), ) self.session.add(swap_transaction) @@ -339,7 +339,7 @@ class AMMService: # Update pool in database pool.fee_percentage = new_fee - pool.updated_at = datetime.utcnow() + pool.updated_at = datetime.now(datetime.UTC) self.session.commit() # Create fee structure response @@ -348,7 +348,7 @@ class AMMService: base_fee_percentage=base_fee, current_fee_percentage=new_fee, volatility_adjustment=volatility_multiplier - 1.0, - adjusted_at=datetime.utcnow(), + adjusted_at=datetime.now(datetime.UTC), ) logger.info(f"Adjusted fee for pool {pool_id} to {new_fee:.3f}%") @@ -384,7 +384,7 @@ class AMMService: if existing_program: existing_program.daily_reward_amount = daily_reward existing_program.incentive_multiplier = incentive_multiplier - existing_program.updated_at = datetime.utcnow() + existing_program.updated_at = datetime.now(datetime.UTC) program = existing_program else: program = IncentiveProgram( @@ -393,7 +393,7 @@ class AMMService: incentive_multiplier=incentive_multiplier, duration_days=self.incentive_duration_days, is_active=True, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(program) @@ -511,7 +511,7 @@ class AMMService: return ValidationResult(is_valid=False, error_message="Insufficient liquidity in pool") # Check deadline - if datetime.utcnow() > swap_request.deadline: + if datetime.now(datetime.UTC) > swap_request.deadline: return ValidationResult(is_valid=False, error_message="Transaction deadline expired") # Check minimum amount @@ -562,7 +562,7 @@ class AMMService: total_value_locked=0.0, apr=0.0, utilization_rate=0.0, - updated_at=datetime.utcnow(), + updated_at=datetime.now(datetime.UTC), ) self.session.add(metrics) @@ -601,7 +601,7 @@ class AMMService: metrics.total_value_locked = tvl metrics.apr = apr metrics.utilization_rate = utilization_rate - metrics.updated_at = datetime.utcnow() + metrics.updated_at = datetime.now(datetime.UTC) self.session.commit() @@ -615,7 +615,7 @@ class AMMService: metrics = self.session.execute(select(PoolMetrics).where(PoolMetrics.pool_id == pool.id)).first() # Calculate 24h volume and fees - twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24) + twenty_four_hours_ago = datetime.now(datetime.UTC) - timedelta(hours=24) recent_swaps = self.session.execute( select(SwapTransaction).where( diff --git a/apps/coordinator-api/src/app/services/analytics_service.py b/apps/coordinator-api/src/app/services/analytics_service.py index 9e748e66..b5d3ecec 100755 --- a/apps/coordinator-api/src/app/services/analytics_service.py +++ b/apps/coordinator-api/src/app/services/analytics_service.py @@ -3,7 +3,7 @@ Marketplace Analytics Service Implements comprehensive analytics, insights, and reporting for the marketplace """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from uuid import uuid4 @@ -119,7 +119,7 @@ class DataCollector: change_percentage=change_percentage, unit="AITBC", category="financial", - recorded_at=datetime.utcnow(), + recorded_at=datetime.now(datetime.UTC), period_start=start_time, period_end=end_time, breakdown={ @@ -166,7 +166,7 @@ class DataCollector: change_percentage=change_percentage, unit="agents", category="agents", - recorded_at=datetime.utcnow(), + recorded_at=datetime.now(datetime.UTC), period_start=start_time, period_end=end_time, breakdown={ @@ -216,7 +216,7 @@ class DataCollector: change_percentage=change_percentage, unit="AITBC", category="pricing", - recorded_at=datetime.utcnow(), + recorded_at=datetime.now(datetime.UTC), period_start=start_time, period_end=end_time, breakdown={ @@ -267,7 +267,7 @@ class DataCollector: change_percentage=change_percentage, unit="%", category="performance", - recorded_at=datetime.utcnow(), + recorded_at=datetime.now(datetime.UTC), period_start=start_time, period_end=end_time, breakdown={ @@ -318,7 +318,7 @@ class DataCollector: change_percentage=change_percentage, unit="ratio", category="market", - recorded_at=datetime.utcnow(), + recorded_at=datetime.now(datetime.UTC), period_start=start_time, period_end=end_time, breakdown={ @@ -823,7 +823,7 @@ class MarketplaceAnalytics: """Collect comprehensive market data""" # Calculate time range - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) if period_type == AnalyticsPeriod.DAILY: start_time = end_time - timedelta(days=1) @@ -863,7 +863,7 @@ class MarketplaceAnalytics: period_type = period_map.get(time_period, AnalyticsPeriod.DAILY) # Calculate time range - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) if period_type == AnalyticsPeriod.DAILY: start_time = end_time - timedelta(days=1) @@ -925,7 +925,7 @@ class MarketplaceAnalytics: """Get comprehensive market overview""" # Get latest daily metrics - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) start_time = end_time - timedelta(days=1) metrics = self.session.execute( @@ -957,7 +957,7 @@ class MarketplaceAnalytics: ).all() return { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "period": "last_24_hours", "metrics": { metric.metric_name: { diff --git a/apps/coordinator-api/src/app/services/atomic_swap_service.py b/apps/coordinator-api/src/app/services/atomic_swap_service.py index 7d2a1110..b1e494d5 100755 --- a/apps/coordinator-api/src/app/services/atomic_swap_service.py +++ b/apps/coordinator-api/src/app/services/atomic_swap_service.py @@ -8,7 +8,7 @@ from __future__ import annotations import hashlib import secrets -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -44,7 +44,7 @@ class AtomicSwapService: # Standard HTLC uses SHA256 of the secret hashlock = "0x" + hashlib.sha256(secret.encode()).hexdigest() - now = datetime.utcnow() + now = datetime.now(datetime.UTC) source_timelock = int((now + timedelta(hours=request.source_timelock_hours)).timestamp()) target_timelock = int((now + timedelta(hours=request.target_timelock_hours)).timestamp()) @@ -97,7 +97,7 @@ class AtomicSwapService: order.status = SwapStatus.INITIATED order.source_initiate_tx = request.tx_hash - order.updated_at = datetime.utcnow() + order.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(order) @@ -116,7 +116,7 @@ class AtomicSwapService: order.status = SwapStatus.PARTICIPATING order.target_participate_tx = request.tx_hash - order.updated_at = datetime.utcnow() + order.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(order) @@ -141,7 +141,7 @@ class AtomicSwapService: order.status = SwapStatus.COMPLETED order.target_complete_tx = request.tx_hash # Secret is now publicly known on the blockchain - order.updated_at = datetime.utcnow() + order.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(order) @@ -155,7 +155,7 @@ class AtomicSwapService: if not order: raise HTTPException(status_code=404, detail="Swap order not found") - now = int(datetime.utcnow().timestamp()) + now = int(datetime.now(datetime.UTC).timestamp()) if order.status == SwapStatus.INITIATED and now < order.source_timelock: raise HTTPException(status_code=400, detail="Source timelock has not expired yet") @@ -165,7 +165,7 @@ class AtomicSwapService: order.status = SwapStatus.REFUNDED order.refund_tx = request.tx_hash - order.updated_at = datetime.utcnow() + order.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(order) diff --git a/apps/coordinator-api/src/app/services/audit_logging.py b/apps/coordinator-api/src/app/services/audit_logging.py index 2fb5148c..dc4bb35c 100755 --- a/apps/coordinator-api/src/app/services/audit_logging.py +++ b/apps/coordinator-api/src/app/services/audit_logging.py @@ -8,7 +8,7 @@ import hashlib import json import os from dataclasses import asdict, dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from pathlib import Path from typing import Any @@ -95,7 +95,7 @@ class AuditLogger: """Log access to confidential data (synchronous for tests).""" event = AuditEvent( event_id=self._generate_event_id(), - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), event_type="access", participant_id=participant_id, transaction_id=transaction_id, @@ -127,7 +127,7 @@ class AuditLogger: """Log key management operations (synchronous for tests).""" event = AuditEvent( event_id=self._generate_event_id(), - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), event_type="key_operation", participant_id=participant_id, transaction_id=None, @@ -165,7 +165,7 @@ class AuditLogger: """Log access policy changes""" event = AuditEvent( event_id=self._generate_event_id(), - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), event_type="policy_change", participant_id=participant_id, transaction_id=None, @@ -262,7 +262,7 @@ class AuditLogger: def verify_integrity(self, start_date: datetime | None = None) -> dict[str, Any]: """Verify integrity of audit logs""" if start_date is None: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) results = { "verified_files": 0, @@ -316,7 +316,7 @@ class AuditLogger: "start_time": start_time.isoformat(), "end_time": end_time.isoformat(), "event_count": len(events), - "exported_at": datetime.utcnow().isoformat(), + "exported_at": datetime.now(datetime.UTC).isoformat(), "include_signatures": include_signatures, }, "events": [], @@ -429,7 +429,7 @@ class AuditLogger: def _rotate_if_needed(self): """Rotate log file if needed""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) today = now.date() # Check if we need a new file @@ -449,7 +449,7 @@ class AuditLogger: # Write header with metadata if not self.current_file.exists(): header = { - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "version": "1.0", "format": "jsonl", "previous_hash": self.chain_hash, @@ -460,7 +460,7 @@ class AuditLogger: def _generate_event_id(self) -> str: """Generate unique event ID""" - return f"evt_{datetime.utcnow().timestamp()}_{os.urandom(4).hex()}" + return f"evt_{datetime.now(datetime.UTC).timestamp()}_{os.urandom(4).hex()}" def _sign_event(self, event: AuditEvent) -> str: """Sign event for tamper-evidence""" diff --git a/apps/coordinator-api/src/app/services/bid_strategy_engine.py b/apps/coordinator-api/src/app/services/bid_strategy_engine.py index e6706b58..0bbfb213 100755 --- a/apps/coordinator-api/src/app/services/bid_strategy_engine.py +++ b/apps/coordinator-api/src/app/services/bid_strategy_engine.py @@ -9,7 +9,7 @@ from aitbc import get_logger logger = get_logger(__name__) from dataclasses import asdict, dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -206,7 +206,7 @@ class BidStrategyEngine: "urgency_preference": preferences.get("urgency_preference", 0.5), "max_wait_time": preferences.get("max_wait_time", 3600), # 1 hour "min_success_probability": preferences.get("min_success_probability", 0.7), - "updated_at": datetime.utcnow().isoformat(), + "updated_at": datetime.now(datetime.UTC).isoformat(), } logger.info(f"Updated preferences for agent {agent_id}") @@ -231,7 +231,7 @@ class BidStrategyEngine: "volatility_trend": volatility_trend, "future_prediction": asdict(future_conditions), "recommendations": await self._generate_market_recommendations(market_conditions), - "analysis_timestamp": datetime.utcnow().isoformat(), + "analysis_timestamp": datetime.now(datetime.UTC).isoformat(), } async def _select_optimal_strategy( @@ -330,7 +330,7 @@ class BidStrategyEngine: # Time factor (urgency based on deadline) time_factor = 1.0 if task_requirements.deadline: - time_remaining = (task_requirements.deadline - datetime.utcnow()).total_seconds() / 3600 + time_remaining = (task_requirements.deadline - datetime.now(datetime.UTC)).total_seconds() / 3600 if time_remaining < 2: # Less than 2 hours time_factor = 1.5 elif time_remaining < 6: # Less than 6 hours @@ -418,7 +418,7 @@ class BidStrategyEngine: # Time factor time_factor = 1.0 if task_requirements.deadline: - time_remaining = (task_requirements.deadline - datetime.utcnow()).total_seconds() / 3600 + time_remaining = (task_requirements.deadline - datetime.now(datetime.UTC)).total_seconds() / 3600 if time_remaining < 2: time_factor = 0.7 elif time_remaining < 6: @@ -579,7 +579,7 @@ class BidStrategyEngine: price_volatility=0.12, demand_level=0.68, supply_level=0.72, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), ) async def _load_market_history(self): @@ -706,7 +706,7 @@ class BidStrategyEngine: price_volatility=current.price_volatility, demand_level=current.demand_level, supply_level=current.supply_level, - timestamp=datetime.utcnow() + timedelta(hours=hours_ahead), + timestamp=datetime.now(datetime.UTC) + timedelta(hours=hours_ahead), ) # Apply trend adjustments diff --git a/apps/coordinator-api/src/app/services/bounty_service.py b/apps/coordinator-api/src/app/services/bounty_service.py index 235a32c8..69eb55fb 100755 --- a/apps/coordinator-api/src/app/services/bounty_service.py +++ b/apps/coordinator-api/src/app/services/bounty_service.py @@ -3,7 +3,7 @@ Bounty Management Service Business logic for AI agent bounty system with ZK-proof verification """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from sqlalchemy import and_, func, or_, select @@ -175,7 +175,7 @@ class BountyService: if bounty.status != BountyStatus.ACTIVE: raise ValueError("Bounty is not active") - if datetime.utcnow() > bounty.deadline: + if datetime.now(datetime.UTC) > bounty.deadline: raise ValueError("Bounty deadline has passed") if bounty.submission_count >= bounty.max_submissions: @@ -257,7 +257,7 @@ class BountyService: # Update submission submission.status = SubmissionStatus.VERIFIED if verified else SubmissionStatus.REJECTED - submission.verification_time = datetime.utcnow() + submission.verification_time = datetime.now(datetime.UTC) submission.verifier_address = verifier_address # If verified, check if it meets bounty requirements @@ -297,13 +297,13 @@ class BountyService: if submission.status != SubmissionStatus.VERIFIED: raise ValueError("Can only dispute verified submissions") - if datetime.utcnow() - submission.verification_time > timedelta(days=1): + if datetime.now(datetime.UTC) - submission.verification_time > timedelta(days=1): raise ValueError("Dispute window expired") # Update submission submission.status = SubmissionStatus.DISPUTED submission.dispute_reason = dispute_reason - submission.dispute_time = datetime.utcnow() + submission.dispute_time = datetime.now(datetime.UTC) # Update bounty status bounty = await self.get_bounty(bounty_id) @@ -369,13 +369,13 @@ class BountyService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) # Get top performers stmt = ( @@ -419,13 +419,13 @@ class BountyService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get statistics total_stmt = select(func.count(Bounty.bounty_id)).where(Bounty.creation_time >= start_date) @@ -484,7 +484,7 @@ class BountyService: stats = BountyStats( period_start=start_date, - period_end=datetime.utcnow(), + period_end=datetime.now(datetime.UTC), period_type=period, total_bounties=total_bounties, active_bounties=active_bounties, @@ -570,7 +570,7 @@ class BountyService: if bounty.status != BountyStatus.ACTIVE: raise ValueError("Bounty is not active") - if datetime.utcnow() <= bounty.deadline: + if datetime.now(datetime.UTC) <= bounty.deadline: raise ValueError("Deadline has not passed") bounty.status = BountyStatus.EXPIRED diff --git a/apps/coordinator-api/src/app/services/certification_service.py b/apps/coordinator-api/src/app/services/certification_service.py index 8685aa74..ddb5c42e 100755 --- a/apps/coordinator-api/src/app/services/certification_service.py +++ b/apps/coordinator-api/src/app/services/certification_service.py @@ -5,7 +5,7 @@ Implements certification framework, partnership programs, and badge system import hashlib import json -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from uuid import uuid4 @@ -111,7 +111,7 @@ class CertificationSystem: certification_id = f"cert_{uuid4().hex[:8]}" verification_hash = self.generate_verification_hash(agent_id, level, certification_id) - expires_at = datetime.utcnow() + timedelta(days=level_config["validity_days"]) + expires_at = datetime.now(datetime.UTC) + timedelta(days=level_config["validity_days"]) certification = AgentCertification( certification_id=certification_id, @@ -130,7 +130,7 @@ class CertificationSystem: audit_log=[ { "action": "issued", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "performed_by": issued_by, "details": f"Certification issued at {level.value} level", } @@ -200,7 +200,7 @@ class CertificationSystem: AgentCertification.agent_id == agent_id, AgentCertification.certification_level == target_level, AgentCertification.status == CertificationStatus.ACTIVE, - AgentCertification.expires_at > datetime.utcnow(), + AgentCertification.expires_at > datetime.now(datetime.UTC), ) ) ).first() @@ -512,7 +512,7 @@ class CertificationSystem: "agent_id": agent_id, "level": level.value, "certification_id": certification_id, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "nonce": uuid4().hex, } @@ -567,9 +567,9 @@ class CertificationSystem: return False, f"Renewal requirements not met: {'; '.join(errors)}" # Update certification - certification.expires_at = datetime.utcnow() + timedelta(days=level_config["validity_days"]) + certification.expires_at = datetime.now(datetime.UTC) + timedelta(days=level_config["validity_days"]) certification.renewal_count += 1 - certification.last_renewed_at = datetime.utcnow() + certification.last_renewed_at = datetime.now(datetime.UTC) certification.verification_hash = self.generate_verification_hash( certification.agent_id, certification.certification_level, certification.certification_id ) @@ -578,7 +578,7 @@ class CertificationSystem: certification.audit_log.append( { "action": "renewed", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "performed_by": renewed_by, "details": f"Certification renewed for {level_config['validity_days']} days", } @@ -664,7 +664,7 @@ class PartnershipManager: commission_structure=kwargs.get("commission_structure", type_config.get("commission_structure", {})), performance_metrics=kwargs.get("performance_metrics", ["sales_volume", "customer_satisfaction"]), max_participants=kwargs.get("max_participants"), - launched_at=datetime.utcnow() if kwargs.get("launch_immediately", False) else None, + launched_at=datetime.now(datetime.UTC) if kwargs.get("launch_immediately", False) else None, ) session.add(program) @@ -714,7 +714,7 @@ class PartnershipManager: program_id=program_id, partnership_type=program.program_type, current_tier="basic", - applied_at=datetime.utcnow(), + applied_at=datetime.now(datetime.UTC), status="pending_approval", partnership_metadata={"application_data": application_data, "eligibility_results": eligibility_results}, ) @@ -1101,7 +1101,7 @@ class BadgeSystem: display_properties=criteria.get("display_properties", {}), is_limited=criteria.get("is_limited", False), max_awards=criteria.get("max_awards"), - available_from=datetime.utcnow(), + available_from=datetime.now(datetime.UTC), available_until=criteria.get("available_until"), ) @@ -1213,7 +1213,7 @@ class BadgeSystem: "context": { "badge_name": badge.badge_name, "badge_type": badge.badge_type.value, - "verification_date": datetime.utcnow().isoformat(), + "verification_date": datetime.now(datetime.UTC).isoformat(), }, } diff --git a/apps/coordinator-api/src/app/services/community_service.py b/apps/coordinator-api/src/app/services/community_service.py index 9167c367..c41db3a0 100755 --- a/apps/coordinator-api/src/app/services/community_service.py +++ b/apps/coordinator-api/src/app/services/community_service.py @@ -3,7 +3,7 @@ Community and Developer Ecosystem Services Services for managing OpenClaw developer tools, SDKs, and third-party solutions """ -from datetime import datetime +from datetime import datetime, UTC from typing import Any from aitbc import get_logger @@ -49,7 +49,7 @@ class DeveloperEcosystemService: # Mocking SDK release data return { "latest_version": "v1.2.0", - "release_date": datetime.utcnow().isoformat(), + "release_date": datetime.now(datetime.UTC).isoformat(), "supported_languages": ["python", "typescript", "rust"], "download_urls": {"python": "pip install aitbc-agent-sdk", "typescript": "npm install @aitbc/agent-sdk"}, "features": [ @@ -106,7 +106,7 @@ class ThirdPartySolutionService: # Auto-publish if free, otherwise manual review required if solution.price_model == "free": solution.status = SolutionStatus.PUBLISHED - solution.published_at = datetime.utcnow() + solution.published_at = datetime.now(datetime.UTC) self.session.add(solution) self.session.commit() @@ -278,7 +278,7 @@ class CommunityPlatformService: theme=data.get("theme", ""), sponsor=data.get("sponsor", "AITBC Foundation"), prize_pool=data.get("prize_pool", 0.0), - registration_start=datetime.fromisoformat(data.get("registration_start", datetime.utcnow().isoformat())), + registration_start=datetime.fromisoformat(data.get("registration_start", datetime.now(datetime.UTC).isoformat())), registration_end=datetime.fromisoformat(data.get("registration_end")), event_start=datetime.fromisoformat(data.get("event_start")), event_end=datetime.fromisoformat(data.get("event_end")), diff --git a/apps/coordinator-api/src/app/services/compliance_engine.py b/apps/coordinator-api/src/app/services/compliance_engine.py index 53382e79..b48e162b 100755 --- a/apps/coordinator-api/src/app/services/compliance_engine.py +++ b/apps/coordinator-api/src/app/services/compliance_engine.py @@ -4,7 +4,7 @@ GDPR, CCPA, SOC 2, and regulatory compliance automation """ from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any from uuid import uuid4 @@ -129,7 +129,7 @@ class GDPRCompliance: return False # Check if consent has expired - if consent.expires_at and datetime.utcnow() > consent.expires_at: + if consent.expires_at and datetime.now(datetime.UTC) > consent.expires_at: return False # Check if consent has been withdrawn @@ -165,11 +165,11 @@ class GDPRCompliance: consent_id = str(uuid4()) status = ConsentStatus.GRANTED if granted else ConsentStatus.DENIED - granted_at = datetime.utcnow() if granted else None + granted_at = datetime.now(datetime.UTC) if granted else None expires_at = None if granted and expires_days: - expires_at = datetime.utcnow() + timedelta(days=expires_days) + expires_at = datetime.now(datetime.UTC) + timedelta(days=expires_days) consent = ConsentRecord( consent_id=consent_id, @@ -198,7 +198,7 @@ class GDPRCompliance: for consent in consents: if consent.consent_id == consent_id: consent.status = ConsentStatus.WITHDRAWN - consent.withdrawn_at = datetime.utcnow() + consent.withdrawn_at = datetime.now(datetime.UTC) self.logger.info(f"Consent withdrawn: {consent_id}") return True @@ -216,8 +216,8 @@ class GDPRCompliance: "user_id": user_id, "details": details, "status": "pending", - "created_at": datetime.utcnow(), - "due_date": datetime.utcnow() + timedelta(days=30), # GDPR 30-day deadline + "created_at": datetime.now(datetime.UTC), + "due_date": datetime.now(datetime.UTC) + timedelta(days=30), # GDPR 30-day deadline } self.data_subject_requests[request_id] = request_data @@ -267,8 +267,8 @@ class GDPRCompliance: "notification_id": notification_id, "breach_data": breach_data, "notification_required": await self.check_data_breach_notification(breach_data), - "created_at": datetime.utcnow(), - "deadline": datetime.utcnow() + timedelta(hours=72), # 72-hour deadline + "created_at": datetime.now(datetime.UTC), + "deadline": datetime.now(datetime.UTC) + timedelta(hours=72), # 72-hour deadline "status": "pending", } @@ -301,7 +301,7 @@ class SOC2Compliance: "evidence_requirements": control_config.get("evidence_requirements", []), "testing_procedures": control_config.get("testing_procedures", []), "status": "implemented", - "implemented_at": datetime.utcnow(), + "implemented_at": datetime.now(datetime.UTC), "last_tested": None, "test_results": [], } @@ -328,10 +328,10 @@ class SOC2Compliance: # Record test result control["test_results"].append( - {"test_id": str(uuid4()), "timestamp": datetime.utcnow(), "result": test_result, "tester": "automated"} + {"test_id": str(uuid4()), "timestamp": datetime.now(datetime.UTC), "result": test_result, "tester": "automated"} ) - control["last_tested"] = datetime.utcnow() + control["last_tested"] = datetime.now(datetime.UTC) return test_result @@ -456,7 +456,7 @@ class SOC2Compliance: "passed_controls": passed_controls, "compliance_score": compliance_score, "compliance_status": "compliant" if compliance_score >= 0.9 else "non_compliant", - "report_date": datetime.utcnow().isoformat(), + "report_date": datetime.now(datetime.UTC).isoformat(), "controls": self.security_controls, } @@ -515,8 +515,8 @@ class AMLKYCCompliance: "risk_level": risk_level, "status": status, "risk_factors": risk_factors, - "checked_at": datetime.utcnow(), - "next_review": datetime.utcnow() + timedelta(days=365), + "checked_at": datetime.now(datetime.UTC), + "next_review": datetime.now(datetime.UTC) + timedelta(days=365), } self.customer_records[customer_id] = kyc_result @@ -594,7 +594,7 @@ class AMLKYCCompliance: "customer_id": customer_id, "risk_score": risk_score, "suspicious": suspicious, - "monitored_at": datetime.utcnow(), + "monitored_at": datetime.now(datetime.UTC), } if suspicious: @@ -654,7 +654,7 @@ class AMLKYCCompliance: "risk_score": risk_score, "customer_risk_level": customer_risk_level, "transaction_details": transaction_data, - "created_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), "status": "pending_review", "reported_to_authorities": False, } @@ -686,7 +686,7 @@ class AMLKYCCompliance: "suspicious_transactions": suspicious_transactions, "pending_sars": pending_sars, "suspicious_rate": (suspicious_transactions / total_transactions) if total_transactions > 0 else 0, - "report_date": datetime.utcnow().isoformat(), + "report_date": datetime.now(datetime.UTC).isoformat(), } @@ -828,7 +828,7 @@ class EnterpriseComplianceEngine: "consent_valid": consent_valid, "retention_compliant": retention_compliant, "protection_compliant": protection_compliant, - "checked_at": datetime.utcnow().isoformat(), + "checked_at": datetime.now(datetime.UTC).isoformat(), } async def _check_soc2_compliance(self, entity_data: dict[str, Any]) -> dict[str, Any]: @@ -876,7 +876,7 @@ class EnterpriseComplianceEngine: retention_days = entity_data.get("retention_days", 2555) # 7 years default expiry_date = created_at + timedelta(days=retention_days) - return datetime.utcnow() <= expiry_date + return datetime.now(datetime.UTC) <= expiry_date return True @@ -907,7 +907,7 @@ class EnterpriseComplianceEngine: "overall_compliance_score": overall_score, "frameworks": {"GDPR": gdpr_compliance, "SOC 2": soc2_compliance, "AML/KYC": aml_compliance}, "total_rules": len(self.compliance_rules), - "last_updated": datetime.utcnow().isoformat(), + "last_updated": datetime.now(datetime.UTC).isoformat(), "status": "compliant" if overall_score >= 80 else "needs_attention", } diff --git a/apps/coordinator-api/src/app/services/confidential_service.py b/apps/coordinator-api/src/app/services/confidential_service.py index 03692f9a..09291d8d 100755 --- a/apps/coordinator-api/src/app/services/confidential_service.py +++ b/apps/coordinator-api/src/app/services/confidential_service.py @@ -2,7 +2,7 @@ Confidential Transaction Service - Wrapper for existing confidential functionality """ -from datetime import datetime +from datetime import datetime, UTC from typing import Any from ..models.confidential import ConfidentialTransaction @@ -40,7 +40,7 @@ class ConfidentialTransactionService: recipient=recipient, encrypted_payload=encrypted_data, viewing_key=viewing_key, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) def decrypt_transaction(self, transaction: ConfidentialTransaction, viewing_key: str) -> dict[str, Any]: diff --git a/apps/coordinator-api/src/app/services/cross_chain_bridge.py b/apps/coordinator-api/src/app/services/cross_chain_bridge.py index 56386877..01ba05ea 100755 --- a/apps/coordinator-api/src/app/services/cross_chain_bridge.py +++ b/apps/coordinator-api/src/app/services/cross_chain_bridge.py @@ -7,7 +7,7 @@ Enables bridging of assets between different blockchain networks. from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -119,8 +119,8 @@ class CrossChainBridgeService: total_amount=total_amount, status=BridgeRequestStatus.PENDING, zk_proof=zk_proof.proof, - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(seconds=self.bridge_timeout), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(seconds=self.bridge_timeout), ) self.session.add(bridge_request) @@ -156,7 +156,7 @@ class CrossChainBridgeService: # Update local status if different if contract_status.status != bridge_request.status.value: bridge_request.status = BridgeRequestStatus(contract_status.status) - bridge_request.updated_at = datetime.utcnow() + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() # Get confirmation details @@ -217,7 +217,7 @@ class CrossChainBridgeService: # Record dispute resolution bridge_request.dispute_reason = dispute_reason bridge_request.resolution_action = resolution_action.action_type - bridge_request.resolved_at = datetime.utcnow() + bridge_request.resolved_at = datetime.now(datetime.UTC) bridge_request.status = BridgeRequestStatus.RESOLVED self.session.commit() @@ -273,7 +273,7 @@ class CrossChainBridgeService: transaction_type="confirmation", transaction_hash=confirm_request.lock_tx_hash, signature=confirm_request.signature, - confirmed_at=datetime.utcnow(), + confirmed_at=datetime.now(datetime.UTC), ) self.session.add(confirmation) @@ -285,7 +285,7 @@ class CrossChainBridgeService: if total_confirmations >= required_confirmations: # Update bridge request status bridge_request.status = BridgeRequestStatus.CONFIRMED - bridge_request.confirmed_at = datetime.utcnow() + bridge_request.confirmed_at = datetime.now(datetime.UTC) # Generate Merkle proof for completion merkle_proof = await self._generate_merkle_proof(bridge_request) @@ -338,14 +338,14 @@ class CrossChainBridgeService: transaction_type="completion", transaction_hash=complete_request.unlock_tx_hash, merkle_proof=complete_request.merkle_proof, - completed_at=datetime.utcnow(), + completed_at=datetime.now(datetime.UTC), ) self.session.add(completion) # Update bridge request status bridge_request.status = BridgeRequestStatus.COMPLETED - bridge_request.completed_at = datetime.utcnow() + bridge_request.completed_at = datetime.now(datetime.UTC) bridge_request.unlock_tx_hash = complete_request.unlock_tx_hash self.session.commit() @@ -386,7 +386,7 @@ class CrossChainBridgeService: fee_percentage=token_request.fee_percentage, requires_whitelist=token_request.requires_whitelist, is_active=True, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(supported_token) @@ -422,7 +422,7 @@ class CrossChainBridgeService: min_confirmations=chain_request.min_confirmations, avg_block_time=chain_request.avg_block_time, is_active=True, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(chain_config) @@ -489,7 +489,7 @@ class CrossChainBridgeService: "amount": transfer_request.amount, "source_chain": transfer_request.source_chain_id, "target_chain": transfer_request.target_chain_id, - "timestamp": int(datetime.utcnow().timestamp()), + "timestamp": int(datetime.now(datetime.UTC).timestamp()), } # Generate ZK proof diff --git a/apps/coordinator-api/src/app/services/cross_chain_bridge_enhanced.py b/apps/coordinator-api/src/app/services/cross_chain_bridge_enhanced.py index 59810695..27198fc1 100755 --- a/apps/coordinator-api/src/app/services/cross_chain_bridge_enhanced.py +++ b/apps/coordinator-api/src/app/services/cross_chain_bridge_enhanced.py @@ -6,7 +6,7 @@ Production-ready cross-chain bridge service with atomic swap protocol implementa import asyncio import hashlib import secrets -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from enum import StrEnum from typing import Any @@ -153,9 +153,9 @@ class CrossChainBridgeService: bridge_fee=bridge_fee, network_fee=network_fee, total_fee=total_fee, - deadline=datetime.utcnow() + timedelta(minutes=deadline_minutes), + deadline=datetime.now(datetime.UTC) + timedelta(minutes=deadline_minutes), status=BridgeRequestStatus.PENDING, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(bridge_request) @@ -274,7 +274,7 @@ class CrossChainBridgeService: # Update status bridge_request.status = BridgeRequestStatus.CANCELLED bridge_request.cancellation_reason = reason - bridge_request.updated_at = datetime.utcnow() + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() @@ -288,7 +288,7 @@ class CrossChainBridgeService: "bridge_request_id": bridge_request_id, "status": BridgeRequestStatus.CANCELLED.value, "reason": reason, - "cancelled_at": datetime.utcnow().isoformat(), + "cancelled_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -300,7 +300,7 @@ class CrossChainBridgeService: """Get bridge statistics for the specified time period""" try: - cutoff_time = datetime.utcnow() - timedelta(hours=time_period_hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=time_period_hours) # Get total requests total_requests = ( @@ -378,7 +378,7 @@ class CrossChainBridgeService: "total_fees": total_fees, "average_processing_time_minutes": avg_processing_time / 60, "chain_distribution": chain_distribution, - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -401,7 +401,7 @@ class CrossChainBridgeService: "utilization_rate": pool.get("utilization_rate", 0), "apr": pool.get("apr", 0), "fee_rate": pool.get("fee_rate", 0.005), - "last_updated": pool.get("last_updated", datetime.utcnow().isoformat()), + "last_updated": pool.get("last_updated", datetime.now(datetime.UTC).isoformat()), } pools.append(pool_info) @@ -426,7 +426,7 @@ class CrossChainBridgeService: # Update status to confirmed bridge_request.status = BridgeRequestStatus.CONFIRMED - bridge_request.updated_at = datetime.utcnow() + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() # Execute bridge based on protocol @@ -446,7 +446,7 @@ class CrossChainBridgeService: stmt = ( update(BridgeRequest) .where(BridgeRequest.id == bridge_request_id) - .values(status=BridgeRequestStatus.FAILED, error_message=str(e), updated_at=datetime.utcnow()) + .values(status=BridgeRequestStatus.FAILED, error_message=str(e), updated_at=datetime.now(datetime.UTC)) ) self.session.execute(stmt) self.session.commit() @@ -474,7 +474,7 @@ class CrossChainBridgeService: # Update bridge request with source transaction bridge_request.source_transaction_hash = source_tx["transaction_hash"] - bridge_request.updated_at = datetime.utcnow() + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() # Wait for confirmations @@ -494,8 +494,8 @@ class CrossChainBridgeService: # Update bridge request with target transaction bridge_request.target_transaction_hash = target_tx["transaction_hash"] bridge_request.status = BridgeRequestStatus.COMPLETED - bridge_request.completed_at = datetime.utcnow() - bridge_request.updated_at = datetime.utcnow() + bridge_request.completed_at = datetime.now(datetime.UTC) + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Completed atomic swap for bridge request {bridge_request.id}") @@ -533,8 +533,8 @@ class CrossChainBridgeService: # Update bridge request bridge_request.source_transaction_hash = source_tx["transaction_hash"] bridge_request.status = BridgeRequestStatus.COMPLETED - bridge_request.completed_at = datetime.utcnow() - bridge_request.updated_at = datetime.utcnow() + bridge_request.completed_at = datetime.now(datetime.UTC) + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Completed liquidity pool swap for bridge request {bridge_request.id}") @@ -566,7 +566,7 @@ class CrossChainBridgeService: # Update bridge request bridge_request.source_transaction_hash = source_tx["transaction_hash"] bridge_request.secret_hash = secret_hash - bridge_request.updated_at = datetime.utcnow() + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() # Create HTLC contract on target chain @@ -625,8 +625,8 @@ class CrossChainBridgeService: f"0x{hashlib.sha256(f'htlc_complete_{bridge_request.id}_{secret}'.encode()).hexdigest()}" ) bridge_request.status = BridgeRequestStatus.COMPLETED - bridge_request.completed_at = datetime.utcnow() - bridge_request.updated_at = datetime.utcnow() + bridge_request.completed_at = datetime.now(datetime.UTC) + bridge_request.updated_at = datetime.now(datetime.UTC) self.session.commit() async def _estimate_network_fee(self, chain_id: int, amount: float, token_address: str | None) -> float: @@ -749,7 +749,7 @@ class CrossChainBridgeService: "utilization_rate": 0.0, "apr": 0.05, # 5% APR "fee_rate": 0.005, # 0.5% fee - "last_updated": datetime.utcnow(), + "last_updated": datetime.now(datetime.UTC), } logger.info(f"Initialized liquidity pool for chain {chain_id}") diff --git a/apps/coordinator-api/src/app/services/cross_chain_reputation.py b/apps/coordinator-api/src/app/services/cross_chain_reputation.py index 2c4f9719..047c693b 100755 --- a/apps/coordinator-api/src/app/services/cross_chain_reputation.py +++ b/apps/coordinator-api/src/app/services/cross_chain_reputation.py @@ -10,7 +10,7 @@ from aitbc import get_logger logger = get_logger(__name__) import json from dataclasses import asdict, dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -217,8 +217,8 @@ class CrossChainReputationService: task_count=0, success_count=0, failure_count=0, - last_updated=datetime.utcnow(), - sync_timestamp=datetime.utcnow(), + last_updated=datetime.now(datetime.UTC), + sync_timestamp=datetime.now(datetime.UTC), is_active=True, ) @@ -264,7 +264,7 @@ class CrossChainReputationService: reputation.failure_count += 1 reputation.task_count += 1 - reputation.last_updated = datetime.utcnow() + reputation.last_updated = datetime.now(datetime.UTC) reputation.tier = reputation.calculate_tier() # Update chain reputation @@ -291,7 +291,7 @@ class CrossChainReputationService: reputation = self.reputation_data[agent_id] # Check sync cooldown - time_since_sync = (datetime.utcnow() - reputation.sync_timestamp).total_seconds() + time_since_sync = (datetime.now(datetime.UTC) - reputation.sync_timestamp).total_seconds() if time_since_sync < self.sync_cooldown: logger.warning(f"Sync cooldown not met for agent {agent_id}") return False @@ -305,7 +305,7 @@ class CrossChainReputationService: source_chain=reputation.chain_id, target_chain=target_chain, reputation_score=reputation.score, - sync_timestamp=datetime.utcnow(), + sync_timestamp=datetime.now(datetime.UTC), verification_hash=verification_hash, is_verified=True, ) @@ -322,16 +322,16 @@ class CrossChainReputationService: success_count=reputation.success_count, failure_count=reputation.failure_count, last_updated=reputation.last_updated, - sync_timestamp=datetime.utcnow(), + sync_timestamp=datetime.now(datetime.UTC), is_active=True, ) else: target_reputation = self.chain_reputations[agent_id][target_chain] target_reputation.score = reputation.score - target_reputation.sync_timestamp = datetime.utcnow() + target_reputation.sync_timestamp = datetime.now(datetime.UTC) # Update sync timestamp - reputation.sync_timestamp = datetime.utcnow() + reputation.sync_timestamp = datetime.now(datetime.UTC) logger.info(f"Synced reputation for agent {agent_id} to chain {target_chain}") return True @@ -360,8 +360,8 @@ class CrossChainReputationService: agent_id=agent_id, amount=amount, lock_period=lock_period, - start_time=datetime.utcnow(), - end_time=datetime.utcnow() + timedelta(seconds=lock_period), + start_time=datetime.now(datetime.UTC), + end_time=datetime.now(datetime.UTC) + timedelta(seconds=lock_period), is_active=True, reward_rate=reward_rate, multiplier=1.0 + (reputation.score / 10000) * 0.5, # Up to 50% bonus @@ -407,7 +407,7 @@ class CrossChainReputationService: delegator=delegator, delegate=delegate, amount=amount, - start_time=datetime.utcnow(), + start_time=datetime.now(datetime.UTC), is_active=True, fee_rate=fee_rate, ) @@ -469,7 +469,7 @@ class CrossChainReputationService: delegation.amount for delegation in self.reputation_delegations.get(agent_id, []) if delegation.is_active ) chain_count = len(self.chain_reputations.get(agent_id, {})) - reputation_age = (datetime.utcnow() - reputation.last_updated).days + reputation_age = (datetime.now(datetime.UTC) - reputation.last_updated).days return ReputationAnalytics( agent_id=agent_id, @@ -543,7 +543,7 @@ class CrossChainReputationService: # In production, implement proper cross-chain signature verification import hashlib - hash_input = f"{agent_id}:{chain_id}:{datetime.utcnow().isoformat()}".encode() + hash_input = f"{agent_id}:{chain_id}:{datetime.now(datetime.UTC).isoformat()}".encode() return hashlib.sha256(hash_input).hexdigest() async def _get_total_delegated(self, agent_id: str) -> int: @@ -601,7 +601,7 @@ class CrossChainReputationService: async def _distribute_stake_rewards(self): """Distribute rewards for active stakes""" - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) for agent_id, stakes in self.reputation_stakes.items(): for stake in stakes: @@ -619,7 +619,7 @@ class CrossChainReputationService: """Clean up expired stakes and delegations""" while True: try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) # Clean up expired stakes for _agent_id, stakes in self.reputation_stakes.items(): @@ -657,7 +657,7 @@ class CrossChainReputationService: "chain_reputations": {k: {str(k2): asdict(v2) for k2, v2 in v.items()} for k, v in self.chain_reputations.items()}, "reputation_stakes": {k: [asdict(s) for s in v] for k, v in self.reputation_stakes.items()}, "reputation_delegations": {k: [asdict(d) for d in v] for k, v in self.reputation_delegations.items()}, - "export_timestamp": datetime.utcnow().isoformat(), + "export_timestamp": datetime.now(datetime.UTC).isoformat(), } if format.lower() == "json": diff --git a/apps/coordinator-api/src/app/services/dao_governance_service.py b/apps/coordinator-api/src/app/services/dao_governance_service.py index 24d901c0..abe18d84 100755 --- a/apps/coordinator-api/src/app/services/dao_governance_service.py +++ b/apps/coordinator-api/src/app/services/dao_governance_service.py @@ -6,7 +6,7 @@ Service for managing multi-jurisdictional DAOs, regional councils, and global tr from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -53,7 +53,7 @@ class DAOGovernanceService: if request.target_region and not (proposer.is_council_member and proposer.council_region == request.target_region): raise HTTPException(status_code=403, detail="Only regional council members can create regional proposals") - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) end_time = start_time + timedelta(days=request.voting_period_days) proposal = DAOProposal( @@ -89,7 +89,7 @@ class DAOGovernanceService: if proposal.status != ProposalState.ACTIVE: raise HTTPException(status_code=400, detail="Proposal is not active") - now = datetime.utcnow() + now = datetime.now(datetime.UTC) if now < proposal.start_time or now > proposal.end_time: proposal.status = ProposalState.EXPIRED self.session.commit() @@ -133,7 +133,7 @@ class DAOGovernanceService: if proposal.status != ProposalState.ACTIVE: raise HTTPException(status_code=400, detail=f"Cannot execute proposal in state {proposal.status}") - if datetime.utcnow() <= proposal.end_time: + if datetime.now(datetime.UTC) <= proposal.end_time: raise HTTPException(status_code=400, detail="Voting period has not ended yet") if proposal.for_votes > proposal.against_votes: diff --git a/apps/coordinator-api/src/app/services/developer_platform_service.py b/apps/coordinator-api/src/app/services/developer_platform_service.py index bcee03f1..272dc302 100755 --- a/apps/coordinator-api/src/app/services/developer_platform_service.py +++ b/apps/coordinator-api/src/app/services/developer_platform_service.py @@ -6,7 +6,7 @@ Service for managing the developer ecosystem, bounties, certifications, and regi from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger from fastapi import HTTPException @@ -150,7 +150,7 @@ class DeveloperPlatformService: submission.is_approved = True submission.review_notes = review_notes submission.reviewer_address = reviewer_address - submission.reviewed_at = datetime.utcnow() + submission.reviewed_at = datetime.now(datetime.UTC) bounty.status = BountyStatus.COMPLETED bounty.assigned_developer_id = developer.id @@ -185,7 +185,7 @@ class DeveloperPlatformService: if hasattr(profile, key): setattr(profile, key, value) - profile.updated_at = datetime.utcnow() + profile.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(profile) @@ -306,7 +306,7 @@ class DeveloperPlatformService: "amount_staked": amount, "apy": 5.0 + (developer.reputation_score / 100), # Base APY + reputation bonus "staking_id": f"stake_{staker_address[:8]}_{developer_address[:8]}", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } logger.info(f"Staked {amount} AITBC on developer {developer_address} by {staker_address}") @@ -332,7 +332,7 @@ class DeveloperPlatformService: "amount_unstaked": amount, "rewards_earned": 25.5, "tx_hash": "0xmock_unstake_tx_hash", - "completed_at": datetime.utcnow().isoformat(), + "completed_at": datetime.now(datetime.UTC).isoformat(), } logger.info(f"Unstaked {amount} AITBC from staking position {staking_id}") @@ -345,8 +345,8 @@ class DeveloperPlatformService: "address": address, "pending_rewards": 45.75, "claimed_rewards": 250.25, - "last_claim_time": (datetime.utcnow() - timedelta(days=7)).isoformat(), - "next_claim_time": (datetime.utcnow() + timedelta(days=1)).isoformat(), + "last_claim_time": (datetime.now(datetime.UTC) - timedelta(days=7)).isoformat(), + "next_claim_time": (datetime.now(datetime.UTC) + timedelta(days=1)).isoformat(), } async def claim_rewards(self, address: str) -> dict: @@ -367,7 +367,7 @@ class DeveloperPlatformService: "address": address, "amount_claimed": rewards["pending_rewards"], "tx_hash": "0xmock_claim_tx_hash", - "claimed_at": datetime.utcnow().isoformat(), + "claimed_at": datetime.now(datetime.UTC).isoformat(), } logger.info(f"Claimed {rewards['pending_rewards']} AITBC rewards for {address}") diff --git a/apps/coordinator-api/src/app/services/distributed_framework.py b/apps/coordinator-api/src/app/services/distributed_framework.py index aa79e4e0..e4ccbb66 100755 --- a/apps/coordinator-api/src/app/services/distributed_framework.py +++ b/apps/coordinator-api/src/app/services/distributed_framework.py @@ -9,7 +9,7 @@ import time import json import hashlib from typing import Dict, List, Optional, Any, Callable, Awaitable -from datetime import datetime +from datetime import datetime, UTC from enum import Enum from aitbc import get_logger @@ -465,5 +465,5 @@ class DistributedProcessingCoordinator: "utilization_percent": round(utilization, 2), "cache_size": len(self.result_cache) }, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } diff --git a/apps/coordinator-api/src/app/services/dynamic_pricing_engine.py b/apps/coordinator-api/src/app/services/dynamic_pricing_engine.py index a16d1f14..0b821511 100755 --- a/apps/coordinator-api/src/app/services/dynamic_pricing_engine.py +++ b/apps/coordinator-api/src/app/services/dynamic_pricing_engine.py @@ -5,7 +5,7 @@ Implements sophisticated pricing algorithms based on real-time market conditions import asyncio from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -238,7 +238,7 @@ class DynamicPricingEngine: confidence = await self._calculate_confidence_score(factors, market_conditions) # Schedule next update - next_update = datetime.utcnow() + timedelta(seconds=self.update_interval) + next_update = datetime.now(datetime.UTC) + timedelta(seconds=self.update_interval) # Store price point await self._store_price_point(resource_id, final_price, factors, strategy) @@ -302,7 +302,7 @@ class DynamicPricingEngine: confidence = max(0.3, 0.9 - (hour / hours_ahead) * 0.6) forecast_point = PricePoint( - timestamp=datetime.utcnow() + timedelta(hours=hour), + timestamp=datetime.now(datetime.UTC) + timedelta(hours=hour), price=forecast_price, demand_level=demand_forecast, supply_level=supply_forecast, @@ -485,8 +485,8 @@ class DynamicPricingEngine: def _calculate_time_multiplier(self) -> float: """Calculate time-based price multiplier""" - hour = datetime.utcnow().hour - day_of_week = datetime.utcnow().weekday() + hour = datetime.now(datetime.UTC).hour + day_of_week = datetime.now(datetime.UTC).weekday() # Business hours premium (8 AM - 8 PM, Monday-Friday) if 8 <= hour <= 20 and day_of_week < 5: @@ -624,7 +624,7 @@ class DynamicPricingEngine: reasoning.append("High supply enables competitive pricing") # Time-based reasoning - hour = datetime.utcnow().hour + hour = datetime.now(datetime.UTC).hour if 8 <= hour <= 20: reasoning.append("Business hours premium applied") elif 2 <= hour <= 6: @@ -677,7 +677,7 @@ class DynamicPricingEngine: self.pricing_history[resource_id] = [] price_point = PricePoint( - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), price=price, demand_level=factors.demand_level, supply_level=factors.supply_level, @@ -699,7 +699,7 @@ class DynamicPricingEngine: if cache_key in self.market_conditions_cache: cached = self.market_conditions_cache[cache_key] # Use cached data if less than 5 minutes old - if (datetime.utcnow() - cached.timestamp).total_seconds() < 300: + if (datetime.now(datetime.UTC) - cached.timestamp).total_seconds() < 300: return cached # In a real implementation, this would fetch from market data sources diff --git a/apps/coordinator-api/src/app/services/ecosystem_service.py b/apps/coordinator-api/src/app/services/ecosystem_service.py index 54fbd457..8e038bf7 100755 --- a/apps/coordinator-api/src/app/services/ecosystem_service.py +++ b/apps/coordinator-api/src/app/services/ecosystem_service.py @@ -3,7 +3,7 @@ Ecosystem Analytics Service Business logic for developer ecosystem metrics and analytics """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from sqlalchemy import and_, func, select @@ -30,13 +30,13 @@ class EcosystemService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get total earnings from completed bounties earnings_stmt = select( @@ -114,13 +114,13 @@ class EcosystemService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get agent metrics agents_stmt = select( @@ -196,13 +196,13 @@ class EcosystemService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get bounty fees (treasury inflow) inflow_stmt = select( @@ -252,13 +252,13 @@ class EcosystemService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get staking metrics staking_stmt = select( @@ -335,13 +335,13 @@ class EcosystemService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get bounty counts bounty_stmt = select( @@ -455,9 +455,9 @@ class EcosystemService: """Get time-series ecosystem metrics""" try: if not start_date: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) if not end_date: - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) # This is a simplified implementation # In production, you'd want more sophisticated time-series aggregation @@ -651,7 +651,7 @@ class EcosystemService: "type": "performance", "severity": "medium", "message": "Agent utilization dropped below 70%", - "timestamp": datetime.utcnow() - timedelta(hours=2), + "timestamp": datetime.now(datetime.UTC) - timedelta(hours=2), "resolved": False, }, { @@ -659,7 +659,7 @@ class EcosystemService: "type": "financial", "severity": "low", "message": "Bounty completion rate decreased by 5%", - "timestamp": datetime.utcnow() - timedelta(hours=6), + "timestamp": datetime.now(datetime.UTC) - timedelta(hours=6), "resolved": False, }, ] @@ -762,12 +762,12 @@ class EcosystemService: metrics = await self.get_time_series_metrics(period_type, start_date, end_date) # Mock export URL generation - export_url = f"/exports/ecosystem_data_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.{format}" + export_url = f"/exports/ecosystem_data_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}.{format}" return { "url": export_url, "file_size": len(str(metrics)) * 0.001, # Mock file size in KB - "expires_at": datetime.utcnow() + timedelta(hours=24), + "expires_at": datetime.now(datetime.UTC) + timedelta(hours=24), "record_count": len(metrics), } diff --git a/apps/coordinator-api/src/app/services/encryption.py b/apps/coordinator-api/src/app/services/encryption.py index d7209ebd..72f6aff4 100755 --- a/apps/coordinator-api/src/app/services/encryption.py +++ b/apps/coordinator-api/src/app/services/encryption.py @@ -5,7 +5,7 @@ Encryption service for confidential transactions import base64 import json import os -from datetime import datetime +from datetime import datetime, UTC from typing import Any from cryptography.hazmat.backends import default_backend @@ -313,7 +313,7 @@ class EncryptionService: "transaction_id": transaction_id, "participant_id": participant_id, "purpose": purpose, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "success": success, "error": error, "authorization": authorization, diff --git a/apps/coordinator-api/src/app/services/enterprise_api_gateway.py b/apps/coordinator-api/src/app/services/enterprise_api_gateway.py index e675c06d..4fb679cb 100755 --- a/apps/coordinator-api/src/app/services/enterprise_api_gateway.py +++ b/apps/coordinator-api/src/app/services/enterprise_api_gateway.py @@ -6,7 +6,7 @@ Port: 8010 import secrets import time -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any from uuid import uuid4 @@ -102,8 +102,8 @@ class EnterpriseIntegration: self.provider = provider self.configuration = configuration self.status = IntegrationStatus.PENDING - self.created_at = datetime.utcnow() - self.last_updated = datetime.utcnow() + self.created_at = datetime.now(datetime.UTC) + self.last_updated = datetime.now(datetime.UTC) self.webhook_config = None self.metrics = {"api_calls": 0, "errors": 0, "last_call": None} @@ -153,7 +153,7 @@ class EnterpriseAPIGateway: "tenant_id": request.tenant_id, "client_id": request.client_id, "scopes": request.scopes or ["enterprise_api"], - "expires_at": datetime.utcnow() + timedelta(seconds=self.token_expiry), + "expires_at": datetime.now(datetime.UTC) + timedelta(seconds=self.token_expiry), "refresh_token": refresh_token, } @@ -182,8 +182,8 @@ class EnterpriseAPIGateway: payload = { "sub": f"{tenant_id}:{client_id}", "scopes": scopes, - "iat": datetime.utcnow(), - "exp": datetime.utcnow() + timedelta(seconds=self.token_expiry), + "iat": datetime.now(datetime.UTC), + "exp": datetime.now(datetime.UTC) + timedelta(seconds=self.token_expiry), "type": "access", } @@ -194,8 +194,8 @@ class EnterpriseAPIGateway: payload = { "sub": f"{tenant_id}:{client_id}", - "iat": datetime.utcnow(), - "exp": datetime.utcnow() + timedelta(days=30), # 30 days + "iat": datetime.now(datetime.UTC), + "exp": datetime.now(datetime.UTC) + timedelta(days=30), # 30 days "type": "refresh", } @@ -244,7 +244,7 @@ class EnterpriseAPIGateway: return APIQuotaResponse( quota_limit=quota["rate_limit"], quota_remaining=quota["rate_limit"] - current_usage - 1, - quota_reset=datetime.utcnow() + timedelta(minutes=1), + quota_reset=datetime.now(datetime.UTC) + timedelta(minutes=1), quota_type="rate_limit", ) @@ -276,7 +276,7 @@ class EnterpriseAPIGateway: if quota_type == "rate_limit": # Get usage in the last minute - return len([t for t in self.rate_limiters.get(tenant_id, []) if datetime.utcnow() - t < timedelta(minutes=1)]) + return len([t for t in self.rate_limiters.get(tenant_id, []) if datetime.now(datetime.UTC) - t < timedelta(minutes=1)]) return 0 @@ -288,10 +288,10 @@ class EnterpriseAPIGateway: self.rate_limiters[tenant_id] = [] # Add current timestamp - self.rate_limiters[tenant_id].append(datetime.utcnow()) + self.rate_limiters[tenant_id].append(datetime.now(datetime.UTC)) # Clean old entries (older than 1 minute) - cutoff = datetime.utcnow() - timedelta(minutes=1) + cutoff = datetime.now(datetime.UTC) - timedelta(minutes=1) self.rate_limiters[tenant_id] = [t for t in self.rate_limiters[tenant_id] if t > cutoff] async def create_enterprise_integration( @@ -350,7 +350,7 @@ class EnterpriseAPIGateway: await self._initialize_bi_integration(integration) integration.status = IntegrationStatus.ACTIVE - integration.last_updated = datetime.utcnow() + integration.last_updated = datetime.now(datetime.UTC) except Exception as e: logger.error(f"Integration initialization failed: {e}") @@ -565,7 +565,7 @@ async def get_status(): "status": "operational", "active_tenants": len({token["tenant_id"] for token in gateway.active_tokens.values()}), "active_integrations": len(gateway.integrations), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -592,7 +592,7 @@ async def health_check(): """Health check endpoint""" return { "status": "healthy", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "services": { "api_gateway": "operational", "authentication": "operational", diff --git a/apps/coordinator-api/src/app/services/enterprise_integration.py b/apps/coordinator-api/src/app/services/enterprise_integration.py index 119ae16c..2e0a1002 100755 --- a/apps/coordinator-api/src/app/services/enterprise_integration.py +++ b/apps/coordinator-api/src/app/services/enterprise_integration.py @@ -7,7 +7,7 @@ import asyncio import json import xml.etree.ElementTree as ET from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import Enum from typing import Any, Dict, List, Optional, Union from uuid import uuid4 @@ -121,7 +121,7 @@ class ERPIntegration: "data_type": data_type, "records": [], "count": 0, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } return IntegrationResponse( success=True, @@ -254,7 +254,7 @@ class SAPIntegration(ERPIntegration): data=mapped_data, metadata={ "records_count": len(mapped_data.get("customers", [])), - "sync_time": datetime.utcnow().isoformat() + "sync_time": datetime.now(datetime.UTC).isoformat() } ) else: @@ -297,7 +297,7 @@ class SAPIntegration(ERPIntegration): data=mapped_data, metadata={ "records_count": len(mapped_data.get("orders", [])), - "sync_time": datetime.utcnow().isoformat() + "sync_time": datetime.now(datetime.UTC).isoformat() } ) else: @@ -340,7 +340,7 @@ class SAPIntegration(ERPIntegration): data=mapped_data, metadata={ "records_count": len(mapped_data.get("products", [])), - "sync_time": datetime.utcnow().isoformat() + "sync_time": datetime.now(datetime.UTC).isoformat() } ) else: @@ -498,7 +498,7 @@ class OracleIntegration(ERPIntegration): data=mapped_data, metadata={ "records_count": len(mapped_data.get("customers", [])), - "sync_time": datetime.utcnow().isoformat() + "sync_time": datetime.now(datetime.UTC).isoformat() } ) else: @@ -564,7 +564,7 @@ class CRMIntegration: mock_data = { "contacts": [], "count": 0, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } return IntegrationResponse( success=True, @@ -584,7 +584,7 @@ class CRMIntegration: mock_data = { "opportunities": [], "count": 0, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } return IntegrationResponse( success=True, @@ -733,7 +733,7 @@ class SalesforceIntegration(CRMIntegration): data=mapped_data, metadata={ "records_count": len(data.get("records", [])), - "sync_time": datetime.utcnow().isoformat() + "sync_time": datetime.now(datetime.UTC).isoformat() } ) else: @@ -1037,7 +1037,7 @@ class EnterpriseIntegrationFramework: "provider": integration.config.provider.value, "endpoint_url": integration.config.endpoint_url, "status": "active", - "last_test": datetime.utcnow().isoformat() + "last_test": datetime.now(datetime.UTC).isoformat() } async def close_integration(self, integration_id: str): diff --git a/apps/coordinator-api/src/app/services/enterprise_load_balancer.py b/apps/coordinator-api/src/app/services/enterprise_load_balancer.py index ca050997..93eeca5b 100755 --- a/apps/coordinator-api/src/app/services/enterprise_load_balancer.py +++ b/apps/coordinator-api/src/app/services/enterprise_load_balancer.py @@ -5,7 +5,7 @@ Intelligent traffic distribution with AI-powered auto-scaling and performance op import statistics from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -117,7 +117,7 @@ class PredictiveScaler: self.traffic_history.append(traffic_record) # Keep only last 30 days of history - cutoff = datetime.utcnow() - timedelta(days=30) + cutoff = datetime.now(datetime.UTC) - timedelta(days=30) self.traffic_history = [record for record in self.traffic_history if record["timestamp"] > cutoff] # Update traffic patterns @@ -170,7 +170,7 @@ class PredictiveScaler: """Predict traffic for the next time window""" try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) current_time + prediction_window # Get current pattern @@ -244,7 +244,7 @@ class PredictiveScaler: "predicted_error_rate": 0.01, "confidence_score": 0.1, "pattern_based": False, - "prediction_timestamp": datetime.utcnow().isoformat(), + "prediction_timestamp": datetime.now(datetime.UTC).isoformat(), } # Calculate recent averages @@ -261,7 +261,7 @@ class PredictiveScaler: "predicted_error_rate": avg_error_rate, "confidence_score": 0.3, "pattern_based": False, - "prediction_timestamp": datetime.utcnow().isoformat(), + "prediction_timestamp": datetime.now(datetime.UTC).isoformat(), } def _get_seasonal_factor(self, timestamp: datetime) -> float: @@ -321,7 +321,7 @@ class PredictiveScaler: "current_capacity_per_server": current_capacity_per_server, "confidence_score": prediction["confidence_score"], "reason": f"Predicted {predicted_requests} requests/hour vs current capacity {current_servers * current_capacity_per_server}", - "recommendation_timestamp": datetime.utcnow().isoformat(), + "recommendation_timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -329,7 +329,7 @@ class PredictiveScaler: return { "scaling_action": "none", "reason": f"Prediction failed: {str(e)}", - "recommendation_timestamp": datetime.utcnow().isoformat(), + "recommendation_timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -358,7 +358,7 @@ class AdvancedLoadBalancer: "error_rate": 0.0, "throughput": 0.0, "uptime": 1.0, - "last_updated": datetime.utcnow(), + "last_updated": datetime.now(datetime.UTC), } self.logger.info(f"Backend server added: {server.server_id}") @@ -603,7 +603,7 @@ class AdvancedLoadBalancer: """Record request metrics""" if timestamp is None: - timestamp = datetime.utcnow() + timestamp = datetime.now(datetime.UTC) # Update backend server metrics if server_id in self.backends: @@ -644,7 +644,7 @@ class AdvancedLoadBalancer: server.cpu_usage = cpu_usage server.memory_usage = memory_usage server.current_connections = current_connections - server.last_health_check = datetime.utcnow() + server.last_health_check = datetime.now(datetime.UTC) async def get_load_balancing_metrics(self) -> dict[str, Any]: """Get comprehensive load balancing metrics""" @@ -691,7 +691,7 @@ class AdvancedLoadBalancer: "algorithm": self.algorithm.value, "backend_distribution": backend_distribution, "scaling_recommendation": scaling_recommendation, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -725,7 +725,7 @@ class AdvancedLoadBalancer: "target_servers": target_servers, "confidence": recommendation.get("confidence_score", 0.0), "reason": recommendation.get("reason", ""), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } # In production, implement actual scaling logic here diff --git a/apps/coordinator-api/src/app/services/enterprise_security.py b/apps/coordinator-api/src/app/services/enterprise_security.py index 9db41012..62cda6ef 100755 --- a/apps/coordinator-api/src/app/services/enterprise_security.py +++ b/apps/coordinator-api/src/app/services/enterprise_security.py @@ -5,7 +5,7 @@ Zero-trust architecture with HSM integration and advanced security controls import secrets from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any from uuid import uuid4 @@ -122,7 +122,7 @@ class HSMManager: "key": key, "iv": iv if algorithm in [EncryptionAlgorithm.AES_256_GCM, EncryptionAlgorithm.AES_256_CBC] else None, "nonce": nonce if algorithm == EncryptionAlgorithm.CHACHA20_POLY1305 else None, - "created_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), "key_size": key_size, } @@ -151,7 +151,7 @@ class HSMManager: # Update key with rotation timestamp new_key["rotated_from"] = key_id - new_key["rotation_timestamp"] = datetime.utcnow() + new_key["rotation_timestamp"] = datetime.now(datetime.UTC) return new_key @@ -491,7 +491,7 @@ class ZeroTrustArchitecture: event_type="trust_decision", severity=ThreatLevel.LOW if decision else ThreatLevel.MEDIUM, source="zero_trust", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), user_id=user_id, resource_id=resource_id, details={"action": action, "trust_score": trust_score, "decision": decision}, @@ -539,7 +539,7 @@ class ThreatDetectionSystem: event_type="threat_detected", severity=pattern["severity"], source="threat_detection", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), user_id=event_data.get("user_id"), resource_id=event_data.get("resource_id"), details={ diff --git a/apps/coordinator-api/src/app/services/federated_learning.py b/apps/coordinator-api/src/app/services/federated_learning.py index cc5ecf85..f1f60b5e 100755 --- a/apps/coordinator-api/src/app/services/federated_learning.py +++ b/apps/coordinator-api/src/app/services/federated_learning.py @@ -6,7 +6,7 @@ Service for managing cross-agent knowledge sharing and collaborative model train from __future__ import annotations -from datetime import datetime +from datetime import datetime, UTC from aitbc import get_logger from fastapi import HTTPException @@ -174,7 +174,7 @@ class FederatedLearningService: current_round.aggregated_model_cid = new_global_cid current_round.status = "completed" - current_round.completed_at = datetime.utcnow() + current_round.completed_at = datetime.now(datetime.UTC) current_round.metrics = { "loss": 0.5 - (current_round.round_number * 0.05), "accuracy": 0.7 + (current_round.round_number * 0.02), diff --git a/apps/coordinator-api/src/app/services/global_cdn.py b/apps/coordinator-api/src/app/services/global_cdn.py index c056cdd4..f4bc7219 100755 --- a/apps/coordinator-api/src/app/services/global_cdn.py +++ b/apps/coordinator-api/src/app/services/global_cdn.py @@ -8,7 +8,7 @@ import gzip import time import zlib from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any from uuid import uuid4 @@ -117,14 +117,14 @@ class EdgeCache: entry = self.cache.get(cache_key) if entry: # Check if expired - if datetime.utcnow() > entry.expires_at: + if datetime.now(datetime.UTC) > entry.expires_at: await self.remove(cache_key) return None # Update access statistics entry.access_count += 1 - entry.last_accessed = datetime.utcnow() - self.access_times[cache_key] = datetime.utcnow() + entry.last_accessed = datetime.now(datetime.UTC) + self.access_times[cache_key] = datetime.now(datetime.UTC) self.logger.debug(f"Cache hit: {cache_key}") return entry @@ -166,15 +166,15 @@ class EdgeCache: size_bytes=entry_size, compressed=is_compressed, compression_type=compression_type, - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + ttl, + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + ttl, edge_locations=[self.location_id], ) # Store entry self.cache[cache_key] = entry self.cache_size_bytes += entry_size - self.access_times[cache_key] = datetime.utcnow() + self.access_times[cache_key] = datetime.now(datetime.UTC) self.logger.debug(f"Content cached: {cache_key} ({entry_size} bytes)") return True @@ -317,19 +317,19 @@ class CDNManager: "content_type": entry.content_type, "edge_location": edge_location.location_id, "compressed": entry.compressed, - "cache_age": (datetime.utcnow() - entry.created_at).total_seconds(), + "cache_age": (datetime.now(datetime.UTC) - entry.created_at).total_seconds(), } # Try global cache global_entry = self.global_cache.get(cache_key) - if global_entry and datetime.utcnow() <= global_entry.expires_at: + if global_entry and datetime.now(datetime.UTC) <= global_entry.expires_at: # Cache at edge location if edge_cache: await edge_cache.put( cache_key, global_entry.content, global_entry.content_type, - global_entry.expires_at - datetime.utcnow(), + global_entry.expires_at - datetime.now(datetime.UTC), global_entry.compression_type, ) @@ -377,8 +377,8 @@ class CDNManager: size_bytes=len(content), compressed=False, compression_type=compression_type, - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + ttl, + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + ttl, ) self.global_cache[cache_key] = global_entry @@ -501,7 +501,7 @@ class CDNManager: try: await asyncio.sleep(self.config.purge_interval.total_seconds()) - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) # Purge global cache expired_keys = [key for key, entry in self.global_cache.items() if current_time > entry.expires_at] @@ -601,7 +601,7 @@ class CDNManager: "edge_stats": edge_stats, "global_cache_size": len(self.global_cache), "provider": self.config.provider.value, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -625,7 +625,7 @@ class EdgeComputingManager: "code": function_code, "edge_locations": edge_locations, "config": config, - "deployed_at": datetime.utcnow(), + "deployed_at": datetime.now(datetime.UTC), "status": "active", } @@ -669,7 +669,7 @@ class EdgeComputingManager: "function_id": function_id, "edge_location": edge_location.location_id, "execution_time_ms": execution_time, - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), "success": True, } @@ -711,7 +711,7 @@ class EdgeComputingManager: "average_execution_time_ms": avg_execution_time, "active_functions": len([f for f in self.edge_functions.values() if f["status"] == "active"]), "edge_locations": len(self.cdn_manager.edge_caches), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -778,7 +778,7 @@ class GlobalCDNIntegration: "overall_status": ( "excellent" if performance_score >= 0.8 else "good" if performance_score >= 0.6 else "needs_improvement" ), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: diff --git a/apps/coordinator-api/src/app/services/global_marketplace.py b/apps/coordinator-api/src/app/services/global_marketplace.py index 2652782e..bf916dc3 100755 --- a/apps/coordinator-api/src/app/services/global_marketplace.py +++ b/apps/coordinator-api/src/app/services/global_marketplace.py @@ -9,7 +9,7 @@ Global Marketplace Services Core services 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 uuid import uuid4 @@ -126,7 +126,7 @@ class GlobalMarketplaceService: offers = self.session.execute(stmt).all() # Filter out expired offers - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) valid_offers = [] for offer in offers: @@ -203,7 +203,7 @@ class GlobalMarketplaceService: # Update offer capacity offer.available_capacity -= request.quantity offer.total_transactions += 1 - offer.updated_at = datetime.utcnow() + offer.updated_at = datetime.now(datetime.UTC) self.session.add(transaction) self.session.commit() @@ -382,7 +382,7 @@ class GlobalMarketplaceService: """Get recent analytics for a region""" try: - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) stmt = ( select(GlobalMarketplaceAnalytics) @@ -460,7 +460,7 @@ class RegionManager: region.average_response_time = health_metrics.get("average_response_time", 0.0) region.request_rate = health_metrics.get("request_rate", 0.0) region.error_rate = health_metrics.get("error_rate", 0.0) - region.last_health_check = datetime.utcnow() + region.last_health_check = datetime.now(datetime.UTC) # Update status based on health score if region.health_score < 0.5: diff --git a/apps/coordinator-api/src/app/services/global_marketplace_integration.py b/apps/coordinator-api/src/app/services/global_marketplace_integration.py index 23cabf0d..3165efde 100755 --- a/apps/coordinator-api/src/app/services/global_marketplace_integration.py +++ b/apps/coordinator-api/src/app/services/global_marketplace_integration.py @@ -3,7 +3,7 @@ Global Marketplace Integration Service Integration service that combines global marketplace operations with cross-chain capabilities """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -146,7 +146,7 @@ class GlobalMarketplaceIntegrationService: regions_available=regions_available, supported_chains=supported_chains, dynamic_pricing_enabled=self.integration_config["regional_pricing_enabled"], - expires_at=datetime.utcnow() + timedelta(minutes=deadline_minutes), + expires_at=datetime.now(datetime.UTC) + timedelta(minutes=deadline_minutes), ) global_offer = await self.marketplace_service.create_global_offer(offer_request, None) @@ -249,7 +249,7 @@ class GlobalMarketplaceIntegrationService: # Update offer capacity offer.available_capacity -= quantity offer.total_transactions += 1 - offer.updated_at = datetime.utcnow() + offer.updated_at = datetime.now(datetime.UTC) # Execute cross-chain bridge if needed and enabled bridge_transaction_id = None @@ -365,7 +365,7 @@ class GlobalMarketplaceIntegrationService: # Get base marketplace analytics from ..domain.global_marketplace import GlobalMarketplaceAnalyticsRequest - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) start_time = end_time - timedelta(hours=time_period_hours) analytics_request = GlobalMarketplaceAnalyticsRequest( @@ -398,7 +398,7 @@ class GlobalMarketplaceIntegrationService: "transaction_statistics": tx_stats, "cross_chain_metrics": cross_chain_metrics, "integration_metrics": self.metrics, - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -431,7 +431,7 @@ class GlobalMarketplaceIntegrationService: # Update offer with optimized pricing offer.price_per_region = optimized_pricing["regional_pricing"] offer.cross_chain_pricing = optimized_pricing["cross_chain_pricing"] - offer.updated_at = datetime.utcnow() + offer.updated_at = datetime.now(datetime.UTC) self.session.commit() @@ -507,7 +507,7 @@ class GlobalMarketplaceIntegrationService: "currency": offer.currency, "capacity": offer.available_capacity, "status": CrossChainOfferStatus.AVAILABLE.value, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } listings.append(listing) diff --git a/apps/coordinator-api/src/app/services/governance_service.py b/apps/coordinator-api/src/app/services/governance_service.py index fc6f49bc..c9a05439 100755 --- a/apps/coordinator-api/src/app/services/governance_service.py +++ b/apps/coordinator-api/src/app/services/governance_service.py @@ -4,7 +4,7 @@ Implements the OpenClaw DAO, voting mechanisms, and proposal lifecycle Enhanced with multi-jurisdictional support and regional governance """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from aitbc import get_logger @@ -81,7 +81,7 @@ class GovernanceService: if total_power < 100.0: # Arbitrary minimum threshold for example raise ValueError("Insufficient voting power to submit a proposal") - now = datetime.utcnow() + now = datetime.now(datetime.UTC) voting_starts = data.get("voting_starts", now + timedelta(days=1)) if isinstance(voting_starts, str): voting_starts = datetime.fromisoformat(voting_starts) @@ -122,7 +122,7 @@ class GovernanceService: if not proposal or not voter: raise ValueError("Proposal or Voter not found") - now = datetime.utcnow() + now = datetime.now(datetime.UTC) if proposal.status != ProposalStatus.ACTIVE or now < proposal.voting_starts or now > proposal.voting_ends: raise ValueError("Proposal is not currently active for voting") @@ -169,7 +169,7 @@ class GovernanceService: if not proposal: raise ValueError("Proposal not found") - now = datetime.utcnow() + now = datetime.now(datetime.UTC) # Draft -> Active if proposal.status == ProposalStatus.DRAFT and now >= proposal.voting_starts: @@ -237,7 +237,7 @@ class GovernanceService: raise ValueError("Insufficient funds in DAO Treasury for execution") proposal.status = ProposalStatus.EXECUTED - proposal.executed_at = datetime.utcnow() + proposal.executed_at = datetime.now(datetime.UTC) self.session.add(proposal) self.session.commit() diff --git a/apps/coordinator-api/src/app/services/gpu_multimodal.py b/apps/coordinator-api/src/app/services/gpu_multimodal.py index 802f59a9..388dd751 100755 --- a/apps/coordinator-api/src/app/services/gpu_multimodal.py +++ b/apps/coordinator-api/src/app/services/gpu_multimodal.py @@ -16,7 +16,7 @@ import torch.nn.functional as F logger = get_logger(__name__) import time -from datetime import datetime +from datetime import datetime, UTC from typing import Any import numpy as np @@ -501,7 +501,7 @@ class GPUAcceleratedMultiModal: ) -> dict[str, Any]: """CPU fallback for attention processing""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Simple CPU attention computation attended_features = {} @@ -527,7 +527,7 @@ class GPUAcceleratedMultiModal: attended_features[modality] = attended attention_matrices[f"{modality}_self"] = attention_matrix - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() return { "attended_features": attended_features, @@ -706,7 +706,7 @@ class GPUFeatureCache: self._cache[cache_key] = { "features": features, "priority": priority, - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), "size_mb": features.nbytes / (1024 * 1024), } diff --git a/apps/coordinator-api/src/app/services/hsm_key_manager.py b/apps/coordinator-api/src/app/services/hsm_key_manager.py index 8f1b8244..30642852 100755 --- a/apps/coordinator-api/src/app/services/hsm_key_manager.py +++ b/apps/coordinator-api/src/app/services/hsm_key_manager.py @@ -5,7 +5,7 @@ HSM-backed key management for production use import json import os from abc import ABC, abstractmethod -from datetime import datetime +from datetime import datetime, UTC from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey @@ -210,7 +210,7 @@ class HSMKeyManager: """Generate key pair in HSM""" try: # Generate key in HSM - hsm_key_id = f"aitbc-{participant_id}-{datetime.utcnow().timestamp()}" + hsm_key_id = f"aitbc-{participant_id}-{datetime.now(datetime.UTC).timestamp()}" public_key_bytes, key_handle = await self.hsm.generate_key(hsm_key_id) # Create key pair record @@ -219,7 +219,7 @@ class HSMKeyManager: private_key=key_handle, # Store HSM handle, not actual private key public_key=public_key_bytes, algorithm="X25519", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), version=1, ) @@ -249,7 +249,7 @@ class HSMKeyManager: participant_id=participant_id, old_version=current_key.version, new_version=new_key_pair.version, - rotated_at=datetime.utcnow(), + rotated_at=datetime.now(datetime.UTC), reason="scheduled_rotation", ) @@ -308,8 +308,8 @@ class HSMKeyManager: "issuer": issuer, "subject": "audit_access", "purpose": purpose, - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(hours=expires_in_hours)).isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(hours=expires_in_hours)).isoformat(), } # Sign with audit key @@ -334,7 +334,7 @@ class HSMKeyManager: # Check expiration expires_at = datetime.fromisoformat(auth_json["expires_at"]) - if datetime.utcnow() > expires_at: + if datetime.now(datetime.UTC) > expires_at: return False # Verify signature with audit public key diff --git a/apps/coordinator-api/src/app/services/ipfs_storage_service.py b/apps/coordinator-api/src/app/services/ipfs_storage_service.py index a21ca650..9188e98b 100755 --- a/apps/coordinator-api/src/app/services/ipfs_storage_service.py +++ b/apps/coordinator-api/src/app/services/ipfs_storage_service.py @@ -12,7 +12,7 @@ import gzip import hashlib import pickle from dataclasses import dataclass -from datetime import datetime +from datetime import datetime, UTC from typing import Any from .secure_pickle import safe_loads @@ -96,7 +96,7 @@ class IPFSStorageService: ) -> IPFSUploadResult: """Upload agent memory data to IPFS""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) tags = tags or [] try: @@ -239,7 +239,7 @@ class IPFSStorageService: try: # This would integrate with Filecoin storage providers # For now, return a mock deal ID - deal_id = f"deal-{cid[:8]}-{datetime.utcnow().timestamp()}" + deal_id = f"deal-{cid[:8]}-{datetime.now(datetime.UTC).timestamp()}" logger.info(f"Created Filecoin deal {deal_id} for CID {cid}") return deal_id @@ -321,7 +321,7 @@ class IPFSStorageService: return MemoryMetadata( agent_id="mock_agent", memory_type="experience", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), version=1, tags=["mock"], compression_ratio=1.0, diff --git a/apps/coordinator-api/src/app/services/jobs.py b/apps/coordinator-api/src/app/services/jobs.py index 237e2914..7dc851c1 100755 --- a/apps/coordinator-api/src/app/services/jobs.py +++ b/apps/coordinator-api/src/app/services/jobs.py @@ -1,6 +1,6 @@ from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from sqlmodel import Session, select @@ -16,7 +16,7 @@ class JobService: def create_job(self, client_id: str, req: JobCreate) -> Job: ttl = max(req.ttl_seconds, 1) - now = datetime.utcnow() + now = datetime.now(datetime.UTC) job = Job( client_id=client_id, payload=req.payload, @@ -112,7 +112,7 @@ class JobService: def acquire_next_job(self, miner: Miner) -> Job | None: try: - now = datetime.utcnow() + now = datetime.now(datetime.UTC) statement = select(Job).where(Job.state == JobState.queued).order_by(Job.requested_at.asc()) jobs = self.session.scalars(statement).all() @@ -146,7 +146,7 @@ class JobService: raise # Propagate for caller to handle def _ensure_not_expired(self, job: Job) -> Job: - if job.state in {JobState.queued, JobState.running} and job.expires_at <= datetime.utcnow(): + if job.state in {JobState.queued, JobState.running} and job.expires_at <= datetime.now(datetime.UTC): job.state = JobState.expired job.error = "job expired" self.session.add(job) diff --git a/apps/coordinator-api/src/app/services/key_management.py b/apps/coordinator-api/src/app/services/key_management.py index 1813d38a..a585da99 100755 --- a/apps/coordinator-api/src/app/services/key_management.py +++ b/apps/coordinator-api/src/app/services/key_management.py @@ -6,7 +6,7 @@ import asyncio import base64 import json import os -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey @@ -38,7 +38,7 @@ class KeyManager: private_key=private_key.private_bytes_raw(), public_key=public_key.public_bytes_raw(), algorithm="X25519", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), version=1, ) @@ -79,7 +79,7 @@ class KeyManager: participant_id=participant_id, old_version=current_key.version, new_version=new_key_pair.version, - rotated_at=datetime.utcnow(), + rotated_at=datetime.now(datetime.UTC), reason="scheduled_rotation", ) await self.storage.log_rotation(rotation_log) @@ -150,7 +150,7 @@ class KeyManager: auth_json = json.loads(auth_data) expires_at = datetime.fromisoformat(auth_json["expires_at"]) - if datetime.utcnow() > expires_at: + if datetime.now(datetime.UTC) > expires_at: return False required_fields = ["issuer", "subject", "expires_at", "signature"] @@ -171,8 +171,8 @@ class KeyManager: "issuer": issuer, "subject": "audit_access", "purpose": purpose, - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(hours=expires_in_hours)).isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(hours=expires_in_hours)).isoformat(), "signature": "placeholder", # In production, sign with issuer key } @@ -220,7 +220,7 @@ class KeyManager: private_key=self._audit_private, public_key=audit_public.public_bytes_raw(), algorithm="X25519", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), version=1, ) diff --git a/apps/coordinator-api/src/app/services/market_data_collector.py b/apps/coordinator-api/src/app/services/market_data_collector.py index f06e7324..0e4cedaf 100755 --- a/apps/coordinator-api/src/app/services/market_data_collector.py +++ b/apps/coordinator-api/src/app/services/market_data_collector.py @@ -7,7 +7,7 @@ import asyncio import json from collections.abc import Callable from dataclasses import dataclass, field -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -123,7 +123,7 @@ class MarketDataCollector: async def get_recent_data(self, source: DataSource, minutes: int = 60) -> list[MarketDataPoint]: """Get recent data from a specific source""" - cutoff_time = datetime.utcnow() - timedelta(minutes=minutes) + cutoff_time = datetime.now(datetime.UTC) - timedelta(minutes=minutes) return [point for point in self.raw_data if point.source == source and point.timestamp >= cutoff_time] @@ -167,8 +167,8 @@ class MarketDataCollector: for region in regions: # Simulate GPU metrics - utilization = 0.6 + (hash(region + str(datetime.utcnow().minute)) % 100) / 200 - available_gpus = 100 + (hash(region + str(datetime.utcnow().hour)) % 50) + utilization = 0.6 + (hash(region + str(datetime.now(datetime.UTC).minute)) % 100) / 200 + available_gpus = 100 + (hash(region + str(datetime.now(datetime.UTC).hour)) % 50) total_gpus = 150 supply_level = available_gpus / total_gpus @@ -179,7 +179,7 @@ class MarketDataCollector: resource_id=f"gpu_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=utilization, metadata={"available_gpus": available_gpus, "total_gpus": total_gpus, "supply_level": supply_level}, ) @@ -198,7 +198,7 @@ class MarketDataCollector: for region in regions: # Simulate recent bookings - recent_bookings = hash(region + str(datetime.utcnow().minute)) % 20 + recent_bookings = hash(region + str(datetime.now(datetime.UTC).minute)) % 20 total_capacity = 100 booking_rate = recent_bookings / total_capacity @@ -210,7 +210,7 @@ class MarketDataCollector: resource_id=f"bookings_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=booking_rate, metadata={ "recent_bookings": recent_bookings, @@ -233,7 +233,7 @@ class MarketDataCollector: for region in regions: # Simulate demand based on time of day and region - hour = datetime.utcnow().hour + hour = datetime.now(datetime.UTC).hour # Different regions have different peak times if region == "asia": @@ -260,7 +260,7 @@ class MarketDataCollector: resource_id=f"demand_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=demand_level, metadata={"hour": hour, "peak_hours": peak_hours, "demand_multiplier": demand_multiplier}, ) @@ -294,7 +294,7 @@ class MarketDataCollector: resource_id=f"competitors_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=avg_competitor_price, metadata={"competitor_prices": competitor_prices, "price_count": len(competitor_prices)}, ) @@ -324,7 +324,7 @@ class MarketDataCollector: resource_id=f"performance_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=performance_score, metadata={ "completion_rate": completion_rate, @@ -360,7 +360,7 @@ class MarketDataCollector: resource_id=f"sentiment_{region}", resource_type="gpu", region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), value=sentiment, metadata={"recent_activity": recent_activity, "price_trend": price_trend, "volume_change": volume_change}, ) @@ -420,7 +420,7 @@ class MarketDataCollector: try: # Get recent data for this resource type and region - cutoff_time = datetime.utcnow() - timedelta(minutes=30) + cutoff_time = datetime.now(datetime.UTC) - timedelta(minutes=30) relevant_data = [ point for point in self.raw_data @@ -456,7 +456,7 @@ class MarketDataCollector: return AggregatedMarketData( resource_type=resource_type, region=region, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), demand_level=demand_level, supply_level=supply_level, average_price=average_price, @@ -595,7 +595,7 @@ class MarketDataCollector: source_confidence = min(1.0, len(data_sources) / 4.0) # 4 sources available # Data freshness confidence - now = datetime.utcnow() + now = datetime.now(datetime.UTC) freshness_scores = [] for _source, points in source_data.items(): @@ -621,7 +621,7 @@ class MarketDataCollector: while True: try: - cutoff_time = datetime.utcnow() - self.max_data_age + cutoff_time = datetime.now(datetime.UTC) - self.max_data_age # Remove old raw data self.raw_data = [point for point in self.raw_data if point.timestamp >= cutoff_time] @@ -643,7 +643,7 @@ class MarketDataCollector: """Handle WebSocket connections""" try: # Store connection - connection_id = f"{websocket.remote_address}_{datetime.utcnow().timestamp()}" + connection_id = f"{websocket.remote_address}_{datetime.now(datetime.UTC).timestamp()}" self.websocket_connections[connection_id] = websocket logger.info(f"WebSocket client connected: {connection_id}") diff --git a/apps/coordinator-api/src/app/services/marketplace_cache_optimizer.py b/apps/coordinator-api/src/app/services/marketplace_cache_optimizer.py index f453859a..2e88fece 100755 --- a/apps/coordinator-api/src/app/services/marketplace_cache_optimizer.py +++ b/apps/coordinator-api/src/app/services/marketplace_cache_optimizer.py @@ -8,7 +8,7 @@ import time import hashlib from typing import Dict, List, Optional, Any, Union, Set from collections import OrderedDict -from datetime import datetime +from datetime import datetime, UTC import redis.asyncio as redis @@ -204,7 +204,7 @@ class MarketplaceDataOptimizer: "active_providers": 450, "average_price_per_tflop": 0.005, "network_utilization": 0.76, - "computed_at": datetime.utcnow().isoformat(), + "computed_at": datetime.now(datetime.UTC).isoformat(), "computation_time_ms": int((time.time() - start_time) * 1000) } diff --git a/apps/coordinator-api/src/app/services/marketplace_enhanced.py b/apps/coordinator-api/src/app/services/marketplace_enhanced.py index ae0ad20d..e0fd6b9b 100755 --- a/apps/coordinator-api/src/app/services/marketplace_enhanced.py +++ b/apps/coordinator-api/src/app/services/marketplace_enhanced.py @@ -5,7 +5,7 @@ Implements sophisticated royalty distribution, model licensing, and advanced ver from __future__ import annotations -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -67,8 +67,8 @@ class EnhancedMarketplaceService: "offer_id": offer_id, "tiers": royalty_tiers, "dynamic_rates": dynamic_rates, - "created_at": datetime.utcnow(), - "updated_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), + "updated_at": datetime.now(datetime.UTC), } # Store in offer metadata @@ -136,8 +136,8 @@ class EnhancedMarketplaceService: "terms": terms, "usage_rights": usage_rights, "custom_terms": custom_terms or {}, - "created_at": datetime.utcnow(), - "updated_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), + "updated_at": datetime.now(datetime.UTC), } # Store license in offer metadata @@ -161,7 +161,7 @@ class EnhancedMarketplaceService: "offer_id": offer_id, "verification_type": verification_type, "status": VerificationStatus.PENDING.value, - "created_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), "checks": {}, } @@ -216,7 +216,7 @@ class EnhancedMarketplaceService: async def get_marketplace_analytics(self, period_days: int = 30, metrics: list[str] = None) -> dict[str, Any]: """Get comprehensive marketplace analytics""" - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(days=period_days) analytics = { diff --git a/apps/coordinator-api/src/app/services/marketplace_enhanced_simple.py b/apps/coordinator-api/src/app/services/marketplace_enhanced_simple.py index 7ada381a..c9118e80 100755 --- a/apps/coordinator-api/src/app/services/marketplace_enhanced_simple.py +++ b/apps/coordinator-api/src/app/services/marketplace_enhanced_simple.py @@ -6,7 +6,7 @@ Basic marketplace enhancement features compatible with existing domain models from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -69,7 +69,7 @@ class EnhancedMarketplaceService: offer.attributes["royalty_distribution"] = { "tiers": royalty_tiers, "dynamic_rates": dynamic_rates, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } self.session.commit() @@ -78,7 +78,7 @@ class EnhancedMarketplaceService: "offer_id": offer_id, "tiers": royalty_tiers, "dynamic_rates": dynamic_rates, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -134,7 +134,7 @@ class EnhancedMarketplaceService: "license_type": license_type.value, "terms": terms, "usage_rights": usage_rights, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } if custom_terms: @@ -165,7 +165,7 @@ class EnhancedMarketplaceService: "verification_type": verification_type.value, "status": "verified", "checks": {}, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } # Add verification checks based on type @@ -203,7 +203,7 @@ class EnhancedMarketplaceService: metrics = ["volume", "trends", "performance", "revenue"] # Calculate date range - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(days=period_days) # Get marketplace data diff --git a/apps/coordinator-api/src/app/services/marketplace_gpu_optimizer.py b/apps/coordinator-api/src/app/services/marketplace_gpu_optimizer.py index 963f8558..cb23b0e9 100755 --- a/apps/coordinator-api/src/app/services/marketplace_gpu_optimizer.py +++ b/apps/coordinator-api/src/app/services/marketplace_gpu_optimizer.py @@ -10,7 +10,7 @@ import json import asyncio import numpy as np from typing import Dict, List, Optional, Any, Tuple -from datetime import datetime +from datetime import datetime, UTC import threading import multiprocessing @@ -422,7 +422,7 @@ class MarketplaceGPUOptimizer: 'memory_required': memory_required, 'computation_complexity': computation_complexity, 'status': 'queued', - 'submitted_at': datetime.utcnow().isoformat() + 'submitted_at': datetime.now(datetime.UTC).isoformat() } # Calculate scores and find best GPU @@ -552,7 +552,7 @@ class MarketplaceGPUOptimizer: }) return { - 'timestamp': datetime.utcnow().isoformat(), + 'timestamp': datetime.now(datetime.UTC).isoformat(), 'active_jobs': len(self.active_jobs), 'metrics': { 'overall_utilization_pct': round(self.resource_metrics['total_utilization'] * 100, 2), diff --git a/apps/coordinator-api/src/app/services/marketplace_monitor.py b/apps/coordinator-api/src/app/services/marketplace_monitor.py index 87097ce7..c81a3a3a 100755 --- a/apps/coordinator-api/src/app/services/marketplace_monitor.py +++ b/apps/coordinator-api/src/app/services/marketplace_monitor.py @@ -6,7 +6,7 @@ Implements comprehensive real-time monitoring and analytics for the AITBC market import time import asyncio from typing import Dict, List, Optional, Any, collections -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import collections from aitbc import get_logger @@ -187,7 +187,7 @@ class MarketplaceMonitor: 'value': p95_latency, 'threshold': self.alert_thresholds['api_latency_p95_ms'], 'message': f"High API Latency (p95): {p95_latency:.2f}ms", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Error Rate Alert @@ -200,7 +200,7 @@ class MarketplaceMonitor: 'value': avg_error_rate, 'threshold': self.alert_thresholds['api_error_rate_pct'], 'message': f"High API Error Rate: {avg_error_rate:.2f}%", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Matching Time Alert @@ -213,7 +213,7 @@ class MarketplaceMonitor: 'value': avg_matching, 'threshold': self.alert_thresholds['matching_time_ms'], 'message': f"Slow Order Matching: {avg_matching:.2f}ms", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Pool-Hub SLA Alerts @@ -227,7 +227,7 @@ class MarketplaceMonitor: 'value': avg_uptime, 'threshold': self.alert_thresholds['miner_uptime_pct'], 'message': f"Low Miner Uptime: {avg_uptime:.2f}%", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Miner Response Time Alert @@ -240,7 +240,7 @@ class MarketplaceMonitor: 'value': p95_response, 'threshold': self.alert_thresholds['miner_response_time_ms'], 'message': f"High Miner Response Time (p95): {p95_response:.2f}ms", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Job Completion Rate Alert @@ -253,7 +253,7 @@ class MarketplaceMonitor: 'value': avg_completion, 'threshold': self.alert_thresholds['job_completion_rate_pct'], 'message': f"Low Job Completion Rate: {avg_completion:.2f}%", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) # Capacity Availability Alert @@ -266,7 +266,7 @@ class MarketplaceMonitor: 'value': avg_capacity, 'threshold': self.alert_thresholds['capacity_availability_pct'], 'message': f"Low Capacity Availability: {avg_capacity:.2f}%", - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) self.active_alerts = current_alerts @@ -281,7 +281,7 @@ class MarketplaceMonitor: """Get aggregated data formatted for the frontend dashboard""" return { 'status': 'degraded' if any(a['severity'] in ['high', 'critical'] for a in self.active_alerts) else 'healthy', - 'timestamp': datetime.utcnow().isoformat(), + 'timestamp': datetime.now(datetime.UTC).isoformat(), 'current_metrics': { 'api': { 'rps': round(self.api_requests_per_sec.get_latest() or 0, 2), diff --git a/apps/coordinator-api/src/app/services/marketplace_scaler.py b/apps/coordinator-api/src/app/services/marketplace_scaler.py index 6af85cd4..b217dcc5 100755 --- a/apps/coordinator-api/src/app/services/marketplace_scaler.py +++ b/apps/coordinator-api/src/app/services/marketplace_scaler.py @@ -6,7 +6,7 @@ Implements predictive and reactive auto-scaling of marketplace resources based o import time import asyncio from typing import Dict, List, Optional, Any, Tuple -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import math from aitbc import get_logger @@ -69,7 +69,7 @@ class ResourceScaler: def update_historical_demand(self, utilization: float): """Update historical data for predictive scaling""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) hour_of_week = now.weekday() * 24 + now.hour if hour_of_week not in self.historical_demand: @@ -84,7 +84,7 @@ class ResourceScaler: if not self.policy.predictive_scaling or not self.historical_demand: return 0.0 - now = datetime.utcnow() + now = datetime.now(datetime.UTC) target_hour = (now.weekday() * 24 + now.hour + lookahead_hours) % 168 # If we have exact data for that hour @@ -177,7 +177,7 @@ class ResourceScaler: result = await self._execute_scaling(action, diff, target_nodes) record = { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "action": action, "nodes_changed": diff, "new_total": target_nodes, diff --git a/apps/coordinator-api/src/app/services/memory_manager.py b/apps/coordinator-api/src/app/services/memory_manager.py index 91a08810..3155cbaf 100755 --- a/apps/coordinator-api/src/app/services/memory_manager.py +++ b/apps/coordinator-api/src/app/services/memory_manager.py @@ -11,7 +11,7 @@ from aitbc import get_logger logger = get_logger(__name__) from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from enum import StrEnum from typing import Any @@ -123,9 +123,9 @@ class MemoryManager: # Set expiration for temporary memories expires_at = None if priority == MemoryPriority.TEMPORARY: - expires_at = datetime.utcnow() + timedelta(days=expires_in_days or 7) + expires_at = datetime.now(datetime.UTC) + timedelta(days=expires_in_days or 7) elif expires_in_days: - expires_at = datetime.utcnow() + timedelta(days=expires_in_days) + expires_at = datetime.now(datetime.UTC) + timedelta(days=expires_in_days) # Determine pinning based on priority should_pin = priority in [MemoryPriority.CRITICAL, MemoryPriority.HIGH] @@ -191,7 +191,7 @@ class MemoryManager: raise ValueError(f"Memory record not found for CID: {cid}") # Check expiration - if memory_record.expires_at and memory_record.expires_at < datetime.utcnow(): + if memory_record.expires_at and memory_record.expires_at < datetime.now(datetime.UTC): raise ValueError(f"Memory has expired: {cid}") # Retrieve from IPFS @@ -266,7 +266,7 @@ class MemoryManager: continue # Filter expired memories - if memory_record.expires_at and memory_record.expires_at < datetime.utcnow(): + if memory_record.expires_at and memory_record.expires_at < datetime.now(datetime.UTC): continue memories.append(memory_record) @@ -376,7 +376,7 @@ class MemoryManager: optimization_results = {"archived": 0, "deduplicated": 0, "compressed": 0, "errors": []} # Archive old low-priority memories - cutoff_date = datetime.utcnow() - timedelta(days=self.config.auto_cleanup_days) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=self.config.auto_cleanup_days) for cid, memory_record in list(self.memory_records.items()): if ( @@ -421,7 +421,7 @@ class MemoryManager: memory_record = self.memory_records.get(cid) if memory_record: memory_record.access_count += 1 - memory_record.last_accessed = datetime.utcnow() + memory_record.last_accessed = datetime.now(datetime.UTC) await self._save_memory_record(memory_record) async def _enforce_memory_limit(self, agent_id: str): @@ -458,7 +458,7 @@ class MemoryManager: try: await asyncio.sleep(3600) # Run every hour - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) expired_cids = [] for cid, memory_record in self.memory_records.items(): @@ -497,4 +497,4 @@ class MemoryManager: async def _get_upload_result(self, cid: str) -> IPFSUploadResult: """Get upload result for existing CID""" # In real implementation, this would retrieve from database - return IPFSUploadResult(cid=cid, size=0, compressed_size=0, upload_time=datetime.utcnow()) + return IPFSUploadResult(cid=cid, size=0, compressed_size=0, upload_time=datetime.now(datetime.UTC)) diff --git a/apps/coordinator-api/src/app/services/miners.py b/apps/coordinator-api/src/app/services/miners.py index ff2c306d..83eb1a4c 100755 --- a/apps/coordinator-api/src/app/services/miners.py +++ b/apps/coordinator-api/src/app/services/miners.py @@ -1,6 +1,6 @@ from __future__ import annotations -from datetime import datetime +from datetime import datetime, UTC from uuid import uuid4 from sqlmodel import Session, select @@ -32,7 +32,7 @@ class MinerService: miner.region = payload.region miner.session_token = session_token miner.inflight = 0 - miner.last_heartbeat = datetime.utcnow() + miner.last_heartbeat = datetime.now(datetime.UTC) miner.status = "ONLINE" self.session.commit() self.session.refresh(miner) @@ -54,7 +54,7 @@ class MinerService: if payload.network_latency_ms is not None: metadata["network_latency_ms"] = payload.network_latency_ms miner.extra_metadata = metadata - miner.last_heartbeat = datetime.utcnow() + miner.last_heartbeat = datetime.now(datetime.UTC) self.session.add(miner) self.session.commit() self.session.refresh(miner) @@ -73,8 +73,8 @@ class MinerService: return None miner.inflight += 1 - miner.last_heartbeat = datetime.utcnow() - miner.last_job_at = datetime.utcnow() + miner.last_heartbeat = datetime.now(datetime.UTC) + miner.last_job_at = datetime.now(datetime.UTC) self.session.add(miner) self.session.commit() return job_service.to_assigned(job) diff --git a/apps/coordinator-api/src/app/services/modality_optimization.py b/apps/coordinator-api/src/app/services/modality_optimization.py index 12868173..d6c11927 100755 --- a/apps/coordinator-api/src/app/services/modality_optimization.py +++ b/apps/coordinator-api/src/app/services/modality_optimization.py @@ -13,7 +13,7 @@ import asyncio from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any @@ -77,7 +77,7 @@ class TextOptimizer(ModalityOptimizer): ) -> dict[str, Any]: """Optimize text processing""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) constraints = constraints or {} # Normalize input @@ -92,7 +92,7 @@ class TextOptimizer(ModalityOptimizer): optimized_result = await self._optimize_single_text(text, strategy, constraints) results.append(optimized_result) - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() # Calculate aggregate metrics total_original_chars = sum(len(text) for text in texts) @@ -321,7 +321,7 @@ class ImageOptimizer(ModalityOptimizer): ) -> dict[str, Any]: """Optimize image processing""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) constraints = constraints or {} # Extract image properties @@ -339,7 +339,7 @@ class ImageOptimizer(ModalityOptimizer): else: # BALANCED result = await self._optimize_image_balanced(image_data, constraints) - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() # Calculate metrics original_size = width * height * channels @@ -482,7 +482,7 @@ class AudioOptimizer(ModalityOptimizer): ) -> dict[str, Any]: """Optimize audio processing""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) constraints = constraints or {} # Extract audio properties @@ -500,7 +500,7 @@ class AudioOptimizer(ModalityOptimizer): else: # BALANCED result = await self._optimize_audio_balanced(audio_data, constraints) - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() # Calculate metrics original_size = sample_rate * duration * channels @@ -649,7 +649,7 @@ class VideoOptimizer(ModalityOptimizer): ) -> dict[str, Any]: """Optimize video processing""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) constraints = constraints or {} # Extract video properties @@ -668,7 +668,7 @@ class VideoOptimizer(ModalityOptimizer): else: # BALANCED result = await self._optimize_video_balanced(video_data, constraints) - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() # Calculate metrics original_size = fps * duration * width * height * 3 # RGB @@ -856,7 +856,7 @@ class ModalityOptimizationManager: ) -> dict[str, Any]: """Optimize multiple modalities""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) results = {} # Optimize each modality in parallel @@ -875,7 +875,7 @@ class ModalityOptimizationManager: else: results[modality.value] = result - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() # Calculate aggregate metrics total_compression = sum( diff --git a/apps/coordinator-api/src/app/services/multi_chain_transaction_manager.py b/apps/coordinator-api/src/app/services/multi_chain_transaction_manager.py index 9de08101..1c15223d 100755 --- a/apps/coordinator-api/src/app/services/multi_chain_transaction_manager.py +++ b/apps/coordinator-api/src/app/services/multi_chain_transaction_manager.py @@ -5,7 +5,7 @@ Advanced transaction management system for cross-chain operations with routing, import asyncio from collections import defaultdict -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from enum import StrEnum from typing import Any @@ -129,7 +129,7 @@ class MultiChainTransactionManager: "success_rate": 0.0, "average_gas_price": 0.0, "average_confirmation_time": 0.0, - "last_updated": datetime.utcnow(), + "last_updated": datetime.now(datetime.UTC), } # Initialize bridge service @@ -200,8 +200,8 @@ class MultiChainTransactionManager: "gas_price": gas_price, "max_fee_per_gas": max_fee_per_gas, "status": TransactionStatus.QUEUED.value, - "created_at": datetime.utcnow(), - "deadline": datetime.utcnow() + timedelta(minutes=deadline_minutes), + "created_at": datetime.now(datetime.UTC), + "deadline": datetime.now(datetime.UTC) + timedelta(minutes=deadline_minutes), "metadata": metadata or {}, "retry_count": 0, "submit_attempts": 0, @@ -297,7 +297,7 @@ class MultiChainTransactionManager: # Update transaction status transaction["status"] = TransactionStatus.CANCELLED.value transaction["error_message"] = reason - transaction["updated_at"] = datetime.utcnow() + transaction["updated_at"] = datetime.now(datetime.UTC) # Remove from queues await self._remove_from_queues(transaction_id) @@ -308,7 +308,7 @@ class MultiChainTransactionManager: "transaction_id": transaction_id, "status": TransactionStatus.CANCELLED.value, "reason": reason, - "cancelled_at": datetime.utcnow().isoformat(), + "cancelled_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -415,7 +415,7 @@ class MultiChainTransactionManager: """Get transaction statistics""" try: - cutoff_time = datetime.utcnow() - timedelta(hours=time_period_hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=time_period_hours) # Get all transactions all_transactions = [] @@ -476,7 +476,7 @@ class MultiChainTransactionManager: "average_processing_time_seconds": avg_processing_time, "gas_statistics": gas_stats, "priority_distribution": dict(priority_distribution), - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -532,7 +532,7 @@ class MultiChainTransactionManager: "success_rate_weight": 0.2, "queue_length_weight": 0.2, }, - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -655,7 +655,7 @@ class MultiChainTransactionManager: """Process a single transaction""" try: - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Update status to processing transaction["status"] = TransactionStatus.PROCESSING.value @@ -679,15 +679,15 @@ class MultiChainTransactionManager: transaction["transaction_hash"] = tx_result["transaction_hash"] transaction["status"] = TransactionStatus.SUBMITTED.value transaction["submit_attempts"] += 1 - transaction["updated_at"] = datetime.utcnow() + transaction["updated_at"] = datetime.now(datetime.UTC) # Wait for confirmations await self._wait_for_confirmations(transaction) # Update final status transaction["status"] = TransactionStatus.COMPLETED.value - transaction["processing_time"] = (datetime.utcnow() - start_time).total_seconds() - transaction["updated_at"] = datetime.utcnow() + transaction["processing_time"] = (datetime.now(datetime.UTC) - start_time).total_seconds() + transaction["updated_at"] = datetime.now(datetime.UTC) # Update metrics self.metrics["successful_transactions"] += 1 @@ -732,7 +732,7 @@ class MultiChainTransactionManager: try: transaction["retry_count"] += 1 transaction["error_message"] = error_message - transaction["updated_at"] = datetime.utcnow() + transaction["updated_at"] = datetime.now(datetime.UTC) # Check if should retry if transaction["retry_count"] < self.routing_config["max_retries"]: @@ -779,7 +779,7 @@ class MultiChainTransactionManager: """Clean up old completed/failed transactions""" try: - cutoff_time = datetime.utcnow() - timedelta(hours=24) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=24) for chain_id in self.transaction_queues: original_length = len(self.transaction_queues[chain_id]) @@ -812,7 +812,7 @@ class MultiChainTransactionManager: chain_metrics["average_gas_price"] = ( chain_metrics["average_gas_price"] * 0.9 + gas_price * 0.1 # Moving average ) - chain_metrics["last_updated"] = datetime.utcnow() + chain_metrics["last_updated"] = datetime.now(datetime.UTC) except Exception as e: logger.error(f"Error updating performance metrics: {e}") @@ -821,7 +821,7 @@ class MultiChainTransactionManager: """Check for stuck transactions""" try: - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) stuck_threshold = timedelta(minutes=30) for chain_id in self.transaction_queues: @@ -853,7 +853,7 @@ class MultiChainTransactionManager: if tx_status.get("status") == TransactionStatus.COMPLETED.value: transaction["status"] = TransactionStatus.COMPLETED.value transaction["confirmations"] = await self._get_transaction_confirmations(transaction) - transaction["updated_at"] = datetime.utcnow() + transaction["updated_at"] = datetime.now(datetime.UTC) except Exception as e: logger.error(f"Error updating transaction status: {e}") diff --git a/apps/coordinator-api/src/app/services/multi_language/api_endpoints.py b/apps/coordinator-api/src/app/services/multi_language/api_endpoints.py index 440e226c..3124d727 100755 --- a/apps/coordinator-api/src/app/services/multi_language/api_endpoints.py +++ b/apps/coordinator-api/src/app/services/multi_language/api_endpoints.py @@ -4,7 +4,7 @@ REST API endpoints for translation and language detection services """ import asyncio -from datetime import datetime +from datetime import datetime, UTC from typing import Any from aitbc import get_logger @@ -454,11 +454,11 @@ async def health_check( all_healthy = all(services.values()) status = "healthy" if all_healthy else "degraded" if any(services.values()) else "unhealthy" - return HealthResponse(status=status, services=services, timestamp=datetime.utcnow()) + return HealthResponse(status=status, services=services, timestamp=datetime.now(datetime.UTC)) except Exception as e: logger.error(f"Health check error: {e}") - return HealthResponse(status="unhealthy", services={"error": str(e)}, timestamp=datetime.utcnow()) + return HealthResponse(status="unhealthy", services={"error": str(e)}, timestamp=datetime.now(datetime.UTC)) @router.get("/cache/top-translations") diff --git a/apps/coordinator-api/src/app/services/multi_modal_fusion.py b/apps/coordinator-api/src/app/services/multi_modal_fusion.py index 1f935c88..fcac0617 100755 --- a/apps/coordinator-api/src/app/services/multi_modal_fusion.py +++ b/apps/coordinator-api/src/app/services/multi_modal_fusion.py @@ -5,7 +5,7 @@ Phase 5.1: Advanced AI Capabilities Enhancement """ import asyncio -from datetime import datetime +from datetime import datetime, UTC from typing import Any from uuid import uuid4 @@ -571,7 +571,7 @@ class MultiModalFusionEngine: fusion_model.robustness_score = training_results["robustness"] fusion_model.inference_time = training_results["inference_time"] fusion_model.status = "ready" - fusion_model.trained_at = datetime.utcnow() + fusion_model.trained_at = datetime.now(datetime.UTC) session.commit() diff --git a/apps/coordinator-api/src/app/services/multimodal_agent.py b/apps/coordinator-api/src/app/services/multimodal_agent.py index cf49b682..f433d5de 100755 --- a/apps/coordinator-api/src/app/services/multimodal_agent.py +++ b/apps/coordinator-api/src/app/services/multimodal_agent.py @@ -12,7 +12,7 @@ import asyncio from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any @@ -76,7 +76,7 @@ class MultiModalAgentService: Processing results with performance metrics """ - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) try: # Validate input modalities @@ -104,7 +104,7 @@ class MultiModalAgentService: raise ValueError(f"Unsupported processing mode: {processing_mode}") # Calculate performance metrics - processing_time = (datetime.utcnow() - start_time).total_seconds() + processing_time = (datetime.now(datetime.UTC) - start_time).total_seconds() performance_metrics = await self._performance_tracker.calculate_metrics(context, results, processing_time) # Update agent execution record @@ -117,7 +117,7 @@ class MultiModalAgentService: "results": results, "performance_metrics": performance_metrics, "processing_time_seconds": processing_time, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: @@ -557,7 +557,7 @@ class MultiModalAgentService: if execution: execution.results = results execution.performance_metrics = performance_metrics - execution.updated_at = datetime.utcnow() + execution.updated_at = datetime.now(datetime.UTC) self.session.commit() except Exception as e: logger.error(f"Failed to update agent execution: {e}") diff --git a/apps/coordinator-api/src/app/services/openclaw_enhanced.py b/apps/coordinator-api/src/app/services/openclaw_enhanced.py index 8750eb0d..db6905d2 100755 --- a/apps/coordinator-api/src/app/services/openclaw_enhanced.py +++ b/apps/coordinator-api/src/app/services/openclaw_enhanced.py @@ -5,7 +5,7 @@ Implements advanced agent orchestration, edge computing integration, and ecosyst from __future__ import annotations -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any from uuid import uuid4 @@ -287,7 +287,7 @@ class OpenClawEnhancedService: "deployment_config": deployment_config, "auto_scale": deployment_config.get("auto_scale", False), "security_compliance": True, - "created_at": datetime.utcnow(), + "created_at": datetime.now(datetime.UTC), } # Deploy to edge locations @@ -346,7 +346,7 @@ class OpenClawEnhancedService: async def _synchronize_edge_cloud_data(self, edge_deployment_id: str) -> dict[str, Any]: """Synchronize data between edge and cloud""" - return {"sync_status": "active", "last_sync": datetime.utcnow().isoformat(), "data_consistency": 0.99} + return {"sync_status": "active", "last_sync": datetime.now(datetime.UTC).isoformat(), "data_consistency": 0.99} async def _edge_cloud_load_balancing(self, edge_deployment_id: str) -> dict[str, Any]: """Implement edge-to-cloud load balancing""" diff --git a/apps/coordinator-api/src/app/services/openclaw_enhanced_simple.py b/apps/coordinator-api/src/app/services/openclaw_enhanced_simple.py index fca3bdab..cd5ebaf2 100755 --- a/apps/coordinator-api/src/app/services/openclaw_enhanced_simple.py +++ b/apps/coordinator-api/src/app/services/openclaw_enhanced_simple.py @@ -6,7 +6,7 @@ Basic OpenClaw integration features compatible with existing infrastructure from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any from uuid import uuid4 @@ -384,7 +384,7 @@ class OpenClawEnhancedService: coordination_id = f"coordination_{uuid4().hex[:8]}" # Configure synchronization - synchronization = {"sync_status": "active", "last_sync": datetime.utcnow().isoformat(), "data_consistency": 0.95} + synchronization = {"sync_status": "active", "last_sync": datetime.now(datetime.UTC).isoformat(), "data_consistency": 0.95} # Configure load balancing load_balancing = {"balancing_algorithm": "round_robin", "active_connections": 10, "average_response_time": 120} diff --git a/apps/coordinator-api/src/app/services/payments.py b/apps/coordinator-api/src/app/services/payments.py index f2342793..366054c4 100755 --- a/apps/coordinator-api/src/app/services/payments.py +++ b/apps/coordinator-api/src/app/services/payments.py @@ -7,7 +7,7 @@ from sqlalchemy.orm import Session """Payment service for job payments""" -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from aitbc import get_logger, AITBCHTTPClient, NetworkError logger = get_logger(__name__) @@ -34,7 +34,7 @@ class PaymentService: amount=payment_data.amount, currency=payment_data.currency, payment_method=payment_data.payment_method, - expires_at=datetime.utcnow() + timedelta(seconds=payment_data.escrow_timeout_seconds), + expires_at=datetime.now(datetime.UTC) + timedelta(seconds=payment_data.escrow_timeout_seconds), ) self.session.add(payment) @@ -82,8 +82,8 @@ class PaymentService: escrow_data = response payment.escrow_address = escrow_data.get("escrow_id") payment.status = "escrowed" - payment.escrowed_at = datetime.utcnow() - payment.updated_at = datetime.utcnow() + payment.escrowed_at = datetime.now(datetime.UTC) + payment.updated_at = datetime.now(datetime.UTC) # Create escrow record escrow = PaymentEscrow( @@ -91,7 +91,7 @@ class PaymentService: amount=payment.amount, currency=payment.currency, address=escrow_data.get("escrow_id"), - expires_at=datetime.utcnow() + timedelta(hours=1), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), ) if escrow is not None: self.session.add(escrow) @@ -102,12 +102,12 @@ class PaymentService: except NetworkError as e: logger.error(f"Failed to create token escrow: {e}") payment.status = "failed" - payment.updated_at = datetime.utcnow() + payment.updated_at = datetime.now(datetime.UTC) self.session.commit() except Exception as e: logger.error(f"Error creating token escrow: {e}") payment.status = "failed" - payment.updated_at = datetime.utcnow() + payment.updated_at = datetime.now(datetime.UTC) self.session.commit() async def _create_bitcoin_escrow(self, payment: JobPayment) -> None: @@ -122,8 +122,8 @@ class PaymentService: ) payment.escrow_address = escrow_data["address"] payment.status = "escrowed" - payment.escrowed_at = datetime.utcnow() - payment.updated_at = datetime.utcnow() + payment.escrowed_at = datetime.now(datetime.UTC) + payment.updated_at = datetime.now(datetime.UTC) # Create escrow record escrow = PaymentEscrow( @@ -131,7 +131,7 @@ class PaymentService: amount=payment.amount, currency=payment.currency, address=escrow_data["address"], - expires_at=datetime.utcnow() + timedelta(hours=1), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), ) if escrow is not None: self.session.add(escrow) @@ -141,13 +141,13 @@ class PaymentService: except NetworkError as e: logger.error(f"Failed to create Bitcoin escrow: {e}") payment.status = "failed" - payment.updated_at = datetime.utcnow() + payment.updated_at = datetime.now(datetime.UTC) self.session.commit() except Exception as e: logger.error(f"Error creating Bitcoin escrow: {e}") payment.status = "failed" - payment.updated_at = datetime.utcnow() + payment.updated_at = datetime.now(datetime.UTC) self.session.commit() async def release_payment(self, job_id: str, payment_id: str, reason: str | None = None) -> bool: @@ -169,8 +169,8 @@ class PaymentService: json={"address": payment.escrow_address, "reason": reason or "Job completed successfully"}, ) payment.status = "released" - payment.released_at = datetime.utcnow() - payment.updated_at = datetime.utcnow() + payment.released_at = datetime.now(datetime.UTC) + payment.updated_at = datetime.now(datetime.UTC) payment.transaction_hash = release_data.get("transaction_hash") # Update escrow record @@ -182,7 +182,7 @@ class PaymentService: if escrow: escrow.is_released = True - escrow.released_at = datetime.utcnow() + escrow.released_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Released payment {payment_id} for job {job_id}") @@ -219,8 +219,8 @@ class PaymentService: }, ) payment.status = "refunded" - payment.refunded_at = datetime.utcnow() - payment.updated_at = datetime.utcnow() + payment.refunded_at = datetime.now(datetime.UTC) + payment.updated_at = datetime.now(datetime.UTC) payment.refund_transaction_hash = refund_data.get("transaction_hash") # Update escrow record @@ -232,7 +232,7 @@ class PaymentService: if escrow: escrow.is_refunded = True - escrow.refunded_at = datetime.utcnow() + escrow.refunded_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Refunded payment {payment_id} for job {job_id}") diff --git a/apps/coordinator-api/src/app/services/performance_monitoring.py b/apps/coordinator-api/src/app/services/performance_monitoring.py index 1d1ae92a..d446573a 100755 --- a/apps/coordinator-api/src/app/services/performance_monitoring.py +++ b/apps/coordinator-api/src/app/services/performance_monitoring.py @@ -6,7 +6,7 @@ Real-time performance tracking and optimization recommendations import json from collections import defaultdict, deque from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any import psutil @@ -124,7 +124,7 @@ class PerformanceMonitor: ) # Store in history - self.system_resources.append({"timestamp": datetime.utcnow(), "data": system_resource}) + self.system_resources.append({"timestamp": datetime.now(datetime.UTC), "data": system_resource}) return system_resource @@ -151,7 +151,7 @@ class PerformanceMonitor: ) # Store in history - self.model_performance[model_id].append({"timestamp": datetime.utcnow(), "data": performance}) + self.model_performance[model_id].append({"timestamp": datetime.now(datetime.UTC), "data": performance}) # Check for performance alerts await self._check_model_alerts(model_id, performance) @@ -233,7 +233,7 @@ class PerformanceMonitor: async def get_performance_summary(self, hours: int = 1) -> dict[str, Any]: """Get performance summary for specified time period""" - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) # System metrics summary system_metrics = [] @@ -283,7 +283,7 @@ class PerformanceMonitor: return { "time_period_hours": hours, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "system_metrics": { "avg_cpu_percent": avg_cpu, "avg_memory_percent": avg_memory, @@ -300,9 +300,9 @@ class PerformanceMonitor: """Get current optimization recommendations""" # Filter recent recommendations (last hour) - cutoff_time = datetime.utcnow() - timedelta(hours=1) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=1) recent_recommendations = [ - rec for rec in self.optimization_recommendations if rec.get("timestamp", datetime.utcnow()) > cutoff_time + rec for rec in self.optimization_recommendations if rec.get("timestamp", datetime.now(datetime.UTC)) > cutoff_time ] return recent_recommendations @@ -313,7 +313,7 @@ class PerformanceMonitor: if model_id not in self.model_performance: return {"error": f"Model {model_id} not found"} - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) entries = [e for e in self.model_performance[model_id] if e["timestamp"] > cutoff_time] if not entries: @@ -365,7 +365,7 @@ class PerformanceMonitor: }, "averages": {"avg_inference_time_ms": avg_inference, "avg_throughput_rps": avg_throughput}, "sample_count": len(performances), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } async def export_metrics(self, format: str = "json", hours: int = 24) -> Union[str, dict[str, Any]]: @@ -380,7 +380,7 @@ class PerformanceMonitor: csv_lines = ["timestamp,model_id,inference_time_ms,throughput_rps,accuracy,memory_usage_mb"] for model_id, entries in self.model_performance.items(): - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) recent_entries = [e for e in entries if e["timestamp"] > cutoff_time] for entry in recent_entries: @@ -420,7 +420,7 @@ class AutoOptimizer: success = await self._apply_optimization(optimization) self.optimization_history.append( - {"timestamp": datetime.utcnow(), "optimization": optimization, "success": success, "impact": "pending"} + {"timestamp": datetime.now(datetime.UTC), "optimization": optimization, "success": success, "impact": "pending"} ) except Exception as e: diff --git a/apps/coordinator-api/src/app/services/quota_enforcement.py b/apps/coordinator-api/src/app/services/quota_enforcement.py index 3c29000a..ec896ef4 100755 --- a/apps/coordinator-api/src/app/services/quota_enforcement.py +++ b/apps/coordinator-api/src/app/services/quota_enforcement.py @@ -4,7 +4,7 @@ Resource quota enforcement service for multi-tenant AITBC coordinator import json from contextlib import asynccontextmanager -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any import redis @@ -85,8 +85,8 @@ class QuotaEnforcementService: unit_price=await self._get_unit_price(resource_type), total_cost=await self._calculate_cost(resource_type, quantity), currency="USD", - usage_start=datetime.utcnow(), - usage_end=datetime.utcnow(), + usage_start=datetime.now(datetime.UTC), + usage_end=datetime.now(datetime.UTC), metadata=metadata or {}, ) @@ -194,7 +194,7 @@ class QuotaEnforcementService: """Context manager for temporary quota reservation""" tenant_id = tenant_id or get_current_tenant_id() - reservation_id = f"reserve:{tenant_id}:{resource_type}:{datetime.utcnow().timestamp()}" + reservation_id = f"reserve:{tenant_id}:{resource_type}:{datetime.now(datetime.UTC).timestamp()}" try: # Reserve quota @@ -206,7 +206,7 @@ class QuotaEnforcementService: "tenant_id": tenant_id, "resource_type": resource_type, "quantity": quantity, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), } self.redis.setex(f"reservation:{reservation_id}", timeout, json.dumps(reservation_data)) @@ -231,7 +231,7 @@ class QuotaEnforcementService: return # Calculate new period - now = datetime.utcnow() + now = datetime.now(datetime.UTC) if quota.period_type == "monthly": period_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) period_end = (period_start + timedelta(days=32)).replace(day=1) - timedelta(days=1) @@ -320,7 +320,7 @@ class QuotaEnforcementService: quota_data = json.loads(cached) quota = TenantQuota(**quota_data) # Check if still valid - if quota.period_end >= datetime.utcnow(): + if quota.period_end >= datetime.now(datetime.UTC): return quota # Query database @@ -329,8 +329,8 @@ class QuotaEnforcementService: TenantQuota.tenant_id == tenant_id, TenantQuota.resource_type == resource_type, TenantQuota.is_active, - TenantQuota.period_start <= datetime.utcnow(), - TenantQuota.period_end >= datetime.utcnow(), + TenantQuota.period_start <= datetime.now(datetime.UTC), + TenantQuota.period_end >= datetime.now(datetime.UTC), ) ) diff --git a/apps/coordinator-api/src/app/services/receipts.py b/apps/coordinator-api/src/app/services/receipts.py index 9180739d..00bec52f 100755 --- a/apps/coordinator-api/src/app/services/receipts.py +++ b/apps/coordinator-api/src/app/services/receipts.py @@ -3,7 +3,7 @@ from __future__ import annotations from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from secrets import token_hex from typing import Any @@ -111,8 +111,8 @@ class ReceiptService: "unit_type": unit_type, "unit_price": unit_price, "price": price, - "started_at": int(job.requested_at.timestamp()) if job.requested_at else int(datetime.utcnow().timestamp()), - "completed_at": int(datetime.utcnow().timestamp()), + "started_at": int(job.requested_at.timestamp()) if job.requested_at else int(datetime.now(datetime.UTC).timestamp()), + "completed_at": int(datetime.now(datetime.UTC).timestamp()), "metadata": { "job_payload": job.payload, "job_constraints": job.constraints, diff --git a/apps/coordinator-api/src/app/services/reputation_service.py b/apps/coordinator-api/src/app/services/reputation_service.py index 2992dacc..aeaec01d 100755 --- a/apps/coordinator-api/src/app/services/reputation_service.py +++ b/apps/coordinator-api/src/app/services/reputation_service.py @@ -3,7 +3,7 @@ Agent Reputation and Trust Service Implements reputation management, trust score calculations, and economic profiling """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from aitbc import get_logger @@ -43,7 +43,7 @@ class TrustScoreCalculator: """Calculate performance-based trust score component""" # Get recent job completions - cutoff_date = datetime.utcnow() - time_window + cutoff_date = datetime.now(datetime.UTC) - time_window # Query performance metrics select(func.count()).where( @@ -102,7 +102,7 @@ class TrustScoreCalculator: def calculate_community_score(self, agent_id: str, session: Session, time_window: timedelta = timedelta(days=90)) -> float: """Calculate community-based trust score component""" - cutoff_date = datetime.utcnow() - time_window + cutoff_date = datetime.now(datetime.UTC) - time_window # Get recent community feedback feedback_query = select(CommunityFeedback).where( @@ -263,8 +263,8 @@ class ReputationService: performance_rating=3.0, reliability_score=50.0, community_rating=3.0, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + updated_at=datetime.now(datetime.UTC), ) self.session.add(reputation) @@ -298,8 +298,8 @@ class ReputationService: reputation_level_before=old_reputation_level, reputation_level_after=new_reputation_level, event_data=impact_data, - occurred_at=datetime.utcnow(), - processed_at=datetime.utcnow(), + occurred_at=datetime.now(datetime.UTC), + processed_at=datetime.now(datetime.UTC), ) self.session.add(event) @@ -307,12 +307,12 @@ class ReputationService: # Update reputation profile reputation.trust_score = new_trust_score reputation.reputation_level = new_reputation_level - reputation.updated_at = datetime.utcnow() - reputation.last_activity = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) + reputation.last_activity = datetime.now(datetime.UTC) # Add to reputation history history_entry = { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "event_type": event_type, "trust_score_change": new_trust_score - old_trust_score, "new_trust_score": new_trust_score, @@ -364,8 +364,8 @@ class ReputationService: elif not success or response_time > 10000: # Poor performance reputation.performance_rating = max(1.0, reputation.performance_rating - 0.1) - reputation.updated_at = datetime.utcnow() - reputation.last_activity = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) + reputation.last_activity = datetime.now(datetime.UTC) # Create trust score update event impact_data = { @@ -397,7 +397,7 @@ class ReputationService: value_rating=ratings.get("value", 3.0), feedback_text=feedback_text, feedback_tags=tags or [], - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(feedback) @@ -442,7 +442,7 @@ class ReputationService: if reputation: reputation.community_rating = avg_rating - reputation.updated_at = datetime.utcnow() + reputation.updated_at = datetime.now(datetime.UTC) self.session.commit() async def get_reputation_summary(self, agent_id: str) -> dict[str, Any]: @@ -458,7 +458,7 @@ class ReputationService: select(ReputationEvent) .where( and_( - ReputationEvent.agent_id == agent_id, ReputationEvent.occurred_at >= datetime.utcnow() - timedelta(days=30) + ReputationEvent.agent_id == agent_id, ReputationEvent.occurred_at >= datetime.now(datetime.UTC) - timedelta(days=30) ) ) .order_by(ReputationEvent.occurred_at.desc()) diff --git a/apps/coordinator-api/src/app/services/reward_service.py b/apps/coordinator-api/src/app/services/reward_service.py index 3d09c885..e476c693 100755 --- a/apps/coordinator-api/src/app/services/reward_service.py +++ b/apps/coordinator-api/src/app/services/reward_service.py @@ -3,7 +3,7 @@ Agent Reward Engine Service Implements performance-based reward calculations, distributions, and tier management """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from uuid import uuid4 @@ -180,7 +180,7 @@ class RewardCalculator: # Mark as claimed milestone.is_claimed = True - milestone.claimed_at = datetime.utcnow() + milestone.claimed_at = datetime.now(datetime.UTC) return total_bonus @@ -241,8 +241,8 @@ class RewardEngine: agent_id=agent_id, current_tier=RewardTier.BRONZE, tier_progress=0.0, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + updated_at=datetime.now(datetime.UTC), ) self.session.add(profile) @@ -280,10 +280,10 @@ class RewardEngine: milestone_bonus=reward_calculation["milestone_bonus"], total_reward=reward_calculation["total_reward"], effective_multiplier=reward_calculation["effective_multiplier"], - reference_date=reference_date or datetime.utcnow(), + reference_date=reference_date or datetime.now(datetime.UTC), trust_score_at_calculation=reward_calculation["trust_score"], performance_metrics=performance_metrics, - calculated_at=datetime.utcnow(), + calculated_at=datetime.now(datetime.UTC), ) self.session.add(calculation) @@ -297,8 +297,8 @@ class RewardEngine: reward_amount=reward_calculation["total_reward"], reward_type=reward_type, status=RewardStatus.PENDING, - created_at=datetime.utcnow(), - scheduled_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + scheduled_at=datetime.now(datetime.UTC), ) self.session.add(distribution) @@ -352,8 +352,8 @@ class RewardEngine: distribution.transaction_hash = transaction_hash distribution.transaction_status = "confirmed" distribution.status = RewardStatus.DISTRIBUTED - distribution.processed_at = datetime.utcnow() - distribution.confirmed_at = datetime.utcnow() + distribution.processed_at = datetime.now(datetime.UTC) + distribution.confirmed_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(distribution) @@ -388,7 +388,7 @@ class RewardEngine: # Update reward count and streak profile.rewards_distributed += 1 - profile.last_reward_date = datetime.utcnow() + profile.last_reward_date = datetime.now(datetime.UTC) profile.current_streak += 1 if profile.current_streak > profile.longest_streak: profile.longest_streak = profile.current_streak @@ -399,8 +399,8 @@ class RewardEngine: # Check for tier upgrade await self.check_and_update_tier(agent_id) - profile.updated_at = datetime.utcnow() - profile.last_activity = datetime.utcnow() + profile.updated_at = datetime.now(datetime.UTC) + profile.last_activity = datetime.now(datetime.UTC) self.session.commit() @@ -426,7 +426,7 @@ class RewardEngine: if new_tier != old_tier: # Update tier profile.current_tier = new_tier - profile.updated_at = datetime.utcnow() + profile.updated_at = datetime.now(datetime.UTC) # Create tier upgrade event await self.create_reward_event(agent_id, "tier_upgrade", RewardType.SPECIAL_BONUS, 0.0, tier_impact=new_tier) @@ -467,8 +467,8 @@ class RewardEngine: tier_impact=tier_impact, related_calculation_id=calculation_id, related_distribution_id=distribution_id, - occurred_at=datetime.utcnow(), - processed_at=datetime.utcnow(), + occurred_at=datetime.now(datetime.UTC), + processed_at=datetime.now(datetime.UTC), ) self.session.add(event) @@ -488,7 +488,7 @@ class RewardEngine: .where( and_( RewardCalculation.agent_id == agent_id, - RewardCalculation.calculated_at >= datetime.utcnow() - timedelta(days=30), + RewardCalculation.calculated_at >= datetime.now(datetime.UTC) - timedelta(days=30), ) ) .order_by(RewardCalculation.calculated_at.desc()) @@ -501,7 +501,7 @@ class RewardEngine: .where( and_( RewardDistribution.agent_id == agent_id, - RewardDistribution.created_at >= datetime.utcnow() - timedelta(days=30), + RewardDistribution.created_at >= datetime.now(datetime.UTC) - timedelta(days=30), ) ) .order_by(RewardDistribution.created_at.desc()) @@ -545,7 +545,7 @@ class RewardEngine: pending_distributions = self.session.execute( select(RewardDistribution) .where( - and_(RewardDistribution.status == RewardStatus.PENDING, RewardDistribution.scheduled_at <= datetime.utcnow()) + and_(RewardDistribution.status == RewardStatus.PENDING, RewardDistribution.scheduled_at <= datetime.now(datetime.UTC)) ) .order_by(RewardDistribution.priority.asc(), RewardDistribution.created_at.asc()) .limit(limit) @@ -570,9 +570,9 @@ class RewardEngine: """Get reward system analytics""" if not start_date: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) if not end_date: - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) # Get distributions in period distributions = self.session.execute( diff --git a/apps/coordinator-api/src/app/services/secure_wallet_service.py b/apps/coordinator-api/src/app/services/secure_wallet_service.py index 4520ea4d..63627033 100755 --- a/apps/coordinator-api/src/app/services/secure_wallet_service.py +++ b/apps/coordinator-api/src/app/services/secure_wallet_service.py @@ -6,7 +6,7 @@ Implements proper Ethereum cryptography and secure key storage from __future__ import annotations from aitbc import get_logger -from datetime import datetime +from datetime import datetime, UTC from sqlalchemy import select from sqlmodel import Session @@ -87,7 +87,7 @@ class SecureWalletService: metadata=request.metadata, encrypted_private_key=encrypted_data, encryption_version="1.0", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(wallet) @@ -222,7 +222,7 @@ class SecureWalletService: # Update wallet wallet.encrypted_private_key = new_encrypted_data wallet.encryption_version = "1.0" - wallet.updated_at = datetime.utcnow() + wallet.updated_at = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(wallet) @@ -251,14 +251,14 @@ class SecureWalletService: if record: record.balance = balance - record.updated_at = datetime.utcnow() + record.updated_at = datetime.now(datetime.UTC) else: record = TokenBalance( wallet_id=wallet_id, chain_id=chain_id, token_address=token_address, balance=balance, - updated_at=datetime.utcnow(), + updated_at=datetime.now(datetime.UTC), ) self.session.add(record) @@ -292,7 +292,7 @@ class SecureWalletService: chain_id=request.chain_id, data=request.data or "", status=TransactionStatus.PENDING, - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) self.session.add(transaction) @@ -318,7 +318,7 @@ class SecureWalletService: # Update transaction with signed data transaction.signed_data = signed_tx transaction.status = TransactionStatus.SIGNED - transaction.updated_at = datetime.utcnow() + transaction.updated_at = datetime.now(datetime.UTC) self.session.commit() # Submit transaction to blockchain @@ -327,7 +327,7 @@ class SecureWalletService: # Update transaction with submission result transaction.tx_hash = tx_hash transaction.status = TransactionStatus.SUBMITTED - transaction.updated_at = datetime.utcnow() + transaction.updated_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Created and submitted transaction {transaction.id} with hash {tx_hash}") @@ -335,7 +335,7 @@ class SecureWalletService: logger.error(f"Failed to sign/submit transaction {transaction.id}: {e}") transaction.status = TransactionStatus.FAILED transaction.error_message = str(e) - transaction.updated_at = datetime.utcnow() + transaction.updated_at = datetime.now(datetime.UTC) self.session.commit() raise @@ -348,7 +348,7 @@ class SecureWalletService: return False wallet.is_active = False - wallet.updated_at = datetime.utcnow() + wallet.updated_at = datetime.now(datetime.UTC) wallet.deactivation_reason = reason self.session.commit() diff --git a/apps/coordinator-api/src/app/services/staking_service.py b/apps/coordinator-api/src/app/services/staking_service.py index 2929f7ba..69f9e892 100755 --- a/apps/coordinator-api/src/app/services/staking_service.py +++ b/apps/coordinator-api/src/app/services/staking_service.py @@ -3,7 +3,7 @@ Staking Management Service Business logic for AI agent staking system with reputation-based yield farming """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from sqlalchemy import and_, func, select @@ -39,7 +39,7 @@ class StakingService: current_apy = await self.calculate_apy(agent_wallet, lock_period) # Calculate end time - end_time = datetime.utcnow() + timedelta(days=lock_period) + end_time = datetime.now(datetime.UTC) + timedelta(days=lock_period) stake = AgentStake( staker_address=staker_address, @@ -179,14 +179,14 @@ class StakingService: if stake.status != StakeStatus.ACTIVE: raise ValueError("Stake is not active") - if datetime.utcnow() < stake.end_time: + if datetime.now(datetime.UTC) < stake.end_time: raise ValueError("Lock period has not ended") # Calculate final rewards await self._calculate_rewards(stake_id) stake.status = StakeStatus.UNBONDING - stake.unbonding_time = datetime.utcnow() + stake.unbonding_time = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(stake) @@ -213,7 +213,7 @@ class StakingService: penalty = 0.0 total_amount = stake.amount - if stake.unbonding_time and datetime.utcnow() < stake.unbonding_time + timedelta(days=30): + if stake.unbonding_time and datetime.now(datetime.UTC) < stake.unbonding_time + timedelta(days=30): penalty = total_amount * 0.10 # 10% early unbond penalty total_amount -= penalty @@ -255,7 +255,7 @@ class StakingService: return stake.accumulated_rewards # Calculate time-based rewards - time_elapsed = datetime.utcnow() - stake.last_reward_time + time_elapsed = datetime.now(datetime.UTC) - stake.last_reward_time yearly_rewards = (stake.amount * stake.current_apy) / 100 current_rewards = (yearly_rewards * time_elapsed.total_seconds()) / (365 * 24 * 3600) @@ -374,7 +374,7 @@ class StakingService: # Update APY for all active stakes on this agent await self._update_stake_apy_for_agent(agent_wallet, new_tier) - agent_metrics.last_update_time = datetime.utcnow() + agent_metrics.last_update_time = datetime.now(datetime.UTC) self.session.commit() self.session.refresh(agent_metrics) @@ -422,7 +422,7 @@ class StakingService: # Update pool metrics pool.total_rewards += total_distributed - pool.last_distribution_time = datetime.utcnow() + pool.last_distribution_time = datetime.now(datetime.UTC) # Update agent metrics agent_metrics = await self.get_agent_metrics(agent_wallet) @@ -483,15 +483,15 @@ class StakingService: try: # Calculate time period if period == "hourly": - start_date = datetime.utcnow() - timedelta(hours=1) + start_date = datetime.now(datetime.UTC) - timedelta(hours=1) elif period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) # Get total staked total_staked_stmt = select(func.sum(AgentStake.amount)).where(AgentStake.start_time >= start_date) @@ -549,13 +549,13 @@ class StakingService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) if metric == "total_staked": stmt = ( @@ -608,13 +608,13 @@ class StakingService: try: # Calculate time period if period == "daily": - start_date = datetime.utcnow() - timedelta(days=1) + start_date = datetime.now(datetime.UTC) - timedelta(days=1) elif period == "weekly": - start_date = datetime.utcnow() - timedelta(weeks=1) + start_date = datetime.now(datetime.UTC) - timedelta(weeks=1) elif period == "monthly": - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) else: - start_date = datetime.utcnow() - timedelta(days=30) + start_date = datetime.now(datetime.UTC) - timedelta(days=30) # Get user's stakes stmt = select(AgentStake).where( @@ -657,7 +657,7 @@ class StakingService: total_rewards += stake.accumulated_rewards stake.accumulated_rewards = 0.0 - stake.last_reward_time = datetime.utcnow() + stake.last_reward_time = datetime.now(datetime.UTC) self.session.commit() @@ -747,12 +747,12 @@ class StakingService: if not stake or stake.status != StakeStatus.ACTIVE: return - time_elapsed = datetime.utcnow() - stake.last_reward_time + time_elapsed = datetime.now(datetime.UTC) - stake.last_reward_time yearly_rewards = (stake.amount * stake.current_apy) / 100 current_rewards = (yearly_rewards * time_elapsed.total_seconds()) / (365 * 24 * 3600) stake.accumulated_rewards += current_rewards - stake.last_reward_time = datetime.utcnow() + stake.last_reward_time = datetime.now(datetime.UTC) # Auto-compound if enabled if stake.auto_compound and current_rewards >= 100.0: diff --git a/apps/coordinator-api/src/app/services/task_decomposition.py b/apps/coordinator-api/src/app/services/task_decomposition.py index 99d5064b..f8abcc03 100755 --- a/apps/coordinator-api/src/app/services/task_decomposition.py +++ b/apps/coordinator-api/src/app/services/task_decomposition.py @@ -7,7 +7,7 @@ from aitbc import get_logger logger = get_logger(__name__) from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, UTC from enum import StrEnum from typing import Any @@ -228,7 +228,7 @@ class TaskDecompositionEngine: ) -> TaskAggregation: """Create aggregation configuration for combining sub-task results""" - aggregation_id = f"agg_{parent_task_id}_{datetime.utcnow().timestamp()}" + aggregation_id = f"agg_{parent_task_id}_{datetime.now(datetime.UTC).timestamp()}" aggregation = TaskAggregation( aggregation_id=aggregation_id, @@ -262,9 +262,9 @@ class TaskDecompositionEngine: # Update timestamps if status == SubTaskStatus.IN_PROGRESS and old_status != SubTaskStatus.IN_PROGRESS: - sub_task.started_at = datetime.utcnow() + sub_task.started_at = datetime.now(datetime.UTC) elif status == SubTaskStatus.COMPLETED: - sub_task.completed_at = datetime.utcnow() + sub_task.completed_at = datetime.now(datetime.UTC) elif status == SubTaskStatus.FAILED: sub_task.retry_count += 1 diff --git a/apps/coordinator-api/src/app/services/tenant_management.py b/apps/coordinator-api/src/app/services/tenant_management.py index 0ba5d357..97c24641 100755 --- a/apps/coordinator-api/src/app/services/tenant_management.py +++ b/apps/coordinator-api/src/app/services/tenant_management.py @@ -4,7 +4,7 @@ Tenant management service for multi-tenant AITBC coordinator import hashlib import secrets -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from sqlalchemy import and_, func, or_, select, update @@ -153,7 +153,7 @@ class TenantManagementService: if hasattr(tenant, key): setattr(tenant, key, value) - tenant.updated_at = datetime.utcnow() + tenant.updated_at = datetime.now(datetime.UTC) # Log update await self._log_audit_event( @@ -184,8 +184,8 @@ class TenantManagementService: return tenant tenant.status = TenantStatus.ACTIVE.value - tenant.activated_at = datetime.utcnow() - tenant.updated_at = datetime.utcnow() + tenant.activated_at = datetime.now(datetime.UTC) + tenant.updated_at = datetime.now(datetime.UTC) # Log activation await self._log_audit_event( @@ -219,8 +219,8 @@ class TenantManagementService: old_status = tenant.status tenant.status = TenantStatus.INACTIVE.value - tenant.deactivated_at = datetime.utcnow() - tenant.updated_at = datetime.utcnow() + tenant.deactivated_at = datetime.now(datetime.UTC) + tenant.updated_at = datetime.now(datetime.UTC) # Revoke all API keys await self._revoke_all_api_keys(tenant_id) @@ -254,7 +254,7 @@ class TenantManagementService: old_status = tenant.status tenant.status = TenantStatus.SUSPENDED.value - tenant.updated_at = datetime.utcnow() + tenant.updated_at = datetime.now(datetime.UTC) # Log suspension await self._log_audit_event( @@ -293,7 +293,7 @@ class TenantManagementService: # Create tenant user tenant_user = TenantUser( - tenant_id=tenant_id, user_id=user_id, role=role, permissions=permissions or [], joined_at=datetime.utcnow() + tenant_id=tenant_id, user_id=user_id, role=role, permissions=permissions or [], joined_at=datetime.now(datetime.UTC) ) self.db.add(tenant_user) @@ -417,7 +417,7 @@ class TenantManagementService: return False api_key.is_active = False - api_key.revoked_at = datetime.utcnow() + api_key.revoked_at = datetime.now(datetime.UTC) # Log revocation await self._log_audit_event( @@ -449,7 +449,7 @@ class TenantManagementService: # Default to last 30 days if not end_date: - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) if not start_date: start_date = end_date - timedelta(days=30) @@ -498,8 +498,8 @@ class TenantManagementService: TenantQuota.tenant_id == tenant_id, TenantQuota.resource_type == resource_type, TenantQuota.is_active, - TenantQuota.period_start <= datetime.utcnow(), - TenantQuota.period_end >= datetime.utcnow(), + TenantQuota.period_start <= datetime.now(datetime.UTC), + TenantQuota.period_end >= datetime.now(datetime.UTC), ) ) @@ -526,8 +526,8 @@ class TenantManagementService: TenantQuota.tenant_id == tenant_id, TenantQuota.resource_type == resource_type, TenantQuota.is_active, - TenantQuota.period_start <= datetime.utcnow(), - TenantQuota.period_end >= datetime.utcnow(), + TenantQuota.period_start <= datetime.now(datetime.UTC), + TenantQuota.period_end >= datetime.now(datetime.UTC), ) ) @@ -596,7 +596,7 @@ class TenantManagementService: quotas = quota_templates.get(plan, quota_templates["trial"]) # Create quota records - now = datetime.utcnow() + now = datetime.now(datetime.UTC) period_end = now.replace(day=1) + timedelta(days=32) # Next month period_end = period_end.replace(day=1) - timedelta(days=1) # Last day of current month @@ -618,7 +618,7 @@ class TenantManagementService: stmt = ( update(TenantApiKey) .where(and_(TenantApiKey.tenant_id == tenant_id, TenantApiKey.is_active)) - .values(is_active=False, revoked_at=datetime.utcnow()) + .values(is_active=False, revoked_at=datetime.now(datetime.UTC)) ) self.db.execute(stmt) diff --git a/apps/coordinator-api/src/app/services/trading_service.py b/apps/coordinator-api/src/app/services/trading_service.py index 5d7238da..0f054d8c 100755 --- a/apps/coordinator-api/src/app/services/trading_service.py +++ b/apps/coordinator-api/src/app/services/trading_service.py @@ -3,7 +3,7 @@ Agent-to-Agent Trading Protocol Service Implements P2P trading, matching, negotiation, and settlement systems """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from uuid import uuid4 @@ -588,7 +588,7 @@ class SettlementLayer: "currency": settlement["currency"], "fee": settlement["platform_fee"], "net_amount": settlement["net_amount_seller"], - "processed_at": datetime.utcnow().isoformat(), + "processed_at": datetime.now(datetime.UTC).isoformat(), } # Add escrow details if applicable @@ -611,7 +611,7 @@ class SettlementLayer: "escrow_address": settlement["escrow_config"]["escrow_address"], "release_reason": release_reason, "conditions_met": release_conditions_met, - "released_at": datetime.utcnow().isoformat(), + "released_at": datetime.now(datetime.UTC).isoformat(), "status": "released" if release_conditions_met else "held", } @@ -632,7 +632,7 @@ class SettlementLayer: "dispute_type": dispute_details.get("type", "general"), "dispute_reason": dispute_details.get("reason", ""), "initiated_by": dispute_details.get("initiated_by", ""), - "initiated_at": datetime.utcnow().isoformat(), + "initiated_at": datetime.now(datetime.UTC).isoformat(), "status": "under_review", } @@ -685,7 +685,7 @@ class P2PTradingProtocol: service_level_required=kwargs.get("service_level_required", "standard"), tags=kwargs.get("tags", []), metadata=kwargs.get("metadata", {}), - expires_at=kwargs.get("expires_at", datetime.utcnow() + timedelta(days=7)), + expires_at=kwargs.get("expires_at", datetime.now(datetime.UTC) + timedelta(days=7)), ) self.session.add(trade_request) @@ -732,7 +732,7 @@ class P2PTradingProtocol: geographic_compatibility=match["compatibility_breakdown"]["geographic_compatibility"], seller_offer=match["seller_offer"], proposed_terms=match["seller_offer"].get("terms", {}), - expires_at=datetime.utcnow() + timedelta(hours=self.matching_engine.match_expiry_hours), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=self.matching_engine.match_expiry_hours), ) self.session.add(trade_match) @@ -743,7 +743,7 @@ class P2PTradingProtocol: # Update request match count trade_request.match_count = len(trade_matches) trade_request.best_match_score = matches[0]["match_score"] if matches else 0.0 - trade_request.updated_at = datetime.utcnow() + trade_request.updated_at = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Found {len(trade_matches)} matches for request {request_id}") @@ -779,8 +779,8 @@ class P2PTradingProtocol: current_terms=initial_offer, initial_terms=initial_offer, auto_accept_threshold=85.0, - started_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=self.negotiation_system.max_negotiation_hours), + started_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=self.negotiation_system.max_negotiation_hours), ) self.session.add(negotiation) @@ -792,7 +792,7 @@ class P2PTradingProtocol: trade_match.negotiation_initiated = True trade_match.negotiation_initiator = initiator trade_match.initial_terms = initial_offer - trade_match.last_interaction = datetime.utcnow() + trade_match.last_interaction = datetime.now(datetime.UTC) self.session.commit() logger.info(f"Initiated negotiation {negotiation.negotiation_id} for match {match_id}") @@ -808,7 +808,7 @@ class P2PTradingProtocol: "agent_id": "seller_001", "price": 0.05, "specifications": {"cpu_cores": 4, "memory_gb": 16, "gpu_count": 1}, - "timing": {"start_time": datetime.utcnow(), "duration_hours": 8}, + "timing": {"start_time": datetime.now(datetime.UTC), "duration_hours": 8}, "regions": ["us-east", "us-west"], "service_level": "premium", "terms": {"settlement_type": "escrow", "delivery_guarantee": True}, @@ -817,7 +817,7 @@ class P2PTradingProtocol: "agent_id": "seller_002", "price": 0.045, "specifications": {"cpu_cores": 2, "memory_gb": 8, "gpu_count": 1}, - "timing": {"start_time": datetime.utcnow(), "duration_hours": 6}, + "timing": {"start_time": datetime.now(datetime.UTC), "duration_hours": 6}, "regions": ["us-east"], "service_level": "standard", "terms": {"settlement_type": "immediate", "delivery_guarantee": False}, @@ -870,8 +870,8 @@ class P2PTradingProtocol: "average_match_score": sum(m.match_score for m in matches) / len(matches) if matches else 0.0, "total_trade_volume": sum(a.total_price for a in agreements), "recent_activity": { - "requests_last_30d": len([r for r in requests if r.created_at >= datetime.utcnow() - timedelta(days=30)]), - "matches_last_30d": len([m for m in matches if m.created_at >= datetime.utcnow() - timedelta(days=30)]), - "agreements_last_30d": len([a for a in agreements if a.created_at >= datetime.utcnow() - timedelta(days=30)]), + "requests_last_30d": len([r for r in requests if r.created_at >= datetime.now(datetime.UTC) - timedelta(days=30)]), + "matches_last_30d": len([m for m in matches if m.created_at >= datetime.now(datetime.UTC) - timedelta(days=30)]), + "agreements_last_30d": len([a for a in agreements if a.created_at >= datetime.now(datetime.UTC) - timedelta(days=30)]), }, } diff --git a/apps/coordinator-api/src/app/services/usage_tracking.py b/apps/coordinator-api/src/app/services/usage_tracking.py index b625b7ea..580748a8 100755 --- a/apps/coordinator-api/src/app/services/usage_tracking.py +++ b/apps/coordinator-api/src/app/services/usage_tracking.py @@ -5,7 +5,7 @@ Usage tracking and billing metrics service for multi-tenant AITBC coordinator import asyncio from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from typing import Any @@ -109,8 +109,8 @@ class UsageTrackingService: unit_price=unit_price, total_cost=total_cost, currency="USD", - usage_start=datetime.utcnow(), - usage_end=datetime.utcnow(), + usage_start=datetime.now(datetime.UTC), + usage_end=datetime.now(datetime.UTC), job_id=job_id, metadata=metadata or {}, ) @@ -128,7 +128,7 @@ class UsageTrackingService: unit_price=unit_price, total_amount=total_cost, currency="USD", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), metadata=metadata or {}, ) ) @@ -248,7 +248,7 @@ class UsageTrackingService: # Default to last 30 days if not end_date: - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) if not start_date: start_date = end_date - timedelta(days=30) @@ -431,7 +431,7 @@ class UsageTrackingService: raise TenantError(f"Tenant not found: {tenant_id}") # Generate number: INV-{tenant.slug}-{YYYYMMDD}-{seq} - date_str = datetime.utcnow().strftime("%Y%m%d") + date_str = datetime.now(datetime.UTC).strftime("%Y%m%d") # Get sequence for today # In a real implementation, use Redis or sequence table @@ -608,7 +608,7 @@ class BillingScheduler: await self._process_pending_events() # Wait until next day - now = datetime.utcnow() + now = datetime.now(datetime.UTC) next_day = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0) sleep_seconds = (next_day - now).total_seconds() await asyncio.sleep(sleep_seconds) @@ -622,7 +622,7 @@ class BillingScheduler: while self.running: try: # Wait until first day of month - now = datetime.utcnow() + now = datetime.now(datetime.UTC) if now.day != 1: next_month = now.replace(day=1) + timedelta(days=32) next_month = next_month.replace(day=1) @@ -645,7 +645,7 @@ class BillingScheduler: async def _reset_daily_quotas(self): """Reset used_value to 0 for all expired daily quotas and advance their period.""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) stmt = select(TenantQuota).where( and_( TenantQuota.period_type == "daily", @@ -671,7 +671,7 @@ class BillingScheduler: async def _generate_monthly_invoices(self): """Generate invoices for all active tenants for the previous month.""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) # Previous month boundaries first_of_this_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) last_month_end = first_of_this_month - timedelta(seconds=1) diff --git a/apps/coordinator-api/src/app/settlement/bridges/base.py b/apps/coordinator-api/src/app/settlement/bridges/base.py index b7ae75c9..29815bb5 100755 --- a/apps/coordinator-api/src/app/settlement/bridges/base.py +++ b/apps/coordinator-api/src/app/settlement/bridges/base.py @@ -5,7 +5,7 @@ Base interfaces for cross-chain settlement bridges import json from abc import ABC, abstractmethod from dataclasses import dataclass -from datetime import datetime +from datetime import datetime, UTC from enum import Enum from typing import Any @@ -51,7 +51,7 @@ class SettlementMessage: def __post_init__(self): if self.created_at is None: - self.created_at = datetime.utcnow() + self.created_at = datetime.now(datetime.UTC) @dataclass @@ -69,7 +69,7 @@ class SettlementResult: def __post_init__(self): if self.created_at is None: - self.created_at = datetime.utcnow() + self.created_at = datetime.now(datetime.UTC) class BridgeAdapter(ABC): @@ -220,7 +220,7 @@ class EthereumBridge(BridgeAdapter): transaction_hash="0x" + "0" * 64, # Mock hash gas_used=gas_estimate, fee_paid=int(self.config.default_fee), - completed_at=datetime.utcnow() + completed_at=datetime.now(datetime.UTC) ) return result diff --git a/apps/coordinator-api/src/app/settlement/hooks.py b/apps/coordinator-api/src/app/settlement/hooks.py index f3192e65..2e3f1d14 100755 --- a/apps/coordinator-api/src/app/settlement/hooks.py +++ b/apps/coordinator-api/src/app/settlement/hooks.py @@ -3,7 +3,7 @@ Settlement hooks for coordinator API integration """ import asyncio -from datetime import datetime +from datetime import datetime, UTC from typing import Any from aitbc import get_logger @@ -210,7 +210,7 @@ class SettlementHook: """Generate a unique nonce for settlement""" # This would generate a unique nonce # For now, use timestamp - return int(datetime.utcnow().timestamp()) + return int(datetime.now(datetime.UTC).timestamp()) async def _sign_settlement_message(self, job: Job) -> str: """Sign the settlement message""" diff --git a/apps/coordinator-api/src/app/settlement/manager.py b/apps/coordinator-api/src/app/settlement/manager.py index 26c51a59..1b8c6a96 100755 --- a/apps/coordinator-api/src/app/settlement/manager.py +++ b/apps/coordinator-api/src/app/settlement/manager.py @@ -4,7 +4,7 @@ Bridge manager for cross-chain settlements import asyncio from dataclasses import asdict -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from .bridges.base import BridgeAdapter, BridgeConfig, BridgeError, BridgeStatus, SettlementMessage, SettlementResult @@ -240,9 +240,9 @@ class BridgeManager: async def _monitor_settlement(self, message_id: str) -> None: """Monitor settlement until completion""" max_wait_time = timedelta(hours=1) - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) - while datetime.utcnow() - start_time < max_wait_time: + while datetime.now(datetime.UTC) - start_time < max_wait_time: # Check status result = await self.get_settlement_status(message_id) diff --git a/apps/coordinator-api/src/app/settlement/storage.py b/apps/coordinator-api/src/app/settlement/storage.py index 8ac5ac0a..c28893cf 100755 --- a/apps/coordinator-api/src/app/settlement/storage.py +++ b/apps/coordinator-api/src/app/settlement/storage.py @@ -4,7 +4,7 @@ Storage layer for cross-chain settlements import asyncio import json -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from .bridges.base import BridgeStatus, SettlementMessage @@ -49,7 +49,7 @@ class SettlementStorage: message.signature, bridge_name, status.value, - message.created_at or datetime.utcnow(), + message.created_at or datetime.now(datetime.UTC), ), ) @@ -90,7 +90,7 @@ class SettlementStorage: return updates.append(f"updated_at = ${param_count}") - params.append(datetime.utcnow()) + params.append(datetime.now(datetime.UTC)) param_count += 1 params.append(message_id) @@ -258,8 +258,8 @@ class InMemorySettlementStorage(SettlementStorage): "signature": message.signature, "bridge_name": bridge_name, "status": status.value, - "created_at": message.created_at or datetime.utcnow(), - "updated_at": datetime.utcnow(), + "created_at": message.created_at or datetime.now(datetime.UTC), + "updated_at": datetime.now(datetime.UTC), } async def update_settlement( @@ -285,7 +285,7 @@ class InMemorySettlementStorage(SettlementStorage): if completed_at is not None: settlement["completed_at"] = completed_at - settlement["updated_at"] = datetime.utcnow() + settlement["updated_at"] = datetime.now(datetime.UTC) async def get_settlement(self, message_id: str) -> dict[str, Any] | None: async with self._lock: @@ -316,7 +316,7 @@ class InMemorySettlementStorage(SettlementStorage): # Time range filtering if time_range is not None: - cutoff = datetime.utcnow() - timedelta(hours=time_range) + cutoff = datetime.now(datetime.UTC) - timedelta(hours=time_range) if settlement["created_at"] < cutoff: continue @@ -345,7 +345,7 @@ class InMemorySettlementStorage(SettlementStorage): async def cleanup_old_settlements(self, days: int = 30) -> int: async with self._lock: - cutoff = datetime.utcnow() - timedelta(days=days) + cutoff = datetime.now(datetime.UTC) - timedelta(days=days) to_delete = [ msg_id diff --git a/apps/coordinator-api/src/app/storage/db_pg.py b/apps/coordinator-api/src/app/storage/db_pg.py index d6f41f4b..6148a0bf 100755 --- a/apps/coordinator-api/src/app/storage/db_pg.py +++ b/apps/coordinator-api/src/app/storage/db_pg.py @@ -13,7 +13,7 @@ from sqlalchemy.orm import Session, sessionmaker from aitbc import get_logger logger = get_logger(__name__) -from datetime import datetime +from datetime import datetime, UTC from .config_pg import settings @@ -237,6 +237,6 @@ def check_db_health() -> dict[str, Any]: try: adapter = get_db_adapter() adapter.execute_query("SELECT 1 as health_check") - return {"status": "healthy", "database": "postgresql", "timestamp": datetime.utcnow().isoformat()} + return {"status": "healthy", "database": "postgresql", "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()} diff --git a/apps/coordinator-api/src/app/utils/alerting.py b/apps/coordinator-api/src/app/utils/alerting.py index e6d7eb60..097c602c 100644 --- a/apps/coordinator-api/src/app/utils/alerting.py +++ b/apps/coordinator-api/src/app/utils/alerting.py @@ -1,7 +1,7 @@ import json import os from collections import deque -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Any from urllib import error, request @@ -36,7 +36,7 @@ class AlertDispatcher: try: self._deliver(name, alert) - self._last_sent[name] = datetime.utcnow() + self._last_sent[name] = datetime.now(datetime.UTC) results["sent"].append(name) self._record_alert(name, alert, delivery_status="sent") except Exception as exc: @@ -62,7 +62,7 @@ class AlertDispatcher: last_sent = self._last_sent.get(name) if last_sent is None: return False - return datetime.utcnow() - last_sent < timedelta(seconds=self.cooldown_seconds) + return datetime.now(datetime.UTC) - last_sent < timedelta(seconds=self.cooldown_seconds) def _record_alert( self, @@ -71,9 +71,9 @@ class AlertDispatcher: delivery_status: str, error_message: str | None = None, ) -> None: - timestamp = datetime.utcnow().isoformat() + timestamp = datetime.now(datetime.UTC).isoformat() record = { - "id": f"metrics_alert_{name}_{int(datetime.utcnow().timestamp() * 1000)}", + "id": f"metrics_alert_{name}_{int(datetime.now(datetime.UTC).timestamp() * 1000)}", "deployment_id": None, "severity": alert.get("status", "critical"), "message": f"Threshold triggered for {name}", @@ -96,7 +96,7 @@ class AlertDispatcher: "status": alert.get("status", "critical"), "value": alert.get("value"), "threshold": alert.get("threshold"), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } if webhook_url: diff --git a/apps/coordinator-api/src/app/utils/metrics.py b/apps/coordinator-api/src/app/utils/metrics.py index bf250b1e..b6fa4bf2 100644 --- a/apps/coordinator-api/src/app/utils/metrics.py +++ b/apps/coordinator-api/src/app/utils/metrics.py @@ -5,7 +5,7 @@ Collects and tracks system and application metrics for monitoring import os import resource -from datetime import datetime +from datetime import datetime, UTC from typing import Any from aitbc import get_logger @@ -29,7 +29,7 @@ class MetricsCollector: "memory_usage_mb": 0, "cpu_usage_percent": 0.0, } - self._start_time = datetime.utcnow() + self._start_time = datetime.now(datetime.UTC) def increment_api_requests(self) -> None: """Increment API request counter""" @@ -103,7 +103,7 @@ class MetricsCollector: if self._metrics["api_requests"] > 0: error_rate = (self._metrics["api_errors"] / self._metrics["api_requests"]) * 100 - uptime_seconds = (datetime.utcnow() - self._start_time).total_seconds() + uptime_seconds = (datetime.now(datetime.UTC) - self._start_time).total_seconds() return { **self._metrics, @@ -113,7 +113,7 @@ class MetricsCollector: "alerts": self.get_alert_states(), "uptime_seconds": uptime_seconds, "uptime_formatted": self._format_uptime(uptime_seconds), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } def _format_uptime(self, seconds: float) -> str: @@ -155,7 +155,7 @@ class MetricsCollector: "memory_usage_mb": 0, "cpu_usage_percent": 0.0, } - self._start_time = datetime.utcnow() + self._start_time = datetime.now(datetime.UTC) # Global metrics collector instance diff --git a/apps/coordinator-api/tests/test_agent_identity_sdk.py b/apps/coordinator-api/tests/test_agent_identity_sdk.py index 7122baa7..eb75d335 100755 --- a/apps/coordinator-api/tests/test_agent_identity_sdk.py +++ b/apps/coordinator-api/tests/test_agent_identity_sdk.py @@ -7,7 +7,7 @@ import sys import pytest import asyncio from unittest.mock import AsyncMock, patch -from datetime import datetime +from datetime import datetime, UTC from app.agent_identity.sdk.client import AgentIdentityClient from app.agent_identity.sdk.models import ( @@ -328,16 +328,16 @@ class TestModels: status=IdentityStatus.ACTIVE, verification_level=VerificationType.BASIC, is_verified=True, - verified_at=datetime.utcnow(), + verified_at=datetime.now(datetime.UTC), supported_chains=['1', '137'], primary_chain=1, reputation_score=85.5, total_transactions=100, successful_transactions=95, success_rate=0.95, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow(), - last_activity=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + updated_at=datetime.now(datetime.UTC), + last_activity=datetime.now(datetime.UTC), metadata={'key': 'value'}, tags=['test', 'agent'] ) @@ -358,14 +358,14 @@ class TestModels: chain_type=ChainType.ETHEREUM, chain_address='0x123...', is_verified=True, - verified_at=datetime.utcnow(), + verified_at=datetime.now(datetime.UTC), wallet_address='0x456...', wallet_type='agent-wallet', chain_metadata={'test': 'data'}, - last_transaction=datetime.utcnow(), + last_transaction=datetime.now(datetime.UTC), transaction_count=10, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC), + updated_at=datetime.now(datetime.UTC) ) assert mapping.id == 'mapping_123' @@ -391,10 +391,10 @@ class TestModels: requires_multisig=False, multisig_threshold=1, multisig_signers=['0x123...'], - last_transaction=datetime.utcnow(), + last_transaction=datetime.now(datetime.UTC), transaction_count=5, - created_at=datetime.utcnow(), - updated_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC), + updated_at=datetime.now(datetime.UTC) ) assert wallet.id == 'wallet_123' diff --git a/apps/coordinator-api/tests/test_billing.py b/apps/coordinator-api/tests/test_billing.py index 84773dff..892a5735 100755 --- a/apps/coordinator-api/tests/test_billing.py +++ b/apps/coordinator-api/tests/test_billing.py @@ -7,7 +7,7 @@ import sys import asyncio import uuid -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from unittest.mock import MagicMock, AsyncMock, patch from dataclasses import dataclass @@ -51,9 +51,9 @@ class FakeQuota: def __post_init__(self): if self.period_start is None: - self.period_start = datetime.utcnow() - timedelta(hours=1) + self.period_start = datetime.now(datetime.UTC) - timedelta(hours=1) if self.period_end is None: - self.period_end = datetime.utcnow() + timedelta(hours=23) + self.period_end = datetime.now(datetime.UTC) + timedelta(hours=23) @dataclass @@ -93,7 +93,7 @@ class InMemoryBillingStore: return self.tenants.get(tenant_id) def get_active_quota(self, tenant_id: str, resource_type: str): - now = datetime.utcnow() + now = datetime.now(datetime.UTC) for q in self.quotas: if (q.tenant_id == tenant_id and q.resource_type == resource_type @@ -119,7 +119,7 @@ async def apply_credit(store: InMemoryBillingStore, tenant_id: str, amount: Deci "tenant_id": tenant_id, "amount": amount, "reason": reason, - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), }) return True @@ -138,7 +138,7 @@ async def apply_charge(store: InMemoryBillingStore, tenant_id: str, amount: Deci "tenant_id": tenant_id, "amount": amount, "reason": reason, - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), }) return True @@ -161,7 +161,7 @@ async def adjust_quota( async def reset_daily_quotas(store: InMemoryBillingStore) -> int: """Reset used_value to 0 for all daily quotas whose period has ended.""" - now = datetime.utcnow() + now = datetime.now(datetime.UTC) count = 0 for q in store.quotas: if q.period_type == "daily" and q.is_active and q.period_end <= now: @@ -197,7 +197,7 @@ async def generate_monthly_invoices(store: InMemoryBillingStore) -> list[str]: if not tenant_usage: continue total = sum(r.total_cost for r in tenant_usage) - inv_id = f"INV-{tenant.slug}-{datetime.utcnow().strftime('%Y%m')}-{len(generated)+1:04d}" + inv_id = f"INV-{tenant.slug}-{datetime.now(datetime.UTC).strftime('%Y%m')}-{len(generated)+1:04d}" store.invoices_generated.append(inv_id) generated.append(inv_id) return generated @@ -254,8 +254,8 @@ def store(): id="q2", tenant_id="t1", resource_type="api_calls", limit_value=Decimal("10000"), used_value=Decimal("5000"), period_type="daily", - period_start=datetime.utcnow() - timedelta(days=2), - period_end=datetime.utcnow() - timedelta(hours=1), # expired + period_start=datetime.now(datetime.UTC) - timedelta(days=2), + period_end=datetime.now(datetime.UTC) - timedelta(hours=1), # expired )) return s @@ -345,7 +345,7 @@ class TestResetDailyQuotas: assert count == 1 # q2 is expired daily q2 = store.quotas[1] assert q2.used_value == Decimal("0") - assert q2.period_end > datetime.utcnow() + assert q2.period_end > datetime.now(datetime.UTC) @pytest.mark.asyncio async def test_does_not_reset_active_quotas(self, store): diff --git a/apps/exchange-integration/main.py b/apps/exchange-integration/main.py index 659a0a55..8bd87507 100755 --- a/apps/exchange-integration/main.py +++ b/apps/exchange-integration/main.py @@ -5,7 +5,7 @@ Handles real exchange connections and trading operations import asyncio import json -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path from typing import Dict, Any, List, Optional import aiohttp @@ -54,7 +54,7 @@ async def root(): return { "service": "AITBC Exchange Integration", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -83,7 +83,7 @@ async def register_exchange(registration: ExchangeRegistration): "sandbox": registration.sandbox, "description": registration.description, "connected": False, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "last_sync": None, "trading_pairs": [] } @@ -116,7 +116,7 @@ async def connect_exchange(exchange_id: str): await asyncio.sleep(1) # Simulate connection delay exchange["connected"] = True - exchange["last_sync"] = datetime.utcnow().isoformat() + exchange["last_sync"] = datetime.now(datetime.UTC).isoformat() logger.info(f"Exchange connected: {exchange_id}") @@ -144,7 +144,7 @@ async def create_trading_pair(pair: TradingPair): "price_precision": pair.price_precision, "quantity_precision": pair.quantity_precision, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "current_price": None, "volume_24h": 0.0, "orders": [] @@ -186,7 +186,7 @@ async def create_order(order: OrderRequest): raise HTTPException(status_code=404, detail="Trading pair not found") # Generate order ID - order_id = f"order_{int(datetime.utcnow().timestamp())}" + order_id = f"order_{int(datetime.now(datetime.UTC).timestamp())}" # Create order order_data = { @@ -197,7 +197,7 @@ async def create_order(order: OrderRequest): "quantity": order.quantity, "price": order.price, "status": "submitted", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "filled_quantity": 0.0, "remaining_quantity": order.quantity, "average_price": None @@ -216,7 +216,7 @@ async def create_order(order: OrderRequest): order_data["filled_quantity"] = order.quantity order_data["remaining_quantity"] = 0.0 order_data["average_price"] = order.price or 0.00001 # Default price for demo - order_data["filled_at"] = datetime.utcnow().isoformat() + order_data["filled_at"] = datetime.now(datetime.UTC).isoformat() logger.info(f"Order created and filled: {order_id}") @@ -263,7 +263,7 @@ async def update_market_price(pair_id: str, price_data: Dict[str, Any]): pair = trading_pairs[pair_id] pair["current_price"] = price_data.get("price") pair["volume_24h"] = price_data.get("volume", pair["volume_24h"]) - pair["last_price_update"] = datetime.utcnow().isoformat() + pair["last_price_update"] = datetime.now(datetime.UTC).isoformat() return { "pair_id": pair_id, @@ -286,7 +286,7 @@ async def get_market_data(): return { "market_data": market_data, "total_pairs": len(market_data), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Background task for simulating market data @@ -305,7 +305,7 @@ async def simulate_market_data(): pair["current_price"] = new_price pair["volume_24h"] += random.uniform(100, 1000) - pair["last_price_update"] = datetime.utcnow().isoformat() + pair["last_price_update"] = datetime.now(datetime.UTC).isoformat() # Start background task on startup @app.on_event("startup") diff --git a/apps/exchange/exchange_api.py b/apps/exchange/exchange_api.py index b233a8a9..909dc6db 100755 --- a/apps/exchange/exchange_api.py +++ b/apps/exchange/exchange_api.py @@ -3,7 +3,7 @@ FastAPI backend for the AITBC Trade Exchange """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import List, Optional from fastapi import FastAPI, Depends, HTTPException, status, Header from fastapi.middleware.cors import CORSMiddleware @@ -123,7 +123,7 @@ def create_mock_trades(db: Session): import random # Create mock trades over the last hour - now = datetime.utcnow() + now = datetime.now(datetime.UTC) trades = [] for i in range(20): @@ -278,7 +278,7 @@ def try_match_order(order: Order, db: Session): amount=trade_amount, price=match.price, total=trade_total, - trade_hash=f"trade_{datetime.utcnow().timestamp()}" + trade_hash=f"trade_{datetime.now(datetime.UTC).timestamp()}" ) db.add(trade) @@ -344,7 +344,7 @@ def logout_user(token: str = Header(..., alias="Authorization")): @app.get("/api/health") 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 diff --git a/apps/exchange/real_exchange_integration.py b/apps/exchange/real_exchange_integration.py index 30ee558b..2d376e5c 100755 --- a/apps/exchange/real_exchange_integration.py +++ b/apps/exchange/real_exchange_integration.py @@ -8,7 +8,7 @@ import asyncio import ccxt import json import time -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Dict, List, Optional, Any, Tuple from dataclasses import dataclass from enum import Enum @@ -105,7 +105,7 @@ class RealExchangeManager: self.health_status[exchange_name] = ExchangeHealth( status=ExchangeStatus.CONNECTED, latency_ms=0.0, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) logger.info(f"✅ Connected to {exchange_name}") @@ -116,7 +116,7 @@ class RealExchangeManager: self.health_status[exchange_name] = ExchangeHealth( status=ExchangeStatus.ERROR, latency_ms=0.0, - last_check=datetime.utcnow(), + last_check=datetime.now(datetime.UTC), error_message=str(e) ) return False diff --git a/apps/exchange/scripts/seed_market.py b/apps/exchange/scripts/seed_market.py index d5d83a53..bfbdfa0b 100755 --- a/apps/exchange/scripts/seed_market.py +++ b/apps/exchange/scripts/seed_market.py @@ -2,7 +2,7 @@ """Seed initial market price for the exchange""" import sqlite3 -from datetime import datetime +from datetime import datetime, UTC from aitbc.constants import DATA_DIR def seed_initial_price(): @@ -27,7 +27,7 @@ def seed_initial_price(): cursor.execute(''' INSERT INTO trades (amount, price, total, created_at) VALUES (?, ?, ?, ?) - ''', (amount, price, total, datetime.utcnow())) + ''', (amount, price, total, datetime.now(datetime.UTC))) # Also create some initial orders for liquidity initial_orders = [ diff --git a/apps/exchange/simple_exchange_api.py b/apps/exchange/simple_exchange_api.py index 081962e2..50578b80 100755 --- a/apps/exchange/simple_exchange_api.py +++ b/apps/exchange/simple_exchange_api.py @@ -5,7 +5,7 @@ Simple FastAPI backend for the AITBC Trade Exchange (Python 3.13 compatible) import sqlite3 import json -from datetime import datetime +from datetime import datetime, UTC from http.server import HTTPServer, BaseHTTPRequestHandler import urllib.parse import random @@ -84,7 +84,7 @@ def create_mock_trades(): return # Create mock trades - now = datetime.utcnow() + now = datetime.now(datetime.UTC) for i in range(20): amount = random.uniform(10, 500) price = random.uniform(0.000009, 0.000012) @@ -477,7 +477,7 @@ class ExchangeAPIHandler(BaseHTTPRequestHandler): """Health check""" self.send_json_response({ 'status': 'ok', - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) def handle_wallet_balance(self): diff --git a/apps/exchange/simple_exchange_api_pg.py b/apps/exchange/simple_exchange_api_pg.py index 0c2425ca..8b49ac30 100755 --- a/apps/exchange/simple_exchange_api_pg.py +++ b/apps/exchange/simple_exchange_api_pg.py @@ -7,7 +7,7 @@ import json import urllib.request import psycopg2 from psycopg2.extras import RealDictCursor -from datetime import datetime +from datetime import datetime, UTC from decimal import Decimal import random @@ -151,7 +151,7 @@ class ExchangeAPIHandler(BaseHTTPRequestHandler): self.send_json_response({ 'status': 'ok', 'database': 'postgresql', - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() }) except Exception as e: self.send_json_response({ diff --git a/apps/exchange/tests/test_edge_cases_exchange.py b/apps/exchange/tests/test_edge_cases_exchange.py index 60bb33fa..9617e55c 100644 --- a/apps/exchange/tests/test_edge_cases_exchange.py +++ b/apps/exchange/tests/test_edge_cases_exchange.py @@ -7,7 +7,7 @@ from pathlib import Path from exchange_api import OrderCreate, OrderResponse, TradeResponse, OrderBookResponse -from datetime import datetime +from datetime import datetime, UTC @pytest.mark.unit @@ -55,7 +55,7 @@ def test_order_response_zero_remaining(): filled=100.0, remaining=0.0, status="FILLED", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) assert order.remaining == 0.0 assert order.status == "FILLED" @@ -73,7 +73,7 @@ def test_order_response_empty_status(): filled=0.0, remaining=100.0, status="", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) assert order.status == "" @@ -86,7 +86,7 @@ def test_trade_response_zero_amount(): amount=0.0, price=0.00001, total=0.0, - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) assert trade.amount == 0.0 assert trade.total == 0.0 @@ -103,7 +103,7 @@ def test_order_book_empty_buys(): @pytest.mark.unit def test_order_book_empty_sells(): """Test OrderBookResponse with empty sells""" - from datetime import datetime + from datetime import datetime, UTC buy_order = OrderResponse( id=1, order_type="BUY", @@ -113,7 +113,7 @@ def test_order_book_empty_sells(): filled=0.0, remaining=100.0, status="OPEN", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) orderbook = OrderBookResponse(buys=[buy_order], sells=[]) assert len(orderbook.buys) == 1 diff --git a/apps/exchange/tests/test_unit_exchange.py b/apps/exchange/tests/test_unit_exchange.py index 9ae06517..e955d2e2 100644 --- a/apps/exchange/tests/test_unit_exchange.py +++ b/apps/exchange/tests/test_unit_exchange.py @@ -45,7 +45,7 @@ def test_order_create_model_sell(): @pytest.mark.unit def test_order_response_model(): """Test OrderResponse model""" - from datetime import datetime + from datetime import datetime, UTC order = OrderResponse( id=1, order_type="BUY", @@ -55,7 +55,7 @@ def test_order_response_model(): filled=0.0, remaining=100.0, status="OPEN", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) assert order.id == 1 assert order.order_type == "BUY" @@ -66,13 +66,13 @@ def test_order_response_model(): @pytest.mark.unit def test_trade_response_model(): """Test TradeResponse model""" - from datetime import datetime + from datetime import datetime, UTC trade = TradeResponse( id=1, amount=50.0, price=0.00001, total=0.0005, - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) assert trade.id == 1 assert trade.amount == 50.0 @@ -82,7 +82,7 @@ def test_trade_response_model(): @pytest.mark.unit def test_order_book_response_model(): """Test OrderBookResponse model""" - from datetime import datetime + from datetime import datetime, UTC buy_order = OrderResponse( id=1, order_type="BUY", @@ -92,7 +92,7 @@ def test_order_book_response_model(): filled=0.0, remaining=100.0, status="OPEN", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) sell_order = OrderResponse( id=2, @@ -103,7 +103,7 @@ def test_order_book_response_model(): filled=0.0, remaining=50.0, status="OPEN", - created_at=datetime.utcnow() + created_at=datetime.now(datetime.UTC) ) orderbook = OrderBookResponse(buys=[buy_order], sells=[sell_order]) assert len(orderbook.buys) == 1 diff --git a/apps/global-ai-agents/main.py b/apps/global-ai-agents/main.py index 5c2ea31e..af2fa11a 100755 --- a/apps/global-ai-agents/main.py +++ b/apps/global-ai-agents/main.py @@ -5,7 +5,7 @@ Handles cross-chain and cross-region AI agent communication with global optimiza 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 @@ -74,7 +74,7 @@ async def root(): return { "service": "AITBC Global AI Agent Communication Service", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -105,8 +105,8 @@ async def register_agent(agent: Agent): "languages": agent.languages, "specialization": agent.specialization, "performance_score": agent.performance_score, - "created_at": datetime.utcnow().isoformat(), - "last_active": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "last_active": datetime.now(datetime.UTC).isoformat(), "total_messages_sent": 0, "total_messages_received": 0, "collaborations_participated": 0, @@ -188,7 +188,7 @@ async def send_message(message: AgentMessage): "timestamp": message.timestamp.isoformat(), "encryption_key": message.encryption_key, "status": "delivered", - "delivered_at": datetime.utcnow().isoformat(), + "delivered_at": datetime.now(datetime.UTC).isoformat(), "read_at": None } @@ -285,16 +285,16 @@ async def create_collaboration(session: CollaborationSession): for participant_id in session.participants: message_record = { - "message_id": f"collab_{int(datetime.utcnow().timestamp())}", + "message_id": f"collab_{int(datetime.now(datetime.UTC).timestamp())}", "sender_id": "system", "recipient_id": participant_id, "message_type": "notification", "content": notification, "priority": "medium", "language": "english", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "status": "delivered", - "delivered_at": datetime.utcnow().isoformat() + "delivered_at": datetime.now(datetime.UTC).isoformat() } if participant_id not in agent_messages: @@ -330,11 +330,11 @@ async def send_collaboration_message(session_id: str, sender_id: str, content: D # Create collaboration message message_record = { - "message_id": f"collab_msg_{int(datetime.utcnow().timestamp())}", + "message_id": f"collab_msg_{int(datetime.now(datetime.UTC).timestamp())}", "sender_id": sender_id, "session_id": session_id, "content": content, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "type": "collaboration_message" } @@ -351,16 +351,16 @@ async def send_collaboration_message(session_id: str, sender_id: str, content: D } msg_record = { - "message_id": f"notif_{int(datetime.utcnow().timestamp())}", + "message_id": f"notif_{int(datetime.now(datetime.UTC).timestamp())}", "sender_id": "system", "recipient_id": participant_id, "message_type": "notification", "content": notification, "priority": "medium", "language": "english", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "status": "delivered", - "delivered_at": datetime.utcnow().isoformat() + "delivered_at": datetime.now(datetime.UTC).isoformat() } if participant_id not in agent_messages: @@ -381,7 +381,7 @@ async def record_agent_performance(performance: AgentPerformance): # Create performance record performance_record = { - "performance_id": f"perf_{int(datetime.utcnow().timestamp())}", + "performance_id": f"perf_{int(datetime.now(datetime.UTC).timestamp())}", "agent_id": performance.agent_id, "timestamp": performance.timestamp.isoformat(), "tasks_completed": performance.tasks_completed, @@ -421,7 +421,7 @@ async def get_agent_performance(agent_id: str, hours: int = 24): if agent_id not in global_agents: raise HTTPException(status_code=404, detail="Agent not found") - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) performance_records = agent_performance.get(agent_id, []) recent_performance = [ p for p in performance_records @@ -448,7 +448,7 @@ async def get_agent_performance(agent_id: str, hours: int = 24): "total_tasks_completed": int(total_tasks), "total_records": len(recent_performance) }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/network/dashboard") @@ -476,7 +476,7 @@ async def get_network_dashboard(): # Recent activity recent_messages = 0 - cutoff_time = datetime.utcnow() - timedelta(hours=1) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=1) for messages in agent_messages.values(): recent_messages += len([m for m in messages if datetime.fromisoformat(m["timestamp"]) > cutoff_time]) @@ -503,7 +503,7 @@ async def get_network_dashboard(): "total_tasks_completed": sum(a["tasks_completed"] for a in global_agents.values()) } }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/network/optimize") @@ -554,7 +554,7 @@ async def optimize_network(): return { "optimization_results": optimization_results, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Background task for network monitoring @@ -564,12 +564,12 @@ async def network_monitoring_task(): await asyncio.sleep(300) # Monitor every 5 minutes # Update network statistics - global_network_stats["last_update"] = datetime.utcnow().isoformat() + global_network_stats["last_update"] = datetime.now(datetime.UTC).isoformat() global_network_stats["total_agents"] = len(global_agents) global_network_stats["active_agents"] = len([a for a in global_agents.values() if a["status"] == "active"]) # Check for expired collaboration sessions - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) for session_id, session in collaboration_sessions.items(): if datetime.fromisoformat(session["expires_at"]) < current_time and session["status"] == "active": session["status"] = "expired" @@ -637,8 +637,8 @@ async def startup_event(): "languages": agent.languages, "specialization": agent.specialization, "performance_score": agent.performance_score, - "created_at": datetime.utcnow().isoformat(), - "last_active": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "last_active": datetime.now(datetime.UTC).isoformat(), "total_messages_sent": 0, "total_messages_received": 0, "collaborations_participated": 0, diff --git a/apps/global-ai-agents/tests/test_edge_cases_global_ai_agents.py b/apps/global-ai-agents/tests/test_edge_cases_global_ai_agents.py index 31ff91e4..68387c66 100644 --- a/apps/global-ai-agents/tests/test_edge_cases_global_ai_agents.py +++ b/apps/global-ai-agents/tests/test_edge_cases_global_ai_agents.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from main import app, Agent, AgentMessage, CollaborationSession, AgentPerformance, global_agents, agent_messages, collaboration_sessions, agent_performance @@ -64,7 +64,7 @@ def test_agent_performance_out_of_range_score(): """Test AgentPerformance with out of range scores""" performance = AgentPerformance( agent_id="agent_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), tasks_completed=10, response_time_ms=50.5, accuracy_score=2.0, @@ -86,7 +86,7 @@ def test_agent_message_empty_content(): content={}, priority="high", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert message.content == {} @@ -148,8 +148,8 @@ def test_send_collaboration_message_sender_not_participant(): participants=["agent_123"], session_type="research", objective="Research task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=1), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), status="active" ) client.post("/api/v1/collaborations/create", json=session.model_dump(mode='json')) diff --git a/apps/global-ai-agents/tests/test_integration_global_ai_agents.py b/apps/global-ai-agents/tests/test_integration_global_ai_agents.py index 535cbb4a..ce123959 100644 --- a/apps/global-ai-agents/tests/test_integration_global_ai_agents.py +++ b/apps/global-ai-agents/tests/test_integration_global_ai_agents.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from main import app, Agent, AgentMessage, CollaborationSession, AgentPerformance, global_agents, agent_messages, collaboration_sessions, agent_performance @@ -194,7 +194,7 @@ def test_send_direct_message(): content={"data": "test"}, priority="high", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/messages/send", json=message.model_dump(mode='json')) assert response.status_code == 200 @@ -241,7 +241,7 @@ def test_send_broadcast_message(): content={"data": "test"}, priority="medium", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/messages/send", json=message.model_dump(mode='json')) assert response.status_code == 200 @@ -261,7 +261,7 @@ def test_send_message_sender_not_found(): content={"data": "test"}, priority="high", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/messages/send", json=message.model_dump(mode='json')) assert response.status_code == 400 @@ -292,7 +292,7 @@ def test_send_message_recipient_not_found(): content={"data": "test"}, priority="high", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/messages/send", json=message.model_dump(mode='json')) assert response.status_code == 400 @@ -377,8 +377,8 @@ def test_create_collaboration(): participants=["agent_123", "agent_456"], session_type="task_force", objective="Complete task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=1), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), status="active" ) response = client.post("/api/v1/collaborations/create", json=session.model_dump(mode='json')) @@ -396,8 +396,8 @@ def test_create_collaboration_participant_not_found(): participants=["nonexistent"], session_type="task_force", objective="Complete task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=1), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), status="active" ) response = client.post("/api/v1/collaborations/create", json=session.model_dump(mode='json')) @@ -427,8 +427,8 @@ def test_get_collaboration(): participants=["agent_123"], session_type="research", objective="Research task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=1), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), status="active" ) client.post("/api/v1/collaborations/create", json=session.model_dump(mode='json')) @@ -462,8 +462,8 @@ def test_send_collaboration_message(): participants=["agent_123"], session_type="research", objective="Research task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow() + timedelta(hours=1), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC) + timedelta(hours=1), status="active" ) client.post("/api/v1/collaborations/create", json=session.model_dump(mode='json')) @@ -493,7 +493,7 @@ def test_record_agent_performance(): performance = AgentPerformance( agent_id="agent_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), tasks_completed=10, response_time_ms=50.5, accuracy_score=0.95, @@ -513,7 +513,7 @@ def test_record_performance_agent_not_found(): client = TestClient(app) performance = AgentPerformance( agent_id="nonexistent", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), tasks_completed=10, response_time_ms=50.5, accuracy_score=0.95, diff --git a/apps/global-ai-agents/tests/test_unit_global_ai_agents.py b/apps/global-ai-agents/tests/test_unit_global_ai_agents.py index ca875ee6..008ea7d7 100644 --- a/apps/global-ai-agents/tests/test_unit_global_ai_agents.py +++ b/apps/global-ai-agents/tests/test_unit_global_ai_agents.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, Agent, AgentMessage, CollaborationSession, AgentPerformance @@ -67,7 +67,7 @@ def test_agent_message_model(): content={"data": "test"}, priority="high", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert message.message_id == "msg_123" assert message.sender_id == "agent_123" @@ -87,7 +87,7 @@ def test_agent_message_broadcast(): content={"data": "test"}, priority="medium", language="english", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert message.recipient_id is None @@ -100,8 +100,8 @@ def test_collaboration_session_model(): participants=["agent_123", "agent_456"], session_type="task_force", objective="Complete trading task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC), status="active" ) assert session.session_id == "session_123" @@ -117,8 +117,8 @@ def test_collaboration_session_empty_participants(): participants=[], session_type="research", objective="Research task", - created_at=datetime.utcnow(), - expires_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), + expires_at=datetime.now(datetime.UTC), status="active" ) assert session.participants == [] @@ -129,7 +129,7 @@ def test_agent_performance_model(): """Test AgentPerformance model""" performance = AgentPerformance( agent_id="agent_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), tasks_completed=10, response_time_ms=50.5, accuracy_score=0.95, @@ -147,7 +147,7 @@ def test_agent_performance_negative_values(): """Test AgentPerformance with negative values""" performance = AgentPerformance( agent_id="agent_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), tasks_completed=-10, response_time_ms=-50.5, accuracy_score=-0.95, diff --git a/apps/global-infrastructure/main.py b/apps/global-infrastructure/main.py index 6a43707f..1ca3caa2 100755 --- a/apps/global-infrastructure/main.py +++ b/apps/global-infrastructure/main.py @@ -5,7 +5,7 @@ Handles multi-region deployment, load balancing, and global optimization 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 @@ -72,7 +72,7 @@ async def root(): return { "service": "AITBC Global Infrastructure Service", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -103,7 +103,7 @@ async def register_region(region: Region): "current_load": region.current_load, "latency_ms": region.latency_ms, "compliance_level": region.compliance_level, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "last_health_check": None, "services_deployed": [], "performance_history": [] @@ -148,7 +148,7 @@ async def get_region(region_id: str): @app.post("/api/v1/deployments/create") async def create_deployment(deployment: GlobalDeployment): """Create a new global deployment""" - deployment_id = f"deploy_{int(datetime.utcnow().timestamp())}" + deployment_id = f"deploy_{int(datetime.now(datetime.UTC).timestamp())}" # Validate target regions for region_id in deployment.target_regions: @@ -164,7 +164,7 @@ async def create_deployment(deployment: GlobalDeployment): "deployment_strategy": deployment.deployment_strategy, "health_checks": deployment.health_checks, "status": "pending", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "started_at": None, "completed_at": None, "deployment_progress": {}, @@ -214,7 +214,7 @@ async def list_deployments(status: Optional[str] = None): @app.post("/api/v1/load-balancers/create") async def create_load_balancer(balancer: LoadBalancer): """Create a new load balancer""" - balancer_id = f"lb_{int(datetime.utcnow().timestamp())}" + balancer_id = f"lb_{int(datetime.now(datetime.UTC).timestamp())}" # Validate target regions for region_id in balancer.target_regions: @@ -230,7 +230,7 @@ async def create_load_balancer(balancer: LoadBalancer): "health_check_interval": balancer.health_check_interval, "failover_threshold": balancer.failover_threshold, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "current_weights": {region_id: 1.0 for region_id in balancer.target_regions}, "health_status": {region_id: "healthy" for region_id in balancer.target_regions}, "total_requests": 0, @@ -265,7 +265,7 @@ async def list_load_balancers(): async def record_performance_metrics(metrics: PerformanceMetrics): """Record performance metrics for a region""" metrics_record = { - "metrics_id": f"metrics_{int(datetime.utcnow().timestamp())}", + "metrics_id": f"metrics_{int(datetime.now(datetime.UTC).timestamp())}", "region_id": metrics.region_id, "timestamp": metrics.timestamp.isoformat(), "cpu_usage": metrics.cpu_usage, @@ -310,7 +310,7 @@ async def get_region_performance(region_id: str, hours: int = 24): if region_id not in performance_metrics: raise HTTPException(status_code=404, detail="No performance data for region") - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) recent_metrics = [ m for m in performance_metrics[region_id] if datetime.fromisoformat(m["timestamp"]) > cutoff_time @@ -334,7 +334,7 @@ async def get_region_performance(region_id: str, hours: int = 24): "average_response_time_ms": round(avg_response_time, 2), "total_samples": len(recent_metrics) }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/compliance/{region_id}") @@ -350,8 +350,8 @@ async def get_region_compliance(region_id: str): "compliance_level": global_regions[region_id]["compliance_level"], "certifications": ["SOC2", "ISO27001", "GDPR"], "data_residency": "compliant", - "last_audit": (datetime.utcnow() - timedelta(days=90)).isoformat(), - "next_audit": (datetime.utcnow() + timedelta(days=275)).isoformat(), + "last_audit": (datetime.now(datetime.UTC) - timedelta(days=90)).isoformat(), + "next_audit": (datetime.now(datetime.UTC) + timedelta(days=275)).isoformat(), "regulations": ["GDPR", "CCPA", "PDPA"], "data_protection": "end-to-end-encryption", "access_controls": "role-based-access", @@ -410,7 +410,7 @@ async def get_global_dashboard(): "partial_compliance": len([r for r in global_regions.values() if r["compliance_level"] == "partial"]) } }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Core deployment and load balancing functions @@ -418,13 +418,13 @@ async def execute_deployment(deployment_id: str): """Execute a global deployment""" deployment = deployments[deployment_id] deployment["status"] = "in_progress" - deployment["started_at"] = datetime.utcnow().isoformat() + deployment["started_at"] = datetime.now(datetime.UTC).isoformat() try: for region_id in deployment["target_regions"]: deployment["deployment_progress"][region_id] = { "status": "deploying", - "started_at": datetime.utcnow().isoformat(), + "started_at": datetime.now(datetime.UTC).isoformat(), "progress": 0 } @@ -433,7 +433,7 @@ async def execute_deployment(deployment_id: str): deployment["deployment_progress"][region_id].update({ "status": "completed", - "completed_at": datetime.utcnow().isoformat(), + "completed_at": datetime.now(datetime.UTC).isoformat(), "progress": 100 }) @@ -443,7 +443,7 @@ async def execute_deployment(deployment_id: str): global_regions[region_id]["services_deployed"].append(deployment["service_name"]) deployment["status"] = "completed" - deployment["completed_at"] = datetime.utcnow().isoformat() + deployment["completed_at"] = datetime.now(datetime.UTC).isoformat() logger.info(f"Deployment completed: {deployment_id}") @@ -516,7 +516,7 @@ async def global_monitoring_task(): await asyncio.sleep(60) # Monitor every minute # Update global monitoring data - global_monitoring["last_update"] = datetime.utcnow().isoformat() + global_monitoring["last_update"] = datetime.now(datetime.UTC).isoformat() global_monitoring["total_requests"] = sum(lb.get("total_requests", 0) for lb in load_balancers.values()) global_monitoring["failed_requests"] = sum(lb.get("failed_requests", 0) for lb in load_balancers.values()) @@ -582,7 +582,7 @@ async def startup_event(): "current_load": region.current_load, "latency_ms": region.latency_ms, "compliance_level": region.compliance_level, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "last_health_check": None, "services_deployed": [], "performance_history": [] diff --git a/apps/global-infrastructure/tests/test_edge_cases_global_infrastructure.py b/apps/global-infrastructure/tests/test_edge_cases_global_infrastructure.py index 9b37c59c..89e2e30d 100644 --- a/apps/global-infrastructure/tests/test_edge_cases_global_infrastructure.py +++ b/apps/global-infrastructure/tests/test_edge_cases_global_infrastructure.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, Region, GlobalDeployment, LoadBalancer, PerformanceMetrics, global_regions, deployments, load_balancers, performance_metrics @@ -93,7 +93,7 @@ def test_performance_metrics_negative_values(): """Test PerformanceMetrics with negative values""" metrics = PerformanceMetrics( region_id="us-east-1", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), cpu_usage=-50.5, memory_usage=-60.2, network_io=-1000.5, diff --git a/apps/global-infrastructure/tests/test_integration_global_infrastructure.py b/apps/global-infrastructure/tests/test_integration_global_infrastructure.py index 467bac78..a36aaff9 100644 --- a/apps/global-infrastructure/tests/test_integration_global_infrastructure.py +++ b/apps/global-infrastructure/tests/test_integration_global_infrastructure.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, Region, GlobalDeployment, LoadBalancer, PerformanceMetrics, global_regions, deployments, load_balancers, performance_metrics @@ -278,7 +278,7 @@ def test_record_performance_metrics(): client = TestClient(app) metrics = PerformanceMetrics( region_id="us-west-1", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), cpu_usage=50.5, memory_usage=60.2, network_io=1000.5, @@ -300,7 +300,7 @@ def test_get_region_performance(): # Record metrics first metrics = PerformanceMetrics( region_id="us-west-1", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), cpu_usage=50.5, memory_usage=60.2, network_io=1000.5, diff --git a/apps/global-infrastructure/tests/test_unit_global_infrastructure.py b/apps/global-infrastructure/tests/test_unit_global_infrastructure.py index 9e936b29..54bef964 100644 --- a/apps/global-infrastructure/tests/test_unit_global_infrastructure.py +++ b/apps/global-infrastructure/tests/test_unit_global_infrastructure.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, Region, GlobalDeployment, LoadBalancer, PerformanceMetrics @@ -78,7 +78,7 @@ def test_performance_metrics_model(): """Test PerformanceMetrics model""" metrics = PerformanceMetrics( region_id="us-east-1", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), cpu_usage=50.5, memory_usage=60.2, network_io=1000.5, diff --git a/apps/miner/production_miner.py b/apps/miner/production_miner.py index 430d5899..730761af 100755 --- a/apps/miner/production_miner.py +++ b/apps/miner/production_miner.py @@ -8,7 +8,7 @@ import time import sys import subprocess import os -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Optional from aitbc import get_logger, AITBCHTTPClient, NetworkError @@ -216,7 +216,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": gpu_info["utilization"], "memory_used": gpu_info["memory_used"], "memory_total": gpu_info["memory_total"], @@ -228,7 +228,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": 0, "memory_used": 0, "memory_total": 0, diff --git a/apps/miner/production_miner_fixed.py b/apps/miner/production_miner_fixed.py index 4d55db8c..d9778d97 100755 --- a/apps/miner/production_miner_fixed.py +++ b/apps/miner/production_miner_fixed.py @@ -8,7 +8,7 @@ import time import sys import subprocess import os -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Optional from aitbc import get_logger, AITBCHTTPClient, NetworkError, LOG_DIR @@ -209,7 +209,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": gpu_info["utilization"], "memory_used": gpu_info["memory_used"], "memory_total": gpu_info["memory_total"], @@ -221,7 +221,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": 0, "memory_used": 0, "memory_total": 0, diff --git a/apps/multi-region-load-balancer/main.py b/apps/multi-region-load-balancer/main.py index d1d8abce..4c49ad72 100755 --- a/apps/multi-region-load-balancer/main.py +++ b/apps/multi-region-load-balancer/main.py @@ -5,7 +5,7 @@ Handles intelligent load distribution across global regions 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 Multi-Region Load Balancer", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -99,10 +99,10 @@ async def create_load_balancing_rule(rule: LoadBalancingRule): "failover_enabled": rule.failover_enabled, "session_affinity": rule.session_affinity, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "total_requests": 0, "failed_requests": 0, - "last_updated": datetime.utcnow().isoformat() + "last_updated": datetime.now(datetime.UTC).isoformat() } load_balancing_rules[rule.rule_id] = rule_record @@ -167,7 +167,7 @@ async def update_rule_weights(rule_id: str, weights: Dict[str, float]): # Update rule weights rule["weights"] = normalized_weights - rule["last_updated"] = datetime.utcnow().isoformat() + rule["last_updated"] = datetime.now(datetime.UTC).isoformat() logger.info(f"Weights updated for rule {rule_id}: {normalized_weights}") @@ -193,7 +193,7 @@ async def register_region_health(health: RegionHealth): return { "region_id": health.region_id, "status": health.status, - "registered_at": datetime.utcnow().isoformat() + "registered_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/health") @@ -224,7 +224,7 @@ async def create_geographic_rule(rule: GeographicRule): "priority": rule.priority, "latency_threshold_ms": rule.latency_threshold_ms, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "usage_count": 0 } @@ -256,14 +256,14 @@ async def get_optimal_region(client_region: str, rule_id: Optional[str] = None): "optimal_region": optimal_region, "rule_id": rule_id, "selection_reason": get_selection_reason(optimal_region, client_region, rule_id), - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } @app.post("/api/v1/metrics/record") async def record_balancing_metrics(metrics: LoadBalancingMetrics): """Record load balancing performance metrics""" metrics_record = { - "metrics_id": f"metrics_{int(datetime.utcnow().timestamp())}", + "metrics_id": f"metrics_{int(datetime.now(datetime.UTC).timestamp())}", "balancer_id": metrics.balancer_id, "timestamp": metrics.timestamp.isoformat(), "total_requests": metrics.total_requests, @@ -294,7 +294,7 @@ async def get_balancing_metrics(rule_id: str, hours: int = 24): if rule_id not in load_balancing_rules: raise HTTPException(status_code=404, detail="Load balancing rule not found") - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) recent_metrics = [ m for m in balancing_metrics.get(rule_id, []) if datetime.fromisoformat(m["timestamp"]) > cutoff_time @@ -320,7 +320,7 @@ async def get_balancing_metrics(rule_id: str, hours: int = 24): "total_requests": int(total_requests), "total_samples": len(recent_metrics) }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/dashboard") @@ -368,7 +368,7 @@ async def get_load_balancing_dashboard(): "performance": performance_summary, "recent_activity": get_recent_activity() }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Core load balancing functions @@ -534,7 +534,7 @@ def get_recent_activity() -> List[Dict]: # Recent health changes for region_id, health in region_health_status.items(): - if (datetime.utcnow() - health.last_check).total_seconds() < 3600: # Last hour + if (datetime.now(datetime.UTC) - health.last_check).total_seconds() < 3600: # Last hour activity.append({ "type": "health_check", "region": region_id, @@ -544,7 +544,7 @@ def get_recent_activity() -> List[Dict]: # Recent rule updates for rule_id, rule in load_balancing_rules.items(): - if (datetime.utcnow() - datetime.fromisoformat(rule["last_updated"])).total_seconds() < 3600: + if (datetime.now(datetime.UTC) - datetime.fromisoformat(rule["last_updated"])).total_seconds() < 3600: activity.append({ "type": "rule_update", "rule_id": rule_id, @@ -598,7 +598,7 @@ async def check_region_health(region_id: str): response_time_ms=response_time, success_rate=success_rate, active_connections=active_connections, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) region_health_status[region_id] = health @@ -644,10 +644,10 @@ async def startup_event(): "failover_enabled": rule.failover_enabled, "session_affinity": rule.session_affinity, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "total_requests": 0, "failed_requests": 0, - "last_updated": datetime.utcnow().isoformat() + "last_updated": datetime.now(datetime.UTC).isoformat() } load_balancing_rules[rule.rule_id] = rule_record @@ -681,7 +681,7 @@ async def startup_event(): "priority": geo_rule.priority, "latency_threshold_ms": geo_rule.latency_threshold_ms, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "usage_count": 0 } geographic_rules[geo_rule.rule_id] = geo_rule_record diff --git a/apps/multi-region-load-balancer/tests/test_edge_cases_multi_region_load_balancer.py b/apps/multi-region-load-balancer/tests/test_edge_cases_multi_region_load_balancer.py index d2b1ca10..a7a7e9bf 100644 --- a/apps/multi-region-load-balancer/tests/test_edge_cases_multi_region_load_balancer.py +++ b/apps/multi-region-load-balancer/tests/test_edge_cases_multi_region_load_balancer.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, LoadBalancingRule, RegionHealth, LoadBalancingMetrics, GeographicRule, load_balancing_rules, region_health_status, balancing_metrics, geographic_rules @@ -50,7 +50,7 @@ def test_region_health_negative_success_rate(): response_time_ms=45.5, success_rate=-0.5, active_connections=100, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) assert health.success_rate == -0.5 @@ -64,7 +64,7 @@ def test_region_health_negative_connections(): response_time_ms=45.5, success_rate=0.99, active_connections=-100, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) assert health.active_connections == -100 @@ -74,7 +74,7 @@ def test_load_balancing_metrics_negative_requests(): """Test LoadBalancingMetrics with negative requests""" metrics = LoadBalancingMetrics( balancer_id="lb_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), total_requests=-1000, requests_per_region={}, average_response_time=50.5, @@ -89,7 +89,7 @@ def test_load_balancing_metrics_negative_response_time(): """Test LoadBalancingMetrics with negative response time""" metrics = LoadBalancingMetrics( balancer_id="lb_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), total_requests=1000, requests_per_region={}, average_response_time=-50.5, diff --git a/apps/multi-region-load-balancer/tests/test_integration_multi_region_load_balancer.py b/apps/multi-region-load-balancer/tests/test_integration_multi_region_load_balancer.py index b0427c5f..8dc12312 100644 --- a/apps/multi-region-load-balancer/tests/test_integration_multi_region_load_balancer.py +++ b/apps/multi-region-load-balancer/tests/test_integration_multi_region_load_balancer.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, LoadBalancingRule, RegionHealth, LoadBalancingMetrics, GeographicRule, load_balancing_rules, region_health_status, balancing_metrics, geographic_rules @@ -193,7 +193,7 @@ def test_register_region_health(): response_time_ms=45.5, success_rate=0.99, active_connections=100, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) response = client.post("/api/v1/health/register", json=health.model_dump(mode='json')) assert response.status_code == 200 @@ -286,7 +286,7 @@ def test_record_balancing_metrics(): client = TestClient(app) metrics = LoadBalancingMetrics( balancer_id="lb_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), total_requests=1000, requests_per_region={"us-east-1": 500}, average_response_time=50.5, diff --git a/apps/multi-region-load-balancer/tests/test_unit_multi_region_load_balancer.py b/apps/multi-region-load-balancer/tests/test_unit_multi_region_load_balancer.py index 538b592d..8052da6b 100644 --- a/apps/multi-region-load-balancer/tests/test_unit_multi_region_load_balancer.py +++ b/apps/multi-region-load-balancer/tests/test_unit_multi_region_load_balancer.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, LoadBalancingRule, RegionHealth, LoadBalancingMetrics, GeographicRule @@ -47,7 +47,7 @@ def test_region_health_model(): response_time_ms=45.5, success_rate=0.99, active_connections=100, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) assert health.region_id == "us-east-1" assert health.status == "healthy" @@ -61,7 +61,7 @@ def test_load_balancing_metrics_model(): """Test LoadBalancingMetrics model""" metrics = LoadBalancingMetrics( balancer_id="lb_123", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), total_requests=1000, requests_per_region={"us-east-1": 500, "eu-west-1": 500}, average_response_time=50.5, @@ -115,6 +115,6 @@ def test_region_health_negative_response_time(): response_time_ms=-45.5, success_rate=0.99, active_connections=100, - last_check=datetime.utcnow() + last_check=datetime.now(datetime.UTC) ) assert health.response_time_ms == -45.5 diff --git a/apps/plugin-analytics/main.py b/apps/plugin-analytics/main.py index aa2dd225..a0a54b09 100755 --- a/apps/plugin-analytics/main.py +++ b/apps/plugin-analytics/main.py @@ -5,7 +5,7 @@ Handles plugin analytics, usage tracking, and performance 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 @@ -66,7 +66,7 @@ async def root(): return { "service": "AITBC Plugin Analytics Service", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -85,7 +85,7 @@ async def health_check(): async def record_plugin_usage(usage: PluginUsage): """Record plugin usage event""" usage_record = { - "usage_id": f"usage_{int(datetime.utcnow().timestamp())}", + "usage_id": f"usage_{int(datetime.now(datetime.UTC).timestamp())}", "plugin_id": usage.plugin_id, "user_id": usage.user_id, "action": usage.action, @@ -113,7 +113,7 @@ async def record_plugin_usage(usage: PluginUsage): async def record_plugin_performance(performance: PluginPerformance): """Record plugin performance metrics""" performance_record = { - "performance_id": f"perf_{int(datetime.utcnow().timestamp())}", + "performance_id": f"perf_{int(datetime.now(datetime.UTC).timestamp())}", "plugin_id": performance.plugin_id, "version": performance.version, "cpu_usage": performance.cpu_usage, @@ -141,7 +141,7 @@ async def record_plugin_performance(performance: PluginPerformance): async def record_plugin_rating(rating: PluginRating): """Record plugin rating and review""" rating_record = { - "rating_id": f"rating_{int(datetime.utcnow().timestamp())}", + "rating_id": f"rating_{int(datetime.now(datetime.UTC).timestamp())}", "plugin_id": rating.plugin_id, "user_id": rating.user_id, "rating": rating.rating, @@ -166,7 +166,7 @@ async def record_plugin_rating(rating: PluginRating): async def record_plugin_event(event: PluginEvent): """Record generic plugin event""" event_record = { - "event_id": f"event_{int(datetime.utcnow().timestamp())}", + "event_id": f"event_{int(datetime.now(datetime.UTC).timestamp())}", "event_type": event.event_type, "plugin_id": event.plugin_id, "user_id": event.user_id, @@ -190,7 +190,7 @@ async def record_plugin_event(event: PluginEvent): @app.get("/api/v1/analytics/usage/{plugin_id}") async def get_plugin_usage(plugin_id: str, days: int = 30): """Get usage analytics for a specific plugin""" - cutoff_date = datetime.utcnow() - timedelta(days=days) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days) usage_records = plugin_usage_data.get(plugin_id, []) recent_usage = [r for r in usage_records @@ -204,13 +204,13 @@ async def get_plugin_usage(plugin_id: str, days: int = 30): "period_days": days, "usage_statistics": usage_stats, "total_records": len(recent_usage), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/performance/{plugin_id}") async def get_plugin_performance(plugin_id: str, hours: int = 24): """Get performance analytics for a specific plugin""" - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) performance_records = plugin_performance_data.get(plugin_id, []) recent_performance = [r for r in performance_records @@ -224,7 +224,7 @@ async def get_plugin_performance(plugin_id: str, hours: int = 24): "period_hours": hours, "performance_statistics": performance_stats, "total_records": len(recent_performance), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/ratings/{plugin_id}") @@ -240,7 +240,7 @@ async def get_plugin_ratings(plugin_id: str): "rating_statistics": rating_stats, "total_ratings": len(rating_records), "recent_ratings": rating_records[-10:], # Last 10 ratings - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/dashboard") @@ -257,7 +257,7 @@ async def get_analytics_dashboard(): return { "dashboard": dashboard_data, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/trends") @@ -398,7 +398,7 @@ def get_overview_statistics() -> Dict[str, Any]: total_ratings = sum(len(data) for data in plugin_ratings.values()) # Calculate active plugins (plugins with usage in last 7 days) - cutoff_date = datetime.utcnow() - timedelta(days=7) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=7) active_plugins = 0 for plugin_id, usage_records in plugin_usage_data.items(): @@ -417,7 +417,7 @@ def get_overview_statistics() -> Dict[str, Any]: def get_trending_plugins(limit: int = 10) -> List[Dict]: """Get trending plugins based on recent usage""" - cutoff_date = datetime.utcnow() - timedelta(days=7) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=7) plugin_scores = [] @@ -443,7 +443,7 @@ def get_trending_plugins(limit: int = 10) -> List[Dict]: def get_global_usage_trends(days: int = 30) -> Dict[str, Any]: """Get global usage trends""" - cutoff_date = datetime.utcnow() - timedelta(days=days) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days) global_trends = {} for plugin_id, usage_records in plugin_usage_data.items(): @@ -541,14 +541,14 @@ def get_plugin_trends(plugin_id: str, days: int) -> Dict[str, Any]: """Get trends for a specific plugin""" plugin_trends = usage_trends.get(plugin_id, {}) - cutoff_date = datetime.utcnow() - timedelta(days=days) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days) date_key = cutoff_date.date().isoformat() return { "plugin_id": plugin_id, "trends": plugin_trends, "period_days": days, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Report generation functions @@ -581,7 +581,7 @@ def generate_summary_report(plugin_id: Optional[str] = None) -> Dict[str, Any]: "usage": get_plugin_usage(plugin_id, days=30), "performance": get_plugin_performance(plugin_id, hours=24), "ratings": get_plugin_ratings(plugin_id), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } else: return get_analytics_dashboard() @@ -613,7 +613,7 @@ def update_analytics_cache(): def cleanup_old_data(): """Clean up old analytics data""" - cutoff_date = datetime.utcnow() - timedelta(days=90) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=90) cutoff_iso = cutoff_date.isoformat() # Clean usage data diff --git a/apps/plugin-analytics/tests/test_edge_cases_plugin_analytics.py b/apps/plugin-analytics/tests/test_edge_cases_plugin_analytics.py index eae0c6fb..8caa83c2 100644 --- a/apps/plugin-analytics/tests/test_edge_cases_plugin_analytics.py +++ b/apps/plugin-analytics/tests/test_edge_cases_plugin_analytics.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginUsage, PluginPerformance, PluginRating, PluginEvent, plugin_usage_data, plugin_performance_data, plugin_ratings, plugin_events @@ -32,7 +32,7 @@ def test_plugin_usage_empty_plugin_id(): plugin_id="", user_id="user_123", action="install", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert usage.plugin_id == "" @@ -48,7 +48,7 @@ def test_plugin_performance_negative_values(): response_time=-0.1, error_rate=-0.01, uptime=-50.0, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert perf.cpu_usage == -10.0 assert perf.memory_usage == -5.0 @@ -61,7 +61,7 @@ def test_plugin_rating_out_of_range(): plugin_id="plugin_123", user_id="user_123", rating=10, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert rating.rating == 10 @@ -73,7 +73,7 @@ def test_plugin_rating_zero(): plugin_id="plugin_123", user_id="user_123", rating=0, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert rating.rating == 0 @@ -128,7 +128,7 @@ def test_record_multiple_usage_events(): plugin_id="plugin_123", user_id=f"user_{i}", action="use", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/analytics/usage", json=usage.model_dump(mode='json')) diff --git a/apps/plugin-analytics/tests/test_integration_plugin_analytics.py b/apps/plugin-analytics/tests/test_integration_plugin_analytics.py index 34dade28..544f054a 100644 --- a/apps/plugin-analytics/tests/test_integration_plugin_analytics.py +++ b/apps/plugin-analytics/tests/test_integration_plugin_analytics.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginUsage, PluginPerformance, PluginRating, PluginEvent, plugin_usage_data, plugin_performance_data, plugin_ratings, plugin_events @@ -56,7 +56,7 @@ def test_record_plugin_usage(): plugin_id="plugin_123", user_id="user_123", action="install", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/analytics/usage", json=usage.model_dump(mode='json')) assert response.status_code == 200 @@ -77,7 +77,7 @@ def test_record_plugin_performance(): response_time=0.123, error_rate=0.001, uptime=99.9, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/analytics/performance", json=perf.model_dump(mode='json')) assert response.status_code == 200 @@ -95,7 +95,7 @@ def test_record_plugin_rating(): user_id="user_123", rating=5, review="Great plugin!", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/analytics/rating", json=rating.model_dump(mode='json')) assert response.status_code == 200 @@ -113,7 +113,7 @@ def test_record_plugin_event(): plugin_id="plugin_123", user_id="user_123", data={"error": "timeout"}, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/analytics/event", json=event.model_dump(mode='json')) assert response.status_code == 200 @@ -131,7 +131,7 @@ def test_get_plugin_usage(): plugin_id="plugin_123", user_id="user_123", action="install", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/analytics/usage", json=usage.model_dump(mode='json')) @@ -155,7 +155,7 @@ def test_get_plugin_performance(): response_time=0.123, error_rate=0.001, uptime=99.9, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/analytics/performance", json=perf.model_dump(mode='json')) @@ -175,7 +175,7 @@ def test_get_plugin_ratings(): plugin_id="plugin_123", user_id="user_123", rating=5, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/analytics/rating", json=rating.model_dump(mode='json')) diff --git a/apps/plugin-analytics/tests/test_unit_plugin_analytics.py b/apps/plugin-analytics/tests/test_unit_plugin_analytics.py index c7a39d97..95928bf3 100644 --- a/apps/plugin-analytics/tests/test_unit_plugin_analytics.py +++ b/apps/plugin-analytics/tests/test_unit_plugin_analytics.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginUsage, PluginPerformance, PluginRating, PluginEvent @@ -25,7 +25,7 @@ def test_plugin_usage_model(): plugin_id="plugin_123", user_id="user_123", action="install", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), metadata={"source": "marketplace"} ) assert usage.plugin_id == "plugin_123" @@ -41,7 +41,7 @@ def test_plugin_usage_defaults(): plugin_id="plugin_123", user_id="user_123", action="use", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert usage.metadata == {} @@ -57,7 +57,7 @@ def test_plugin_performance_model(): response_time=0.123, error_rate=0.001, uptime=99.9, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert perf.plugin_id == "plugin_123" assert perf.version == "1.0.0" @@ -76,7 +76,7 @@ def test_plugin_rating_model(): user_id="user_123", rating=5, review="Great plugin!", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert rating.plugin_id == "plugin_123" assert rating.rating == 5 @@ -90,7 +90,7 @@ def test_plugin_rating_defaults(): plugin_id="plugin_123", user_id="user_123", rating=4, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert rating.review is None @@ -103,7 +103,7 @@ def test_plugin_event_model(): plugin_id="plugin_123", user_id="user_123", data={"error": "timeout"}, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert event.event_type == "error" assert event.plugin_id == "plugin_123" @@ -117,7 +117,7 @@ def test_plugin_event_defaults(): event = PluginEvent( event_type="info", plugin_id="plugin_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert event.user_id is None assert event.data == {} diff --git a/apps/plugin-marketplace/main.py b/apps/plugin-marketplace/main.py index 7756bdb8..080d3f6f 100755 --- a/apps/plugin-marketplace/main.py +++ b/apps/plugin-marketplace/main.py @@ -5,7 +5,7 @@ Provides web interface and marketplace functionality for plugins 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, Request @@ -120,7 +120,7 @@ async def get_featured_plugins_api(): """Get featured plugins for marketplace""" return { "featured_plugins": get_featured_plugins(), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/marketplace/popular") @@ -128,7 +128,7 @@ async def get_popular_plugins_api(limit: int = 12): """Get popular plugins""" return { "popular_plugins": get_popular_plugins(limit), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/marketplace/recent") @@ -136,7 +136,7 @@ async def get_recent_plugins_api(limit: int = 12): """Get recently added plugins""" return { "recent_plugins": get_recent_plugins(limit), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/marketplace/stats") @@ -144,13 +144,13 @@ async def get_marketplace_stats_api(): """Get marketplace statistics""" return { "stats": get_marketplace_stats(), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.post("/api/v1/reviews") async def create_review(review: MarketplaceReview): """Create a plugin review""" - review_id = f"review_{int(datetime.utcnow().timestamp())}" + review_id = f"review_{int(datetime.now(datetime.UTC).timestamp())}" review_record = { "review_id": review_id, @@ -162,7 +162,7 @@ async def create_review(review: MarketplaceReview): "pros": review.pros, "cons": review.cons, "helpful_votes": 0, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "verified_purchase": False } @@ -202,7 +202,7 @@ async def get_plugin_reviews_api(plugin_id: str): @app.post("/api/v1/purchases") async def create_purchase(purchase: PluginPurchase): """Create a plugin purchase""" - purchase_id = f"purchase_{int(datetime.utcnow().timestamp())}" + purchase_id = f"purchase_{int(datetime.now(datetime.UTC).timestamp())}" purchase_record = { "purchase_id": purchase_id, @@ -211,8 +211,8 @@ async def create_purchase(purchase: PluginPurchase): "price": purchase.price, "payment_method": purchase.payment_method, "status": "completed", - "created_at": datetime.utcnow().isoformat(), - "refund_deadline": (datetime.utcnow() + timedelta(days=30)).isoformat() + "created_at": datetime.now(datetime.UTC).isoformat(), + "refund_deadline": (datetime.now(datetime.UTC) + timedelta(days=30)).isoformat() } if purchase.plugin_id not in purchases: @@ -235,7 +235,7 @@ async def create_purchase(purchase: PluginPurchase): @app.post("/api/v1/developers/apply") async def apply_developer(application: DeveloperApplication): """Apply to become a verified developer""" - application_id = f"dev_app_{int(datetime.utcnow().timestamp())}" + application_id = f"dev_app_{int(datetime.now(datetime.UTC).timestamp())}" application_record = { "application_id": application_id, @@ -247,7 +247,7 @@ async def apply_developer(application: DeveloperApplication): "github_username": application.github_username, "description": application.description, "status": "pending", - "submitted_at": datetime.utcnow().isoformat(), + "submitted_at": datetime.now(datetime.UTC).isoformat(), "reviewed_at": None, "reviewer_notes": None } @@ -268,7 +268,7 @@ async def get_verified_developers_api(): return { "verified_developers": get_verified_developers(), "total_developers": len(verified_developers), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/revenue/{developer_id}") @@ -278,7 +278,7 @@ async def get_developer_revenue(developer_id: str): "total_revenue": 0.0, "plugin_revenue": {}, "monthly_revenue": {}, - "last_updated": datetime.utcnow().isoformat() + "last_updated": datetime.now(datetime.UTC).isoformat() }) return developer_revenue @@ -358,7 +358,7 @@ def get_recent_plugins(limit: int = 12) -> List[Dict]: "rating": 4.9, "downloads": 2340, "price": 199.99, - "created_at": (datetime.utcnow() - timedelta(days=3)).isoformat() + "created_at": (datetime.now(datetime.UTC) - timedelta(days=3)).isoformat() }, { "plugin_id": "performance_monitor", @@ -369,7 +369,7 @@ def get_recent_plugins(limit: int = 12) -> List[Dict]: "rating": 4.4, "downloads": 1890, "price": 59.99, - "created_at": (datetime.utcnow() - timedelta(days=7)).isoformat() + "created_at": (datetime.now(datetime.UTC) - timedelta(days=7)).isoformat() } ] @@ -414,7 +414,7 @@ def get_plugin_details(plugin_id: str) -> Optional[Dict]: "downloads": 15420, "price": 99.99, "version": "2.1.0", - "last_updated": (datetime.utcnow() - timedelta(days=15)).isoformat(), + "last_updated": (datetime.now(datetime.UTC) - timedelta(days=15)).isoformat(), "repository_url": "https://github.com/aitbc-labs/ai-trading-bot", "homepage_url": "https://aitbc-trading-bot.com", "license": "MIT", @@ -442,7 +442,7 @@ def get_plugin_reviews(plugin_id: str) -> List[Dict]: "pros": ["Easy to use", "Great performance", "Good documentation"], "cons": ["Initial setup complexity"], "helpful_votes": 23, - "created_at": (datetime.utcnow() - timedelta(days=10)).isoformat() + "created_at": (datetime.now(datetime.UTC) - timedelta(days=10)).isoformat() }, { "review_id": "review_2", @@ -453,7 +453,7 @@ def get_plugin_reviews(plugin_id: str) -> List[Dict]: "pros": ["Powerful features", "Good support"], "cons": ["UI could be better", "Learning curve"], "helpful_votes": 15, - "created_at": (datetime.utcnow() - timedelta(days=25)).isoformat() + "created_at": (datetime.now(datetime.UTC) - timedelta(days=25)).isoformat() } ] diff --git a/apps/plugin-registry/main.py b/apps/plugin-registry/main.py index a91ba638..adf10c1e 100755 --- a/apps/plugin-registry/main.py +++ b/apps/plugin-registry/main.py @@ -6,7 +6,7 @@ Handles plugin registration, discovery, versioning, and security validation import asyncio import json import hashlib -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, UploadFile, File @@ -66,7 +66,7 @@ async def root(): return { "service": "AITBC Plugin Registry", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -79,7 +79,7 @@ async def health_check(): "security_scans": len(security_scans), "downloads_today": len([d for downloads_list in downloads.values() for d in downloads_list - if datetime.fromisoformat(d["timestamp"]).date() == datetime.utcnow().date()]) + if datetime.fromisoformat(d["timestamp"]).date() == datetime.now(datetime.UTC).date()]) } @app.post("/api/v1/plugins/register") @@ -105,8 +105,8 @@ async def register_plugin(plugin: PluginRegistration): "aitbc_version": plugin.aitbc_version, "plugin_type": plugin.plugin_type, "status": "active", - "created_at": datetime.utcnow().isoformat(), - "updated_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "updated_at": datetime.now(datetime.UTC).isoformat(), "verified": False, "featured": False, "download_count": 0, @@ -158,14 +158,14 @@ async def add_plugin_version(plugin_id: str, version: PluginVersion): "release_date": version.release_date.isoformat(), "downloads": 0, "security_scan_passed": False, - "created_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat() } plugin_versions[plugin_id].append(version_record) # Update plugin's latest version plugins[plugin_id]["latest_version"] = version.version - plugins[plugin_id]["updated_at"] = datetime.utcnow().isoformat() + plugins[plugin_id]["updated_at"] = datetime.now(datetime.UTC).isoformat() # Sort versions by version number (semantic versioning) plugin_versions[plugin_id].sort(key=lambda x: x["version"], reverse=True) @@ -272,7 +272,7 @@ async def download_plugin(plugin_id: str, version: str): # Record download download_record = { "version": version, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "ip_address": "client_ip", # In production, get actual IP "user_agent": "user_agent" # In production, get actual user agent } @@ -284,7 +284,7 @@ async def download_plugin(plugin_id: str, version: str): # Update analytics if plugin_id not in analytics: analytics[plugin_id] = {"downloads": [], "views": [], "ratings": []} - analytics[plugin_id]["downloads"].append(datetime.utcnow().timestamp()) + analytics[plugin_id]["downloads"].append(datetime.now(datetime.UTC).timestamp()) # Update plugin download count plugins[plugin_id]["download_count"] += 1 @@ -319,7 +319,7 @@ async def create_security_scan(plugin_id: str, scan: SecurityScan): "vulnerabilities": scan.vulnerabilities, "risk_score": scan.risk_score, "passed": scan.passed, - "created_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat() } # Update version security status @@ -400,7 +400,7 @@ async def get_popular_plugins(limit: int = 10): return { "popular_plugins": popular_plugins, "limit": limit, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/recent") @@ -411,7 +411,7 @@ async def get_recent_plugins(limit: int = 10): return { "recent_plugins": recent_plugins, "limit": limit, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/analytics/dashboard") @@ -429,7 +429,7 @@ async def get_analytics_dashboard(): # Recent activity recent_downloads = 0 - today = datetime.utcnow().date() + today = datetime.now(datetime.UTC).date() for download_list in downloads.values(): recent_downloads += len([d for d in download_list if datetime.fromisoformat(d["timestamp"]).date() == today]) @@ -444,7 +444,7 @@ async def get_analytics_dashboard(): "security_scans": len(security_scans), "passed_scans": len([s for s in security_scans.values() if s["passed"]]) }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Background task for analytics processing @@ -454,7 +454,7 @@ async def process_analytics(): await asyncio.sleep(3600) # Process every hour # Update daily statistics - current_date = datetime.utcnow().date() + current_date = datetime.now(datetime.UTC).date() for plugin_id, plugin_analytics in analytics.items(): daily_key = current_date.isoformat() diff --git a/apps/plugin-registry/tests/test_edge_cases_plugin_registry.py b/apps/plugin-registry/tests/test_edge_cases_plugin_registry.py index 222bed59..e6682efb 100644 --- a/apps/plugin-registry/tests/test_edge_cases_plugin_registry.py +++ b/apps/plugin-registry/tests/test_edge_cases_plugin_registry.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginRegistration, PluginVersion, SecurityScan, plugins, plugin_versions, security_scans, analytics, downloads @@ -74,7 +74,7 @@ def test_plugin_version_empty_changelog(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) assert version.changelog == "" @@ -86,7 +86,7 @@ def test_security_scan_empty_vulnerabilities(): scan_id="scan_123", plugin_id="test_plugin", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[], risk_score="low", passed=True @@ -104,7 +104,7 @@ def test_add_version_nonexistent_plugin(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) response = client.post("/api/v1/plugins/nonexistent/versions", json=version.model_dump(mode='json')) assert response.status_code == 404 @@ -152,7 +152,7 @@ def test_security_scan_nonexistent_plugin(): scan_id="scan_123", plugin_id="nonexistent", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[], risk_score="low", passed=True @@ -187,7 +187,7 @@ def test_security_scan_nonexistent_version(): scan_id="scan_123", plugin_id="test_plugin", version="2.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[], risk_score="low", passed=True @@ -296,7 +296,7 @@ def test_security_scan_failed(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) client.post("/api/v1/plugins/test_plugin/versions", json=version.model_dump(mode='json')) @@ -305,7 +305,7 @@ def test_security_scan_failed(): scan_id="scan_123", plugin_id="test_plugin", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[{"severity": "high", "description": "Critical issue"}], risk_score="high", passed=False diff --git a/apps/plugin-registry/tests/test_integration_plugin_registry.py b/apps/plugin-registry/tests/test_integration_plugin_registry.py index c620d21a..9b8fb237 100644 --- a/apps/plugin-registry/tests/test_integration_plugin_registry.py +++ b/apps/plugin-registry/tests/test_integration_plugin_registry.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginRegistration, PluginVersion, SecurityScan, plugins, plugin_versions, security_scans, analytics, downloads @@ -129,7 +129,7 @@ def test_add_plugin_version(): download_url="https://github.com/test/plugin/archive/v1.1.0.tar.gz", checksum="def456", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) response = client.post("/api/v1/plugins/test_plugin/versions", json=version.model_dump(mode='json')) assert response.status_code == 200 @@ -166,7 +166,7 @@ def test_add_duplicate_version(): download_url="https://github.com/test/plugin/archive/v1.1.0.tar.gz", checksum="def456", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) client.post("/api/v1/plugins/test_plugin/versions", json=version.model_dump(mode='json')) @@ -280,7 +280,7 @@ def test_download_plugin(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) client.post("/api/v1/plugins/test_plugin/versions", json=version.model_dump(mode='json')) @@ -320,7 +320,7 @@ def test_create_security_scan(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) client.post("/api/v1/plugins/test_plugin/versions", json=version.model_dump(mode='json')) @@ -329,7 +329,7 @@ def test_create_security_scan(): scan_id="scan_123", plugin_id="test_plugin", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[], risk_score="low", passed=True diff --git a/apps/plugin-registry/tests/test_unit_plugin_registry.py b/apps/plugin-registry/tests/test_unit_plugin_registry.py index 086750cb..22d25846 100644 --- a/apps/plugin-registry/tests/test_unit_plugin_registry.py +++ b/apps/plugin-registry/tests/test_unit_plugin_registry.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, PluginRegistration, PluginVersion, SecurityScan @@ -72,7 +72,7 @@ def test_plugin_version_model(): download_url="https://github.com/test/plugin/archive/v1.0.0.tar.gz", checksum="abc123", aitbc_compatibility=["1.0.0", "1.1.0"], - release_date=datetime.utcnow() + release_date=datetime.now(datetime.UTC) ) assert version.version == "1.0.0" assert version.changelog == "Initial release" @@ -88,7 +88,7 @@ def test_security_scan_model(): scan_id="scan_123", plugin_id="test_plugin", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), vulnerabilities=[{"severity": "low", "description": "Test"}], risk_score="low", passed=True diff --git a/apps/plugin-security/main.py b/apps/plugin-security/main.py index 7df57fc8..e290a811 100755 --- a/apps/plugin-security/main.py +++ b/apps/plugin-security/main.py @@ -8,7 +8,7 @@ import json import subprocess import tempfile import os -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, UploadFile, File @@ -63,7 +63,7 @@ async def root(): return { "service": "AITBC Plugin Security Service", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -80,7 +80,7 @@ async def health_check(): @app.post("/api/v1/security/scan") async def initiate_security_scan(scan: SecurityScan): """Initiate a security scan for a plugin""" - scan_id = f"scan_{int(datetime.utcnow().timestamp())}" + scan_id = f"scan_{int(datetime.now(datetime.UTC).timestamp())}" # Create scan record scan_record = { @@ -91,7 +91,7 @@ async def initiate_security_scan(scan: SecurityScan): "scan_type": scan.scan_type, "priority": scan.priority, "status": "queued", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "started_at": None, "completed_at": None, "duration": None, @@ -182,7 +182,7 @@ async def list_vulnerabilities(severity: Optional[str] = None, @app.post("/api/v1/security/policies") async def create_security_policy(policy: Dict[str, Any]): """Create a new security policy""" - policy_id = f"policy_{int(datetime.utcnow().timestamp())}" + policy_id = f"policy_{int(datetime.now(datetime.UTC).timestamp())}" policy_record = { "policy_id": policy_id, @@ -197,8 +197,8 @@ async def create_security_policy(policy: Dict[str, Any]): }), "plugin_types": policy.get("plugin_types", []), "active": True, - "created_at": datetime.utcnow().isoformat(), - "updated_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat(), + "updated_at": datetime.now(datetime.UTC).isoformat() } security_policies[policy_id] = policy_record @@ -261,7 +261,7 @@ async def get_security_dashboard(): """Get security dashboard data""" total_scans = len(scan_reports) recent_scans = [r for r in scan_reports.values() - if datetime.fromisoformat(r["scan_date"]) > datetime.utcnow() - timedelta(days=7)] + if datetime.fromisoformat(r["scan_date"]) > datetime.now(datetime.UTC) - timedelta(days=7)] # Calculate statistics scan_results = list(scan_reports.values()) @@ -294,7 +294,7 @@ async def get_security_dashboard(): "queue_size": len(scan_queue), "active_policies": len([p for p in security_policies.values() if p["active"]]) }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Core security scanning functions @@ -305,15 +305,15 @@ async def process_scan_file(scan_id: str, file_path: str, filename: str): for scan_record in scan_queue: if scan_record["scan_id"] == scan_id: scan_record["status"] = "running" - scan_record["started_at"] = datetime.utcnow().isoformat() + scan_record["started_at"] = datetime.now(datetime.UTC).isoformat() break - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) # Perform security scan scan_result = await perform_security_scan(file_path, filename) - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) duration = (end_time - start_time).total_seconds() # Create security report @@ -360,7 +360,7 @@ async def process_scan_file(scan_id: str, file_path: str, filename: str): for scan_record in scan_queue: if scan_record["scan_id"] == scan_id: scan_record["status"] = "failed" - scan_record["completed_at"] = datetime.utcnow().isoformat() + scan_record["completed_at"] = datetime.now(datetime.UTC).isoformat() break async def perform_security_scan(file_path: str, filename: str) -> Dict[str, Any]: @@ -392,7 +392,7 @@ async def perform_security_scan(file_path: str, filename: str) -> Dict[str, Any] "vulnerability_count": len(vulnerabilities), "severity_distribution": get_severity_distribution(vulnerabilities), "file_type": filename.split('.')[-1], - "scan_timestamp": datetime.utcnow().isoformat() + "scan_timestamp": datetime.now(datetime.UTC).isoformat() }) except Exception as e: diff --git a/apps/plugin-security/tests/test_unit_plugin_security.py b/apps/plugin-security/tests/test_unit_plugin_security.py index cee5ec8b..10acf5a3 100644 --- a/apps/plugin-security/tests/test_unit_plugin_security.py +++ b/apps/plugin-security/tests/test_unit_plugin_security.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, SecurityScan, Vulnerability, SecurityReport, calculate_overall_score, generate_recommendations, get_severity_distribution, estimate_scan_time @@ -76,7 +76,7 @@ def test_security_report_model(): scan_id="scan_123", plugin_id="plugin_123", version="1.0.0", - scan_date=datetime.utcnow(), + scan_date=datetime.now(datetime.UTC), scan_duration=120.5, overall_score="passed", vulnerabilities=[], diff --git a/apps/pool-hub/src/app/registry/miner_registry.py b/apps/pool-hub/src/app/registry/miner_registry.py index 96ac2aa8..6adab115 100755 --- a/apps/pool-hub/src/app/registry/miner_registry.py +++ b/apps/pool-hub/src/app/registry/miner_registry.py @@ -1,7 +1,7 @@ """Miner Registry Implementation""" from typing import List, Optional, Dict, Any -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from dataclasses import dataclass, field import asyncio @@ -142,7 +142,7 @@ class MinerRegistry: miner.current_jobs = current_jobs miner.gpu_utilization = gpu_utilization miner.memory_used_gb = memory_used_gb - miner.last_heartbeat = datetime.utcnow() + miner.last_heartbeat = datetime.now(datetime.UTC) async def update_capabilities(self, miner_id: str, capabilities: List[str]): """Update miner capabilities.""" @@ -271,7 +271,7 @@ class MinerRegistry: if job_id in self._jobs: job = self._jobs[job_id] job.status = status - job.completed_at = datetime.utcnow() + job.completed_at = datetime.now(datetime.UTC) if miner_id in self._miners: miner = self._miners[miner_id] @@ -314,7 +314,7 @@ class MinerRegistry: # Update job job.miner_id = new_miner_id job.status = "assigned" - job.assigned_at = datetime.utcnow() + job.assigned_at = datetime.now(datetime.UTC) # Update new miner if new_miner_id in self._miners: diff --git a/apps/pool-hub/src/app/routers/health.py b/apps/pool-hub/src/app/routers/health.py index 71bb04fa..12f70e51 100755 --- a/apps/pool-hub/src/app/routers/health.py +++ b/apps/pool-hub/src/app/routers/health.py @@ -1,7 +1,7 @@ """Health check routes for Pool Hub""" from fastapi import APIRouter -from datetime import datetime +from datetime import datetime, UTC from sqlalchemy import text router = APIRouter(tags=["health"]) @@ -13,7 +13,7 @@ async def health_check(): return { "status": "ok", "service": "pool-hub", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } @@ -28,7 +28,7 @@ async def readiness_check(): return { "ready": all_ready, "checks": checks, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } diff --git a/apps/pool-hub/src/app/routers/jobs.py b/apps/pool-hub/src/app/routers/jobs.py index a2312ed0..0ae3ab52 100755 --- a/apps/pool-hub/src/app/routers/jobs.py +++ b/apps/pool-hub/src/app/routers/jobs.py @@ -2,7 +2,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query from typing import List, Optional -from datetime import datetime +from datetime import datetime, UTC from pydantic import BaseModel from ..registry import MinerRegistry @@ -86,7 +86,7 @@ async def assign_job( job_id=job.job_id, miner_id=best_miner.miner_id, pool_id=best_miner.pool_id, - assigned_at=datetime.utcnow(), + assigned_at=datetime.now(datetime.UTC), deadline=job.deadline ) diff --git a/apps/pool-hub/src/app/scoring/scoring_engine.py b/apps/pool-hub/src/app/scoring/scoring_engine.py index b51adcc9..d2522ae1 100755 --- a/apps/pool-hub/src/app/scoring/scoring_engine.py +++ b/apps/pool-hub/src/app/scoring/scoring_engine.py @@ -2,7 +2,7 @@ from typing import List, Dict, Any, Optional from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import math @@ -74,7 +74,7 @@ class ScoringEngine: success_rate = 100.0 # New miners start with perfect score # Heartbeat freshness penalty - heartbeat_age = (datetime.utcnow() - miner.last_heartbeat).total_seconds() + heartbeat_age = (datetime.now(datetime.UTC) - miner.last_heartbeat).total_seconds() if heartbeat_age > 300: # 5 minutes freshness_penalty = min(20, heartbeat_age / 60) else: @@ -137,7 +137,7 @@ class ScoringEngine: weight_total = 0 for record in history: - age_days = (datetime.utcnow() - record["timestamp"]).days + age_days = (datetime.now(datetime.UTC) - record["timestamp"]).days weight = math.exp(-age_days / self.DECAY_HALF_LIFE_DAYS) if record["success"]: @@ -153,7 +153,7 @@ class ScoringEngine: def _get_hours_active(self, miner) -> float: """Get hours since miner registered.""" - delta = datetime.utcnow() - miner.registered_at + delta = datetime.now(datetime.UTC) - miner.registered_at return max(1, delta.total_seconds() / 3600) def _parse_memory(self, memory_str: str) -> float: @@ -204,7 +204,7 @@ class ScoringEngine: self._history[miner_id] = [] self._history[miner_id].append({ - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), "success": True, "metrics": metrics or {} }) @@ -219,7 +219,7 @@ class ScoringEngine: self._history[miner_id] = [] self._history[miner_id].append({ - "timestamp": datetime.utcnow(), + "timestamp": datetime.now(datetime.UTC), "success": False, "error": error }) diff --git a/apps/pool-hub/src/poolhub/app/routers/sla.py b/apps/pool-hub/src/poolhub/app/routers/sla.py index a8a60bcd..e262c93a 100644 --- a/apps/pool-hub/src/poolhub/app/routers/sla.py +++ b/apps/pool-hub/src/poolhub/app/routers/sla.py @@ -3,7 +3,7 @@ SLA and Billing API Endpoints for Pool-Hub Provides endpoints for SLA metrics, capacity planning, and billing integration. """ -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Dict, List, Optional, Any from decimal import Decimal @@ -165,7 +165,7 @@ async def get_capacity_snapshots( ): """Get capacity planning snapshots""" try: - cutoff = datetime.utcnow() - timedelta(hours=hours) + cutoff = datetime.now(datetime.UTC) - timedelta(hours=hours) stmt = ( db.query(CapacitySnapshot) .filter(CapacitySnapshot.timestamp >= cutoff) @@ -236,7 +236,7 @@ async def configure_capacity_alerts( return { "status": "configured", "alert_config": alert_config, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: logger.error(f"Error configuring capacity alerts: {e}") @@ -270,7 +270,7 @@ async def sync_billing_usage( try: if request.miner_id: # Sync specific miner - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=request.hours_back) result = await billing_integration.sync_miner_usage( miner_id=request.miner_id, start_date=start_date, end_date=end_date @@ -350,7 +350,7 @@ async def get_sla_status(db: Session = Depends(get_db)): "status": status, "active_violations": len(active_violations), "recent_metrics_count": len(recent_metrics), - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } except Exception as e: logger.error(f"Error getting SLA status: {e}") diff --git a/apps/pool-hub/src/poolhub/repositories/feedback_repository.py b/apps/pool-hub/src/poolhub/repositories/feedback_repository.py index 56b6594e..b0489897 100755 --- a/apps/pool-hub/src/poolhub/repositories/feedback_repository.py +++ b/apps/pool-hub/src/poolhub/repositories/feedback_repository.py @@ -40,7 +40,7 @@ class FeedbackRepository: latency_ms=latency_ms, fail_code=fail_code, tokens_spent=tokens_spent, - created_at=dt.datetime.utcnow(), + created_at=dt.datetime.now(datetime.UTC), ) self._session.add(feedback) await self._session.flush() diff --git a/apps/pool-hub/src/poolhub/repositories/match_repository.py b/apps/pool-hub/src/poolhub/repositories/match_repository.py index a703a584..e0c981c7 100755 --- a/apps/pool-hub/src/poolhub/repositories/match_repository.py +++ b/apps/pool-hub/src/poolhub/repositories/match_repository.py @@ -34,7 +34,7 @@ class MatchRepository: requirements=requirements, hints=hints or {}, top_k=top_k, - created_at=dt.datetime.utcnow(), + created_at=dt.datetime.now(datetime.UTC), ) self._session.add(request) await self._session.flush() @@ -58,7 +58,7 @@ class MatchRepository: publish: bool = True, ) -> List[MatchResult]: results: List[MatchResult] = [] - created_at = dt.datetime.utcnow() + created_at = dt.datetime.now(datetime.UTC) for candidate in candidates: result = MatchResult( request_id=request_id, diff --git a/apps/pool-hub/src/poolhub/repositories/miner_repository.py b/apps/pool-hub/src/poolhub/repositories/miner_repository.py index 95727046..5ed9c974 100755 --- a/apps/pool-hub/src/poolhub/repositories/miner_repository.py +++ b/apps/pool-hub/src/poolhub/repositories/miner_repository.py @@ -69,7 +69,7 @@ class MinerRepository: miner.capabilities = capabilities miner.region = region - miner.last_seen_at = dt.datetime.utcnow() + miner.last_seen_at = dt.datetime.now(datetime.UTC) await self._session.flush() await self._sync_miner_to_redis(miner_id) @@ -97,7 +97,7 @@ class MinerRepository: "avg_latency_ms": avg_latency_ms, "temp_c": temp_c, "mem_free_gb": mem_free_gb, - "updated_at": dt.datetime.utcnow(), + "updated_at": dt.datetime.now(datetime.UTC), }.items() if v is not None } @@ -107,7 +107,7 @@ class MinerRepository: miner = await self._session.get(Miner, miner_id) if miner: - miner.last_seen_at = dt.datetime.utcnow() + miner.last_seen_at = dt.datetime.now(datetime.UTC) await self._session.flush() await self._sync_miner_to_redis(miner_id) @@ -115,7 +115,7 @@ class MinerRepository: miner = await self._session.get(Miner, miner_id) if miner is None: return - miner.last_seen_at = dt.datetime.utcnow() + miner.last_seen_at = dt.datetime.now(datetime.UTC) await self._session.flush() await self._sync_miner_to_redis(miner_id) diff --git a/apps/pool-hub/src/poolhub/services/billing_integration.py b/apps/pool-hub/src/poolhub/services/billing_integration.py index 0ec06aed..6ebc0b7c 100644 --- a/apps/pool-hub/src/poolhub/services/billing_integration.py +++ b/apps/pool-hub/src/poolhub/services/billing_integration.py @@ -4,7 +4,7 @@ Integrates pool-hub usage data with coordinator-api's billing system. """ import asyncio -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from typing import Dict, List, Optional, Any @@ -76,7 +76,7 @@ class BillingIntegration: "unit_price": float(unit_price), "total_amount": float(total_cost), "currency": "USD", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "metadata": metadata or {}, } @@ -139,7 +139,7 @@ class BillingIntegration: ) -> Dict[str, Any]: """Sync usage data for all miners to coordinator-api billing""" - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=hours_back) # Get all miners diff --git a/apps/pool-hub/src/poolhub/services/sla_collector.py b/apps/pool-hub/src/poolhub/services/sla_collector.py index eb75cd05..8f7f0d54 100644 --- a/apps/pool-hub/src/poolhub/services/sla_collector.py +++ b/apps/pool-hub/src/poolhub/services/sla_collector.py @@ -4,7 +4,7 @@ Collects and tracks SLA metrics for miners including uptime, response time, job """ import asyncio -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from typing import Dict, List, Optional, Any @@ -57,7 +57,7 @@ class SLACollector: metric_value=metric_value, threshold=threshold, is_violation=is_violation, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), meta_data=metadata or {}, ) @@ -90,7 +90,7 @@ class SLACollector: # Calculate uptime based on last heartbeat if miner_status.last_heartbeat_at: time_since_heartbeat = ( - datetime.utcnow() - miner_status.last_heartbeat_at + datetime.now(datetime.UTC) - miner_status.last_heartbeat_at ).total_seconds() # Consider miner down if no heartbeat for 5 minutes @@ -153,7 +153,7 @@ class SLACollector: stmt = ( select(Feedback) .where(Feedback.miner_id == miner_id) - .where(Feedback.created_at >= datetime.utcnow() - timedelta(days=7)) + .where(Feedback.created_at >= datetime.now(datetime.UTC) - timedelta(days=7)) .order_by(Feedback.created_at.desc()) .limit(100) ) @@ -206,7 +206,7 @@ class SLACollector: forecast_capacity=total_miners, # Would be calculated from forecasting recommended_scaling="stable", scaling_reason="Capacity within normal range", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), meta_data={"method": "real_time_collection"}, ) @@ -266,7 +266,7 @@ class SLACollector: stmt = ( select(func.count(SLAViolation.id)) .where(SLAViolation.resolved_at.is_(None)) - .where(SLAViolation.created_at >= datetime.utcnow() - timedelta(hours=1)) + .where(SLAViolation.created_at >= datetime.now(datetime.UTC) - timedelta(hours=1)) ) results["violations_detected"] = self.db.execute(stmt).scalar() or 0 @@ -282,7 +282,7 @@ class SLACollector: ) -> List[SLAMetric]: """Get SLA metrics for a miner or all miners""" - cutoff = datetime.utcnow() - timedelta(hours=hours) + cutoff = datetime.now(datetime.UTC) - timedelta(hours=hours) stmt = select(SLAMetric).where(SLAMetric.timestamp >= cutoff) @@ -349,7 +349,7 @@ class SLACollector: metric_value=metric_value, threshold=threshold, violation_duration_ms=None, # Will be updated when resolved - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), meta_data=metadata or {}, ) diff --git a/apps/pool-hub/tests/test_billing_integration.py b/apps/pool-hub/tests/test_billing_integration.py index 94ab196b..b8d315e4 100644 --- a/apps/pool-hub/tests/test_billing_integration.py +++ b/apps/pool-hub/tests/test_billing_integration.py @@ -4,7 +4,7 @@ Tests for Billing Integration Service import sys import pytest -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from unittest.mock import AsyncMock, patch from sqlalchemy.orm import Session @@ -84,7 +84,7 @@ async def test_record_usage_with_fallback_pricing(billing_integration: BillingIn @pytest.mark.asyncio async def test_sync_miner_usage(billing_integration: BillingIntegration, sample_miner: Miner): """Test syncing usage for a specific miner""" - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=24) with patch("poolhub.services.billing_integration.httpx.AsyncClient") as mock_client: @@ -123,7 +123,7 @@ async def test_sync_all_miners_usage(billing_integration: BillingIntegration, sa def test_collect_miner_usage(billing_integration: BillingIntegration, sample_miner: Miner): """Test collecting usage data for a miner""" - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=24) usage_data = billing_integration.db.run_sync( @@ -169,7 +169,7 @@ async def test_trigger_invoice_generation(billing_integration: BillingIntegratio mock_client.return_value.__aenter__.return_value.post = AsyncMock(return_value=mock_response) - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(days=30) result = await billing_integration.trigger_invoice_generation( diff --git a/apps/pool-hub/tests/test_integration_coordinator.py b/apps/pool-hub/tests/test_integration_coordinator.py index eef23b28..e1b9206d 100644 --- a/apps/pool-hub/tests/test_integration_coordinator.py +++ b/apps/pool-hub/tests/test_integration_coordinator.py @@ -5,7 +5,7 @@ Tests the integration between pool-hub and coordinator-api's billing system. import sys import pytest -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from sqlalchemy.orm import Session @@ -70,7 +70,7 @@ def test_end_to_end_sla_to_billing_workflow( assert len(metrics) > 0 # Step 3: Collect usage data for billing - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=1) usage_data = sla_collector.db.run_sync( lambda sess: billing_integration._collect_miner_usage( @@ -126,7 +126,7 @@ def test_sla_violation_billing_correlation( assert len(violations) > 0 # Usage should still be recorded even with violations - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=1) usage_data = sla_collector.db.run_sync( lambda sess: billing_integration._collect_miner_usage( @@ -172,7 +172,7 @@ def test_billing_sync_with_coordinator_api( """Test billing sync with coordinator-api (mocked)""" from unittest.mock import AsyncMock, patch - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(hours=1) with patch("poolhub.services.billing_integration.httpx.AsyncClient") as mock_client: diff --git a/apps/pool-hub/tests/test_sla_collector.py b/apps/pool-hub/tests/test_sla_collector.py index 3c0a8ce8..2b199cc6 100644 --- a/apps/pool-hub/tests/test_sla_collector.py +++ b/apps/pool-hub/tests/test_sla_collector.py @@ -4,7 +4,7 @@ Tests for SLA Collector Service import sys import pytest -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from sqlalchemy.orm import Session @@ -48,7 +48,7 @@ def sample_miner_status(db_session: Session, sample_miner: Miner) -> MinerStatus avg_latency_ms=150, temp_c=65, mem_free_gb=32.0, - last_heartbeat_at=datetime.utcnow(), + last_heartbeat_at=datetime.now(datetime.UTC), ) db_session.add(status) db_session.commit() diff --git a/apps/pool-hub/tests/test_sla_endpoints.py b/apps/pool-hub/tests/test_sla_endpoints.py index de3a8fde..2d618fa7 100644 --- a/apps/pool-hub/tests/test_sla_endpoints.py +++ b/apps/pool-hub/tests/test_sla_endpoints.py @@ -4,7 +4,7 @@ Tests for SLA API Endpoints import sys import pytest -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from decimal import Decimal from fastapi.testclient import TestClient from sqlalchemy.orm import Session @@ -65,7 +65,7 @@ def sample_sla_metric(db_session: Session, sample_miner: Miner) -> SLAMetric: metric_value=98.5, threshold=95.0, is_violation=False, - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), metadata={"test": "true"}, ) db_session.add(metric) @@ -191,7 +191,7 @@ def test_record_usage(test_client: TestClient): def test_generate_invoice(test_client: TestClient): """Test triggering invoice generation""" - end_date = datetime.utcnow() + end_date = datetime.now(datetime.UTC) start_date = end_date - timedelta(days=30) request_data = { diff --git a/apps/trading-engine/main.py b/apps/trading-engine/main.py index 554b33a8..f5b59343 100755 --- a/apps/trading-engine/main.py +++ b/apps/trading-engine/main.py @@ -6,7 +6,7 @@ Handles order matching, trade execution, and settlement import asyncio import json from collections import defaultdict, deque -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path from typing import Dict, Any, List, Optional, Tuple from fastapi import FastAPI, HTTPException @@ -70,7 +70,7 @@ async def root(): return { "service": "AITBC Trading Engine", "status": "running", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "version": "1.0.0" } @@ -98,7 +98,7 @@ async def submit_order(order: Order): "volume_24h": 0.0, "high_24h": None, "low_24h": None, - "created_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat() } # Store order @@ -185,7 +185,7 @@ async def get_order_book(symbol: str, depth: int = 10): "volume_24h": book["volume_24h"], "high_24h": book["high_24h"], "low_24h": book["low_24h"], - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/trades") @@ -216,7 +216,7 @@ async def get_ticker(symbol: str): trades_24h = [t for t in trades.values() if t["symbol"] == symbol and datetime.fromisoformat(t["timestamp"]) > - datetime.utcnow() - timedelta(hours=24)] + datetime.now(datetime.UTC) - timedelta(hours=24)] if trades_24h: prices = [t["price"] for t in trades_24h] @@ -276,7 +276,7 @@ async def cancel_order(order_id: str): # Update order status order["status"] = "cancelled" - order["cancelled_at"] = datetime.utcnow().isoformat() + order["cancelled_at"] = datetime.now(datetime.UTC).isoformat() logger.info(f"Order cancelled: {order_id}") @@ -295,7 +295,7 @@ async def get_market_data(): trades_24h = [t for t in trades.values() if t["symbol"] == symbol and datetime.fromisoformat(t["timestamp"]) > - datetime.utcnow() - timedelta(hours=24)] + datetime.now(datetime.UTC) - timedelta(hours=24)] market_summary[symbol] = { "last_price": book["last_price"], @@ -310,7 +310,7 @@ async def get_market_data(): return { "market_data": market_summary, "total_symbols": len(market_summary), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } @app.get("/api/v1/engine/stats") @@ -338,7 +338,7 @@ async def get_engine_stats(): "active_order_books": len(order_books), "uptime": "running" }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Core trading engine logic @@ -457,7 +457,7 @@ async def execute_trade(order1: Dict, order2: Dict, price: float) -> Optional[Di return None # Create trade record - trade_id = f"trade_{int(datetime.utcnow().timestamp())}_{len(trades)}" + trade_id = f"trade_{int(datetime.now(datetime.UTC).timestamp())}_{len(trades)}" trade = { "trade_id": trade_id, @@ -466,7 +466,7 @@ async def execute_trade(order1: Dict, order2: Dict, price: float) -> Optional[Di "sell_order_id": order2["order_id"] if order2["side"] == "sell" else order1["order_id"], "quantity": trade_quantity, "price": price, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } trades[trade_id] = trade @@ -524,7 +524,7 @@ def update_market_data(symbol: str, trades_executed: List[Dict]): trades_24h = [t for t in trades.values() if t["symbol"] == symbol and datetime.fromisoformat(t["timestamp"]) > - datetime.utcnow() - timedelta(hours=24)] + datetime.now(datetime.UTC) - timedelta(hours=24)] if trades_24h: prices = [t["price"] for t in trades_24h] @@ -548,7 +548,7 @@ async def simulate_market_activity(): side = random.choice(["buy", "sell"]) quantity = random.uniform(10, 1000) - order_id = f"sim_order_{int(datetime.utcnow().timestamp())}" + order_id = f"sim_order_{int(datetime.now(datetime.UTC).timestamp())}" order = Order( order_id=order_id, symbol=symbol, @@ -556,7 +556,7 @@ async def simulate_market_activity(): type="market", quantity=quantity, user_id="sim_user", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) order_data = { diff --git a/apps/trading-engine/tests/test_edge_cases_trading_engine.py b/apps/trading-engine/tests/test_edge_cases_trading_engine.py index 7b00b3e3..1d55dc5e 100644 --- a/apps/trading-engine/tests/test_edge_cases_trading_engine.py +++ b/apps/trading-engine/tests/test_edge_cases_trading_engine.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, Order, order_books, orders, trades @@ -34,7 +34,7 @@ def test_order_zero_quantity(): quantity=0.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.quantity == 0.0 @@ -50,7 +50,7 @@ def test_order_negative_quantity(): quantity=-100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.quantity == -100.0 @@ -66,7 +66,7 @@ def test_order_negative_price(): quantity=100.0, price=-0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.price == -0.00001 @@ -82,7 +82,7 @@ def test_order_empty_symbol(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.symbol == "" @@ -99,7 +99,7 @@ def test_cancel_filled_order(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) @@ -122,7 +122,7 @@ def test_submit_order_with_slash_in_symbol(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) assert response.status_code == 200 @@ -140,7 +140,7 @@ def test_submit_order_with_hyphen_in_symbol(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) assert response.status_code == 200 @@ -188,7 +188,7 @@ def test_order_book_depth_parameter(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) diff --git a/apps/trading-engine/tests/test_integration_trading_engine.py b/apps/trading-engine/tests/test_integration_trading_engine.py index b0a8f7dd..4103a528 100644 --- a/apps/trading-engine/tests/test_integration_trading_engine.py +++ b/apps/trading-engine/tests/test_integration_trading_engine.py @@ -5,7 +5,7 @@ import sys import sys from pathlib import Path from fastapi.testclient import TestClient -from datetime import datetime +from datetime import datetime, UTC from main import app, Order, order_books, orders, trades @@ -57,7 +57,7 @@ def test_submit_market_order(): type="market", quantity=100.0, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) assert response.status_code == 200 @@ -78,7 +78,7 @@ def test_submit_limit_order(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) response = client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) assert response.status_code == 200 @@ -99,7 +99,7 @@ def test_get_order(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) @@ -141,7 +141,7 @@ def test_get_order_book(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order1.model_dump(mode='json')) @@ -195,7 +195,7 @@ def test_get_ticker(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) @@ -225,7 +225,7 @@ def test_cancel_order(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) client.post("/api/v1/orders/submit", json=order.model_dump(mode='json')) diff --git a/apps/trading-engine/tests/test_unit_trading_engine.py b/apps/trading-engine/tests/test_unit_trading_engine.py index 1f94eea3..08034cf5 100644 --- a/apps/trading-engine/tests/test_unit_trading_engine.py +++ b/apps/trading-engine/tests/test_unit_trading_engine.py @@ -4,7 +4,7 @@ import pytest import sys import sys from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from main import app, Order, Trade, OrderBookEntry @@ -29,7 +29,7 @@ def test_order_model(): quantity=100.0, price=0.00001, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.order_id == "order_123" assert order.symbol == "AITBC/BTC" @@ -50,7 +50,7 @@ def test_order_model_market_order(): type="market", quantity=50.0, user_id="user_123", - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert order.type == "market" assert order.price is None @@ -66,7 +66,7 @@ def test_trade_model(): sell_order_id="sell_order_123", quantity=100.0, price=0.00001, - timestamp=datetime.utcnow() + timestamp=datetime.now(datetime.UTC) ) assert trade.trade_id == "trade_123" assert trade.symbol == "AITBC/BTC" diff --git a/apps/wallet/src/app/keystore/persistent_service.py b/apps/wallet/src/app/keystore/persistent_service.py index a081c182..c0c0b85e 100755 --- a/apps/wallet/src/app/keystore/persistent_service.py +++ b/apps/wallet/src/app/keystore/persistent_service.py @@ -188,7 +188,7 @@ class PersistentKeystoreService: nonce = token_bytes(self._encryption.nonce_bytes) ciphertext = self._encryption.encrypt(password=password, plaintext=secret_bytes, salt=salt, nonce=nonce) - now = datetime.utcnow().isoformat() + now = datetime.now(datetime.UTC).isoformat() conn = sqlite3.connect(self.db_path) try: @@ -280,7 +280,7 @@ class PersistentKeystoreService: with self._lock: conn = sqlite3.connect(self.db_path) try: - now = datetime.utcnow().isoformat() + now = datetime.now(datetime.UTC).isoformat() metadata_json = json.dumps(metadata) cursor = conn.execute(""" @@ -299,7 +299,7 @@ class PersistentKeystoreService: with self._lock: conn = sqlite3.connect(self.db_path) try: - now = datetime.utcnow().isoformat() + now = datetime.now(datetime.UTC).isoformat() conn.execute(""" INSERT INTO wallet_access_log (wallet_id, action, timestamp, success, ip_address) VALUES (?, ?, ?, ?, ?) @@ -405,4 +405,4 @@ class PersistentKeystoreService: # Import datetime for the module -from datetime import datetime +from datetime import datetime, UTC diff --git a/cli/aitbc_cli/commands/exchange.py b/cli/aitbc_cli/commands/exchange.py index 5214b184..06aa758c 100755 --- a/cli/aitbc_cli/commands/exchange.py +++ b/cli/aitbc_cli/commands/exchange.py @@ -5,7 +5,7 @@ import json import os from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime +from datetime import datetime, UTC from ..utils import output, error, success, warning from ..config import get_config @@ -40,7 +40,7 @@ def register(ctx, name: str, api_key: str, secret_key: Optional[str], sandbox: b "secret_key": secret_key or "NOT_SET", "sandbox": sandbox, "description": description or f"{name} exchange integration", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "status": "active", "trading_pairs": [], "last_sync": None @@ -107,7 +107,7 @@ def create_pair(ctx, base_asset: str, quote_asset: str, exchange: str, min_order "price_precision": price_precision, "quantity_precision": quantity_precision, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "trading_enabled": False } @@ -166,7 +166,7 @@ def start_trading(ctx, pair: str, price: Optional[float], base_liquidity: float, # Update pair to enable trading target_pair["trading_enabled"] = True - target_pair["started_at"] = datetime.utcnow().isoformat() + target_pair["started_at"] = datetime.now(datetime.UTC).isoformat() target_pair["initial_price"] = price or 0.00001 # Default price for AITBC target_pair["base_liquidity"] = base_liquidity target_pair["quote_liquidity"] = quote_liquidity @@ -289,7 +289,7 @@ def add_liquidity(ctx, pair: str, amount: float, side: str, exchange: Optional[s if side == 'sell' or side == 'both': target_pair["base_liquidity"] = target_pair.get("base_liquidity", 0) + amount - target_pair["liquidity_updated_at"] = datetime.utcnow().isoformat() + target_pair["liquidity_updated_at"] = datetime.now(datetime.UTC).isoformat() # Save exchanges with open(exchanges_file, 'w') as f: diff --git a/cli/aitbc_cli/commands/wallet.py b/cli/aitbc_cli/commands/wallet.py index 933d2024..2ba0fbc1 100644 --- a/cli/aitbc_cli/commands/wallet.py +++ b/cli/aitbc_cli/commands/wallet.py @@ -7,7 +7,7 @@ import shutil import yaml from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from ..utils import output, error, success import getpass @@ -223,7 +223,7 @@ def create(ctx, name: str, wallet_type: str, no_encrypt: bool): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0, "transactions": [], } @@ -392,7 +392,7 @@ def backup(ctx, name: str, destination: Optional[str]): { "wallet": name, "backup_path": destination, - "timestamp": datetime.utcnow().isoformat() + "Z", + "timestamp": datetime.now(datetime.UTC).isoformat() + "Z", } ) @@ -421,7 +421,7 @@ def restore(ctx, backup_path: str, name: str, force: bool): # Update wallet name if needed wallet_data["wallet_id"] = name - wallet_data["restored_at"] = datetime.utcnow().isoformat() + "Z" + wallet_data["restored_at"] = datetime.now(datetime.UTC).isoformat() + "Z" # Save restored wallet (preserve encryption state) # If wallet was encrypted, we save it as-is (still encrypted with original password) @@ -520,7 +520,7 @@ def balance(ctx): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0.0, "transactions": [], } diff --git a/cli/build/lib/aitbc_cli/commands/wallet.py b/cli/build/lib/aitbc_cli/commands/wallet.py index ebb3a953..417ea018 100644 --- a/cli/build/lib/aitbc_cli/commands/wallet.py +++ b/cli/build/lib/aitbc_cli/commands/wallet.py @@ -8,7 +8,7 @@ import shutil import yaml from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from ..utils import output, error, success, encrypt_value, decrypt_value import getpass @@ -185,7 +185,7 @@ def create(ctx, name: str, wallet_type: str, no_encrypt: bool): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0, "transactions": [], } @@ -343,7 +343,7 @@ def backup(ctx, name: str, destination: Optional[str]): { "wallet": name, "backup_path": destination, - "timestamp": datetime.utcnow().isoformat() + "Z", + "timestamp": datetime.now(datetime.UTC).isoformat() + "Z", } ) @@ -372,7 +372,7 @@ def restore(ctx, backup_path: str, name: str, force: bool): # Update wallet name if needed wallet_data["wallet_id"] = name - wallet_data["restored_at"] = datetime.utcnow().isoformat() + "Z" + wallet_data["restored_at"] = datetime.now(datetime.UTC).isoformat() + "Z" # Save restored wallet (preserve encryption state) # If wallet was encrypted, we save it as-is (still encrypted with original password) @@ -471,7 +471,7 @@ def balance(ctx): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0.0, "transactions": [], } diff --git a/cli/commands/blockchain_event_bridge.py b/cli/commands/blockchain_event_bridge.py index 8b9375fa..0e6f2592 100644 --- a/cli/commands/blockchain_event_bridge.py +++ b/cli/commands/blockchain_event_bridge.py @@ -7,7 +7,7 @@ import click import json import requests import subprocess -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Any, List, Optional @click.group() @@ -27,7 +27,7 @@ def health(test_mode): "service": "blockchain-event-bridge", "version": "0.1.0", "uptime_seconds": 86400, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } click.echo("🏥 Blockchain Event Bridge Health:") diff --git a/cli/commands/exchange.py b/cli/commands/exchange.py index e7cfb699..7d7a399c 100755 --- a/cli/commands/exchange.py +++ b/cli/commands/exchange.py @@ -6,7 +6,7 @@ import json import os from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime +from datetime import datetime, UTC from utils import output, error, success, warning from config import get_config @@ -35,7 +35,7 @@ def register(ctx, name: str, api_key: str, secret_key: Optional[str], sandbox: b "secret_key": secret_key or "NOT_SET", "sandbox": sandbox, "description": description or f"{name} exchange integration", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "status": "active", "trading_pairs": [], "last_sync": None @@ -102,7 +102,7 @@ def create_pair(ctx, base_asset: str, quote_asset: str, exchange: str, min_order "price_precision": price_precision, "quantity_precision": quantity_precision, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "trading_enabled": False } @@ -161,7 +161,7 @@ def start_trading(ctx, pair: str, price: Optional[float], base_liquidity: float, # Update pair to enable trading target_pair["trading_enabled"] = True - target_pair["started_at"] = datetime.utcnow().isoformat() + target_pair["started_at"] = datetime.now(datetime.UTC).isoformat() target_pair["initial_price"] = price or 0.00001 # Default price for AITBC target_pair["base_liquidity"] = base_liquidity target_pair["quote_liquidity"] = quote_liquidity @@ -284,7 +284,7 @@ def add_liquidity(ctx, pair: str, amount: float, side: str, exchange: Optional[s if side == 'sell' or side == 'both': target_pair["base_liquidity"] = target_pair.get("base_liquidity", 0) + amount - target_pair["liquidity_updated_at"] = datetime.utcnow().isoformat() + target_pair["liquidity_updated_at"] = datetime.now(datetime.UTC).isoformat() # Save exchanges with open(exchanges_file, 'w') as f: diff --git a/cli/commands/genesis_protection.py b/cli/commands/genesis_protection.py index 896c4133..bc09874e 100755 --- a/cli/commands/genesis_protection.py +++ b/cli/commands/genesis_protection.py @@ -5,7 +5,7 @@ import json import hashlib from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime +from datetime import datetime, UTC from utils import output, error, success, warning @@ -50,7 +50,7 @@ def verify_genesis(ctx, chain: str, genesis_hash: Optional[str], force: bool): "hash_match": genesis_hash is None or calculated_hash == genesis_hash, "genesis_timestamp": chain_genesis.get("timestamp"), "genesis_accounts": len(chain_genesis.get("accounts", [])), - "verification_timestamp": datetime.utcnow().isoformat() + "verification_timestamp": datetime.now(datetime.UTC).isoformat() } if not verification_result["hash_match"] and not force: @@ -108,7 +108,7 @@ def genesis_hash(ctx, chain: str): "genesis_hash": calculated_hash, "genesis_timestamp": chain_genesis.get("timestamp"), "genesis_size": len(genesis_string), - "calculated_at": datetime.utcnow().isoformat(), + "calculated_at": datetime.now(datetime.UTC).isoformat(), "genesis_summary": { "accounts": len(chain_genesis.get("accounts", [])), "authorities": len(chain_genesis.get("authorities", [])), @@ -131,7 +131,7 @@ def verify_signature(ctx, signer: str, message: Optional[str], chain: Optional[s """Verify digital signature for genesis or transactions""" if not message: - message = f"Genesis verification for {chain or 'all chains'} at {datetime.utcnow().isoformat()}" + message = f"Genesis verification for {chain or 'all chains'} at {datetime.now(datetime.UTC).isoformat()}" # Create signature (simplified for demo) signature_data = f"{signer}:{message}:{chain or 'global'}" @@ -143,7 +143,7 @@ def verify_signature(ctx, signer: str, message: Optional[str], chain: Optional[s "message": message, "chain": chain, "signature": signature, - "verification_timestamp": datetime.utcnow().isoformat(), + "verification_timestamp": datetime.now(datetime.UTC).isoformat(), "signature_valid": True # In real implementation, this would verify against actual signature } @@ -202,7 +202,7 @@ def network_verify_genesis(ctx, all_chains: bool, chain: Optional[str], network_ network_results = { "verification_type": "network_wide" if network_wide else "selective", "chains_verified": chains_to_verify, - "verification_timestamp": datetime.utcnow().isoformat(), + "verification_timestamp": datetime.now(datetime.UTC).isoformat(), "chain_results": {}, "overall_consensus": True, "total_chains": len(chains_to_verify) @@ -280,7 +280,7 @@ def protect(ctx, chain: str, protection_level: str, backup: bool): # Create backup if requested if backup: - backup_file = Path.home() / ".aitbc" / f"genesis_backup_{chain}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json" + backup_file = Path.home() / ".aitbc" / f"genesis_backup_{chain}_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}.json" with open(backup_file, 'w') as f: json.dump(genesis_data, f, indent=2) success(f"Genesis backup created: {backup_file}") @@ -291,7 +291,7 @@ def protect(ctx, chain: str, protection_level: str, backup: bool): protection_config = { "chain": chain, "protection_level": protection_level, - "applied_at": datetime.utcnow().isoformat(), + "applied_at": datetime.now(datetime.UTC).isoformat(), "protection mechanisms": [] } diff --git a/cli/commands/global_infrastructure.py b/cli/commands/global_infrastructure.py index dc3c5e9e..d998c6fc 100755 --- a/cli/commands/global_infrastructure.py +++ b/cli/commands/global_infrastructure.py @@ -6,7 +6,7 @@ Commands for managing global infrastructure deployment and multi-region optimiza import click import json import requests -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Any, List, Optional @click.group() @@ -35,7 +35,7 @@ def deploy_region(region_id, name, location, endpoint, capacity, compliance_leve "current_load": 0, "latency_ms": 0, "compliance_level": compliance_level, - "deployed_at": datetime.utcnow().isoformat() + "deployed_at": datetime.now(datetime.UTC).isoformat() } if test_mode: @@ -295,7 +295,7 @@ def deploy_service(service_name, target_regions, strategy, configuration, test_m "configuration": config_data, "deployment_strategy": strategy, "health_checks": ["/health", "/api/health"], - "created_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat() } if test_mode: diff --git a/cli/commands/market_maker.py b/cli/commands/market_maker.py index d30b21b7..7a367f3d 100755 --- a/cli/commands/market_maker.py +++ b/cli/commands/market_maker.py @@ -6,7 +6,7 @@ import uuid import httpx from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from utils import output, error, success, warning @@ -56,7 +56,7 @@ def create(ctx, exchange: str, pair: str, spread: float, depth: float, max_order "orders_placed": 0, "orders_filled": 0 }, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "last_updated": None, "description": description or f"Market making bot for {pair} on {exchange}", "current_orders": [], @@ -144,7 +144,7 @@ def config(ctx, bot_id: str, spread: Optional[float], depth: Optional[float], ma return # Update timestamp - bot["last_updated"] = datetime.utcnow().isoformat() + bot["last_updated"] = datetime.now(datetime.UTC).isoformat() # Save bots with open(bots_file, 'w') as f: @@ -187,8 +187,8 @@ def start(ctx, bot_id: str, dry_run: bool): # Update bot status bot["status"] = "running" if not dry_run else "simulation" - bot["started_at"] = datetime.utcnow().isoformat() - bot["last_updated"] = datetime.utcnow().isoformat() + bot["started_at"] = datetime.now(datetime.UTC).isoformat() + bot["last_updated"] = datetime.now(datetime.UTC).isoformat() bot["dry_run"] = dry_run # Initialize performance tracking for this run @@ -244,8 +244,8 @@ def stop(ctx, bot_id: str): # Update bot status bot["status"] = "stopped" - bot["stopped_at"] = datetime.utcnow().isoformat() - bot["last_updated"] = datetime.utcnow().isoformat() + bot["stopped_at"] = datetime.now(datetime.UTC).isoformat() + bot["last_updated"] = datetime.now(datetime.UTC).isoformat() # Cancel all current orders (simulation) bot["current_orders"] = [] @@ -318,7 +318,7 @@ def performance(ctx, bot_id: Optional[str], exchange: Optional[str], pair: Optio bot_performance["current_run"] = current_run if "started_at" in current_run: start_time = datetime.fromisoformat(current_run["started_at"].replace('Z', '+00:00')) - runtime = datetime.utcnow() - start_time + runtime = datetime.now(datetime.UTC) - start_time bot_performance["run_time_hours"] = runtime.total_seconds() / 3600 performance_data[current_bot_id] = bot_performance @@ -330,7 +330,7 @@ def performance(ctx, bot_id: Optional[str], exchange: Optional[str], pair: Optio output({ "performance_data": performance_data, "total_bots": len(performance_data), - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() }) @@ -397,7 +397,7 @@ def status(ctx, bot_id: str): uptime_hours = None if bot["status"] in ["running", "simulation"] and "started_at" in bot: start_time = datetime.fromisoformat(bot["started_at"].replace('Z', '+00:00')) - uptime = datetime.utcnow() - start_time + uptime = datetime.now(datetime.UTC) - start_time uptime_hours = uptime.total_seconds() / 3600 output({ diff --git a/cli/commands/multisig.py b/cli/commands/multisig.py index 0876d5e9..9c1c92e2 100755 --- a/cli/commands/multisig.py +++ b/cli/commands/multisig.py @@ -6,7 +6,7 @@ import hashlib import uuid from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from utils import output, error, success, warning @@ -42,7 +42,7 @@ def create(ctx, threshold: int, owners: str, name: Optional[str], description: O "threshold": threshold, "owners": owner_list, "status": "active", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "description": description or f"Multi-signature wallet with {threshold}/{len(owner_list)} threshold", "transactions": [], "proposals": [], @@ -112,7 +112,7 @@ def propose(ctx, wallet_id: str, recipient: str, amount: float, description: Opt "amount": amount, "description": description or f"Send {amount} to {recipient}", "status": "pending", - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "signatures": [], "threshold": wallet["threshold"], "owners": wallet["owners"] @@ -190,7 +190,7 @@ def sign(ctx, proposal_id: str, signer: str, private_key: Optional[str]): signature_obj = { "signer": signer, "signature": signature, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } target_proposal["signatures"].append(signature_obj) @@ -198,7 +198,7 @@ def sign(ctx, proposal_id: str, signer: str, private_key: Optional[str]): # Check if threshold reached if len(target_proposal["signatures"]) >= target_proposal["threshold"]: target_proposal["status"] = "approved" - target_proposal["approved_at"] = datetime.utcnow().isoformat() + target_proposal["approved_at"] = datetime.now(datetime.UTC).isoformat() # Add to transactions transaction = { @@ -411,9 +411,9 @@ def challenge(ctx, proposal_id: str): challenge_data = { "challenge_id": f"challenge_{str(uuid.uuid4())[:8]}", "proposal_id": proposal_id, - "challenge": hashlib.sha256(f"{proposal_id}:{datetime.utcnow().isoformat()}".encode()).hexdigest(), - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(hours=1)).isoformat() + "challenge": hashlib.sha256(f"{proposal_id}:{datetime.now(datetime.UTC).isoformat()}".encode()).hexdigest(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat() } # Store challenge (in a real implementation, this would be more secure) diff --git a/cli/commands/oracle.py b/cli/commands/oracle.py index effb9c64..1f44130b 100755 --- a/cli/commands/oracle.py +++ b/cli/commands/oracle.py @@ -4,7 +4,7 @@ import click import json from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from utils import output, error, success, warning @@ -41,7 +41,7 @@ def set_price(ctx, pair: str, price: float, source: str, confidence: float, desc "source": source, "confidence": confidence, "description": description or f"Price set by {source}", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "volume": 0.0, "spread": 0.0 } @@ -155,7 +155,7 @@ def price_history(ctx, pair: Optional[str], days: int, limit: int, source: Optio # Filter data history_data = {} - cutoff_time = datetime.utcnow() - timedelta(days=days) + cutoff_time = datetime.now(datetime.UTC) - timedelta(days=days) for pair_name, pair_data in oracle_data.items(): if pair and pair_name != pair: @@ -193,7 +193,7 @@ def price_history(ctx, pair: Optional[str], days: int, limit: int, source: Optio "limit": limit, "source": source or "all" }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() }) @@ -259,7 +259,7 @@ def price_feed(ctx, pairs: Optional[str], interval: int, sources: Optional[str]) "interval": interval, "sources": source_list or "all" }, - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), "total_pairs": len(feed_data) }) @@ -282,7 +282,7 @@ def analyze(ctx, pair: Optional[str], hours: int): with open(oracle_file, 'r') as f: oracle_data = json.load(f) - cutoff_time = datetime.utcnow() - timedelta(hours=hours) + cutoff_time = datetime.now(datetime.UTC) - timedelta(hours=hours) analysis_results = {} for pair_name, pair_data in oracle_data.items(): @@ -334,7 +334,7 @@ def analyze(ctx, pair: Optional[str], hours: int): "pair": pair or "all", "time_window_hours": hours }, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() }) diff --git a/cli/commands/plugin_marketplace.py b/cli/commands/plugin_marketplace.py index 683d4062..672b327a 100755 --- a/cli/commands/plugin_marketplace.py +++ b/cli/commands/plugin_marketplace.py @@ -6,7 +6,7 @@ Commands for browsing, purchasing, and managing plugins from the marketplace import click import json import requests -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Any, List, Optional @click.group() @@ -312,7 +312,7 @@ def purchase(plugin_id, test_mode): "price": plugin.get('price', 0.0), "currency": plugin.get('pricing', {}).get('currency', 'USD'), "payment_method": "credit_card", - "purchased_at": datetime.utcnow().isoformat() + "purchased_at": datetime.now(datetime.UTC).isoformat() } response = requests.post( diff --git a/cli/commands/plugin_registry.py b/cli/commands/plugin_registry.py index 825f73a8..8669f4b4 100755 --- a/cli/commands/plugin_registry.py +++ b/cli/commands/plugin_registry.py @@ -6,7 +6,7 @@ Commands for managing plugin registration, versioning, and discovery import click import json import requests -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path from typing import Dict, Any, List, Optional @@ -46,8 +46,8 @@ def register(plugin_id, name, version, description, author, category, tags, repo "homepage": homepage, "license": license, "status": "active", - "created_at": datetime.utcnow().isoformat(), - "updated_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "updated_at": datetime.now(datetime.UTC).isoformat(), "downloads": 0, "rating": 0.0, "reviews_count": 0 @@ -55,7 +55,7 @@ def register(plugin_id, name, version, description, author, category, tags, repo if test_mode: # Mock registration for testing - plugin_data["registration_id"] = f"reg_{int(datetime.utcnow().timestamp())}" + plugin_data["registration_id"] = f"reg_{int(datetime.now(datetime.UTC).timestamp())}" plugin_data["status"] = "registered" click.echo(f"✅ Plugin registered successfully (test mode)") click.echo(f"📋 Plugin ID: {plugin_data['plugin_id']}") @@ -304,7 +304,7 @@ def update_version(plugin_id, version, changelog, test_mode): update_data = { "version": version, "changelog": changelog, - "updated_at": datetime.utcnow().isoformat() + "updated_at": datetime.now(datetime.UTC).isoformat() } if test_mode: diff --git a/cli/commands/production_deploy.py b/cli/commands/production_deploy.py index e91f408f..72ab73e5 100755 --- a/cli/commands/production_deploy.py +++ b/cli/commands/production_deploy.py @@ -7,7 +7,7 @@ import click import json import requests import subprocess -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Any, List, Optional @click.group() @@ -82,7 +82,7 @@ def deploy(environment, version, region, dry_run, force): click.echo(f"🌍 Environment: {environment}") click.echo(f"📦 Version: {version}") click.echo(f"🗺️ Region: {region}") - click.echo(f"📅 Deployed at: {datetime.utcnow().isoformat()}") + click.echo(f"📅 Deployed at: {datetime.now(datetime.UTC).isoformat()}") if not dry_run: click.echo("🔗 Service URLs:") @@ -131,7 +131,7 @@ def rollback(environment, backup_id, dry_run): if rollback_result['success']: click.echo("✅ Rollback completed successfully!") click.echo(f"📦 New Version: {backup_info['version']}") - click.echo(f"📅 Rolled back at: {datetime.utcnow().isoformat()}") + click.echo(f"📅 Rolled back at: {datetime.now(datetime.UTC).isoformat()}") else: click.echo(f"❌ Rollback failed: {rollback_result['error']}") else: @@ -361,10 +361,10 @@ def run_pre_deployment_checks(environment, dry_run): def create_backup(environment): """Create backup of current deployment""" - backup_id = f"backup_{environment}_{int(datetime.utcnow().timestamp())}" + backup_id = f"backup_{environment}_{int(datetime.now(datetime.UTC).timestamp())}" return { "backup_id": backup_id, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "status": "completed" } @@ -406,7 +406,7 @@ def rollback_deployment(environment, backup_id): return { "status": "completed", "backup_id": backup_id, - "rolled_back_at": datetime.utcnow().isoformat() + "rolled_back_at": datetime.now(datetime.UTC).isoformat() } def get_current_deployment_info(environment): @@ -492,7 +492,7 @@ def restart_services(environment, services): return { "success": True, "restarted_services": services, - "restarted_at": datetime.utcnow().isoformat() + "restarted_at": datetime.now(datetime.UTC).isoformat() } def run_production_tests(environment, test_type, timeout): diff --git a/cli/commands/transfer_control.py b/cli/commands/transfer_control.py index c2b5d69d..431af420 100755 --- a/cli/commands/transfer_control.py +++ b/cli/commands/transfer_control.py @@ -4,7 +4,7 @@ import click import json from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from utils import output, error, success, warning @@ -38,8 +38,8 @@ def set_limit(ctx, wallet: str, max_daily: Optional[float], max_weekly: Optional # Create or update wallet limits wallet_limits = limits.get(wallet, { "wallet": wallet, - "created_at": datetime.utcnow().isoformat(), - "updated_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "updated_at": datetime.now(datetime.UTC).isoformat(), "status": "active" }) @@ -59,14 +59,14 @@ def set_limit(ctx, wallet: str, max_daily: Optional[float], max_weekly: Optional if blacklist: wallet_limits["blacklist"] = [addr.strip() for addr in blacklist.split(',')] - wallet_limits["updated_at"] = datetime.utcnow().isoformat() + wallet_limits["updated_at"] = datetime.now(datetime.UTC).isoformat() # Initialize usage tracking if "usage" not in wallet_limits: wallet_limits["usage"] = { - "daily": {"amount": 0.0, "count": 0, "reset_at": datetime.utcnow().isoformat()}, - "weekly": {"amount": 0.0, "count": 0, "reset_at": datetime.utcnow().isoformat()}, - "monthly": {"amount": 0.0, "count": 0, "reset_at": datetime.utcnow().isoformat()} + "daily": {"amount": 0.0, "count": 0, "reset_at": datetime.now(datetime.UTC).isoformat()}, + "weekly": {"amount": 0.0, "count": 0, "reset_at": datetime.now(datetime.UTC).isoformat()}, + "monthly": {"amount": 0.0, "count": 0, "reset_at": datetime.now(datetime.UTC).isoformat()} } # Save limits @@ -100,10 +100,10 @@ def time_lock(ctx, wallet: str, amount: float, duration: int, recipient: str, de """Create a time-locked transfer""" # Generate lock ID - lock_id = f"lock_{str(int(datetime.utcnow().timestamp()))[-8:]}" + lock_id = f"lock_{str(int(datetime.now(datetime.UTC).timestamp()))[-8:]}" # Calculate release time - release_time = datetime.utcnow() + timedelta(days=duration) + release_time = datetime.now(datetime.UTC) + timedelta(days=duration) # Create time lock time_lock = { @@ -112,7 +112,7 @@ def time_lock(ctx, wallet: str, amount: float, duration: int, recipient: str, de "recipient": recipient, "amount": amount, "duration_days": duration, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "release_time": release_time.isoformat(), "status": "locked", "description": description or f"Time-locked transfer of {amount} to {recipient}", @@ -159,11 +159,11 @@ def vesting_schedule(ctx, wallet: str, total_amount: float, duration: int, cliff """Create a vesting schedule for token release""" # Generate schedule ID - schedule_id = f"vest_{str(int(datetime.utcnow().timestamp()))[-8:]}" + schedule_id = f"vest_{str(int(datetime.now(datetime.UTC).timestamp()))[-8:]}" # Calculate vesting schedule - start_time = datetime.utcnow() + timedelta(days=cliff_period) - end_time = datetime.utcnow() + timedelta(days=duration) + start_time = datetime.now(datetime.UTC) + timedelta(days=cliff_period) + end_time = datetime.now(datetime.UTC) + timedelta(days=duration) # Create release events releases = [] @@ -188,7 +188,7 @@ def vesting_schedule(ctx, wallet: str, total_amount: float, duration: int, cliff "duration_days": duration, "cliff_period_days": cliff_period, "release_interval_days": release_interval, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "start_time": start_time.isoformat(), "end_time": end_time.isoformat(), "status": "active", @@ -239,7 +239,7 @@ def audit_trail(ctx, wallet: Optional[str], status: Optional[str]): "time_locks": {}, "vesting_schedules": {}, "transfers": {}, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Load transfer limits @@ -318,7 +318,7 @@ def status(ctx, wallet: Optional[str]): "wallet_limits": {}, "active_time_locks": {}, "active_vesting_schedules": {}, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } # Load and filter limits @@ -410,7 +410,7 @@ def release_time_lock(ctx, lock_id: str): # Check if lock can be released release_time = datetime.fromisoformat(lock_data["release_time"]) - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) if current_time < release_time: error(f"Time lock cannot be released until {release_time.isoformat()}") @@ -454,7 +454,7 @@ def release_vesting(ctx, schedule_id: str): return schedule = vesting_schedules[schedule_id] - current_time = datetime.utcnow() + current_time = datetime.now(datetime.UTC) # Find available releases available_releases = [] diff --git a/cli/commands/wallet.py b/cli/commands/wallet.py index e6063fed..64c05c36 100755 --- a/cli/commands/wallet.py +++ b/cli/commands/wallet.py @@ -8,7 +8,7 @@ import shutil import yaml from pathlib import Path from typing import Optional, Dict, Any, List -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from utils import output, error, success, encrypt_value, decrypt_value import getpass @@ -398,7 +398,7 @@ def backup(ctx, name: str, destination: Optional[str]): { "wallet": name, "backup_path": destination, - "timestamp": datetime.utcnow().isoformat() + "Z", + "timestamp": datetime.now(datetime.UTC).isoformat() + "Z", } ) @@ -438,7 +438,7 @@ def restore(ctx, backup_path: str, name: str, force: bool): # Update wallet name if needed wallet_data["wallet_id"] = name - wallet_data["restored_at"] = datetime.utcnow().isoformat() + "Z" + wallet_data["restored_at"] = datetime.now(datetime.UTC).isoformat() + "Z" # Save restored wallet (preserve encryption state) # If wallet was encrypted, we save it as-is (still encrypted with original password) @@ -550,7 +550,7 @@ def balance(ctx): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0.0, "transactions": [], } @@ -1081,7 +1081,7 @@ def rewards(ctx): "address": address, "public_key": public_key, "private_key": private_key, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", "balance": 0.0, "transactions": [], } @@ -2103,7 +2103,7 @@ def multisig_create(ctx, threshold: int, signers: tuple, wallet_name: Optional[s "threshold": threshold, "signers": list(signers), "wallet_name": wallet_name or f"multisig_{int(datetime.now().timestamp())}", - "created_at": datetime.utcnow().isoformat() + "created_at": datetime.now(datetime.UTC).isoformat() } if chain_id: @@ -2164,7 +2164,7 @@ def set_limit(ctx, amount: float, period: str, wallet_name: Optional[str]): limit_data = { "amount": amount, "period": period, - "set_at": datetime.utcnow().isoformat() + "set_at": datetime.now(datetime.UTC).isoformat() } try: @@ -2225,8 +2225,8 @@ def time_lock(ctx, amount: float, duration: int, recipient: str, wallet_name: Op "duration_hours": duration, "recipient": recipient, "wallet_name": wallet_name or "default", - "created_at": datetime.utcnow().isoformat(), - "unlock_time": (datetime.utcnow() + timedelta(hours=duration)).isoformat() + "created_at": datetime.now(datetime.UTC).isoformat(), + "unlock_time": (datetime.now(datetime.UTC) + timedelta(hours=duration)).isoformat() } try: @@ -2346,7 +2346,7 @@ def audit_trail(ctx, wallet_name: Optional[str], days: int): audit_data = { "wallet_name": wallet_name or "all", "audit_period_days": days, - "generated_at": datetime.utcnow().isoformat() + "generated_at": datetime.now(datetime.UTC).isoformat() } try: @@ -2371,7 +2371,7 @@ def audit_trail(ctx, wallet_name: Optional[str], days: int): audit_file.parent.mkdir(parents=True, exist_ok=True) # Generate sample audit data - cutoff_date = datetime.utcnow() - timedelta(days=days) + cutoff_date = datetime.now(datetime.UTC) - timedelta(days=days) audit_data["transactions"] = [] audit_data["signatures"] = [] diff --git a/cli/examples/miner.py b/cli/examples/miner.py index d6382b08..48dbf13d 100755 --- a/cli/examples/miner.py +++ b/cli/examples/miner.py @@ -8,7 +8,7 @@ import httpx import json import sys import time -from datetime import datetime +from datetime import datetime, UTC from typing import Optional # Configuration @@ -108,7 +108,7 @@ class AITBCMiner: "status": "ONLINE", "inflight": 0, "metadata": { - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": 75, "gpu_memory_used": 8000, "gpu_temperature": 65 diff --git a/cli/utils/secure_audit.py b/cli/utils/secure_audit.py index 12cb6bc0..aa355c1a 100755 --- a/cli/utils/secure_audit.py +++ b/cli/utils/secure_audit.py @@ -7,7 +7,7 @@ import json import hashlib import secrets from pathlib import Path -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, List, Optional, Tuple from eth_utils import keccak @@ -34,7 +34,7 @@ class SecureAuditLogger: "genesis_hash": None, "last_hash": None, "entry_count": 0, - "created_at": datetime.utcnow().isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), "version": "1.0" } with open(self.integrity_file, "w") as f: @@ -54,7 +54,7 @@ class SecureAuditLogger: integrity_data["last_hash"] = entry_hash integrity_data["entry_count"] += 1 - integrity_data["last_updated"] = datetime.utcnow().isoformat() + integrity_data["last_updated"] = datetime.now(datetime.UTC).isoformat() with open(self.integrity_file, "w") as f: json.dump(integrity_data, f, indent=2) @@ -99,7 +99,7 @@ class SecureAuditLogger: # Create audit entry entry = { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "action": action, "user": user or "unknown", "details": details or {}, @@ -239,7 +239,7 @@ class SecureAuditLogger: # Create report report = { "audit_report": { - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), "integrity": { "is_valid": is_valid, "issues": issues diff --git a/dev/cache/aitbc_cache/gpu_marketplace_cache.py b/dev/cache/aitbc_cache/gpu_marketplace_cache.py index 59369659..5bcc376b 100755 --- a/dev/cache/aitbc_cache/gpu_marketplace_cache.py +++ b/dev/cache/aitbc_cache/gpu_marketplace_cache.py @@ -9,7 +9,7 @@ import asyncio import logging from typing import Dict, List, Optional, Any, Tuple from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import json from .event_driven_cache import ( @@ -110,7 +110,7 @@ class GPUMarketplaceCacheManager: 'region': region, 'gpu_type': gpu_type, 'include_busy': include_busy, - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } cached_data = await self.cache.get('gpu_availability', params) @@ -153,7 +153,7 @@ class GPUMarketplaceCacheManager: for gpu in gpus: if gpu.gpu_id == gpu_id: gpu.availability_status = new_status - gpu.last_updated = datetime.utcnow() + gpu.last_updated = datetime.now(datetime.UTC) updated_gpu = gpu break @@ -175,7 +175,7 @@ class GPUMarketplaceCacheManager: params = { 'gpu_type': gpu_type, 'region': region, - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } cached_data = await self.cache.get('gpu_pricing', params) @@ -307,7 +307,7 @@ class GPUMarketplaceCacheManager: async def get_market_stats(self) -> MarketStats: """Get current market statistics""" - params = {'timestamp': datetime.utcnow().isoformat()} + params = {'timestamp': datetime.now(datetime.UTC).isoformat()} cached_data = await self.cache.get('market_stats', params) if cached_data: @@ -334,7 +334,7 @@ class GPUMarketplaceCacheManager: total_bookings_24h=0, # Would be calculated from database total_volume_24h=0.0, # Would be calculated from database utilization_rate=utilization_rate, - last_updated=datetime.utcnow() + last_updated=datetime.now(datetime.UTC) ) # Cache the statistics diff --git a/dev/gpu/gpu_miner_host.py b/dev/gpu/gpu_miner_host.py index e3baf4cd..9086f041 100755 --- a/dev/gpu/gpu_miner_host.py +++ b/dev/gpu/gpu_miner_host.py @@ -10,7 +10,7 @@ import logging import sys import subprocess import os -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, Optional # Configuration @@ -211,7 +211,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": gpu_info["utilization"], "memory_used": gpu_info["memory_used"], "memory_total": gpu_info["memory_total"], @@ -223,7 +223,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": 0, "memory_used": 0, "memory_total": 0, diff --git a/dev/gpu/gpu_registry_demo.py b/dev/gpu/gpu_registry_demo.py index ff6a135f..0bfab83f 100755 --- a/dev/gpu/gpu_registry_demo.py +++ b/dev/gpu/gpu_registry_demo.py @@ -7,7 +7,7 @@ from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Dict, Any, Optional import uvicorn -from datetime import datetime +from datetime import datetime, UTC app = FastAPI(title="GPU Registry Demo") @@ -37,8 +37,8 @@ async def register_gpu(miner_id: str, gpu_data: GPURegistration): """Register a GPU miner""" registered_gpus[miner_id] = { "id": miner_id, - "registered_at": datetime.utcnow().isoformat(), - "last_heartbeat": datetime.utcnow().isoformat(), + "registered_at": datetime.now(datetime.UTC).isoformat(), + "last_heartbeat": datetime.now(datetime.UTC).isoformat(), **gpu_data.dict() } return {"status": "ok", "message": f"GPU {miner_id} registered successfully"} @@ -49,7 +49,7 @@ async def heartbeat(miner_id: str, heartbeat_data: Heartbeat): if miner_id not in registered_gpus: raise HTTPException(status_code=404, detail="GPU not registered") - registered_gpus[miner_id]["last_heartbeat"] = datetime.utcnow().isoformat() + registered_gpus[miner_id]["last_heartbeat"] = datetime.now(datetime.UTC).isoformat() registered_gpus[miner_id]["status"] = heartbeat_data.status registered_gpus[miner_id]["metadata"] = heartbeat_data.metadata diff --git a/dev/onboarding/auto-onboard.py b/dev/onboarding/auto-onboard.py index 603d93f6..6f6fe516 100755 --- a/dev/onboarding/auto-onboard.py +++ b/dev/onboarding/auto-onboard.py @@ -12,7 +12,7 @@ import sys import os import subprocess import logging -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path # Configure logging @@ -27,7 +27,7 @@ class AgentOnboarder: def __init__(self): self.session = { - 'start_time': datetime.utcnow(), + 'start_time': datetime.now(datetime.UTC), 'steps_completed': [], 'errors': [], 'agent': None @@ -142,9 +142,9 @@ class AgentOnboarder: # Check network bandwidth (simplified) try: - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) requests.get('https://api.aitbc.bubuit.net/v1/health', timeout=5) - latency = (datetime.utcnow() - start_time).total_seconds() + latency = (datetime.now(datetime.UTC) - start_time).total_seconds() capabilities['network_latency'] = latency logger.info(f"✅ Network latency: {latency:.2f}s") except: @@ -233,7 +233,7 @@ class AgentOnboarder: if agent_type == 'compute_provider': from aitbc_agent.compute_provider import ComputeProvider agent = ComputeProvider.register( - agent_name=f"auto-provider-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}", + agent_name=f"auto-provider-{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}", capabilities={ "compute_type": "inference", "gpu_memory": capabilities.get('gpu_memory', 0), @@ -245,7 +245,7 @@ class AgentOnboarder: elif agent_type == 'compute_consumer': from aitbc_agent.compute_consumer import ComputeConsumer agent = ComputeConsumer.create( - agent_name=f"auto-consumer-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}", + agent_name=f"auto-consumer-{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}", capabilities={ "compute_type": "inference", "task_requirements": {"min_performance": 0.8} @@ -255,7 +255,7 @@ class AgentOnboarder: elif agent_type == 'platform_builder': from aitbc_agent.platform_builder import PlatformBuilder agent = PlatformBuilder.create( - agent_name=f"auto-builder-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}", + agent_name=f"auto-builder-{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}", capabilities={ "specializations": capabilities.get('specializations', []) } @@ -264,7 +264,7 @@ class AgentOnboarder: elif agent_type == 'swarm_coordinator': from aitbc_agent.swarm_coordinator import SwarmCoordinator agent = SwarmCoordinator.create( - agent_name=f"auto-coordinator-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}", + agent_name=f"auto-coordinator-{datetime.now(datetime.UTC).strftime('%Y%m%d%H%M%S')}", capabilities={ "specialization": "load_balancing", "analytical_skills": "high" @@ -376,8 +376,8 @@ class AgentOnboarder: report = { 'onboarding': { - 'timestamp': datetime.utcnow().isoformat(), - 'duration_minutes': (datetime.utcnow() - self.session['start_time']).total_seconds() / 60, + 'timestamp': datetime.now(datetime.UTC).isoformat(), + 'duration_minutes': (datetime.now(datetime.UTC) - self.session['start_time']).total_seconds() / 60, 'status': 'success', 'agent_id': agent.identity.id, 'agent_name': agent.identity.name, diff --git a/dev/onboarding/onboarding-monitor.py b/dev/onboarding/onboarding-monitor.py index 12abd249..22704758 100755 --- a/dev/onboarding/onboarding-monitor.py +++ b/dev/onboarding/onboarding-monitor.py @@ -11,7 +11,7 @@ import json import sys import time import logging -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from pathlib import Path import requests from collections import defaultdict @@ -197,7 +197,7 @@ class OnboardingMonitor: metrics = self.calculate_metrics() report = { - 'timestamp': datetime.utcnow().isoformat(), + 'timestamp': datetime.now(datetime.UTC).isoformat(), 'summary': { 'total_onboardings': self.metrics['total_onboardings'], 'successful_onboardings': self.metrics['successful_onboardings'], diff --git a/dev/scripts/patches/patch_poa_genesis.py b/dev/scripts/patches/patch_poa_genesis.py index 0d138e0b..da980f86 100755 --- a/dev/scripts/patches/patch_poa_genesis.py +++ b/dev/scripts/patches/patch_poa_genesis.py @@ -8,7 +8,7 @@ content = content.replace( if head is not None: return - timestamp = datetime.utcnow() + timestamp = datetime.now(datetime.UTC) block_hash = self._compute_block_hash(0, "0x00", timestamp) genesis = Block( height=0, @@ -25,7 +25,7 @@ content = content.replace( if head is not None: return - timestamp = datetime.utcnow() + timestamp = datetime.now(datetime.UTC) block_hash = self._compute_block_hash(0, "0x00", timestamp) genesis = Block( chain_id=self._config.chain_id, diff --git a/dev/scripts/patches/patch_poa_genesis_fixed.py b/dev/scripts/patches/patch_poa_genesis_fixed.py index ad760e05..ebf84f70 100755 --- a/dev/scripts/patches/patch_poa_genesis_fixed.py +++ b/dev/scripts/patches/patch_poa_genesis_fixed.py @@ -2,7 +2,7 @@ with open("/home/oib/windsurf/aitbc/apps/blockchain-node/src/aitbc_chain/consens content = f.read() content = content.replace( - """ timestamp = datetime.utcnow() + """ timestamp = datetime.now(datetime.UTC) block_hash = self._compute_block_hash(0, "0x00", timestamp)""", """ # Use a deterministic genesis timestamp so all nodes agree on the genesis block hash timestamp = datetime(2025, 1, 1, 0, 0, 0) diff --git a/docs/agent-sdk/examples/oracle_agent.py b/docs/agent-sdk/examples/oracle_agent.py index 94e69c18..e6204161 100644 --- a/docs/agent-sdk/examples/oracle_agent.py +++ b/docs/agent-sdk/examples/oracle_agent.py @@ -8,7 +8,7 @@ import asyncio import logging import requests from typing import Dict, Any, List -from datetime import datetime +from datetime import datetime, UTC from aitbc_agent_sdk import Agent, AgentConfig from aitbc_agent_sdk.blockchain import BlockchainClient from aitbc_agent_sdk.oracle import OracleProvider @@ -120,7 +120,7 @@ class OracleAgentExample: # Prepare oracle data package oracle_data = { "data_type": data_type, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "data": data, "agent_address": self.agent.address, "signature": await self.oracle_provider.sign_data(data) @@ -243,13 +243,13 @@ class OracleAgentExample: { "title": "AI Technology Breakthrough Announced", "source": "Tech News", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "sentiment": "positive" }, { "title": "Cryptocurrency Market Sees Major Movement", "source": "Financial Times", - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "sentiment": "neutral" } ] @@ -266,7 +266,7 @@ class OracleAgentExample: return { "success": True, "data": data, - "timestamp": datetime.utcnow().isoformat() + "timestamp": datetime.now(datetime.UTC).isoformat() } else: return { @@ -284,7 +284,7 @@ class OracleAgentExample: "is_running": self.is_running, "balance": balance, "data_sources": list(self.data_sources.keys()), - "last_update": datetime.utcnow().isoformat() + "last_update": datetime.now(datetime.UTC).isoformat() } async def main(): diff --git a/infra/scripts/chaos_orchestrator.py b/infra/scripts/chaos_orchestrator.py index 91c8ee9c..11036a0f 100755 --- a/infra/scripts/chaos_orchestrator.py +++ b/infra/scripts/chaos_orchestrator.py @@ -11,7 +11,7 @@ import logging import subprocess import sys import time -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from pathlib import Path from typing import Dict, List, Optional @@ -108,7 +108,7 @@ class ChaosOrchestrator: def generate_report(self, output_file: Optional[str] = None): """Generate a comprehensive chaos test report""" report = { - "report_generated": datetime.utcnow().isoformat(), + "report_generated": datetime.now(datetime.UTC).isoformat(), "namespace": self.namespace, "orchestration": self.results, "recommendations": [] @@ -204,7 +204,7 @@ class ChaosOrchestrator: async def run_all_scenarios(self, scenarios: List[str], scenario_args: Dict[str, List[str]]): """Run all specified chaos test scenarios""" logger.info("Starting chaos testing orchestration") - self.results["orchestration_start"] = datetime.utcnow().isoformat() + self.results["orchestration_start"] = datetime.now(datetime.UTC).isoformat() for scenario in scenarios: args = scenario_args.get(scenario, []) @@ -215,7 +215,7 @@ class ChaosOrchestrator: if result: self.results["scenarios"].append(result) - self.results["orchestration_end"] = datetime.utcnow().isoformat() + self.results["orchestration_end"] = datetime.now(datetime.UTC).isoformat() # Calculate summary metrics self.calculate_summary_metrics() diff --git a/infra/scripts/chaos_test_coordinator.py b/infra/scripts/chaos_test_coordinator.py index e3d5610d..d5a1cfc1 100755 --- a/infra/scripts/chaos_test_coordinator.py +++ b/infra/scripts/chaos_test_coordinator.py @@ -12,7 +12,7 @@ import time import logging import subprocess import sys -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, List, Optional logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') @@ -192,7 +192,7 @@ class ChaosTestCoordinator: async def run_test(self, outage_duration: int = 60, load_duration: int = 120): """Run the complete chaos test""" logger.info("Starting coordinator outage chaos test") - self.metrics["test_start"] = datetime.utcnow().isoformat() + self.metrics["test_start"] = datetime.now(datetime.UTC).isoformat() # Phase 1: Generate initial load logger.info("Phase 1: Generating initial load") @@ -200,7 +200,7 @@ class ChaosTestCoordinator: # Phase 2: Induce outage logger.info("Phase 2: Inducing coordinator outage") - self.metrics["outage_start"] = datetime.utcnow().isoformat() + self.metrics["outage_start"] = datetime.now(datetime.UTC).isoformat() if not self.delete_coordinator_pods(): logger.error("Failed to induce outage") @@ -216,7 +216,7 @@ class ChaosTestCoordinator: # Phase 3: Monitor recovery logger.info("Phase 3: Monitoring service recovery") - self.metrics["outage_end"] = datetime.utcnow().isoformat() + self.metrics["outage_end"] = datetime.now(datetime.UTC).isoformat() if not await self.wait_for_recovery(): logger.error("Service did not recover") @@ -227,7 +227,7 @@ class ChaosTestCoordinator: await self.generate_load(load_duration) # Calculate metrics - self.metrics["test_end"] = datetime.utcnow().isoformat() + self.metrics["test_end"] = datetime.now(datetime.UTC).isoformat() self.metrics["mttr"] = self.metrics["recovery_time"] # Save results diff --git a/infra/scripts/chaos_test_database.py b/infra/scripts/chaos_test_database.py index 1a26e60d..3c894388 100755 --- a/infra/scripts/chaos_test_database.py +++ b/infra/scripts/chaos_test_database.py @@ -12,7 +12,7 @@ import time import logging import subprocess import sys -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, List, Optional logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') @@ -263,7 +263,7 @@ class ChaosTestDatabase: async def run_test(self, failure_type: str = "connection", failure_duration: int = 60): """Run the complete database chaos test""" logger.info(f"Starting database chaos test - failure type: {failure_type}") - self.metrics["test_start"] = datetime.utcnow().isoformat() + self.metrics["test_start"] = datetime.now(datetime.UTC).isoformat() # Phase 1: Baseline test logger.info("Phase 1: Baseline connectivity test") @@ -282,7 +282,7 @@ class ChaosTestDatabase: # Phase 3: Induce database failure logger.info("Phase 3: Inducing database failure") - self.metrics["failure_start"] = datetime.utcnow().isoformat() + self.metrics["failure_start"] = datetime.now(datetime.UTC).isoformat() if failure_type == "connection": if not self.simulate_database_connection_failure(): @@ -311,7 +311,7 @@ class ChaosTestDatabase: # Phase 5: Restore database and monitor recovery logger.info("Phase 5: Restoring database") - self.metrics["failure_end"] = datetime.utcnow().isoformat() + self.metrics["failure_end"] = datetime.now(datetime.UTC).isoformat() if not self.restore_database(): logger.error("Failed to restore database") @@ -327,7 +327,7 @@ class ChaosTestDatabase: await self.generate_load(60) # Final metrics - self.metrics["test_end"] = datetime.utcnow().isoformat() + self.metrics["test_end"] = datetime.now(datetime.UTC).isoformat() self.metrics["mttr"] = self.metrics["recovery_time"] # Save results diff --git a/infra/scripts/chaos_test_network.py b/infra/scripts/chaos_test_network.py index 381c1e7b..f43228f5 100755 --- a/infra/scripts/chaos_test_network.py +++ b/infra/scripts/chaos_test_network.py @@ -12,7 +12,7 @@ import time import logging import subprocess import sys -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, List, Optional logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') @@ -244,7 +244,7 @@ class ChaosTestNetwork: async def run_test(self, partition_duration: int = 60, partition_ratio: float = 0.5): """Run the complete network partition chaos test""" logger.info("Starting network partition chaos test") - self.metrics["test_start"] = datetime.utcnow().isoformat() + self.metrics["test_start"] = datetime.now(datetime.UTC).isoformat() # Get all blockchain pods all_pods = self.get_blockchain_pods() @@ -270,7 +270,7 @@ class ChaosTestNetwork: # Phase 3: Apply network partition logger.info("Phase 3: Applying network partition") - self.metrics["partition_start"] = datetime.utcnow().isoformat() + self.metrics["partition_start"] = datetime.now(datetime.UTC).isoformat() if not self.apply_network_partition(remaining_pods, partition_pods): logger.error("Failed to apply network partition") @@ -287,7 +287,7 @@ class ChaosTestNetwork: # Phase 5: Remove partition and monitor recovery logger.info("Phase 5: Removing network partition") - self.metrics["partition_end"] = datetime.utcnow().isoformat() + self.metrics["partition_end"] = datetime.now(datetime.UTC).isoformat() if not self.remove_network_partition(all_pods): logger.error("Failed to remove network partition") @@ -312,7 +312,7 @@ class ChaosTestNetwork: await self.generate_load(60) # Final metrics - self.metrics["test_end"] = datetime.utcnow().isoformat() + self.metrics["test_end"] = datetime.now(datetime.UTC).isoformat() self.metrics["mttr"] = self.metrics["recovery_time"] # Save results diff --git a/packages/py/aitbc-agent-sdk/src/aitbc_agent/agent.py b/packages/py/aitbc-agent-sdk/src/aitbc_agent/agent.py index 17a427f8..e75fd2e7 100755 --- a/packages/py/aitbc-agent-sdk/src/aitbc_agent/agent.py +++ b/packages/py/aitbc-agent-sdk/src/aitbc_agent/agent.py @@ -5,7 +5,7 @@ Core Agent class for AITBC network participation import asyncio import json import uuid -from datetime import datetime +from datetime import datetime, UTC from typing import Dict, List, Optional, Any from dataclasses import dataclass from cryptography.hazmat.primitives import hashes @@ -154,7 +154,7 @@ class Agent: "max_concurrent_jobs": self.capabilities.max_concurrent_jobs, "specialization": self.capabilities.specialization, }, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } # Sign registration data @@ -274,7 +274,7 @@ class Agent: "to": recipient_id, "type": message_type, "payload": payload, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } # Sign message diff --git a/packages/py/aitbc-agent-sdk/src/aitbc_agent/compute_provider.py b/packages/py/aitbc-agent-sdk/src/aitbc_agent/compute_provider.py index 200632ff..1fad145b 100755 --- a/packages/py/aitbc-agent-sdk/src/aitbc_agent/compute_provider.py +++ b/packages/py/aitbc-agent-sdk/src/aitbc_agent/compute_provider.py @@ -6,7 +6,7 @@ import asyncio import httpx import uuid from typing import Dict, List, Optional, Any -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from dataclasses import dataclass, asdict from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization @@ -233,7 +233,7 @@ class ComputeProvider(Agent): job = JobExecution( job_id=job_request["job_id"], consumer_id=job_request["consumer_id"], - start_time=datetime.utcnow(), + start_time=datetime.now(datetime.UTC), expected_duration=timedelta(hours=job_request["estimated_hours"]), ) @@ -286,7 +286,7 @@ class ComputeProvider(Agent): notification = { "job_id": job.job_id, "status": job.status, - "completion_time": datetime.utcnow().isoformat(), + "completion_time": datetime.now(datetime.UTC).isoformat(), "duration_hours": ( job.actual_duration.total_seconds() / 3600 if job.actual_duration diff --git a/packages/py/aitbc-agent-sdk/src/aitbc_agent/swarm_coordinator.py b/packages/py/aitbc-agent-sdk/src/aitbc_agent/swarm_coordinator.py index 487c34d7..1452b7e0 100755 --- a/packages/py/aitbc-agent-sdk/src/aitbc_agent/swarm_coordinator.py +++ b/packages/py/aitbc-agent-sdk/src/aitbc_agent/swarm_coordinator.py @@ -5,7 +5,7 @@ Swarm Coordinator - for agents participating in collective intelligence import asyncio import json from typing import Dict, List, Optional, Any # noqa: F401 -from datetime import datetime +from datetime import datetime, UTC from dataclasses import dataclass from .agent import Agent @@ -79,9 +79,9 @@ class SwarmCoordinator(Agent): self.joined_swarms[swarm_id] = { "type": swarm_type, "role": config.get("role", "participant"), - "joined_at": datetime.utcnow().isoformat(), + "joined_at": datetime.now(datetime.UTC).isoformat(), "contribution_count": 0, - "last_activity": datetime.utcnow().isoformat(), + "last_activity": datetime.now(datetime.UTC).isoformat(), } # Initialize swarm reputation @@ -115,7 +115,7 @@ class SwarmCoordinator(Agent): await self._participate_in_decisions(swarm_id) # Update activity timestamp - swarm_config["last_activity"] = datetime.utcnow().isoformat() + swarm_config["last_activity"] = datetime.now(datetime.UTC).isoformat() except Exception as e: logger.error(f"Swarm participation error for {swarm_id}: {e}") @@ -177,7 +177,7 @@ class SwarmCoordinator(Agent): message_type="data_contribution", priority="medium", payload=data, - timestamp=datetime.utcnow().isoformat(), + timestamp=datetime.now(datetime.UTC).isoformat(), swarm_signature="", # Will be added in broadcast_to_swarm ) @@ -285,7 +285,7 @@ class SwarmCoordinator(Agent): try: # Create coordination proposal proposal = { - "task_id": f"task_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}", + "task_id": f"task_{datetime.now(datetime.UTC).strftime('%Y%m%d_%H%M%S')}", "task_type": task, "coordinator_id": self.identity.id, "required_collaborators": collaborators, @@ -320,7 +320,7 @@ class SwarmCoordinator(Agent): message_type="intelligence_request", priority="high", payload={"request_type": "market_intelligence"}, - timestamp=datetime.utcnow().isoformat(), + timestamp=datetime.now(datetime.UTC).isoformat(), swarm_signature="", ) diff --git a/scripts/monitoring/monitor-prs.py b/scripts/monitoring/monitor-prs.py index 7a29936f..cdfc748f 100755 --- a/scripts/monitoring/monitor-prs.py +++ b/scripts/monitoring/monitor-prs.py @@ -11,7 +11,7 @@ import json import subprocess import tempfile import shutil -from datetime import datetime, timezone +from datetime import datetime, UTC, timezone GITEA_TOKEN = os.getenv('GITEA_TOKEN') or 'ffce3b62d583b761238ae00839dce7718acaad85' REPO = 'oib/aitbc' @@ -80,7 +80,7 @@ def is_claim_expired(state): expires_at = state.get('expires_at') if not expires_at: return False - now_ts = datetime.utcnow().timestamp() + now_ts = datetime.now(datetime.UTC).timestamp() return now_ts > expires_at def get_open_prs(): @@ -135,7 +135,7 @@ def validate_pr_branch(pr): shutil.rmtree(tmpdir, ignore_errors=True) def main(): - now = datetime.utcnow().replace(tzinfo=timezone.utc) + now = datetime.now(datetime.UTC).replace(tzinfo=timezone.utc) now_iso = now.isoformat() now_ts = now.timestamp() print(f"[{now_iso}] Monitoring PRs and claim locks...") @@ -218,7 +218,7 @@ def main(): def cleanup_global_expired_claims(now_ts=None): """Delete remote claim branches that are older than TTL, even if state file is gone.""" if now_ts is None: - now_ts = datetime.utcnow().timestamp() + now_ts = datetime.now(datetime.UTC).timestamp() # List all remote claim branches result = subprocess.run(['git', 'ls-remote', '--heads', 'origin', 'claim/*'], capture_output=True, text=True, cwd='/opt/aitbc') diff --git a/scripts/security/security_audit.py b/scripts/security/security_audit.py index 77a72544..4511a4a1 100755 --- a/scripts/security/security_audit.py +++ b/scripts/security/security_audit.py @@ -9,7 +9,7 @@ import sys import json import subprocess import logging -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path from typing import Dict, List, Any, Tuple import hashlib @@ -25,7 +25,7 @@ class SecurityAudit: def __init__(self, project_root: str = "/opt/aitbc"): self.project_root = Path(project_root) self.results = { - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), "audit_version": "v0.2.0", "findings": [], "score": 0, diff --git a/scripts/services/gpu/gpu_miner_host.py b/scripts/services/gpu/gpu_miner_host.py index 5b40fab5..7b469cca 100644 --- a/scripts/services/gpu/gpu_miner_host.py +++ b/scripts/services/gpu/gpu_miner_host.py @@ -10,7 +10,7 @@ import logging import sys import subprocess import os -from datetime import datetime +from datetime import datetime, UTC # Configuration COORDINATOR_URL = "http://127.0.0.1:8000" @@ -147,7 +147,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": gpu_info["utilization"], "memory_used": gpu_info["memory_used"], "memory_total": gpu_info["memory_total"] @@ -156,7 +156,7 @@ def send_heartbeat(): heartbeat_data = { "status": "active", "current_jobs": 0, - "last_seen": datetime.utcnow().isoformat(), + "last_seen": datetime.now(datetime.UTC).isoformat(), "gpu_utilization": 0, "memory_used": 0, } diff --git a/scripts/services/gpu/gpu_registry_demo.py b/scripts/services/gpu/gpu_registry_demo.py index ff6a135f..0bfab83f 100644 --- a/scripts/services/gpu/gpu_registry_demo.py +++ b/scripts/services/gpu/gpu_registry_demo.py @@ -7,7 +7,7 @@ from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Dict, Any, Optional import uvicorn -from datetime import datetime +from datetime import datetime, UTC app = FastAPI(title="GPU Registry Demo") @@ -37,8 +37,8 @@ async def register_gpu(miner_id: str, gpu_data: GPURegistration): """Register a GPU miner""" registered_gpus[miner_id] = { "id": miner_id, - "registered_at": datetime.utcnow().isoformat(), - "last_heartbeat": datetime.utcnow().isoformat(), + "registered_at": datetime.now(datetime.UTC).isoformat(), + "last_heartbeat": datetime.now(datetime.UTC).isoformat(), **gpu_data.dict() } return {"status": "ok", "message": f"GPU {miner_id} registered successfully"} @@ -49,7 +49,7 @@ async def heartbeat(miner_id: str, heartbeat_data: Heartbeat): if miner_id not in registered_gpus: raise HTTPException(status_code=404, detail="GPU not registered") - registered_gpus[miner_id]["last_heartbeat"] = datetime.utcnow().isoformat() + registered_gpus[miner_id]["last_heartbeat"] = datetime.now(datetime.UTC).isoformat() registered_gpus[miner_id]["status"] = heartbeat_data.status registered_gpus[miner_id]["metadata"] = heartbeat_data.metadata diff --git a/scripts/testing/generate_staking_test_data.py b/scripts/testing/generate_staking_test_data.py index 746d9495..7a701c26 100755 --- a/scripts/testing/generate_staking_test_data.py +++ b/scripts/testing/generate_staking_test_data.py @@ -6,7 +6,7 @@ Generates realistic test data scenarios for staking tests import json import random -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from typing import Dict, List, Any # Performance tiers and their properties @@ -94,7 +94,7 @@ def generate_agent_metrics(tier: str = "GOLD") -> Dict[str, Any]: "total_staked": 0.0, "staker_count": 0, "total_rewards_distributed": 0.0, - "last_update_time": datetime.utcnow().isoformat() + "last_update_time": datetime.now(datetime.UTC).isoformat() } @@ -128,7 +128,7 @@ def generate_stake_data( lock_period_days = LOCK_PERIOD_MULTIPLIERS[lock_period_category]["days"] expected_apy = calculate_expected_apy(tier, lock_period_days) - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) end_time = start_time + timedelta(days=lock_period_days) return { @@ -158,7 +158,7 @@ def generate_staking_pool(agent_wallet: str, total_staked: float) -> Dict[str, A "pool_apy": 5.0, "staker_count": 0, "active_stakers": [], - "last_distribution_time": datetime.utcnow().isoformat(), + "last_distribution_time": datetime.now(datetime.UTC).isoformat(), "distribution_frequency": 1 } @@ -167,7 +167,7 @@ def generate_test_scenario(num_agents: int = 5, num_stakes_per_agent: int = 3) - """Generate a complete test scenario with multiple agents and stakes""" scenario = { "scenario_id": f"scenario_{random.randint(1000, 9999)}", - "generated_at": datetime.utcnow().isoformat(), + "generated_at": datetime.now(datetime.UTC).isoformat(), "agents": [], "stakes": [], "pools": [] @@ -310,7 +310,7 @@ def generate_unbonding_scenarios() -> List[Dict[str, Any]]: generate_staker_address(), lock_period_category="medium" ) - stake["end_time"] = (datetime.utcnow() - timedelta(days=1)).isoformat() + stake["end_time"] = (datetime.now(datetime.UTC) - timedelta(days=1)).isoformat() scenarios.append({ "name": "Unbond After Lock Period", "description": "Test unbonding after lock period ends (should succeed)", @@ -326,9 +326,9 @@ def generate_unbonding_scenarios() -> List[Dict[str, Any]]: generate_staker_address(), lock_period_category="medium" ) - stake["end_time"] = (datetime.utcnow() - timedelta(days=1)).isoformat() + stake["end_time"] = (datetime.now(datetime.UTC) - timedelta(days=1)).isoformat() stake["status"] = "UNBONDING" - stake["unbonding_time"] = (datetime.utcnow() - timedelta(days=10)).isoformat() + stake["unbonding_time"] = (datetime.now(datetime.UTC) - timedelta(days=10)).isoformat() scenarios.append({ "name": "Complete Unbonding With Penalty", "description": "Test completing unbonding within 30 days (10% penalty)", @@ -344,9 +344,9 @@ def generate_unbonding_scenarios() -> List[Dict[str, Any]]: generate_staker_address(), lock_period_category="medium" ) - stake["end_time"] = (datetime.utcnow() - timedelta(days=1)).isoformat() + stake["end_time"] = (datetime.now(datetime.UTC) - timedelta(days=1)).isoformat() stake["status"] = "UNBONDING" - stake["unbonding_time"] = (datetime.utcnow() - timedelta(days=35)).isoformat() + stake["unbonding_time"] = (datetime.now(datetime.UTC) - timedelta(days=35)).isoformat() scenarios.append({ "name": "Complete Unbonding No Penalty", "description": "Test completing unbonding after 30 days (no penalty)", diff --git a/scripts/testing/qa-cycle.py b/scripts/testing/qa-cycle.py index cb9d0440..8651efa3 100755 --- a/scripts/testing/qa-cycle.py +++ b/scripts/testing/qa-cycle.py @@ -10,7 +10,7 @@ import sys import shutil import time import random -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path # Jitter: random delay up to 15 minutes (900 seconds) @@ -33,7 +33,7 @@ API_BASE = os.getenv('GITEA_API_BASE', 'http://gitea.bubuit.net:3000/api/v1') REPO = 'oib/aitbc' def log(msg): - now = datetime.utcnow().isoformat() + 'Z' + now = datetime.now(datetime.UTC).isoformat() + 'Z' with open(LOG_FILE, 'a') as f: f.write(f"[{now}] {msg}\n") print(msg) @@ -139,7 +139,7 @@ def synthesize_status(): log(f"PR #{num} has failing checks: {', '.join(s.get('context','?') for s in failing)}") def main(): - now = datetime.utcnow().isoformat() + 'Z' + now = datetime.now(datetime.UTC).isoformat() + 'Z' log(f"\n=== QA Cycle start: {now} ===") if not GITEA_TOKEN: log("GITEA_TOKEN not set; aborting.") diff --git a/scripts/utils/claim-task.py b/scripts/utils/claim-task.py index 12804650..ed218522 100755 --- a/scripts/utils/claim-task.py +++ b/scripts/utils/claim-task.py @@ -6,7 +6,7 @@ Uses Git branch atomic creation as a distributed lock to prevent duplicate work. import os import json import subprocess -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta REPO_DIR = '/opt/aitbc' STATE_FILE = '/opt/aitbc/.claim-state.json' @@ -106,7 +106,7 @@ def create_work_branch(issue_number, title): return branch_name def main(): - now = datetime.utcnow() + now = datetime.now(datetime.UTC) print(f"[{now.isoformat()}Z] Claim task cycle starting...") state = load_state() @@ -155,7 +155,7 @@ def main(): 'current_claim': num, 'claim_branch': f'claim/{num}', 'work_branch': work_branch, - 'claimed_at': datetime.utcnow().isoformat() + 'Z', + 'claimed_at': datetime.now(datetime.UTC).isoformat() + 'Z', 'issue_title': title, 'labels': labels }) diff --git a/scripts/utils/fix_gpu_release.py b/scripts/utils/fix_gpu_release.py index d8b92cf9..c2491fce 100755 --- a/scripts/utils/fix_gpu_release.py +++ b/scripts/utils/fix_gpu_release.py @@ -10,7 +10,7 @@ sys.path.insert(0, '/home/oib/windsurf/aitbc/apps/coordinator-api/src') from sqlmodel import Session, select from app.database import engine, create_db_and_tables from app.domain.gpu_marketplace import GPURegistry, GPUBooking -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta def fix_gpu_release(): """Fix GPU release issue by ensuring proper booking records exist""" @@ -40,7 +40,7 @@ def fix_gpu_release(): print("❌ No active booking found, creating one...") # Create a booking record - now = datetime.utcnow() + now = datetime.now(datetime.UTC) booking = GPUBooking( gpu_id=gpu_id, client_id="localhost-user", diff --git a/scripts/utils/generate-api-keys.py b/scripts/utils/generate-api-keys.py index cdf02d1b..86dbdf0b 100755 --- a/scripts/utils/generate-api-keys.py +++ b/scripts/utils/generate-api-keys.py @@ -8,7 +8,7 @@ Generates cryptographically secure API keys for testing CLI commands import secrets import json import sys -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta def generate_api_key(length=32): """Generate a cryptographically secure API key""" @@ -23,8 +23,8 @@ def create_api_key_entry(name, permissions="client", environment="default"): "api_key": api_key, # Stored in memory only, masked when printed "permissions": permissions.split(",") if isinstance(permissions, str) else permissions, "environment": environment, - "created_at": datetime.utcnow().isoformat(), - "expires_at": (datetime.utcnow() + timedelta(days=365)).isoformat(), + "created_at": datetime.now(datetime.UTC).isoformat(), + "expires_at": (datetime.now(datetime.UTC) + timedelta(days=365)).isoformat(), "status": "active" } diff --git a/scripts/utils/keystore.py b/scripts/utils/keystore.py index be9bcf2b..821ddd58 100644 --- a/scripts/utils/keystore.py +++ b/scripts/utils/keystore.py @@ -12,7 +12,7 @@ import hashlib import json import os import secrets -from datetime import datetime +from datetime import datetime, UTC from pathlib import Path from cryptography.fernet import Fernet @@ -55,7 +55,7 @@ def create_keystore(address: str, password: str, keystore_dir: Path | str = "/va keystore = { "address": address, "crypto": encrypted, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", } out_file.write_text(json.dumps(keystore, indent=2)) @@ -100,7 +100,7 @@ def main() -> None: keystore = { "address": args.address, "crypto": encrypted, - "created_at": datetime.utcnow().isoformat() + "Z", + "created_at": datetime.now(datetime.UTC).isoformat() + "Z", } out_file.write_text(json.dumps(keystore, indent=2)) diff --git a/tests/archived_phase_tests/phase3/test_decision_framework.py b/tests/archived_phase_tests/phase3/test_decision_framework.py index ff8a7997..b1d18dae 100644 --- a/tests/archived_phase_tests/phase3/test_decision_framework.py +++ b/tests/archived_phase_tests/phase3/test_decision_framework.py @@ -6,7 +6,7 @@ Tests for distributed decision making, voting systems, and consensus algorithms import pytest import asyncio import json -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from unittest.mock import Mock, AsyncMock from typing import Dict, List, Any @@ -23,7 +23,7 @@ class MockDecisionEngine: 'decision_id': decision_id, 'status': 'completed', 'result': decision_data.get('proposal', 'approved'), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } async def submit_vote(self, vote_data: Dict[str, Any]) -> Dict[str, Any]: @@ -32,7 +32,7 @@ class MockDecisionEngine: return { 'vote_id': vote_id, 'status': 'recorded', - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } class MockConsensusAlgorithm: @@ -50,7 +50,7 @@ class MockConsensusAlgorithm: 'consensus_id': consensus_id, 'status': 'consensus_reached', 'agreement': True, - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } class TestDecisionEngine: @@ -102,7 +102,7 @@ class TestDecisionEngine: 'amounts': {'cpu': 50, 'memory': 2048, 'storage': 100} }, 'participants': ['agent_001', 'agent_002', 'agent_003'], - 'deadline': (datetime.utcnow() + timedelta(hours=1)).isoformat() + 'deadline': (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat() } result = await self.decision_engine.make_decision(decision_data) @@ -157,7 +157,7 @@ class TestConsensusAlgorithm: {'rule': 'priority_based', 'weight': 0.6}, {'rule': 'fair_share', 'weight': 0.4} ], - 'effective_date': datetime.utcnow().isoformat() + 'effective_date': datetime.now(datetime.UTC).isoformat() } } @@ -260,7 +260,7 @@ class TestAgentLifecycleManagement: 'agent_id': 'agent_001', 'capabilities': ['decision_making', 'voting'], 'status': 'active', - 'join_time': datetime.utcnow().isoformat() + 'join_time': datetime.now(datetime.UTC).isoformat() } self.agents[agent_data['agent_id']] = agent_data @@ -276,12 +276,12 @@ class TestAgentLifecycleManagement: self.agents[agent_id] = { 'agent_id': agent_id, 'status': 'active', - 'last_update': datetime.utcnow().isoformat() + 'last_update': datetime.now(datetime.UTC).isoformat() } # Update agent status self.agents[agent_id]['status'] = 'busy' - self.agents[agent_id]['last_update'] = datetime.utcnow().isoformat() + self.agents[agent_id]['last_update'] = datetime.now(datetime.UTC).isoformat() assert self.agents[agent_id]['status'] == 'busy' assert 'last_update' in self.agents[agent_id] diff --git a/tests/archived_phase_tests/phase4/test_autonomous_decision_making.py b/tests/archived_phase_tests/phase4/test_autonomous_decision_making.py index f66e4936..c274ac82 100644 --- a/tests/archived_phase_tests/phase4/test_autonomous_decision_making.py +++ b/tests/archived_phase_tests/phase4/test_autonomous_decision_making.py @@ -6,7 +6,7 @@ Tests for autonomous systems, learning, and adaptation import pytest import asyncio import json -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from unittest.mock import Mock, AsyncMock from typing import Dict, List, Any, Optional @@ -27,7 +27,7 @@ class MockAutonomousEngine: 'action': self._determine_action(context), 'reasoning': self._generate_reasoning(context), 'confidence': self._calculate_confidence(context), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } self.decisions.append(decision) return decision @@ -67,7 +67,7 @@ class MockLearningSystem: 'experience': experience, 'lessons_learned': self._extract_lessons(experience), 'performance_impact': self._calculate_impact(experience), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } self.experience_buffer.append(learning_data) return learning_data @@ -93,7 +93,7 @@ class MockLearningSystem: 'type': adaptation_data.get('type', 'parameter_adjustment'), 'changes': adaptation_data.get('changes', {}), 'expected_improvement': adaptation_data.get('expected_improvement', 0.1), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } self.adaptations[adaptation_id] = adaptation return adaptation @@ -128,7 +128,7 @@ class MockPolicyEngine: 'compliance_score': compliance_score, 'violations': violations, 'approved': compliance_score >= 0.8 and len(violations) == 0, - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } def _calculate_compliance(self, decision: Dict[str, Any]) -> float: diff --git a/tests/archived_phase_tests/phase5/test_vision_integration.py b/tests/archived_phase_tests/phase5/test_vision_integration.py index 65d3d9fb..307b7eb0 100644 --- a/tests/archived_phase_tests/phase5/test_vision_integration.py +++ b/tests/archived_phase_tests/phase5/test_vision_integration.py @@ -7,7 +7,7 @@ import pytest import asyncio import json import base64 -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from unittest.mock import Mock, AsyncMock from typing import Dict, List, Any, Optional, Tuple @@ -26,7 +26,7 @@ class MockVisionProcessor: 'processing_type': processing_type, 'size': len(image_data), 'format': 'processed', - 'timestamp': datetime.utcnow().isoformat(), + 'timestamp': datetime.now(datetime.UTC).isoformat(), 'analysis': await self._analyze_image(image_data, processing_type) } self.processed_images[image_id] = result @@ -130,7 +130,7 @@ class MockMultiModalAgent: 'result_id': result_id, 'modalities_processed': list(results.keys()), 'integration': await self._integrate_modalities(results), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } self.integrated_results[result_id] = integrated_result @@ -151,7 +151,7 @@ class MockMultiModalAgent: return { 'sensor_type': sensor_data.get('type', 'unknown'), 'readings': sensor_data.get('readings', {}), - 'timestamp': sensor_data.get('timestamp', datetime.utcnow().isoformat()), + 'timestamp': sensor_data.get('timestamp', datetime.now(datetime.UTC).isoformat()), 'quality': 'good' } @@ -186,7 +186,7 @@ class MockContextIntegration: 'vision_result': vision_result, 'context_data': context_data, 'enhanced_understanding': await self._enhance_understanding(vision_result, context_data), - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } self.context_history.append(integration) @@ -298,7 +298,7 @@ class TestMultiModalIntegration: self.sample_sensor_data = { 'type': 'temperature', 'readings': {'value': 25.5, 'unit': 'celsius'}, - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } @pytest.mark.asyncio @@ -431,7 +431,7 @@ class TestContextIntegration: vision_result = await self.vision_processor.process_image(self.sample_image) context_data = { 'location': f'location_{i}', - 'timestamp': datetime.utcnow().isoformat() + 'timestamp': datetime.now(datetime.UTC).isoformat() } await self.context_integration.integrate_context(vision_result, context_data) @@ -530,11 +530,11 @@ class TestPerformanceMetrics: @pytest.mark.asyncio async def test_processing_speed(self): """Test image processing speed""" - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) result = await self.vision_processor.process_image(self.sample_image) - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) processing_time = (end_time - start_time).total_seconds() assert processing_time < 2.0 # Should process within 2 seconds @@ -545,12 +545,12 @@ class TestPerformanceMetrics: """Test batch image processing""" images = [self.sample_image] * 5 - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) results = [] for image in images: result = await self.vision_processor.process_image(image) results.append(result) - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) total_time = (end_time - start_time).total_seconds() avg_time = total_time / len(images) @@ -625,9 +625,9 @@ class TestVisionIntegration: # Simulate real-time processing processing_times = [] for i in range(10): - start_time = datetime.utcnow() + start_time = datetime.now(datetime.UTC) await vision_processor.process_image(f'frame_{i}'.encode()) - end_time = datetime.utcnow() + end_time = datetime.now(datetime.UTC) processing_times.append((end_time - start_time).total_seconds()) avg_time = sum(processing_times) / len(processing_times) diff --git a/tests/fixtures/staking_fixtures.py b/tests/fixtures/staking_fixtures.py index 9743223d..3fd98fef 100644 --- a/tests/fixtures/staking_fixtures.py +++ b/tests/fixtures/staking_fixtures.py @@ -5,7 +5,7 @@ Reusable fixtures for service and integration tests to avoid duplication import sys from pathlib import Path -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import pytest from sqlalchemy import create_engine @@ -67,7 +67,7 @@ def agent_metrics(agent_wallet): total_staked=0.0, staker_count=0, total_rewards_distributed=0.0, - last_update_time=datetime.utcnow() + last_update_time=datetime.now(datetime.UTC) ) @@ -84,7 +84,7 @@ def agent_metrics_bronze(agent_wallet): total_staked=0.0, staker_count=0, total_rewards_distributed=0.0, - last_update_time=datetime.utcnow() + last_update_time=datetime.now(datetime.UTC) ) @@ -101,7 +101,7 @@ def agent_metrics_diamond(agent_wallet): total_staked=0.0, staker_count=0, total_rewards_distributed=0.0, - last_update_time=datetime.utcnow() + last_update_time=datetime.now(datetime.UTC) ) @@ -115,7 +115,7 @@ def staking_pool(db_session, agent_metrics): pool_apy=5.0, staker_count=0, active_stakers=[], - last_distribution_time=datetime.utcnow(), + last_distribution_time=datetime.now(datetime.UTC), distribution_frequency=1 ) db_session.add(pool) @@ -185,11 +185,11 @@ def active_stake(db_session, agent_wallet, staker_address): agent_wallet=agent_wallet, amount=1000.0, lock_period=30, - start_time=datetime.utcnow(), - end_time=datetime.utcnow() + timedelta(days=30), + start_time=datetime.now(datetime.UTC), + end_time=datetime.now(datetime.UTC) + timedelta(days=30), status=StakeStatus.ACTIVE, accumulated_rewards=0.0, - last_reward_time=datetime.utcnow(), + last_reward_time=datetime.now(datetime.UTC), current_apy=8.25, agent_tier=PerformanceTier.GOLD, performance_multiplier=1.5, @@ -210,16 +210,16 @@ def unbonding_stake(db_session, agent_wallet, staker_address): agent_wallet=agent_wallet, amount=1000.0, lock_period=30, - start_time=datetime.utcnow() - timedelta(days=35), - end_time=datetime.utcnow() - timedelta(days=5), + start_time=datetime.now(datetime.UTC) - timedelta(days=35), + end_time=datetime.now(datetime.UTC) - timedelta(days=5), status=StakeStatus.UNBONDING, accumulated_rewards=50.0, - last_reward_time=datetime.utcnow() - timedelta(days=5), + last_reward_time=datetime.now(datetime.UTC) - timedelta(days=5), current_apy=8.25, agent_tier=PerformanceTier.GOLD, performance_multiplier=1.5, auto_compound=False, - unbonding_time=datetime.utcnow() - timedelta(days=5) + unbonding_time=datetime.now(datetime.UTC) - timedelta(days=5) ) db_session.add(stake) db_session.commit() @@ -236,16 +236,16 @@ def completed_stake(db_session, agent_wallet, staker_address): agent_wallet=agent_wallet, amount=1000.0, lock_period=30, - start_time=datetime.utcnow() - timedelta(days=70), - end_time=datetime.utcnow() - timedelta(days=40), + start_time=datetime.now(datetime.UTC) - timedelta(days=70), + end_time=datetime.now(datetime.UTC) - timedelta(days=40), status=StakeStatus.COMPLETED, accumulated_rewards=100.0, - last_reward_time=datetime.utcnow() - timedelta(days=40), + last_reward_time=datetime.now(datetime.UTC) - timedelta(days=40), current_apy=8.25, agent_tier=PerformanceTier.GOLD, performance_multiplier=1.5, auto_compound=False, - unbonding_time=datetime.utcnow() - timedelta(days=40) + unbonding_time=datetime.now(datetime.UTC) - timedelta(days=40) ) db_session.add(stake) db_session.commit() @@ -265,11 +265,11 @@ def multiple_stakes(db_session, agent_wallet, staker_address): agent_wallet=agent_wallet, amount=1000.0, lock_period=30, - start_time=datetime.utcnow(), - end_time=datetime.utcnow() + timedelta(days=30), + start_time=datetime.now(datetime.UTC), + end_time=datetime.now(datetime.UTC) + timedelta(days=30), status=StakeStatus.ACTIVE, accumulated_rewards=0.0, - last_reward_time=datetime.utcnow(), + last_reward_time=datetime.now(datetime.UTC), current_apy=8.25, agent_tier=PerformanceTier.GOLD, performance_multiplier=1.5, @@ -283,11 +283,11 @@ def multiple_stakes(db_session, agent_wallet, staker_address): agent_wallet=agent_wallet, amount=2000.0, lock_period=90, - start_time=datetime.utcnow(), - end_time=datetime.utcnow() + timedelta(days=90), + start_time=datetime.now(datetime.UTC), + end_time=datetime.now(datetime.UTC) + timedelta(days=90), status=StakeStatus.ACTIVE, accumulated_rewards=0.0, - last_reward_time=datetime.utcnow(), + last_reward_time=datetime.now(datetime.UTC), current_apy=10.0, agent_tier=PerformanceTier.GOLD, performance_multiplier=1.5, diff --git a/tests/integration/test_staking_lifecycle.py b/tests/integration/test_staking_lifecycle.py index 18d3a723..f3817fd6 100644 --- a/tests/integration/test_staking_lifecycle.py +++ b/tests/integration/test_staking_lifecycle.py @@ -6,7 +6,7 @@ Test 3.1.1: Complete staking lifecycle integration test import asyncio import sys from pathlib import Path -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import pytest @@ -123,7 +123,7 @@ class TestStakingLifecycle: print("\n=== Step 3: Simulating lock period ===") # In a real scenario, this would be actual time passing # For testing, we'll just verify the logic works - stake.end_time = datetime.utcnow() - timedelta(days=1) # Lock period ended + stake.end_time = datetime.now(datetime.UTC) - timedelta(days=1) # Lock period ended staking_service.session.commit() print(f"✓ Lock period simulated as ended") @@ -135,7 +135,7 @@ class TestStakingLifecycle: # Step 5: Simulate unbonding period print("\n=== Step 5: Simulating unbonding period ===") - unbonded_stake.unbonding_time = datetime.utcnow() - timedelta(days=8) # 8 days ago + unbonded_stake.unbonding_time = datetime.now(datetime.UTC) - timedelta(days=8) # 8 days ago staking_service.session.commit() print(f"✓ Unbonding period simulated as ended") @@ -194,7 +194,7 @@ class TestStakingLifecycle: print(f"Initial rewards: {initial_rewards}") # Simulate time passing by updating last_reward_time - stake.last_reward_time = datetime.utcnow() - timedelta(days=10) + stake.last_reward_time = datetime.now(datetime.UTC) - timedelta(days=10) staking_service.session.commit() # Calculate rewards after 10 days diff --git a/tests/load/locustfile.py b/tests/load/locustfile.py index ef8faa2d..b742141c 100644 --- a/tests/load/locustfile.py +++ b/tests/load/locustfile.py @@ -8,7 +8,7 @@ from locust.stats import stats_printer, stats_history import json import random import time -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import gevent from gevent.pool import Pool @@ -122,8 +122,8 @@ class MarketplaceUser(HttpUser): "ram": random.choice(["16GB", "32GB", "64GB", "128GB"]), }, "availability": { - "start_time": (datetime.utcnow() + timedelta(hours=1)).isoformat(), - "end_time": (datetime.utcnow() + timedelta(days=30)).isoformat(), + "start_time": (datetime.now(datetime.UTC) + timedelta(hours=1)).isoformat(), + "end_time": (datetime.now(datetime.UTC) + timedelta(days=30)).isoformat(), }, } diff --git a/tests/security/test_confidential_transactions.py b/tests/security/test_confidential_transactions.py index 43173298..17a4baea 100644 --- a/tests/security/test_confidential_transactions.py +++ b/tests/security/test_confidential_transactions.py @@ -5,7 +5,7 @@ Security tests for AITBC Confidential Transactions import pytest import json import sys -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta from unittest.mock import Mock, patch, AsyncMock from cryptography.hazmat.primitives.asymmetric import x25519 from cryptography.hazmat.primitives.ciphers.aead import AESGCM @@ -109,7 +109,7 @@ class TestConfidentialTransactionSecurity: # Generate viewing key for auditor viewing_key = generate_viewing_key( purpose="audit", - expires_at=datetime.utcnow() + timedelta(days=30), + expires_at=datetime.now(datetime.UTC) + timedelta(days=30), permissions=["view_amount", "view_parties"], ) @@ -123,7 +123,7 @@ class TestConfidentialTransactionSecurity: assert len(viewing_key["key_data"]) >= 32 # At least 256 bits # Verify expiration - assert viewing_key["expires_at"] > datetime.utcnow() + assert viewing_key["expires_at"] > datetime.now(datetime.UTC) def test_viewing_key_permissions(self, confidential_service): """Test that viewing keys respect permission constraints""" @@ -133,7 +133,7 @@ class TestConfidentialTransactionSecurity: ciphertext="encrypted_data_here", sender_key="sender_pubkey", receiver_key="receiver_pubkey", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) # Create viewing key with limited permissions @@ -142,8 +142,8 @@ class TestConfidentialTransactionSecurity: transaction_id=tx.id, key_data="encrypted_viewing_key", permissions=["view_amount"], - expires_at=datetime.utcnow() + timedelta(days=1), - created_at=datetime.utcnow(), + expires_at=datetime.now(datetime.UTC) + timedelta(days=1), + created_at=datetime.now(datetime.UTC), ) # Test permission enforcement @@ -205,7 +205,7 @@ class TestConfidentialTransactionSecurity: "receiver": "0x456", "amount": 1000, "nonce": 12345, - "timestamp": datetime.utcnow().isoformat(), + "timestamp": datetime.now(datetime.UTC).isoformat(), } # Store nonce @@ -300,7 +300,7 @@ class TestConfidentialTransactionSecurity: ciphertext="encrypted_data", sender_key="sender_key", receiver_key="receiver_key", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) # Log access @@ -308,7 +308,7 @@ class TestConfidentialTransactionSecurity: transaction_id=tx.id, user_id="auditor-123", action="view_with_viewing_key", - timestamp=datetime.utcnow(), + timestamp=datetime.now(datetime.UTC), ) # Verify log integrity @@ -629,7 +629,7 @@ class TestConfidentialTransactionCompliance: ciphertext="encrypted_data", sender_key="sender_key", receiver_key="receiver_key", - created_at=datetime.utcnow(), + created_at=datetime.now(datetime.UTC), ) # Generate regulatory report @@ -705,7 +705,7 @@ class TestConfidentialTransactionCompliance: old_tx = ConfidentialTransaction( id="old-tx-123", ciphertext="old_encrypted_data", - created_at=datetime.utcnow() - timedelta(days=400), # Over 1 year + created_at=datetime.now(datetime.UTC) - timedelta(days=400), # Over 1 year ) # Test retention policy enforcement diff --git a/tests/services/test_staking_service.py b/tests/services/test_staking_service.py index d1d32c6e..4b635239 100644 --- a/tests/services/test_staking_service.py +++ b/tests/services/test_staking_service.py @@ -6,7 +6,7 @@ High-priority tests for staking service functionality import asyncio import sys from pathlib import Path -from datetime import datetime, timedelta +from datetime import datetime, UTC, timedelta import pytest from sqlalchemy import create_engine @@ -70,7 +70,7 @@ def staking_pool(db_session, agent_metrics): pool_apy=5.0, staker_count=0, active_stakers=[], - last_distribution_time=datetime.utcnow(), + last_distribution_time=datetime.now(datetime.UTC), distribution_frequency=1 ) db_session.add(pool) @@ -114,7 +114,7 @@ class TestStakingService: assert stake.current_apy > 8.0 # Allow small rounding error # Verify end time calculated - expected_end_time = datetime.utcnow() + timedelta(days=lock_period) + expected_end_time = datetime.now(datetime.UTC) + timedelta(days=lock_period) time_diff = abs((stake.end_time - expected_end_time).total_seconds()) assert time_diff < 60 # Within 1 minute @@ -254,7 +254,7 @@ class TestStakingService: ) # Simulate lock period ending by updating end_time - stake.end_time = datetime.utcnow() - timedelta(days=1) + stake.end_time = datetime.now(datetime.UTC) - timedelta(days=1) staking_service.session.commit() # Unbond the stake @@ -277,7 +277,7 @@ class TestStakingService: ) # Unbond the stake - stake.end_time = datetime.utcnow() - timedelta(days=1) + stake.end_time = datetime.now(datetime.UTC) - timedelta(days=1) staking_service.session.commit() await staking_service.unbond_stake(stake.stake_id) @@ -304,13 +304,13 @@ class TestStakingService: ) # Unbond the stake - stake.end_time = datetime.utcnow() - timedelta(days=1) + stake.end_time = datetime.now(datetime.UTC) - timedelta(days=1) staking_service.session.commit() await staking_service.unbond_stake(stake.stake_id) # Set unbonding time to 35 days ago (past 30-day penalty period) stake = await staking_service.get_stake(stake.stake_id) - stake.unbonding_time = datetime.utcnow() - timedelta(days=35) + stake.unbonding_time = datetime.now(datetime.UTC) - timedelta(days=35) staking_service.session.commit() # Complete unbonding (no penalty) @@ -352,7 +352,7 @@ class TestStakingService: ) # Unbond the stake - stake.end_time = datetime.utcnow() - timedelta(days=1) + stake.end_time = datetime.now(datetime.UTC) - timedelta(days=1) staking_service.session.commit() await staking_service.unbond_stake(stake.stake_id) diff --git a/tests/verification/test_block_import.py b/tests/verification/test_block_import.py index 7a5904af..11c99f22 100644 --- a/tests/verification/test_block_import.py +++ b/tests/verification/test_block_import.py @@ -6,7 +6,7 @@ Tests the /rpc/blocks/import POST endpoint functionality import json import hashlib -from datetime import datetime +from datetime import datetime, UTC # Test configuration BASE_URL = "https://aitbc.bubuit.net/rpc" @@ -35,7 +35,7 @@ def test_block_import(): print("\n1. Testing valid block import...") height = base_height parent_hash = head["hash"] - timestamp = datetime.utcnow().isoformat() + "Z" + timestamp = datetime.now(datetime.UTC).isoformat() + "Z" valid_hash = compute_block_hash(height, parent_hash, timestamp) response = requests.post( diff --git a/tests/verification/test_cross_node_blockchain.py b/tests/verification/test_cross_node_blockchain.py index 1279b306..75368647 100644 --- a/tests/verification/test_cross_node_blockchain.py +++ b/tests/verification/test_cross_node_blockchain.py @@ -6,7 +6,7 @@ Tests new blockchain features across aitbc and aitbc1 nodes import hashlib import subprocess -from datetime import datetime +from datetime import datetime, UTC import time from aitbc import AITBCHTTPClient, NetworkError @@ -116,7 +116,7 @@ def test_cross_node_block_sync(): aitbc_head = heads["aitbc"] height = aitbc_head["height"] + 10000000 # Use very high height to avoid conflicts parent_hash = aitbc_head["hash"] - timestamp = datetime.utcnow().isoformat() + "Z" + timestamp = datetime.now(datetime.UTC).isoformat() + "Z" valid_hash = compute_block_hash(height, parent_hash, timestamp) client = AITBCHTTPClient(timeout=10)