Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
6ee8224
uvicorn asgi
jmlago Sep 8, 2025
e1af102
fastapi migration workiing with uvicorn
jmlago Sep 8, 2025
7fbca4f
fastapi endpoints working
jmlago Sep 9, 2025
0e3c61c
add validators working
jmlago Sep 9, 2025
eb8e9ca
update and delete vals fixed
jmlago Sep 9, 2025
cab942f
consensus background tasks working
jmlago Sep 9, 2025
eb388ee
some fixes
jmlago Sep 9, 2025
27a8120
non dead workers and RPC logs showing on frontend
jmlago Sep 9, 2025
d7cf210
gen_call working
jmlago Sep 9, 2025
ba31a27
fix: db sharing session management across endpoints
cristiam86 Sep 10, 2025
f492f97
chore: improved logging
cristiam86 Sep 10, 2025
27935cf
Merge remote-tracking branch 'origin/main' into gunicorn
cristiam86 Sep 10, 2025
35715a9
chore: removed unused code
cristiam86 Sep 10, 2025
8a0e6f9
chore: early return for health ping method and improved db session ma…
cristiam86 Sep 10, 2025
09f4d43
chore: removed unused workflow
cristiam86 Sep 10, 2025
b568f18
Merge remote-tracking branch 'origin/main' into gunicorn
cristiam86 Sep 11, 2025
9236b62
fix: json rpc response no compliant
cristiam86 Sep 11, 2025
c1d248d
fix: disabled raising error when consensus_service forward transactio…
cristiam86 Sep 11, 2025
1220c4b
fix: remove contract state from transaction data
cristiam86 Sep 11, 2025
4bedf3c
chore: add logs to RPC execution
cristiam86 Sep 11, 2025
e1263b1
wip: fixing validators registry
cristiam86 Sep 11, 2025
3f91499
wip: fixing validators registry
cristiam86 Sep 11, 2025
4f10fc3
fix: singleton websocket
kstroobants Sep 12, 2025
965d9da
fix: disable some logs with env var DISABLE_INFO_LOGS_ENDPOINTS
kstroobants Sep 12, 2025
5aaf83d
fix: success logs are green
kstroobants Sep 12, 2025
2a50687
fix: duplicated finality window log for new browser
kstroobants Sep 12, 2025
486cf90
fix: bug in process round data returns error when appealing
kstroobants Sep 12, 2025
2545d4a
fix: application now shuts down gracefully without errors
kstroobants Sep 12, 2025
52122ab
fix: standarized JSONRPC Errors
cristiam86 Sep 12, 2025
99f7e38
fix: simplify llm and web modules execution
cristiam86 Sep 15, 2025
7d35fa3
chore: removed tx execution semaphore
cristiam86 Sep 15, 2025
bbc3d93
chore: disable hardhat and allow RPC batch calls
cristiam86 Sep 15, 2025
fe85b76
consensus worker
jmlago Sep 10, 2025
7241733
alembic migration
jmlago Sep 11, 2025
a91f014
integration tests
jmlago Sep 15, 2025
1582f8a
transactions and sockets working with workers
jmlago Sep 15, 2025
a9db8ff
redis and traefik for load balancing and proper scaling
jmlago Sep 15, 2025
b20609c
remove unnecessary logs
jmlago Sep 15, 2025
1d3ff67
Merge remote-tracking branch 'origin/main' into hscale
cristiam86 Oct 13, 2025
079aa25
fix: forbid multiple workers picking up the same transaction
cristiam86 Oct 14, 2025
f6cdce8
fix: simplified logging and receipt data
cristiam86 Oct 14, 2025
c9e517f
chore: unify docker-compose and differentiate cpu and mem limits
cristiam86 Oct 15, 2025
27a1918
fix: rpc endpoint manager tests
cristiam86 Oct 15, 2025
a0955fc
fix: remove unused code
cristiam86 Oct 15, 2025
bb5efe9
fix: temporary disable finality window setup
cristiam86 Oct 15, 2025
f8f806a
chore: reverted genvm compilation for non aarch64 env
cristiam86 Oct 15, 2025
0e87a65
fix: tests
cristiam86 Oct 15, 2025
c8369b2
fix: tx processor bug
cristiam86 Oct 15, 2025
b02fb1f
chore: separated env config for memory and cpu by rpc and workers
cristiam86 Oct 15, 2025
8e53027
fix: triggered websocket revealing and accepted events without delay
cristiam86 Oct 15, 2025
0ac6761
chore: adopted logger in consensus worker
cristiam86 Oct 15, 2025
2144383
fix: improve websockets status update notifications
cristiam86 Oct 15, 2025
c92db6b
fix: process appeals
cristiam86 Oct 15, 2025
1f6bd36
chore: added proper async/await to tx executiuon states
cristiam86 Oct 15, 2025
90352fb
fix: tests
cristiam86 Oct 16, 2025
5482ff6
fix: terminate validators manager on worker shutdown
cristiam86 Oct 16, 2025
1fde575
fix: code rabbit review, improvements and minor fixes
cristiam86 Oct 16, 2025
6fe5ebd
chore: added genlayer.org to allowed hosts
cristiam86 Oct 16, 2025
395e73e
fix: high volume concurrent transactions processing errors and minor …
cristiam86 Oct 16, 2025
0953f82
chore: make db env variables consistent in docker-compose
cristiam86 Oct 16, 2025
b42523d
chore: added consensus-worker service to docker hub publish
cristiam86 Oct 16, 2025
0f9423c
Merge branch 'main' into hscale
cristiam86 Oct 17, 2025
67cce5d
test: improved load tests
cristiam86 Oct 17, 2025
2b96558
fix: traefik configuration
cristiam86 Oct 17, 2025
c0a0a91
fix traefik labels
rrabenda Oct 17, 2025
74b3dd6
fix traefik labels 2
rrabenda Oct 17, 2025
54ed831
fix traefik labels 3
rrabenda Oct 17, 2025
27c867d
traefik old setup
rrabenda Oct 17, 2025
2f4b6ef
traefik old setup 2
rrabenda Oct 17, 2025
88cd1e5
traefik old setup 3
rrabenda Oct 17, 2025
3d85cfe
Merge remote-tracking branch 'origin/main' into rafal/fix-hscale-depl…
cristiam86 Oct 17, 2025
28e6af6
chore: remove comments
cristiam86 Oct 17, 2025
3546b53
chore: remove more comments
cristiam86 Oct 17, 2025
d3887dd
chore: removed unused traefik config
cristiam86 Oct 17, 2025
d9536af
chore: re-applied missing studio profile
cristiam86 Oct 17, 2025
b906eb7
fix: local jsonrpc connection
cristiam86 Oct 17, 2025
98fb7b4
fix: jsonrpc traefik labels
cristiam86 Oct 17, 2025
2e9c6c5
fix: transactions hash genration in same second
cristiam86 Oct 17, 2025
d4de871
fix: improved consensus worker queries and transaction processing
cristiam86 Oct 18, 2025
a16914d
chore: stability improvements and logging
cristiam86 Oct 19, 2025
2ed32a5
chore: added logs for worker termination
cristiam86 Oct 19, 2025
0ebd12d
chore: improvements on memory leak
cristiam86 Oct 19, 2025
217eda5
chore: remove max amount of restart for consensus worker
cristiam86 Oct 21, 2025
235848e
chore: only log genvm warnings or higher level
cristiam86 Oct 21, 2025
390cc5c
chore: added monitoring endpoints
cristiam86 Oct 21, 2025
2d1cb86
chore: monitoring dashboard v1
cristiam86 Oct 21, 2025
16ed278
fix: return error on get transaction status when not found
cristiam86 Oct 21, 2025
4b23d91
fix: return error on get transaction status when not found
cristiam86 Oct 21, 2025
43897b6
chore: open jsonrpc monitoring endpoint
cristiam86 Oct 22, 2025
f1ce499
chore: added memswap param to jsonrpc and consensus worker
cristiam86 Oct 24, 2025
c76e3c0
chore: fix swap mem allocation
cristiam86 Oct 24, 2025
24d1da9
chore: removed docker from health endpoints, added new metrics for tx…
cristiam86 Oct 24, 2025
c8badcd
fix: avoid showing complete result on execution finished GenVM event
cristiam86 Oct 28, 2025
d1d40bd
fix: added catch all error on rpc entry point to avoid doctype failure
cristiam86 Oct 28, 2025
0173b06
fix: comment
cristiam86 Oct 28, 2025
f5677ae
fix: get_transaction methods errors and return types
cristiam86 Oct 28, 2025
438533a
fix: remove monitoring dashboard
cristiam86 Oct 28, 2025
28eadc6
chore: added longer traefik timeout
cristiam86 Oct 28, 2025
9edfa56
chore: adjusting timeouts for the traefik proxy
cristiam86 Oct 28, 2025
ed0fc13
fix: removed unused code
cristiam86 Oct 28, 2025
7042f60
chore: removed docker socket bind
cristiam86 Oct 28, 2025
1a7ec79
wip: fixes for traefic routing
cristiam86 Oct 28, 2025
b7e6038
fix: clean traefik config
cristiam86 Oct 28, 2025
a8a499f
debug: added call params to gen_call error
cristiam86 Oct 28, 2025
18b726f
debug: rise genvm timeout
cristiam86 Oct 28, 2025
41d855e
wip: testing traefic timeout config
cristiam86 Oct 28, 2025
abc6753
fix: traefik config
cristiam86 Oct 28, 2025
90e24cb
debug: added request params to method completed log
cristiam86 Oct 28, 2025
d8be379
add ssl config for traefik
rrabenda Oct 29, 2025
bbcdcc9
add ssl config for traefik 2
rrabenda Oct 29, 2025
1e71986
chore: raise genvm timeout to 30 mins
cristiam86 Oct 29, 2025
41289a2
Merge branch 'rafal/fix-hscale-deployment' of github.com:yeagerai/gen…
cristiam86 Oct 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ RPCPORT="4000"
RPCDEBUGPORT="4678"
ENABLE_DEBUG_ENDPOINTS="false"

