High availability ethereum-like node proxy
Abstract
En el ecosistema de las aplicaciones descentralizadas (DApps), la dependencia de un único nodo de blockchain para realizar todas las transacciones presenta varios desafíos críticos, entre ellos la falta de redundancia y la potencial inestabilidad en caso de fallos en dicho nodo. Este problema subraya la necesidad de un sistema que permita la configuración y monitoreo de múltiples nodos, asegurando una alta disponibilidad y un equilibrio de carga eficiente. El presente Trabajo de Final de Grado, titulado "HIGH AVAILABILITY ETHEREUM-LIKE NODE PROXY", aborda esta problemática proponiendo una solución basada en una aplicación desarrollada en Python para monitorear y equilibrar el tráfico entre varios nodos Ethereum JSON-RPC.
Full text
HIGH AVAILABILITY ETHEREUM-LIKE NODE PROXY Bachelor’s Degree Thesis Submitted to the Faculty at the Escola Tècnica Superior d'Enginyeria de Telecomunicació de Barcelona de la Universitat Politècnica de Catalunya by JORGE ORTEGA GARCÍA In partial fulfillment of the requirements for the DEGREE IN TELECOMUNICATION TECHNOLOGIES AND SERVICES ENGINEERING Advisor: OSCAR ESPARZA MARTIN Reviewer: RAFAEL GENÉS DURÁN Barcelona, June 2024 ETSETB – Degree in Telecommunication Technologies and Services Engineering
-2- Summary Resum______________________________ En l'ecosistema de les aplicacions descentralitzades (DApps), la dependència d'un únic node de blockchain per executar totes les transaccions presenta diversos desafiaments crítics, incloent la manca de redundància i la potencial inestabilitat en cas de fallades del node. Aquest problema ressalta la necessitat d'un sistema que permeti la configuració i monitorització de múltiples nodes, assegurant una alta disponibilitat i un equilibrament eficient de la càrrega. Aquest Treball de Final de Grau, titulat "HIGH AVAILABILITY ETHEREUM-LIKE NODE PROXY," aborda aquesta problemàtica proposant una solució basada en una aplicació desenvolupada en Python per monitoritzar i equilibrar el tràfic entre diversos nodes Ethereum JSON-RPC. ____________________________Resumen En el ecosistema de las aplicaciones descentralizadas (DApps), la dependencia de un único nodo de blockchain para realizar todas las transacciones presenta varios desafíos críticos, entre ellos la falta de redundancia y la potencial inestabilidad en caso de fallos en dicho nodo. Este problema subraya la necesidad de un sistema que permita la configuración y monitoreo de múltiples nodos, asegurando una alta disponibilidad y un equilibrio de carga eficiente. El presente Trabajo de Final de Grado, titulado "HIGH AVAILABILITY ETHEREUM-LIKE NODE PROXY", aborda esta problemática proponiendo una solución basada en una aplicación desarrollada en Python para monitorear y equilibrar el tráfico entre varios nodos Ethereum JSON-RPC. Summary____________________________ In the ecosystem of decentralized applications (DApps), the reliance on a single blockchain node for executing all transactions presents several critical challenges, including a lack of redundancy and potential instability in the event of node failures. This problem highlights the need for a system that enables the configuration and monitoring of multiple nodes, ensuring high availability and efficient load balancing. This Bachelor’s Degree Thesis, titled "HIGH AVAILABILITY ETHEREUM-LIKE NODE PROXY," addresses this issue by proposing a solution based on a Python API designed to monitor and balance traffic among various Ethereum JSON-RPC nodes.
-3- Acknowledgements This thesis was entire developed by me, Jorge Ortega. I would like to express gratitude to my two project supervisors: Oscar Esparza Martin and Rafael Genes Durán. They proposed the project idea and helped me with everything I need, giving advises and tools for dealing with any trouble I encountered.
-4- Revision history and approval record Revision Date Author(s) Description 1.0 27/05/2024 JOR Document creation 1.1 05/06/2024 JOR Error correction 2.0 14/06/2024 JOR, RGD Revised after review 3.0 17/06/2024 JOR, RGD, OEM Error correction 4.0 17/06/2024 JOR, RGD, OEM Final version LLISTA DE DISTRIBUCIÓ DEL DOCUMENT Role Surname(s) and Name Student Jorge Ortega García Project Supervisor 1 Oscar Esparza Martín Project Supervisor 2 (if applicable) Rafael Genes Durán Written by: Reviewed and approved by: Date 27/05/2024 Date 17/06/2024 Name Jorge Ortega García Nome Oscar Esparza Martín Role Project Author Role Project Supervisor
-5- Contents Summary ........................................................................................................................................................................ 2 Acknowledgements ................................................................................................................................................... 3 Revision history and approval record ............................................................................................................... 4 Contents ......................................................................................................................................................................... 5 List of Figures............................................................................................................................................................... 7 List of Tables ................................................................................................................................................................ 8 Abbreviations ............................................................................................................................................................... 9 1. Introduction ..................................................................................................................................................... 10 1.1. Work goals .............................................................................................................................................. 10 1.2. Requirements and specifications .................................................................................................. 12 1.3. Methods and procedures .................................................................................................................. 13 1.4. Work plan ................................................................................................................................................ 14 1.4.1. Work packages and milestones.................................................................................................14 1.4.2. Gantt diagram....................................................................................................................................18 2. State of the art of the technology used or applied in this thesis ................................................ 19 2.1. Blockchain Technology ...................................................................................................................... 19 2.1.1. Decentralized Systems...................................................................................................................19 2.1.2. How does a blockchain network works?................................................................................20 2.1.3. Types of Blockchain........................................................................................................................23 2.2. Ethereum ................................................................................................................................................. 24 2.2.1. Ethereum JSON-RPC Nodes.........................................................................................................25 3. Methodology / project development ..................................................................................................... 27 3.1. Methodology and techniques .......................................................................................................... 27 3.1.1. Agile methodology..........................................................................................................................28 3.1.2. Techniques.........................................................................................................................................28 3.2. Development process ......................................................................................................................... 29 3.2.1. Prerequisites.....................................................................................................................................30 3.2.2. API Development.............................................................................................................................30 3.2.3. Health checks and load balancing algorithm.......................................................................32
-6- 3.2.3.1. Health checks...................................................................................................................33 3.2.3.2. Load balancing algorithm...........................................................................................34 3.2.4. Monitoring stack: Telegraf - InfluxDB - Grafana - Loki....................................................35 3.2.4.1. Monitoring stack set up...............................................................................................36 4. Results ................................................................................................................................................................ 38 4.1 Experiments and Tests ............................................................................................................................. 38 4.2. Data Visualization ...................................................................................................................................... 40 4.3. Limitations .................................................................................................................................................... 42 5. Sustainability Analysis and Ethical Implications .............................................................................. 44 5.1. Sustainability Matrix........................................................................................................................... 44 5.1.1. Environmental impact...................................................................................................................45 5.1.2. Economic impact..............................................................................................................................46 5.1.3. Social impact......................................................................................................................................48 5.2. Ethical Implications ............................................................................................................................ 49 5.3. Relation with Sustainable Development Goals ........................................................................ 50 6. Conclusions and Future Work .................................................................................................................. 51 6.1. Conclusions ............................................................................................................................................. 51 6.2. Future Directions ................................................................................................................................. 53 Bibliography .............................................................................................................................................................. 54 Appendix A ................................................................................................................................................................. 55
-7- List of Figures Figure 1. Workplan GANTT diagram ............................................................................................................... 18 Figure 2. Centralized and decentralized systems ...................................................................................... 20 Figure 3. PoW diagram .......................................................................................................................................... 21 Figure 4. Blockchain ............................................................................................................................................... 22 Figure 5. Types of Blockchain ............................................................................................................................ 23 Figure 6. JSON-RPC payload ................................................................................................................................ 25 Figure 7. Directory structure .............................................................................................................................. 29 Figure 8. Application flux diagram ................................................................................................................... 30 Figure 9. Application functionality................................................................................................................... 31 Figure 10. Load balancing algorithm files ..................................................................................................... 32 Figure 11. Monitoring stack diagram .............................................................................................................. 36 Figure 12. Grafana dashboard ............................................................................................................................ 40 Figure 13. Status code panel ............................................................................................................................... 40 Figure 14. Response time panel ........................................................................................................................ 41 Figure 15. Block number panel.......................................................................................................................... 41 Figure 16. Logs panel ............................................................................................................................................. 42
-8- List of Tables Table 1. WP1: Previous work ............................................................................................................................. 14 Table 2. WP2: API Development ....................................................................................................................... 14 Table 3. WP3: Load Balancing ............................................................................................................................ 15 Table 4. WP4: Monitoring stack ........................................................................................................................ 15 Table 5. WP5: Integration .................................................................................................................................... 16 Table 6. WP6: Integration .................................................................................................................................... 16 Table 7. Milestones ................................................................................................................................................. 17 Table 8. Sustainability Matrix............................................................................................................................. 44 Table 9. Direct costs - Salaries ........................................................................................................................... 46 Table 10. Direct costs - Amortization ............................................................................................................. 46 Table 11. Indirect costs ......................................................................................................................................... 46
-9- Abbreviations ETSETB Escola Tècnica d’Enginyeria de Telecomunicació de Barcelona BT Bachelor Thesis DAPP Decentralized application API Application Programming interface JSON JavaScript Object Notation RPC Remote Procedure Call WP Work Package PoW Proof of Work EVM Ethereum Virtual Machine GRI Global Reporting Initiative SDG Sustainable Development Goals
-16- Project: Integration WP ref: WP5 Major constituent: Software Sheet 3 of 3 Short description: Combining all the WPs in the same work directory, structuring the folders and making the final tests of the application. Planned start date: 03/04/2024 Planned end date: 14/06/2024 Start event: 11/03/2024 End event: 17/06/2024 Internal task T1: Structuring the app Internal task T2: Integrating all WP Internal task T3: Testing Deliverables: - Dates: - Table 5. WP5: Integration Project: Documentation WP ref: WP6 Major constituent: Documentation Sheet 3 of 3 Short description: Organize the three big deliverables and writing them properly. Planned start date: 01/03/2024 Planned end date: 19/06/2024 Start event: 01/03/2024 End event: 17/06/2024 Internal task T1: Project proposal and workplan Internal task T2: Critical Review Internal task T3: Final memory Deliverables: - Dates: - Table 6. WP6: Integration
-17- Milestones WP# Task# Short title Milestone / deliverable Date (week) WP6 Task6.1 Workplan Project proposal Workplan 10/03/2024 WP1 Task1.1, Task1.2 Basic knowledge acquired - 13/03/2024 WP2, WP6 Task2.1, Task2.2, Task6.2 Simple API with one endpoint receiving request. Critical Review 03/04/2024 WP2, WP3 Task2.3 Task3.1, Task3.2 Basic algorithms implemented and API working - 01/05/2024 WP4 Task4.1, Task4.2, Task4.3 Basic monitoring stack implemented - 17/05/2024 WP4, WP5 Task4.4, Task5.2 Everything implemented and integrated - 07/06/2024 WP5, WP6 Task5.3, Task6.3 Application tests and Final memo Final Memory 17/06/2024 Table 7. Milestones
-18- 1.4.2. Gantt diagram Figure 1. Workplan GANTT diagram
-19- 2. State of the art of the technology used or applied in this thesis ___________________________________________________________ CHAPTER 2 State of the art of the technology used or applied in this thesis In the past years, the cryptocurrency market has exploded and it is taking more importance inside the global economy. Nowadays, the cryptocurrencies allow to create and transfer stocks quickly, cheaply and globally, even being a match against the global bank system. How can this be possible? Blockchain technology is the answer. This chapter provides a detailed view of the current state of blockchain decentralized systems, with a particular focus on Ethereum, to set the context for my work, the development of a high availability Ethereum-like node proxy application. 2.1. Blockchain Technology 2.1.1. Decentralized Systems Various of the current major technologies are working over the decentralization idea, such as cryptocurrency (Bitcoin or Ethereum), NFT’s, smart contracts, Artificial Intelligence (AI)… The decentralized systems rely on a set of independent computers connected through a network with the same common goal, besides the fact that the idea is all of them function as a one single computer. The characteristic of these type of networks is the lack of a central server controlling the users’ traffic of the application. Otherwise, the participants, called nodes, are working Peer-to-Peer (P2P) managing the data and exchanging it between all of them. Furthermore, if a node stops working, the network will still be operating.
-20- In particular, Peer-to-Peer networks as opposed to a standard one is that instead of storing data in a single centralized server it distributes small chunks of it and stores them across the entire network nodes. That it means the nodes are spreading and collecting this data from other participants. For example, a file is split in different parts saved in different computers, if a user wants to download it the participant will find all the chunks to restore the whole file, meanwhile others are entering to the user’s computer for obtaining their data. Figure 2. Centralized and decentralized systems This idea was first introduced in 2008 with a mysterious white paper called “Bitcoin: A peer-to-peer electronic cash system” and signed by an anonymous person or group known as Satoshi Nakamoto. He proposed a decentralized Peer-to-Peer electronic cash system based on a chain of blocks with the aim to remove intermediaries like banks from payments and global data transfer. This was the origin of Bitcoin based on the Blockchain Technology. 2.1.2. How does a blockchain network works? Blockchain is a distributed, decentralized system comprising a network of various nodes that collectively maintain a distributed ledger. This technology is particularly utilized in the cryptocurrency market, where the exchanged data involves monetary transactions between users. The entire transaction record is stored in a ledger, which must be kept up-to-date by all nodes.
-21- To avoid synchronization problems, among others, transactions occurring within the same time frame are grouped and stored in a single data unit called a block. Network participants are responsible for gathering multiple transactions, validating them, and constructing the block to exchange it with others. Importantly, no single authority controls the network. This ledger is essentially a chain of different blocks. The reward for these participants is the ability to include a transaction of their own within the block. Thousands of participants can add their own blocks to the ledger, but which block should be chosen? Voting could be a solution, but Sybil attacks could manipulate it. Hence, the Proof of Work (PoW) mechanism was introduced. The idea is that each participant, known as a miner, who wants to add a block must solve a difficult cryptographic puzzle that requires significant computational power. In this way, if an attacker wanted to create multiple fake identities to gain control of the blockchain network, they would need to solve numerous puzzles, consuming a lot of computational power. Specifically, this PoW mechanism relies on a hash function. Imagine a hash function as a machine that takes data as input and outputs a sequence of numbers with a fixed bit length that appears random. If the input undergoes a minimal change, the output hash code will be entirely different. With this concept, miners input the constructed block, and the puzzle is to change a numerical digit of the block and try to find a hash code with a certain number of leading zeros. The coding complexity is very high, but the first one to solve the puzzle will add and share their block to the blockchain. Figure 3. PoW diagram
-22- There is still a potential issue: two miners might mine a block simultaneously and spread it to the network, causing some nodes to have different blockchains. To resolve this, it is established that "the majority decision is represented by the longest chain, which has the greatest proof-of-work effort invested in it." When another miner adds a new block to one of the chains, that chain becomes the official one. Additionally, the security of the system relies on the collective group rather than a single centralized system, because the ledger is always distributed across nodes and not stored on a single machine. An important point to ensure security is that a new block can only be appended at the end of the chain if it is linked to the previous block, containing its hash code. Then, when it is added, an agreement is required by all the nodes in the network, and no single entity can modify it. Figure 4. Blockchain In conclusion, a blockchain a data structure made up of blocks chained together by their hash and which, due to the design, is practically immutable. This technology has introduced a new method for networks that require transparency, enhanced security, greater trust, accountability, and traceability.
-23- 2.1.3. Types of Blockchain Blockchain networks can be classified according to their deployment models, which determine who has the authority to maintain and operate them. The primary types of blockchain networks include: public, private and consortium blockchains. Figure 5. Types of Blockchain In public blockchains there are no barriers to entry, allowing any user to engage in network activities, including reading and writing data on the blockchain. This type of blockchain relies on an incentive mechanism to attract new participants and maintain network vitality. Bitcoin and Ethereum are prime examples of public blockchains. On the other hand, the private blockchains restricts access to a select group of verified participants. Entry into the network requires an authenticated invitation, and a central authority oversees the network, managing membership and transaction validation. In private blockchains, user identities can be partially known to assign roles and control access to specific data and operations within the network. Unlike public blockchains, private blockchains are more centralized, and consensus mechanisms are often unnecessary since a single entity usually controls block creation. Finally, a consortium blockchain, also known as a federated blockchain, blends elements of both public and private blockchains. In this setup, the network is managed by a group of pre-approved nodes or organizations, each of which has a say in the validation of transactions and maintenance of the ledger. This model offers a balance between decentralization and control, making it suitable for business-to-business interactions where multiple organizations need to collaborate securely.
-24- 2.2. Ethereum Nowadays there are a lot of public permissionless blockchains such as Bitcoin, Litecoin or NEO but Ethereum blockchain is considered one of the main leaders. It was proposed by Vitalik Buterin in 2013 and launched in 2015 and Ethereum significantly expanded the capabilities of blockchain by introducing the concept of smart contracts. The, Ethereum is defined as a blockchain-based digital platform designed to run a multitude of decentralized applications, process transactions and execute smart contracts. Its main function is to record transactions between users and smart contracts, which can subsequently alter the global state or world state of Ethereum. A smart contract is a piece of code which is stored inside the data blocks of a blockchain. These are automatically executed by the clients on the Ethereum Virtual Machine (EVM) when predetermined conditions are met, and can automatically enforce contractual agreements without the need for intermediaries. An example of use is, for example, to ensure that a digital work, such as videos, images or an NFT, has a specific owner inside the blockchain. In addition, the EVM is the runtime environment for smart contracts on Ethereum. It allows anyone to execute code of arbitrary algorithmic complexity, making the Ethereum blockchain a global, decentralized computer. Furthermore, the native cryptocurrency of the Ethereum network is Ether (ETH), it is used to pay transaction fees and computational services, incentivizing nodes to process transactions and execute smart contracts. On the other hand, being a permissionless public blockchain, Ethereum allows anyone to send transactions to the network. These transactions must reach a node that will record and propagate them to other participants. Since it is impossible for all transactions to reach every node quickly, they are stored in a memory pool known as the “Mempool” on each client. The Mempool temporarily stores pending transactions before they are included in a new block. This system helps manage the flow of transactions and ensures that they are processed efficiently. Initially, Ethereum utilized the Proof of Work (PoW) consensus protocol, where miners were responsible for inserting new blocks, as well it was explained before.
-25- However, with the advent of Ethereum 2.0, the network is transitioning to Proof of Stake (PoS). PoS involves proponents, not miners, who propose and validate new blocks based on the number of coins they hold and are willing to "stake" as collateral, significantly reducing the computational power required. 2.2.1. Ethereum JSON-RPC Nodes First of all, Ethereum has three different networks: Mainnet, Sepolia and Holesky. Mainnet, as the name says, refers to the primary public blockchain network where all the thigs explained before take place. Sepolia and Holesky are Ethereum testnets for users. Interact with a node on the Ethereum network can be carried out in several ways. The main one requires an application called Ethereum client, which needs to be deployed on a machine The clients implement the Ethereum protocol and mechanism to interact with the network. The most common are Geth and OpenEthereum. They are capable of running a full node with a command line interface (CLI) to make requests through the others nodes. On the other hand, is able to do it via remote procedure calls (RPC). The Ethereum network operates through numerous nodes that communicate using the JSON-RPC protocol. This protocol defines a standard for remote procedure calls, enabling interactions with the Ethereum blockchain. This means that it allows us to execute methods in a node remotely by writing the requests in JSON format. These requests can be sent over HTTP. The experiments of this thesis are done with HTTP requests using JSON-RPC protocol. The structure of a JSON-RPC request is, notice it is a JSON data structure: Figure 6. JSON-RPC payload
-32- This approach ensures that the API can dynamically route requests to the most efficient node available, enhancing the reliability and performance of the system. Moreover, by maintaining a JSON file updating the efficient node information with a different thread, the system can easily update which node is considered the most efficient without needing to change the API code. In summary, this basic API setup allows for efficient handling and routing of JSON-RPC requests to Ethereum nodes, ensuring that the best-performing node is utilized for each request. The use of FastAPI provides a robust and high-performance framework to build and manage the API, making it an effective solution for this project. 3.2.3. Health checks and load balancing algorithm The load balancing algorithm is another main component of the project. Thanks to the periodical health checks among the Ethereum network that are monitoring it, ensures the JSON-RPC requests are always directed to the most efficient Ethereum node, stored in a list of available nodes, with the lowest response time. What is more, if a specific node is been flooded of traffic, its response time will increase and the efficient node election will change. This dynamic selection process enhances the reliability and performance of the system, ensuring optimal operation of the decentralized applications that depend on these available nodes. On the other hand, in the application, the algorithms and data lake of the results are found in the ‘/scripts’ directory, split into the Python files ‘/scripts/python_scripts’ and the JSON data ‘/scripts/data_json’. Figure 10. Load balancing algorithm files
-33- 3.2.3.1. Health checks The core functionality of the algorithm is implemented in the ‘healthcheck.py’ script, located in the ‘/scripts/python_scripts’ directory. This script periodically evaluates each node's performance in the ‘node_list.py’ file and updates the two JSON files accordingly, one with the health checks results ‘healthcheck.json’ and the other one with the election of the most efficient node ‘efficient_node.json’, both stored in the ‘/scripts/data_json’ directory. Digging deeper in, an agent of Telegraf is going to run the ‘healthcheck.py’ regularly in a set time interval, 60 seconds. Notice that it is a different thread from the main one, which executes the API script. The metrics recollected of the Ethereum network are the node HTTP status response, the last block number of the blockchain and the response time. It is made a list of dictionaries in Python with all the information and finally it is stored in the according JSON file. How the monitoring algorithm works: 1. Building the request: The script constructs a JSON-RPC payload with the method “eth_blockNumber” for interacting with the Ethereum network. The aim of the request is getting the current block number from each node in the list, previously imported from the ‘node_list.py’. 2. Measuring performance: For each node, the script measures the time taken to receive a response ‘response_time’ with the help of ‘time’ Python package. Then, checks the HTTP status code “status_code” of the response and retrieves the latest block number “block_number” given by the node. 3. Data Management: with all the information of the metrics spread in different variables, all of them are appended in the list “healthcheck”. Finally with the easy-way Python allows interacting with JSON, the ‘healthcheck.json’ file is update with the new data. 4. Error handling: notice that if something happens it will be captured and reported to the user. The implementation keeps in mind the cases if the node does not respond with a HTTP status code of 200 (OK), and the metrics are set to “None”. Even the node is not found, the status code is going to be -1.
-34- 3.2.3.2. Load balancing algorithm The load balancing algorithm operates by the health check results which continuously monitors the performance of the available Ethereum nodes in the ‘node_list.py’. It utilizes the metric of the “response_time” to determinate which one is the most efficient. The idea is to look for the node with the fastest reply and store all its information in the JSON fila ‘efficient_node.json’. How the load balancing algorithm works: 1. Setting a variable storing the less response time “less_response_time” initialized to a very big number. It is chosen 101 seconds, because the default timeout of a HTTP request is 100 seconds. In order to keep in mind the situation of all the nodes in the list are not found. 2. Setting a variable storing the efficient node “efficient_node”, by default, it is chosen the first node in the list. 3. Efficient node update: every time the response time of a node is known, it is compared with the “less_response_time” value. If it is lower, the update both the efficient node and the new less response time. 4. Data Management: finally, the ‘efficient_node.json’ is update with the newest data. By continuously evaluating and updating the efficiency of each node, the load balancing algorithm ensures that requests are routed to the best-performing node available. This dynamic selection process not only optimizes the performance of the Ethereum network interactions but also enhances the overall reliability and responsiveness of the DApps relying on these nodes. In addition, this way of scheduling and implementing the project allows for seamless updates and adjustments as new nodes are added or existing nodes' performance changes, without needing to make big changes in the code. Furthermore, the fact of separating both threads, one running the API and the other one the algorithm, improves exponentially the user experience. If both of them are the same, every user must wait until the application does the health check, stores the data and then looks for the efficient node before the request is redirected.
-35- 3.2.4. Monitoring stack: Telegraf – InfluxDB – Grafana – Loki The monitoring stack, composed by Telegraf, InfluxDB, Loki and Grafana, plays a critical role in tracking the performance and health of the Ethereum nodes. Each component in the stack has a specific function and is configured to work seamlessly together to ensure accurate and real-time monitoring and data visualization of the nodes. All of them deployed with Docker Compose. Telegraf is an open-source agent for collecting, processing, aggregating, and writing metrics of a network. It supports a wide range of input and output plugins, making it highly extensible and adaptable to various monitoring needs, in this project three of them are configured. First, an input plugin type ‘exec’ for executing the ‘healthcheck.py’ script and two output plugins, one for sending the data to the InfluxDB type ‘influxdb_v2’ and the other one type ‘file’ for showing it in the ‘stdout’. With the last one, you can see the data in the logs of the container. InfluxDB acts as the time-series database where all metrics collected by Telegraf are stored. The use of InfluxDB ensures efficient storage and retrieval of time-series data, which is essential for monitoring performance over time. InfluxDB stores the data in buckets, I chose a custom one called ‘_ethereum’. What is more, the communication between Telegraf and InfluxDB is authenticated with a token for enhance the security, the developer must choose it and keep the secret. You can access to the interface at the URL “http://localhost:8086” by default. Grafana allows users to visualize and analyze data from various sources and it provides a rich set of features for creating interactive and customizable dashboards. In this project, Grafana is used to display the metrics collected by Telegraf and stored in InfluxDB. On the other hand, Loki is a database for logs (information given by the application) and depends on another tool for collecting them, Alloy. Both will be configured to sniff the ‘fastapi.log’ file and report the logs to Grafana. Also, a customized Grafana dashboard has been created to present the key metrics of the response times, status codes, the block numbers and the API logs. This dashboard provides real-time insights into the performance and health of the Ethereum nodes, enabling proactive monitoring and management, you will find more information below. Grafana service is deployed in “http://localhost:3000” by default.
-36- Figure 11. Monitoring stack diagram 3.2.4.1. Monitoring stack set up The entire stack is implemented using Docker Compose, providing a robust and scalable solution for monitoring and visualizing the system's metrics. This fact also simplifies the deployment and the management of multiple containers, the application will deploy five, one running each tool. Everything is in ‘/monitoring-stack’ directory. The Docker Compose configuration file is called ‘docker-compose.yml’. It will deploy all the containers over the real images of the provider, but notice that a customized Telegraf image is been created. This is the only one that needs to be built with a Dockerfile stored in the ‘/docker_image’ directory, by executing: $ docker build -t telegraf_ethereum:latest /docker_image The reason is the image pulled of telegraf:alpine does not have Python already incorporate and it is indispensable for running the health check script. Then, this basic Dockerfile is configured for downloading it and some extra dependences. On the other hand, the ‘.env’ file contains all necessary environment variables for the Docker Compose setup. This file centralizes the configuration, making it easier to manage and modify settings for the entire stack. For replicating the application, take a look and then you must set all of them according to your needs.
-37- In particular, inside the ‘/monitoring-stack/telegraf’ and ‘/monitoring-stack/grafana’ directories you can find configuration files for these services. There is the ‘telegraf.conf’ containing the Telegraf plugins set up. On the other hand, for Grafana, in order to automatize much the application, the ‘database.yaml’ YAML file contains the configuration of the InfluxDB and Loki databases in Grafana, so you do not need to set them up manually. Finally, the Grafana dashboard is the JSON file called ‘healthcheck_dashboard.json’ that it must be imported in the application for visualizing the different panels with the real-time data collection. This is configured according my needs, for reproducing the application you can use it as a template changing the configuration by hand inside Grafana. Moreover, the corresponding configuration files of Loki and Alloy are inside ‘/monitoring-stack/loki’ and ‘/monitoring-stack/alloy’ directories. I recommend using the same templates that are already in the GitHub, in particular, the only change to do is in ‘alloy-config.alloy’ put the correct path to the log file. After that, the five containers can be deployed at the same time using Docker Compose. Run the following command in the ‘/monitoring-stack’ directory: $ docker compose up -d Finally, for stopping everything execute: (it is optional to use the ‘-v’ parameter, this means to erase all the docker volumes created) $ docker compose down -v Summing up, by leveraging Docker Compose for orchestration, a customized Telegraf image for metric collection, and a secure communication setup, this monitoring stack provides a comprehensive solution for tracking and visualizing the performance of Ethereum nodes. The detailed and real-time insights offered by the Grafana dashboard enable proactive management and optimization of the node infrastructure.
-38- 4. Results ___________________________________________________________ CHAPTER 4 Results This chapter presents a detailed analysis of the data collected and the findings derived from the experiments conducted to evaluate the performance of the Ethereum node proxy system. The goal of these experiments was to find out how well the system balances the load across different Ethereum nodes and ensures high availability and efficiency. This section includes descriptions of the experiments, visualizations of the data, and a discussion of the limitations encountered during the project. 4.1 Experiments and Tests To assess the performance of the project, several experiments were conducted. Related to the monitoring stack, it has been used a total of six nodes, three from the Ethereum Mainnet network and three from Sepolia. Two of them are from Infura provider and one from Alchemy. For ensuring the correct working of the load balancing algorithm, several JSON-RPC test requests were sent through the API. These experiments aimed to simulate real-world scenarios where multiple requests are made to the nodes, and the system needs to dynamically select the most efficient node to handle each request. The experiments focused on the following aspects: • Traffic Redirection Verification: Ensuring that JSON-RPC requests made to the API are correctly redirected to the most efficient node and return the expected responses.
-39- • Node Response Time: Measuring the time taken by each Ethereum node to respond to JSON-RPC requests. This metric is crucial for understanding the latency introduced by each node and the overall responsiveness of the system. • Node Health Status: Tracking the status codes returned by each node to determine their operational status. This helps in identifying nodes that are down or experiencing issues. • Block Synchronization: Monitoring the latest block numbers reported by each node to ensure they are in sync with the blockchain. This ensures that the data provided by the nodes is current and accurate. As well as it was explained at the previous subsection, the data is collected using the ‘healthcheck.py’ script, which is periodically executed by the configured Telegraf agent. The script sends JSON-RPC requests with the method “eth_blockNumber” to each node and recorded the response times, status codes, and block numbers. These metrics were then sent to InfluxDB, where they were stored for analysis. On the other hand, the traffic redirection verification is made by sending different type of JSON-RPC requests to the ‘/receive_request’ endpoint of the API and the responses were recorded. In order to make easier this process, the ‘user.py’ is a helper script that automatically send the request. The collected data was processed to extract meaningful insights. The response times were averaged over multiple runs to smooth out any anomalies. Status codes were categorized to identify nodes that were consistently returning errors. Block numbers were compared across nodes to detect any synchronization issues. For the traffic redirection verification, the responses were analyzed to ensure they matched the expected results.
-40- 4.2. Data Visualization To better understand the performance of the Ethereum nodes, several visualizations were created using Grafana. These visualizations provide a clear and concise representation of the data, allowing for easy interpretation and analysis. Users must keep in mind that they can customize the Grafana dashboard in their own way, in this case is adapted to the experiments explained. The dashboard of my experiments is below: Figure 12. Grafana dashboard As can be seen in the Figure, the data is split into two columns, one with the Mainnet and other for Sepolia nodes, and each metric is distributed in three different panels: • Code state: to visualize the current state of the node, at the top of the image appear the HTTP codes, in this situation whole of them are answering properly. Figure 13. Status code panel
-41- • Latency: the most important metric measuring the latency of the nodes is situated in the two middle graphs. During the experiment the responses times are quite different, but the Alchemy nodes are the fasters one, so all the time the requests will be redirected to them Figure 14. Response time panel • Block number: the two last scatters show that all the nodes are synchronized having the same block numbers all the time. As it is exposed below, all of them are properly synchronized with the blockchain, it make sense that the graph is a straight line with positive slope. Figure 15. Block number panel
-48- 5.1.3. Social impact The development of this BT has had a notable impact on the individuals directly involved, the student and the supervisors. The supervisors provided several valuable ideas and helped troubleshoot various challenges encountered during the development process. Their guidance was instrumental in shaping the project's direction and overcoming obstacles. Additionally, other decisions like which the monitoring stack implement was independently made by the student, fostering a sense of ownership and enhancing problem-solving skills. This collaborative effort not only raised awareness of the complexities and intricacies involved in the project but also highlighted the importance of diverse perspectives in achieving successful outcomes. During the project execution would have diverse social impacts on various groups directly or indirectly involved. These groups include the managers, workers, suppliers, direct users (consumers), and indirect users. The implementation of an efficient Ethereum-like node proxy system could improve operational efficiency and user satisfaction, potentially benefiting managers by reducing downtime and improving service reliability. Workers and suppliers might experience changes in their workflows or demand for their services. Consumers, as direct users, would benefit from a more seamless and reliable service. Indirect users might see broader technological improvements and increased trust in blockchain systems. However, social repercussions are challenging to predict and quantify due to the diverse and complex nature of social sustainability indicators, as outlined in the GRI standards . Addressing the social risks and limitations of the project involves recognizing potential challenges that could negatively impact various stakeholder groups. These risks include misunderstandings of project goals among stakeholders, leading to dissatisfaction. Predicting social reactions and behaviors is complex, making it difficult to fully anticipate the project's effects on different groups. Mitigation strategies include proactive communication, stakeholder engagement throughout the project lifecycle, and continuous monitoring to address emerging concerns. By navigating these risks and limitations conscientiously, the project can strive to maximize its positive social impact while minimizing adverse effects on affected communities and stakeholders.
-49- 5.2. Ethical Implications In addressing the ethical implications of this Bachelor's Thesis, it is essential to consider the specific needs it aims to fulfill and who has defined these needs. The project primarily addresses the demand within the field of decentralized applications by enhancing the reliability and efficiency of Ethereum-like node proxies through load balancing techniques. These needs are substantiated by the increasing reliance on blockchain technology for secure and transparent digital transactions, aligning with broader technological advancements and potentially contributing to Sustainable Development Goals (SDGs) related to innovation and infrastructure. Anticipating consequences beyond the project's initial objectives is crucial. While the primary aim is to optimize node selection and enhance system reliability, unintended consequences could include increased dependency on digital infrastructures, potential disparities in access to technology, or unforeseen environmental impacts arising from increased energy consumption in data centers. Regarding ethical considerations, adherence to professional codes of ethics is paramount. In the realm of technology and software development, ethical guidelines emphasize transparency, accountability, and respect for user privacy and data security. This project aligns with these principles by prioritizing data integrity, implementing secure coding practices, and ensuring robust authentication mechanisms for accessing blockchain nodes. Continuous evaluation and adaptation to ethical standards are essential to uphold the integrity and trustworthiness of the project's outcomes in an evolving technological landscape.
-50- 5.3. Relation with Sustainable Development Goals In concluding this report, it is pertinent to assess whether this Bachelor's thesis contributes to any of the 17 Sustainable Development Goals established by the United Nations in its Agenda 2030. The SDGs encompass a broad spectrum of global challenges and aspirations, including poverty eradication, environmental sustainability, and social equity. This project primarily aligns with SDG 9 (Industry, Innovation, and Infrastructure) and SDG 7 (Affordable and Clean Energy). By optimizing the efficiency and reliability of Ethereum-like node proxies through innovative load balancing techniques, the thesis supports the advancement of digital infrastructure (SDG 9). Additionally, by potentially reducing energy consumption through optimized node selection, it promotes cleaner and more sustainable energy practices (SDG 7). While the project's direct impact on other SDGs may be indirect, such as promoting technological advancement (SDG 9) and fostering partnerships for the goals (SDG 17), its contribution lies in facilitating secure and efficient digital transactions, thus supporting broader sustainable development objectives. This alignment underscores the project's commitment to leveraging technology for social and environmental benefits in line with the global agenda set forth by the United Nations.
-51- 6. Conclusions and Future Work ___________________________________________________________ CHAPTER 6 Conclusions and Future Work 6.1. Conclusions In the evolving landscape of blockchain technology, ensuring high availability and efficient performance of the blockchain network nodes is critical for the seamless operation of decentralized applications (DApps). As DApps become increasingly integral to various sectors, from finance to supply chain management, the reliability and efficiency of the underlying infrastructure gain paramount importance. This project, focused on developing a high availability Ethereum-like node proxy system, addresses these real-world needs by providing a scalable solution to monitor and balance the load across multiple Ethereum nodes. And with the thesis development, several key results have been achieved. Firstly, focusing on the main goal, the implemented load balancing algorithm successfully redirected JSON-RPC requests to the most efficient node based on the real-time health checks. This approach ensured minimal response times and maximized node availability, thereby enhancing the user experience for DApp interactions. Moreover, by integrating Telegraf, InfluxDB, and Grafana, the system provided robust network monitoring capabilities. Custom dashboards in Grafana effectively visualized node performance metrics, enabling quick identification and resolution of issues. This comprehensive monitoring is crucial for maintaining the operational integrity of blockchain networks.
-52- Related with the experiments, using three nodes from the Ethereum Mainnet and Sepolia network validated the system’s functionality. The results demonstrated that the node proxy could handle traffic effectively and maintain node synchronization, proving its practical applicability in real-world scenarios. While the experiments were conducted with only three nodes and two networks, this setup was sufficient to demonstrate the system's core functionality. In a real-world deployment, the list of nodes can be easily expanded to meet the needs of the consumer, allowing for scalability and adaptability based on demand. Finally, linking it with the last comment, the use of Docker Compose for deploying the monitoring stack ensured a resilient and scalable system architecture. The customized Telegraf agent, with Python script execution capabilities, enhanced the flexibility of health checks, allowing for continuous monitoring and dynamic adjustments based on node performance. Concluding, the project successfully met its initial objectives of creating a reliable, efficient, and easily deployable node proxy system. It contributed significantly to the field by providing a practical solution for improving the performance and reliability of, in this case, Ethereum-based DApps. The insights gained from monitoring and load balancing are invaluable for developers and operators of blockchain networks, offering a pathway to enhanced user experiences and operational stability. By addressing the critical need for high availability and efficient performance in the rapidly growing blockchain ecosystem, this project not only advances technical capabilities but also supports the broader adoption and trust in decentralized technologies.
-53- 6.2. Future Directions While this project has laid a strong foundation for a high availability Ethereum-like node proxy system, there are several promising areas for future research and development that can further enhance its functionality and applicability. Future work could focus on scaling the system to handle a larger number of nodes and higher request volumes. Implementing more advanced load balancing algorithms, such as machine learning-based predictive models, could further optimize performance. This would allow the system to adapt to varying loads and ensure consistent high performance even as the demand increases. In addition, security is the most important part of the current networks nowadays. Enhancing the security of the system by incorporating advanced authentication mechanisms, encryption for data in transit, and more sophisticated attack detection methods would be beneficial. Ensuring that the node proxy can withstand malicious attacks is crucial for its reliability. Given the sensitivity and value of transactions handled by Ethereum nodes, robust security measures are essential. Also, try to find second plans against DDoS attacks. On the other hand, a possible way to improve the project can be by implementing an user-friendly interface with features that allow for the dynamic addition and removal of nodes without downtime could improve the system’s flexibility. This would enable easier maintenance and scaling of the node network. In practical terms, users could add new nodes to accommodate increased traffic or remove underperforming nodes without disrupting service. In conclusion, while the project has successfully addressed its primary goals, significant potential exists for future enhancement and expansion. By focusing on scalability, security, dynamic management, detailed monitoring, blockchain integration, and community involvement, the system can evolve to meet the growing demands of decentralized applications and blockchain networks. These future directions will ensure that the node proxy system remains relevant and effective in the rapidly changing landscape of blockchain technology.
-54- Bibliography [1] S. Nakamoto, “Bitcoin: A peer-to-peer electronic cash system”, 2008. [2] Akshat Jhalani, “Highly available Ethereum blockchain nodes”, 2022. [Online] Available: https://library.constructor.org/sites/default/files/2022-06/Highly_ Available_Blockchain_Client.pdf [3] “Blockchain explained”, https://ide.mit.edu/insights/blockchain-explained/ [4] “Blockchain: What it is, how it really can change the world”, https://www. weforum.org/agenda/2016/06/the-blockchain/ [5] “Blockchain”, https://en.wikipedia.org/wiki/Blockchain [6] “Ethereum ORG”, https://ethereum.org/es/ [7] “JSON-RPC API”, https://ethereum.org/en/developers/docs/apis/json-rpc/ [8] Web3school, “Programming Ethereum”, https://www.youtube.com/watch ?v=2QVQs5CkZEU&list=PLcHFfc1qa5C2LY_RJB4oAukLjKW6gHnF [9] Bit2Me Academy, “What is Ethereum (ETH)? How does it work?”, https:// www.youtube.com/watch?v=7dDU76LyCpw [10] V. Buterin, “Ethereum: A next-generation smart contract and decentralized application platform”, 2014. [Online] Available: https://ethereum.org/en/ whitepaper/ [11] “Intro to Ethereum”, https://ethereum.org/en/developers/docs/intro-to- ethereum/ [12] Dot CSV, “Today you will understand what blockchain is”, https://www. youtube.com/watch?v=V9Kr2SujqHw&t=1031s [13] Infura, https://www.infura.io/ [14] Alchemy, https://www.alchemy.com/ [15] Jerson Martinez, “Monitoring data with InfluxDB, Telegraf and Grafana”, 2022. [Online] Available: https://openwebinars.net/blog/monitorizando-datos-con- influxdb-telegraf-y-grafana/ [16] “Get Started with Grafana and InfluxDB”, https://grafana.com/docs/grafana/ latest/getting-started/get-started-grafana-influxdb/ [17] Grafana Loki, https://grafana.com/docs/loki/latest/
-55- Appendix A _________________________________________________________ APPENDIX A GitHub repository All the code and resources for this project are available on GitHub. You can access the repository at the following link: https://github.com/Kokews2/high-availability-ethereum-like-node-proxy.git In the repository, you will find comprehensive instructions on how to set up and run the project. The README file provides an overview of the project and installation steps. This makes it easy for anyone to replicate the environment, run the code, and verify the results. By making the code publicly available on GitHub, I aim to encourage transparency, facilitate collaboration, and allow others to build upon this work. Whether you're interested in examining the implementation details, contributing improvements, or adapting the system for your own use case, the repository provides all the necessary resources.