diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 386e70c..89cfd1b 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1,6 +1,8 @@ import os import requests import random +import threading +import time from pathlib import Path from dotenv import load_dotenv @@ -138,6 +140,45 @@ def route_transactions(): pubsub.broadcast_transaction(transaction) transaction_pool.set_transaction(transaction) +def poll_root_blockchain(): + """ + Poll the root blockchain at specified intervals and attempt to sync. + This runs in a background thread when POLL_ROOT environment variable is True. + """ + poll_interval = int(os.environ.get('POLL_INTERVAL', '15')) + + while True: + try: + # Get the root host from environment, fallback to localhost + root_host = os.environ.get('ROOT_BACKEND_HOST', 'localhost') + root_port = ROOT_PORT + + # Fetch blockchain from root host + response = requests.get(f'http://{root_host}:{root_port}/blockchain', timeout=10) + response.raise_for_status() + + # Parse the blockchain + result_blockchain = Blockchain.from_json(response.json()) + + # Attempt to replace the local chain with the root chain + blockchain.replace_chain(result_blockchain.chain) + print(f'\n -- Successfully synchronized with root blockchain at {root_host}:{root_port}') + + except requests.exceptions.RequestException as e: + print(f'\n -- Error fetching blockchain from root: {e}') + except Exception as e: + print(f'\n -- Error synchronizing with root blockchain: {e}') + + # Wait for the configured interval before next poll + time.sleep(poll_interval) + +if os.environ.get('POLL_ROOT') == 'True': + # Start the polling thread + poll_thread = threading.Thread(target=poll_root_blockchain, daemon=True) + poll_thread.start() + poll_interval = os.environ.get('POLL_INTERVAL', '15') + print(f'\n -- Started polling root blockchain every {poll_interval} seconds') + if __name__ == "__main__": app.run(host="0.0.0.0", port=PORT, debug=True)