# Docker Configuration (for health monitoring)
# Set to the GID of your docker group - use: stat -c %g /var/run/docker.sock (Linux) or stat -f %g /var/run/docker.sock (Mac)
DOCKER_GID="999"

# Horizontal Scaling Configuration
# IMPORTANT: Redis is REQUIRED for the distributed worker architecture
JSONRPC_REPLICAS='1' # Number of JSON-RPC API server replicas (minimum: 1)
Expand Down
7 changes: 5 additions & 2 deletions backend/consensus/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1171,7 +1171,10 @@ async def exec_transaction(
break
elif next_state == ConsensusRound.ACCEPTED:
if (
("consensus_results" in context.transaction.consensus_history)
(context.transaction.consensus_history is not None)
and (
"consensus_results" in context.transaction.consensus_history
)
and (
len(
context.transaction.consensus_history[
Expand Down Expand Up @@ -2219,7 +2222,7 @@ def get_used_leader_addresses_from_consensus_history(
set[str]: Set of used leader addresses.
"""
used_leader_addresses = set()
if "consensus_results" in consensus_history:
if consensus_history is not None and "consensus_results" in consensus_history:
for consensus_round in consensus_history["consensus_results"]:
leader_receipt = consensus_round["leader_result"]
if leader_receipt:
Expand Down
30 changes: 24 additions & 6 deletions backend/consensus/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def __init__(
self.poll_interval = poll_interval
self.transaction_timeout_minutes = transaction_timeout_minutes
self.running = True
self.current_transaction = None # Track currently processing transaction

# Create a ConsensusAlgorithm instance to reuse its exec_transaction method
self.consensus_algorithm = ConsensusAlgorithm(
Expand Down Expand Up @@ -277,7 +278,7 @@ async def claim_next_transaction(self, session: Session) -> Optional[dict]:
# Ensures only one transaction per contract is processed at a time
query = text(
"""
WITH locked_transactions AS (
WITH candidate_transactions AS (
SELECT t.*
FROM transactions t
WHERE t.status IN ('PENDING', 'ACTIVATED')
Expand All @@ -294,19 +295,26 @@ async def claim_next_transaction(self, session: Session) -> Optional[dict]:
ORDER BY t.created_at ASC
FOR UPDATE SKIP LOCKED
),
available_transactions AS (
oldest_per_contract AS (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY to_address
ORDER BY created_at ASC
) as rn
FROM locked_transactions
FROM candidate_transactions
),
single_transaction AS (
-- Select only ONE transaction (oldest across all contracts)
SELECT *
FROM oldest_per_contract
WHERE rn = 1
ORDER BY created_at ASC
LIMIT 1
)
UPDATE transactions
SET blocked_at = NOW(),
worker_id = :worker_id
FROM available_transactions
WHERE transactions.hash = available_transactions.hash
AND available_transactions.rn = 1
FROM single_transaction
WHERE transactions.hash = single_transaction.hash
RETURNING transactions.hash, transactions.from_address, transactions.to_address,
transactions.data, transactions.value, transactions.type, transactions.nonce,
transactions.gaslimit, transactions.r, transactions.s, transactions.v,
Expand Down Expand Up @@ -416,6 +424,8 @@ async def recover_stuck_transactions(self, session: Session) -> int:
UPDATE transactions
SET blocked_at = NULL,
worker_id = NULL,
consensus_data = NULL,
consensus_history = NULL,
status = 'PENDING'
WHERE (
-- Case 1: Transactions with expired blocks
Expand Down Expand Up @@ -459,6 +469,12 @@ async def process_transaction(self, transaction_data: dict, session: Session):
session: Database session
"""
try:
# Track current transaction for health monitoring
self.current_transaction = {
"hash": transaction_data.get("hash"),
"blocked_at": transaction_data.get("blocked_at"),
}

# Convert to Transaction domain object
transaction = Transaction.from_dict(transaction_data)

Expand Down Expand Up @@ -554,6 +570,8 @@ async def process_transaction(self, transaction_data: dict, session: Session):
)
session.rollback()
finally:
# Clear current transaction tracking
self.current_transaction = None
# Always release the transaction when done
self.release_transaction(session, transaction_data["hash"])

Expand Down
160 changes: 130 additions & 30 deletions backend/consensus/worker_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import os
import asyncio
import signal
import time
from contextlib import asynccontextmanager
from typing import Optional

Expand Down Expand Up @@ -38,8 +40,22 @@ async def lifespan(app: FastAPI):
"""Manage the worker lifecycle."""
global worker, worker_task

# Set up signal handlers for graceful shutdown logging
def handle_signal(sig, frame):
logger.warning(f"Received signal {sig}, initiating graceful shutdown...")

signal.signal(signal.SIGTERM, handle_signal)
signal.signal(signal.SIGINT, handle_signal)

logger.info("Starting Consensus Worker Service...")
print("Starting Consensus Worker Service...")

# CRITICAL: Kill any orphaned GenVM processes from previous crashes
# These zombie processes can consume gigabytes of memory outside Docker limits
logger.info("Cleaning up orphaned GenVM processes from previous crashes...")
os.system("pkill -9 -f 'genvm (llm|web)' 2>/dev/null || true")
logger.info("GenVM cleanup complete")

# Database setup
database_name = "genlayer"
db_uri = f"postgresql+psycopg2://{os.environ.get('DBUSER')}:{os.environ.get('DBPASSWORD')}@{os.environ.get('DBHOST')}/{get_db_name(database_name)}"
Expand Down Expand Up @@ -97,9 +113,11 @@ def get_session():
raise RuntimeError(error_msg) from e
consensus_service = ConsensusService()

# Initialize validators manager
# Initialize validators manager (MUST use global to prevent garbage collection)
global validators_manager # Declare before assignment to use the global variable
validators_manager = validators.Manager(SessionLocal())
await validators_manager.restart()
logger.info("Validators manager initialized and restarted")

# Create and start the worker
worker = ConsensusWorker(
Expand All @@ -112,55 +130,137 @@ def get_session():
transaction_timeout_minutes=transaction_timeout,
)

# Start the worker in a background task
worker_task = asyncio.create_task(worker.run())

print(f"Consensus Worker {worker.worker_id} started successfully")

yield

# Cleanup on shutdown
print("Shutting down Consensus Worker Service...")

if worker:
worker.stop()

if worker_task:
worker_task.cancel()
try:
await worker_task
except asyncio.CancelledError:
pass

# Terminate validators manager to shut down background tasks
if validators_manager:
# Start the worker in a background task with exception handling
async def run_worker_with_error_handling():
try:
await validators_manager.terminate()
await worker.run()
except Exception as e:
logger.error(f"Error terminating validators manager: {e}")
logger.critical(
f"FATAL: Worker {worker.worker_id} crashed with unhandled exception: {e}",
exc_info=True,
)
# Re-raise to let the container crash and restart
raise

worker_task = asyncio.create_task(run_worker_with_error_handling())

# Clean up message handler
if msg_handler:
await msg_handler.close()
print(f"Consensus Worker {worker.worker_id} started successfully")

print("Consensus Worker Service stopped")
try:
yield
finally:
# CRITICAL: Always cleanup GenVM processes, even on crash
# This prevents memory leaks from orphaned genvm subprocesses

# Cleanup on shutdown
logger.info("Shutting down Consensus Worker Service...")
print("Shutting down Consensus Worker Service...")

if worker:
worker.stop()

if worker_task:
worker_task.cancel()
try:
await worker_task
except asyncio.CancelledError:
pass

# Terminate validators manager to shut down background tasks
if validators_manager:
try:
logger.info("Terminating validators manager and GenVM subprocesses...")
await validators_manager.terminate()
logger.info("Validators manager terminated successfully")
except Exception as e:
logger.error(f"Error terminating validators manager: {e}")

# Clean up message handler
if msg_handler:
try:
await msg_handler.close()
except Exception as e:
logger.error(f"Error closing message handler: {e}")

# Final safety check: Kill any remaining genvm processes
logger.info("Final cleanup: killing any remaining GenVM processes...")
os.system("pkill -9 -f 'genvm (llm|web)' 2>/dev/null || true")
logger.info("GenVM cleanup complete")

print("Consensus Worker Service stopped")


# Create FastAPI app
app = FastAPI(title="Consensus Worker Service", version="1.0.0", lifespan=lifespan)
start_time = time.time()


@app.get("/health")
async def health_check():
"""Health check endpoint for the worker."""
global worker
import psutil
from datetime import datetime

global worker, worker_task

endpoint_start = time.time()

if worker is None:
return {"status": "initializing", "worker_id": None}

# Check if worker task has died
if worker_task and worker_task.done():
# Worker task finished unexpectedly - this is a failure
try:
# This will re-raise any exception from the task
worker_task.result()
except Exception as e:
logger.error(f"Worker task died with exception: {e}")
return {
"status": "failed",
"worker_id": worker.worker_id,
"error": "worker_task_died",
}

Comment on lines +211 to +224

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Health check: avoid task.result() and blind except; handle cancellation separately.

Calling result() re-raises and forced a blind except (BLE001). Use cancelled()/exception() to inspect safely; treat cancellation as “stopping,” not “failed.” As per static analysis hints.

-    # Check if worker task has died
-    if worker_task and worker_task.done():
-        # Worker task finished unexpectedly - this is a failure
-        try:
-            # This will re-raise any exception from the task
-            worker_task.result()
-        except Exception as e:
-            logger.error(f"Worker task died with exception: {e}")
-        return {
-            "status": "failed",
-            "worker_id": worker.worker_id,
-            "error": "worker_task_died",
-        }
+    # Check if worker task has finished
+    if worker_task and worker_task.done():
+        if worker_task.cancelled():
+            logger.info("Worker task cancelled; service stopping")
+            return {"status": "stopping", "worker_id": worker.worker_id}
+        exc = worker_task.exception()
+        if exc is not None:
+            logger.error(f"Worker task died with exception: {exc!r}")
+            return {
+                "status": "failed",
+                "worker_id": worker.worker_id,
+                "error": "worker_task_exception",
+            }
+        # Unexpected: task finished without exception
+        return {
+            "status": "failed",
+            "worker_id": worker.worker_id,
+            "error": "worker_task_finished",
+        }
🧰 Tools
🪛 Ruff (0.14.0)

187-187: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
In backend/consensus/worker_service.py around lines 181 to 194, avoid calling
worker_task.result() and a blind except; instead check worker_task.cancelled()
and worker_task.exception() to differentiate cancellation from failure. If
cancelled(), return a stopping/stopped status for the worker (not failed); if
exception() is not None, fetch that exception, log it with full context, and
return status "failed" with the error; otherwise handle the unexpected
completion as a failure with a sensible message. Ensure you do not re-raise via
result() and do not use a bare except.

# Get basic metrics
metrics = {}
try:
process = psutil.Process()
metrics = {
"memory_mb": round(process.memory_info().rss / 1024 / 1024, 2),
"cpu_percent": round(process.cpu_percent(), 2),
"memory_percent": round(process.memory_percent(), 2),
}
except:
pass

# Get current transaction info with time calculation
current_tx = None
if worker.current_transaction:
tx = worker.current_transaction.copy()
if tx.get("blocked_at"):
try:
blocked_at = datetime.fromisoformat(
tx["blocked_at"].replace("Z", "+00:00")
)
elapsed = datetime.utcnow() - blocked_at.replace(tzinfo=None)

# Format as human-readable time ago
minutes = int(elapsed.total_seconds() / 60)
if minutes < 60:
tx["blocked_at"] = f"{minutes}m ago"
else:
hours = minutes // 60
tx["blocked_at"] = f"{hours}h ago"
except:
pass
current_tx = tx

return {
"status": "healthy" if worker.running else "stopping",
"worker_id": worker.worker_id,
"current_transaction": current_tx,
**metrics,
}


Expand Down
23 changes: 17 additions & 6 deletions backend/database_handler/transactions_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,10 @@ def _generate_transaction_hash(
to_bytes(hexstr=to_address) if is_address(to_address) else b"\x00" * 20
)

# Use current timestamp to mimic block.timestamp
timestamp = int(time.time())
timestamp_bytes = timestamp.to_bytes(32, byteorder="big", signed=False)
# Use current timestamp with microsecond precision to ensure uniqueness
timestamp = time.time()
timestamp_int = int(timestamp * 1_000_000) # Convert to microseconds as integer
timestamp_bytes = timestamp_int.to_bytes(32, byteorder="big", signed=False)

# Derive a deterministic pseudo-random seed from the recipient address
seed_source = f"{to_address or '0x0'}:{timestamp}"
Comment on lines +198 to 204

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use consistent timestamp precision in seed_source.

The timestamp handling uses microsecond precision (timestamp_int) for timestamp_bytes but still uses the float timestamp in the seed_source on line 204. This creates an inconsistency that could lead to subtle issues with float-to-string representation.

Apply this diff for consistency:

 # Use current timestamp with microsecond precision to ensure uniqueness
 timestamp = time.time()
 timestamp_int = int(timestamp * 1_000_000)  # Convert to microseconds as integer
 timestamp_bytes = timestamp_int.to_bytes(32, byteorder="big", signed=False)

 # Derive a deterministic pseudo-random seed from the recipient address
-seed_source = f"{to_address or '0x0'}:{timestamp}"
+seed_source = f"{to_address or '0x0'}:{timestamp_int}"
🤖 Prompt for AI Agents
In backend/database_handler/transactions_processor.py around lines 198 to 204,
the code uses a float timestamp for seed_source while converting a
microsecond-precision integer (timestamp_int) to bytes, causing inconsistent
representations; fix by using the same microsecond integer (or its canonical
string) in seed_source instead of the float (e.g., use timestamp_int or
str(timestamp_int)) so seed_source and timestamp_bytes derive from the identical
timestamp representation.

Expand Down Expand Up @@ -290,7 +291,10 @@ def insert_transaction(
def _process_round_data(self, transaction_data: dict) -> dict:
"""Process round data and prepare transaction data."""

if "consensus_results" in transaction_data["consensus_history"]:
if (
transaction_data["consensus_history"] is not None
and "consensus_results" in transaction_data["consensus_history"]
):
transaction_data["num_of_rounds"] = str(
len(transaction_data["consensus_history"]["consensus_results"])
)
Expand All @@ -301,7 +305,10 @@ def _process_round_data(self, transaction_data: dict) -> dict:
validator_votes = []
validator_votes_hash = []
round_validators = []
if "consensus_results" in transaction_data["consensus_history"]:
if (
transaction_data["consensus_history"] is not None
and "consensus_results" in transaction_data["consensus_history"]
):
round_number = str(
len(transaction_data["consensus_history"]["consensus_results"]) - 1
)
Expand Down Expand Up @@ -380,7 +387,10 @@ def _prepare_basic_transaction_data(self, transaction_data: dict) -> dict:
"processing_block": "0",
"proposal_block": "0",
}
if "consensus_results" in transaction_data["consensus_history"]:
if (
transaction_data["consensus_history"] is not None
and "consensus_results" in transaction_data["consensus_history"]
):
transaction_data["activator"] = transaction_data["consensus_history"][
"consensus_results"
][0]["leader_result"][0]["node_config"]["address"]
Expand Down Expand Up @@ -443,6 +453,7 @@ def _process_messages(self, transaction_data: dict) -> dict:
eq_output = []
if (
"consensus_history" in transaction_data
and transaction_data["consensus_history"] is not None
and "consensus_results" in transaction_data["consensus_history"]
):
for consensus_round in transaction_data["consensus_history"][
Expand Down
Loading