scieee AI-readable full text Open interactive document viewer

Improving Trustworthiness in DeFi: Anomaly Detection for Blockchain Oracle Price Feed Data

Gross, Lukas Sebastian

Abstract

This thesis investigates the application of anomaly detection techniques to blockchain oracle data, specifically focusing on the Ethereum - US Dollar exchange rate from the Chainlink oracle. The study addresses a critical gap in the reliability of decentralized finance applications by exploring both traditional static machine learning algorithms and novel streaming methods for identifying irregularities in oracle data feeds. The research compares the performance of various anomaly detection algorithms, including Support Vector Machines (SVM), DBSCAN, KMeans, Self-Organizing Maps (SOM), K-Nearest Neighbors (KNN), and Isolation Forest for static methods, and Sliding Window KNN (SWKNN), Robust Random Cut Forest (RRCF), and Half-Space Trees for streaming methods. These algorithms are evaluated using F1 score and recall as primary metrics, with a focus on their ability to detect sudden price spikes. Furthermore, the study examines the incorporating financial indicators such as Relative Strength Index, Average True Range, and Exponential Moving Average to enhance anomaly detection capabilities. The research utilizes UMAP projections for initial visual analysis and conducts comprehensive comparisons between the originally fetched univariate dataset and different multivariate datasets enhanced with additional features in form of financial indicators. The results indicate that multivariate datasets generally improve F1 scores, for static as well as streaming methods, while the streaming methods achieve a higher baseline on univariate datasets, compared to the static methods. This research contributes to the field by addressing the understudied aspect of anomaly detection in blockchain oracle data, providing insights into the effectiveness of various machine learning techniques in enhancing the security and reliability of DeFi applications.

Full text

MDSAA Master Degree Program in Data Science and Advanced Analytics Improving Trustworthiness in DeFi: Anomaly Detection for Blockchain Oracle Price Feed Data Lukas Gross Master Thesis presented as partial requirement for obtaining a Master’s Degree in Data Science and Advanced Analytics NOVA Information Management School Instituto Superior de Estatística e Gestão de Informação Universidade Nova de Lisboa Improving Trustworthiness in DeFi: Anomaly Detection for Blockchain Oracle Price Feed Data by Lukas Gross Master Thesis presented as partial requirement for obtaining the Master’s degree in Data Science and Advanced Analytics, with a specialization in Business Analytics Supervised by Fernando José Ferreira Lucas Bação July 2024 i STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Rules of Conduct and Code of Honor from the NOVA Information Management School. Lisbon, 27.06.2024 ii ABSTRACT This thesis investigates the application of anomaly detection techniques to blockchain oracle data, specifically focusing on the Ethereum - US Dollar exchange rate from the Chainlink oracle. The study addresses a critical gap in the reliability of decentralized finance applications by exploring both traditional static machine learning algorithms and novel streaming methods for identifying irregularities in oracle data feeds. The research compares the performance of various anomaly detection algorithms, including Support Vector Machines (SVM), DBSCAN, K- Means, Self-Organizing Maps (SOM), K-Nearest Neighbors (KNN), and Isolation Forest for static methods, and Sliding Window KNN (SWKNN), Robust Random Cut Forest (RRCF), and Half-Space Trees for streaming methods. These algorithms are evaluated using F1 score and recall as primary metrics, with a focus on their ability to detect sudden price spikes. Furthermore, the study examines the incorporating financial indicators such as Relative Strength Index, Average True Range, and Exponential Moving Average to enhance anomaly detection capabilities. The research utilizes UMAP projections for initial visual analysis and conducts comprehensive comparisons between the originally fetched univariate dataset and different multivariate datasets enhanced with additional features in form of financial indicators. The results indicate that multivariate datasets generally improve F1 scores, for static as well as streaming methods, while the streaming methods achieve a higher baseline on univariate datasets, compared to the static methods. This research contributes to the field by addressing the understudied aspect of anomaly detection in blockchain oracle data, providing insights into the effectiveness of various machine learning techniques in enhancing the security and reliability of DeFi applications. KEYWORDS Blockchain; Smart Contracts; Decentralized Finance; Blockchain Oracles; Anomaly Detection; Streaming Data iii TABLE OF CONTENTS 1. Introduction .................................................................................................................. 1 1.1 Problem Statement and Research Gap ................................................................... 1 1.2. Research Questions ............................................................................................... 1 1.3. Research Objectives ............................................................................................... 2 1.4. Thesis Structure ..................................................................................................... 2 2. Background ................................................................................................................... 3 2.1. Blockchain Technology ........................................................................................... 3 2.2. Smart Contracts ..................................................................................................... 4 2.3. Decentralized Finance (DeFi) ................................................................................. 5 2.4. Blockchain Oracles ................................................................................................. 7 2.5. Oracle Solutions ..................................................................................................... 9 2.5.1. Chainlink 2.0 ................................................................................................... 9 2.5.2. Chainlink Data Streams ................................................................................ 11 2.5.3. Pyth Data Oracle .......................................................................................... 12 2.6. Anomaly Detection .............................................................................................. 13 2.6.1. Classification of Traditional Anomaly Detection Techniques ....................... 15 2.6.2. Classification Based Methods ...................................................................... 15 2.6.2.1. One Class Support Vector Machines (SVM) ........................................... 15 2.6.3. Clustering / Density Based Methods ............................................................ 17 2.6.3.1. Density-Based Spatial Clustering of Applications with Noise (DBSCAN)17 2.6.3.2. K-Means .................................................................................................. 19 2.6.3.3. Self-Organizing Map (SOM) .................................................................... 19 2.6.4. Nearest Neighbor / Proximity Based Methods ............................................ 20 2.6.4.1. K-Nearest Neighbors (k-NN) ................................................................... 20 2.6.5. Isolation Forest ............................................................................................. 21 2.7. Streaming Algorithms vs. Static Algorithms ......................................................... 22 2.7.1. Sliding Window k-Nearest Neighbor (SWkNN) ............................................ 23 2.7.2. Robust Random Cut Forest (RRCF) ............................................................... 23 2.7.3. Half-Space Trees (HST) ................................................................................. 24 2.8. Challenges of Streaming Data .............................................................................. 24 3. Related Work .............................................................................................................. 26 iv 4. Research Methodology ................................................................................................ 30 4.1. Experimental Data ............................................................................................... 30 4.2. Algorithms and Parameters ................................................................................. 30 4.3. Preprocessing ....................................................................................................... 32 4.3.1. Resampling ................................................................................................... 32 4.3.2. Linear Interpolation ..................................................................................... 33 4.3.3. Artificial Anomaly Insertion .......................................................................... 33 4.4. Feature Engineering ............................................................................................. 34 4.5. Feature Selection ................................................................................................. 35 4.6. Experimental Procedure ...................................................................................... 35 4.7. Performance Metrics ........................................................................................... 37 4.8. Software implementation .................................................................................... 39 5. Results .......................................................................................................................... 40 6. Conclusion .................................................................................................................... 46 Bibliographical References .............................................................................................. 49 Appendix A ....................................................................................................................... 53 v LIST OF FIGURES Figure 2.1- Chainlink 2.0 Design Architecture .......................................................................... 10 Figure 2.2 - Chainlink 2.0 Off-Chain Reporting Execution Flow ............................................... 10 Figure 2.3 - Chainlink Data Streams Design Architecture ......................................................... 11 Figure 2.4 - Chainlink Data Streams Data Retrieval Execution Flow ........................................ 12 Figure 2.5 - Pyth Oracle Design Architecture ............................................................................ 13 Figure 2.6 - Anomalies in a 2-dimensional Dataset .................................................................. 14 Figure 2.7 - Types of Anomalies in Time Series Data. ............................................................... 14 Figure 2.8 - Illustration of the Concept of Support Vector Machines (SVM) ........................... 17 Figure 2.9 - Illustration of the DBSCAN Clustering Algorithmn ................................................ 18 Figure 2.10 - Illustration of the k-NN Algorithm ....................................................................... 21 Figure 2.11 - Illustration the Isolation Forest Algorithm .......................................................... 22 Figure 4.1 - Illustration of the ETH/USD Rate with Artificial Anomalies ................................... 34 Figure 4.2 - Experimental Procedure ........................................................................................ 37 Figure 5.1 - Feature Importance and Correlation analysis ....................................................... 40 Figure 5.2 - Umap Projection of the RSI, ATR, ETH/USD Rate feature set. .............................. 41 Figure 5.3 - Umap Projection of the RSI, ATR, ETH/USD Rate, EMA feautre set. ..................... 41 Figure 5.4 - UMAP Projection with DBSCAN Clustering ............................................................ 42 Figure 5.5 - Mean ETH/USD rate, RSI, and ATR by Cluster and Anomaly Type. ....................... 42 Figure 5.6 - Initial F1 Score Comparison of Algorithms and Feature Sets ................................ 43 vi LIST OF TABLES Table 3.1 - Traditional Algorithms and the Associated Literature ............................................ 28 Table 4.1 - Dataset Information (Preprocessed) ...................................................................... 30 Table 4.2 - Anomaly Detection Algorithms and Parameters .................................................... 31 Table 4.3 – List and Description of the Engineered Features ................................................... 35 Table 5.1 - Performance metrics of the anomaly detection techniques .................................. 44 vii LIST OF ABBREVIATIONS AND ACRONYMS AMM Automated Market Maker API Application Programming Interface ATR Average True Range BFT Byzantine Fault Tolerant CeFi Centralized Finance DBSCAN Density-Based Spatial Clustering of Applications with Noise DeFi Decentralized Finance DEX Decentralized Exchange DON Decentralized Oracle Network EMA Exponential Moving Average ETH Ethereum HST Half-Space Trees KNN K-Nearest Neighbors LMPC Latest Mass Profile Counter MACD Moving Average Convergence Divergence OCR Off-Chain Reporting PBFT Practical Byzantine Fault Tolerance PLF Protocol for Loanable Funds PoS Proof of Stake PoW Proof of Work RMPC Reference Mass Profile Counter RRCF Robust Random Cut Forest RSI Relative Strength Index SOM Self-Organizing Maps SVM Support Vector Machines 6 allows for the development of financial contracts that can be accessed by participants, provided they comply with the network's rules. DeFi presents several key characteristics that distinguish it from traditional centralized finance (CeFi) services, largely inherited from its blockchain origin. Transparency is a fundamental feature, enabling users to examine and verify the specific rules of financial products. This is facilitated by the execution through smart contracts and the public storage of data on the blockchain. The open nature of DeFi protocols allows for continuous scrutiny by the community, potentially affecting the identification and resolution of issues or vulnerabilities. DeFi also changes the way users interact with their assets. Users act as custodians of their own assets, which means these assets cannot be manipulated, transferred, or destroyed without their explicit consent. This approach differs from traditional financial systems, where intermediaries often hold and manage assets on behalf of users. The concept of self-custody in DeFi aligns with the broader blockchain principle of decentralization. Additionally, DeFi aims to increase accessibility, potentially allowing individuals with basic computer knowledge and internet access to create and use DeFi products. This approach may expand financial services to a broader audience, addressing some barriers that exist in traditional finance (Qin et al., 2021). This permissionless nature of DeFi platforms means that users can participate in complex financial activities without needing to meet traditional banking requirements or credit checks, potentially democratizing access to financial services. The growth of DeFi is evident, with the total value locked (TVL) in DeFi protocols reaching USD 62 billion in February 2024 (DefiLlama). This figure suggests an increasing adoption of DeFi solutions. As the DeFi sector expands, it has begun to offer services traditionally associated with centralized Finance (CeFi). Among the various types of DeFi protocols, three main categories have emerged: Decentralized exchanges (DEXs) are protocols that facilitate the exchange of digital assets without a centralized intermediary. By enabling peer-to-peer transactions, DEXs aim to reduce the need for traditional exchange platforms. Many DEXs utilize automated market maker (AMM) models, which employ liquidity pools and mathematical formulas to determine asset prices, as an alternative to traditional order books. Protocols for loanable funds (PLFs) provide lending and borrowing services. In these protocols, lenders contribute their funds to a smart contract with a predefined interest rate. Borrowers can access loans by providing collateral that exceeds the borrowed amount, based on a predefined collateral multiplier. This system is designed to secure loans and protect lenders' funds in case of borrower default. 7 Stablecoins are digital assets designed to maintain a stable value relative to a specific currency, addressing the challenge of price volatility in cryptocurrencies. One method of achieving price stability is through on-chain collateral, where the stablecoin is backed by a reserve of digital assets held in a smart contract on the blockchain. This mechanism allows stablecoins to offer loan solutions while aiming to maintain a stable value pegged to a currency (Werner et al., 2022). 2.4. BLOCKCHAIN ORACLES Blockchain oracles serve as a critical link between smart contracts and the external world, providing the necessary data for contract execution. They bridge the gap between the isolated blockchain environment and real-world information sources, enabling smart contracts to interact with and respond to external events and data. The nature of data sources leads to different types of blockchain oracles. Software oracles handle data from online sources, extracting real-time information such as currency exchange rates, stock prices, and commodity costs. They access APIs to fetch this information and deliver it to the blockchain in a format that smart contracts can utilize. Moving from the digital to the physical realm, hardware oracles interact directly with the physical world to gather and verify data from external sources. They use a range of devices, including sensors, scanners, and internet of things devices, to collect real-world data such as temperature readings, physical movements, or logistical data. While software and hardware oracles automate data collection, there are scenarios where human judgment is irreplaceable. This is where human oracles come into play. Human oracles rely on human input to provide data or verify its accuracy. They often use mechanisms like voting to aggregate responses, ensuring that the data provided to smart contracts reflects the consensus of a group rather than a single source. This approach is particularly useful in scenarios where automated systems cannot easily judge data, such as in subjective assessments or events not easily quantifiable by machines (Al-Breiki et al., 2020). These oracle types can serve a wide range of applications, from automating payments based on financial indices to executing contracts based on sensor data in supply chain management. The choice of oracle type depends on the specific requirements of the application, including the need for speed, reliability, and the nature of the data required. Ensuring the integrity and accuracy of the data provided to smart contracts is crucial for blockchain oracles. Different trust models address how oracles manage data sources and mitigate risks of data manipulation. Centralized oracles rely on data from a single source or node. While this setup offers high efficiency and fast data retrieval, it introduces significant risks, as the singular data source represents a single point of failure, making it susceptible to manipulation or errors. To address these vulnerabilities, decentralized or consensus-based oracles have emerged. These enhance security and reliability by using data from multiple 8 nodes. These nodes work together to verify data, which is then aggregated to form a median value. This consensus-based approach aims to reduce the risk of manipulation, as corrupting the data would require compromising multiple nodes. Design patterns in blockchain oracles describe how data is stored, accessed, and transmitted. The immediate-read pattern stores data directly within their contracts on the blockchain, allowing other smart contracts to immediately access the data via request calls. An example of this is a university system where academic certificates are stored on the blockchain, allowing instant verification without external data sources. The publish-subscribe pattern enables oracles to act as a broadcast service, pushing updates as they become available. This pattern is suitable for data that frequently changes, such as financial market prices or weather updates, ensuring smart contracts receive timely and relevant data. In the request-response pattern, oracles respond to specific requests by delivering the needed data subset at the requested time. This method is efficient for managing large volumes of data while maintaining adequate performance (Beniiche, 2020). Oracles engage in various interactions with the external world, either inserting data into the blockchain or delivering data from the blockchain. Inbound oracles bring external data, such as asset prices or weather conditions, onto the blockchain. These are used for contracts that depend on external events to trigger actions within the blockchain. Outbound oracles allow the blockchain to interact with external systems. For instance, a smart contract might automatically notify an external database or trigger a payment system outside the blockchain once certain conditions are met within the contract (Al-Breiki et al., 2020). As oracle technology has evolved, decentralized oracles have demonstrated advantages and are increasingly used to provide data feeds for DeFi projects. While centralized oracles typically excel in data processing speed and are simpler to develop and implement, decentralized oracles receive data from multiple sources and use decentralized validation mechanisms. This approach decreases the potential impact of malicious data and manipulation attempts, thereby enhancing the security and reliability of the data provided. Decentralized oracles can employ various methods for data validation and aggregation. Aggregation-based processing uses predefined rules and mechanisms, such as taking the median, to generate a result from multiple data providers, regardless of the individual quality or performance of the provided data. This method aims to neutralize the impact of single malicious data sources. Staking-based processing involves participants locking a specific amount of cryptocurrency as collateral to validate data. This mechanism encourages honest behavior by penalizing validators who provide inaccurate information. Reputation-based processing assigns reputation scores to data providers based on their historical performance in terms of the accuracy of the reported data. Providers with higher reputations then receive greater influence in the data validation process (Zhao et al., 2022). 9 2.5. ORACLE SOLUTIONS This chapter examines contemporary oracle solutions, focusing on Chainlink 2.0, Chainlink Data Streams, and the Pyth Data Oracle. The analysis highlights their architecture and functionality. These specific oracles were selected based on several criteria: their total secured value (TVS), the number of protocols each oracle secures, the availability of an ETH/USD Exchange rate broadcast, and the accessibility of technical documentation provided by the oracle providers (DefiLlama/Oracles). 2.5.1. Chainlink 2.0 Chainlink 2.0 represents the second-generation oracle network from the provider Chainlink. It functions as a decentralized publish-subscribe oracle, integrating multiple components to enhance the security and accuracy of data feeds provided to consumer blockchains. Central to the Chainlink 2.0 network is the Decentralized Oracle Network (DON), which serves as the primary framework for data consensus and aggregation. The DON employs off-chain computing resources to optimize the efficiency of price feed transmissions to blockchain systems. Several key components contribute to the functionality of Chainlink 2.0. Oracle Nodes, operated independently, are crucial for the DON's operation. They retrieve external data via APIs and adapters, which is then processed and transmitted to the DON. External APIs serve as the interface through which oracle nodes interact with external data sources, facilitating the retrieval and transmission of off-chain data to the blockchain. Adapters, standardized software components, streamline communication between APIs and oracle nodes. The Aggregator Contract, a smart contract, receives data from multiple oracle nodes and combines it according to pre-programmed rules to calculate a consensus-based price feed. The Hybrid Smart Contract, a variant of a conventional smart contract, includes both an onchain component (following programmed rules and logic) and an off-chain component (executing data acquisition and processing algorithms of the DON). Finally, the Storage Component serves as a repository for aggregated data, ensuring its persistence and accessibility for smart contract execution (Breidenbach et al., 2021). 10 Figure 2.1- Chainlink 2.0 design architecture A key aspect of this system is its consensus mechanism, known as Off-Chain Reporting (OCR). This mechanism facilitates the aggregation of oracle reports produced by DONs and is based on the Byzantine Fault Tolerant (BFT) protocol. The aim of said mechanism is to maintain the liveness and correctness of the price feeds even in the presence of f < n/3 arbitrarily faulty nodes, if the number of faulty nodes f is less than one-third of the total number of participating nodes n. Furthermore, OCR can maintain reliability and security properties in the presence of faulty nodes as long as at least 2f+1 honest nodes participate in the aggregation. The OCR process consists of three main phases: oracle report creation, verification, and price feed broadcasting. During creation, a leader node, selected by the network nodes' quorum, requests signed price observations from follower nodes. These observations are then aggregated into an oracle report. In the verification phase, this report is sent to the follower nodes for validation and signing, after which a final quorum report is created. The broadcasting phase involves a randomly selected node sending the final attested report to the aggregator contract, which verifies the signatures and calculates the aggregated median value. Figure 2.2 - Chainlink 2.0 Off-Chain Reporting execution flow 11 The pillars of Off-Chain Reporting (OCR) include several key concepts. All-or-Nothing Off-Chain Report Broadcasting ensures that the final attested report is either released to all participating nodes or to none, thereby promoting fairness and participation in the report broadcast. Reliable Transmission guarantees that OCR reports and messages are transmitted reliably to the smart contract within a predefined time interval, even in the presence of faulty or malicious nodes. Contract-Based Trust Minimization represents the employment of additional filtering mechanisms by the aggregation contract, to identify and discard potentially faulty OCR- generated reports, such as those with values that deviate significantly from other recently received reports. This approach provides an additional layer of correctness enforcement (Chainlink 2.0). 2.5.2. Chainlink Data Streams Chainlink Data Streams builds upon the principles of Chainlink 2.0, aiming to provide price feeds on demand and reduce on-chain operations. While it shares the foundation of Decentralized Oracle Networks (DONs) with Chainlink 2.0, it introduces additional components to its structure. The design of Chainlink Data Streams incorporates several interconnected elements. The Chainlink Data Engine stores signed reports from the DON and delivers them to the Chainlink Automation Registry until they are requested. This setup ensures that data is available when needed. The Automation Registry’s role is to monitor and execute both on-chain and off-chain upkeep contracts, facilitating interactions and ensuring the correct execution of scheduled tasks. When specific events are triggered on consumer contracts, the Off-Chain Upkeep Contract monitors these events and requests price feeds from the DON as necessary. Once the price feeds are obtained, the On-Chain Upkeep Contract is responsible for deploying them onto the blockchain, ensuring that the data is accessible. To safeguard the authenticity and integrity of the data, the Verifier Contract operates on the target blockchain to cryptographically verify the signatures of incoming price reports (Chainlink Data Streams). Figure 2.3 - Chainlink Data Streams design architecture The data retrieval process follows a structured execution flow. When a user initiates an action on the blockchain, such as a trade on a broker platform, a trigger is activated within the client 12 contract. This trigger is then identified by the off-chain upkeep contract, which requests a price report from the data engine. Subsequently, the data engine produces a signed report and transmits it back to the off-chain upkeep contract, which forwards the report to the onchain upkeep contract. The on-chain upkeep contract then calls the verifier contract, responsible for verifying the report and providing the output (Chainlink Data Streams - Execution Flow). Figure 2.4 - Chainlink Data Streams data retrieval execution flow Chainlink Data Streams supports various trigger types for data retrieval. Time-based triggers execute functions on a predefined schedule, suitable for regular updates. Custom logic triggers allow function execution based on specific conditions written in Solidity syntax, offering flexibility for complex scenarios. Log triggers respond to specific blockchain events, enabling real-time data retrieval (Chainlink Data Streams - Trigger). 2.5.3. Pyth Data Oracle Pyth Data Oracle also operates as a request-response oracle, transmitting data only upon request. The design includes several key participants that collaborate to collect, validate, and transfer price data between blockchains in real-time. At the core of the oracle is the pythnet blockchain, which receives price data from various Publisher APIs via its validator nodes. These APIs transfer off-chain data collected from independent publishers to the validator nodes on the pythnet blockchain. Validator Nodes then perform the task of validating and verifying the received price data before it is sent to the aggregation mechanism. The Aggregation Mechanism is responsible for combining the data feeds from the validator nodes into a median based on predefined conditions. Once the data is aggregated, the Message Buffer Program creates a message on the pythnet blockchain encapsulating the aggregated price data, ready for cross-chain transmission. The Cross-Chain Messaging Protocol, utilizing networks like the Wormhole network, transmits the aggregated price data from the pythnet blockchain to the target blockchain. Finally, the Consumer Smart Contract on the target blockchain receives and integrates the aggregated price data into its operations. 13 Figure 2.5 - Pyth Oracle design architecture A key component of the Pyth protocol is its aggregation algorithm. This algorithm processes data in the form of price feeds and confidence intervals from individual publishers. For example, a publisher might submit a confidence interval of ±5€ along with their reported price of 2500€ for ETH/USD. The algorithm uses a weighted median that accounts for the stakeweights of the respective publishers. Each publisher is given three votes: one for the reported price and the other two for their reported negative and positive confidence intervals. For this it uses the following objective function: In the first step, the algorithm calculates the weighted median of the price using an objective function. The first term is the sum of the absolute differences between the aggregate price R and the reported prices of individual publishers pi, weighted by the stake-weight of each publisher si. This term aims to ensure that the aggregate price is more influenced by publishers with higher stake-weights. The second term reflects the varying levels of accuracy of the publishers and their confidence intervals, contributing to the determination of the aggregate price. It ensures that the aggregate price lies within the confidence intervals of the publishers, reflecting the collective information provided by the publishers while accounting for their varying levels of accuracy. In a second step the algorithm calculates the weighted 25th and 75th percentiles of the median and sets the higher of both values as the confidence interval for the aggregated price (Pyth Data Association, 2023). 2.6. ANOMALY DETECTION Anomaly detection is a process used to identify data points or patterns that differ significantly from defined normal behavior. This section examines various anomaly detection techniques, comparing their functionalities. 14 Anomalies, as described by (Prasad et al., 2009) are data points or patterns that deviate substantially from what is considered normal behavior. To illustrate this concept, Figure 2.6 presents a 2-dimensional dataset where the majority of data points form a dense cluster. Points labeled 1, 2, and 3 in this figure are notably distant from this cluster, potentially indicating anomalies. Figure 2.6 - Anomalies in a 2-dimensional dataset, where points 1, 2, and 3 are significantly different from the majority of data points, indicating that they are anomalies. Anomalies can be classified into several categories, each with distinct characteristics. Point anomalies refer to individual data instances that are considered anomalous when compared to the rest of the data. Contextual anomalies are data instances that are deemed anomalous in one specific context but not in another, highlighting their context-dependent nature. Collective anomalies occur when a group of related data instances is considered anomalous when evaluated within the context of the entire dataset (Choi et al., 2021). Figure 2.7 - Types of Anomalies in Time Series Data. From left to right, the subplots illustrate point anomaly, contextual anomaly, and collective anomalies. 15 2.6.1. Classification of Traditional Anomaly Detection Techniques Anomaly detection techniques rely on algorithms and models that learn from data and recognize patterns without explicit rules or instructions. These techniques can be categorized based on the availability and use of labeled data. Supervised anomaly detection methods involve training models to differentiate between normal and anomalous data using labeled training data containing both normal and anomalous instances. This approach is particularly useful when there's a clear understanding of what constitutes an anomaly in the system. Unsupervised anomaly detection identifies anomalies without the need for labeled training data. The model learns the normal patterns in the data independently and detects deviations as anomalies. This method is valuable in systems where new types of anomalies may emerge over time. Semi-supervised anomaly detection techniques combine elements of supervised and unsupervised methods by using both labeled and unlabeled data to identify anomalies. This approach can be beneficial when there's limited labeled data available, which is often the case in evolving systems (Nassif et al., 2021). 2.6.2. Classification Based Methods Classification-based anomaly detection techniques use labeled data instances to train a model and classify test instances as either normal or anomalous. They can be categorized into multiclass and one-class approaches. Multi-class techniques train the model on data instances labeled with multiple normal classes to distinguish them from anomalies. This approach is useful when there are distinct categories of normal behavior in the data. One-class techniques assume that all training instances belong to a single normal class and learn a discriminative boundary around these instances to identify anomalies. This method is particularly effective when anomalies are rare and diverse. The effectiveness of classification-based methods depends on the availability of labeled data for both normal and anomalous instances. Obtaining labeled anomalous data can be challenging in some scenarios, which can limit the applicability of these methods (Prasad et al., 2009). 2.6.2.1. One Class Support Vector Machines (SVM) Support Vector Machines (SVM) find the optimal hyperplane that separates different classes in the feature space with a maximum margin. One-Class SVM learns to identify normal behavior and flag deviations as potential anomalies. 22 The average path length of a data point across all trees in the forest is calculated by the formula: Where: ■ 𝑡#is the number of trees in the forest. ■ ℎ𝑖(𝑥) is the path length of sample x in the i-th tree. The anomaly score is computed using the formula: Where the normalization factor to adjust the path length relative to the size of the tree is calculated as: Where: ■ 𝑛#is the number of external nodes. ■ 𝛾#is Euler’s constant, approximately 0.5772. Figure 2.11 - Illustration the Isolation Forest algorithm using multiple decision trees. Anomalies that require fewer splits to isolate are marked in red and to normal points are marked blue. The color bar indicates the anomaly threshold, 2.7. STATIC ALGORITHMS VS. STREAMING ALGORITHMS Anomaly detection techniques can be broadly categorized into two main types based on how they process data: static (offline) algorithms and streaming (online) algorithms. This section explores the characteristics and applications of these two approaches. 23 Static algorithms, also referred to as offline or traditional machine learning algorithms in this thesis, operate on complete datasets that have been fully collected and remain unchanged during processing. These algorithms are typically used in scenarios where comprehensive analysis of the entire dataset is required to produce results. When new data becomes available, static algorithms often require reprocessing and retraining of the entire dataset, which may present challenges in situations demanding real-time processing. In contrast, streaming algorithms, also known as online algorithms, process data sequentially, one data point at a time, without needing access to the entire dataset simultaneously. These algorithms are designed to update their output continuously as new data becomes available. Streaming algorithms often have lower memory requirements compared to static algorithms, as they typically store only a constant amount of memory rather than entire large datasets. Additionally, streaming algorithms have the potential to adapt to new trends or changes in data patterns as they occur (Lu et al., 2023). 2.7.1. Sliding Window k-Nearest Neighbor (SWkNN) The Sliding Window k-Nearest Neighbors (SWkNN) algorithm is a variation of the traditional k-Nearest Neighbors (kNN). SWkNN uses a sliding window approach to maintain a recent subset of the data. This window only includes the most recent observations and moves over time, discarding older data points. For each incoming data point, the algorithm calculates the distance to other points in the sliding window. It then selects the k closest neighbors based on these distances (L. Zhang et al., 2017). Data points are considered anomalies if they are far away from their nearest neighbors. The sliding window of SWkNN gets defined as: Where: ■ xt is the data point at time t. ■ n is the window size. 2.7.2. Robust Random Cut Forest (RRCF) Robust Random Cut Forest (RRCF) is a collection of independent Robust Random Cut Trees (RRCTs). The process involves recursively partitioning the data based on random dimensions and cuts. At each node of the tree, a random dimension is selected from the available dimensions of the data, and a random cut point along that dimension is chosen to split the data into two subsets. When a new data point arrives in the data stream, the RRCF algorithm evaluates the anomaly score of this point by considering its impact on each tree in the ensemble. The anomaly score of the new point is calculated based on its average depth across 24 the ensemble of trees (Guha et al., 2016). Points that deviate significantly from the expected depth are then flagged as anomalies. 2.7.3. Half-Space Trees (HST) Half-Space Trees (HST) organize the dataset into a tree structure of smaller sub-spaces. Each node in the tree represents a specific sub-space, known as the node's workspace. When a node has children, its workspace is split into halves with the same volume of data points along a hyperplane of a randomly chosen dimension. The data stream is then divided into two windows of a fixed length: the latest window and the reference window. The reference window is initialized with a set of historical data points and serves as the baseline for comparison with the incoming data. As new data points arrive in the data stream, the algorithm slides the window forward. The latest window is updated with the new data point, and the oldest data point in the window is removed to maintain a fixed window size. The data points in the latest window are compared to the data points in the reference window with the help of so-called mass counters. When the tree is constructed, each node is equipped with a reference mass profile counter (RMPC) and a latest mass profile counter (LMPC). The RMPC tracks the flow of data points from the reference window. It stores the count of data points that have passed through the node in the previous time frame. The LMPC tracks the flow of data points from the latest window. It stores the count of data points that have passed through the node in the current time frame. As a new data point moves through the tree from the root to a leaf node, the counters at each node are updated (Tan et al., 2011). The counts stored in the reference and latest mass profile counters at each node are then used to calculate the anomaly score for each data point. The anomaly score for HS-Trees gets calculated as follows: Where: ■ Score(x,T) is the anomaly score for streaming point x in HS-Tree T. ■ h is the maximum depth of the tree. ■ ri is the mass of the node in the reference window at depth i. ■ li is the mass of the node in the latest window at depth i. 2.8. CHALLENGES OF STREAMING DATA Streaming data, as described by (Tan et al., 2011), refers to information that is continuously generated by various sources and processed in real-time. This approach to data processing presents several challenges: 25 One primary consideration in streaming data is velocity. The high speed at which data flows into the system requires real-time processing capabilities. This involves quick ingestion and analysis of the data, which poses challenges in terms of computational requirements and system latency. Closely related to velocity is the challenge of volume. The potentially infinite amount of data generated continuously in a stream can be overwhelming for offline learning algorithms due to their memory requirements, as they typically need to load the entire dataset into the main memory to perform anomaly detection. Furthermore, handling large volumes of data requires a robust infrastructure and optimized data pipelines (Ahmad & Purdy, 2016). As data streams continuously, another challenge emerges: evolving data distribution. The data distribution underlying streaming data can evolve over time, a phenomenon also known as concept drift. This can gradually diminish the efficacy of offline learning algorithms in accurately detecting anomalies as the data shifts, as the algorithms cannot adapt to these shifts due to their static design (Iglesias Vázquez et al., 2023). 26 3. RELATED WORK This chapter presents a comprehensive review of the current state of research regarding blockchain oracles and anomaly detection, highlighting key findings and their relevance to this thesis. It explores the challenges faced by blockchain oracles in DeFi applications, including vulnerabilities and past incidents that have undermined trust in these systems. The reliability of blockchain oracles is crucial for the effective functioning of DeFi applications. Oracles, which provide external data to smart contracts, are often considered a single point of failure due to the potential of unintended centralization when third-party data providers are introduced (Beniiche, 2020). As noted by (Kaleem & Shi, 2021), there is a growing demand for price data feeds, driven by the expanding role of DeFi as an alternative to centralized finance (CeFi) services. However, this increased reliance on oracles, often referred to as the "oracle problem", exposes DeFi protocols to several attack vectors. These vectors include front running, where early access to data is exploited to execute advantageous trades, and Sybil attacks, which involve creating fake nodes to manipulate data feeds. Technical malfunctions can lead to incorrect data transmission, intentional tampering with data during transmission can lead to manipulation through bad actors. Additionally, flash loans can be used to manipulate market prices within a single transaction block (Caldarelli & Ellul, 2021). In the past, several severe oracle incidents have undermined the trust in DeFi protocols. One example is the the Compound liquidation from November 2020 that led to over $85 million in wrongful liquidations because of an inaccurate DAI/USDC price feed from CoinbasePRO (Caldarelli & Ellul, 2021). Similarly, in June 2019, the Synthetix incident involved a corrupted API that reported prices inflated by 1000x, resulting in nearly $37 million in wrongful profits due to price arbitrage (Gu et al., 2021). To address these vulnerabilities, there has been a transition from centralized oracle solutions to a decentralized architecture, which aims to mitigate these attack vectors through various data validation mechanisms. (Zhao et al., 2022) introduce oracles deployed in real-life scenarios They further outline the mechanisms they employ, which mostly involves the construction of a median value of multiple data sources. They highlight the lack of machine learning techniques in the data validation process and argue that incorporating machine learning could enhance the trustworthiness of data feeds provided by oracles, but do not specify particular techniques. Despite these advancements, (Liu et al., 2021) mention deviations between real-time market prices and oracle-reported prices for MakerDAO, Compound, Synthetix, and AmpleForth, as well as disparities between the oracles and their respective price sources. Additionally, (Ankit Gangwal et al., 2022) come to similar conclusions regarding the discrepancies between price sources and oracle output prices for the Chainlink oracle. These deviations reveal potential security risks in DeFi platforms. 27 Given these ongoing issues, employing traditional machine learning techniques, such as anomaly detection, can be effective in flagging these discrepancies. In traditional finance, anomaly detection has already been used to detect manipulations in stock market data, as demonstrated with k-NN by (Koosha Golmohammadi & Osmar R. Zaiane, 2015). Expanding on the use of machine learning for financial data, (Fu et al., 2001) discuss the application of the Self-Organizing Maps (SOM) algorithm for pattern discovery in financial time series data in the Hang Seng Index of Hong Kong Stock Exchange. By using SOM, similar patterns in the time series can be grouped together. This pattern recognition abilities can also be used for anomaly detection, identifying deviations from expected data behavior. (Huang et al., 2019) present a hybrid algorithm for forecasting financial time series data, utilizing different versions of the DBSCAN algorithm for stock market data from the Shanghai and Shenzhen Stock Exchanges. While their primary focus lays on price prediction, an approach based on DBSCAN can also be adapted for an anomaly detection scenario. A further application of anomaly detection in financial networks is demonstrated by Pham and (Pham & Lee, 2016). While they focus on the DeFi domain rather than traditional finance, they also detect anomalies using unsupervised learning methods. Their approach employs K-Means clustering and Support Vector Machines on transaction data from the Bitcoin network. Similarly, (Kaufman & Iaremenko, 2022) focus on detecting anomalies in Ethereum transaction data. Their study explores various anomaly detection algorithms, including Isolation Forest to identify potentially fraudulent activities in real-time. Expanding further on the use of Isolation Forest, (Feremans et al., 2020) address the challenge of identifying anomalies in univariate, and multivariate mixed-type data. They propose a method that uses Isolation Forest for anomaly detection on various real-world time-series datasets. In addition to these studies, numerous other papers have mentioned these algorithms as suitable for anomaly detection applications without applying them directly. These papers are summarized in the following Table 3.1. 28 Table 3.1 - Traditional Algorithms and the Associated Literature Technique Literature SVM (Koosha Golmohammadi & Osmar R. Zaiane, 2015), (Nassif et al., 2021) DBSCAN (Braei & Wagner, 2020) K-Means (Koosha Golmohammadi & Osmar R. Zaiane, 2015), (Schmidl et al., 2022) SOM (Prasad et al., 2009) k-NN (Koosha Golmohammadi & Osmar R. Zaiane, 2015) Isolation Forest (Schmidl et al., 2022), (Nassif et al., 2021) While these algorithms are frequently referenced in the literature and have been applied to time series datasets in various closely related fields of traditional and decentralized finance, the continuous data provision by blockchain oracles to smart contracts also exhibits attributes of streaming data. This aligns with (Tan et al., 2011) description of streaming data as information that is continuously generated and processed in real-time. Furthermore, (Ahmad & Purdy, 2016) describe that the potentially infinite volume of streaming data can overwhelm traditional machine learning algorithms due to their memory requirements. In contrast streaming algorithms, process data that arrives in sequential order, without needing to access the entire dataset. According to (Lu et al., 2023), these algorithms are designed to update their output as new data becomes available. Further benefits of streaming algorithms they describe include lower memory requirements, as they do not need to store large datasets fully but only a constant amount of memory, as well as their adaptability to changes in underlying data patterns. Regarding streaming data algorithms, (Iglesias Vázquez et al., 2023) highlight SWKNN as the most popular approach for outlier detection in streaming data. SWKNN's implementation of the k-NN algorithm within a sliding window framework is considered well-suited for handling streaming data and detecting anomalies in real-time. (Guha et al., 2016) introduce Robust Random Cut Forest (RRCF) as an algorithm specifically engineered to address the challenges introduced by dynamic data streams, making it suitable for real-time anomaly detection tasks where the data distribution is changing over time. Finally, (Tan et al., 2011) present the concept of Streaming Half-Space Trees (HS-Trees) as a fast one-class anomaly detector for evolving data streams, where HS-Trees capture the data points within specific subspaces of the data stream and use a mass measure to rank anomalies. 29 While research has explored anomaly detection in related fields such as traditional finance (Koosha Golmohammadi & Osmar R. Zaiane, 2015) and DeFi (Pham & Lee, 2016; Kaufman & Iaremenko, 2022), its application regarding blockchain oracles remains largely unexplored. The current body of research acknowledges the "oracle problem" and identifies oracles as potential single points of failure (Beniiche, 2020), but it generally overlooks the application of machine learning approaches, particularly anomaly detection, to enhance the robustness of oracle environments. Some studies have conducted statistical deviation analyses of oracle price feeds by comparing them to their price sources (Ankit Gangwal et al., 2022; B. Liu et al., 2021), and theoretical discussions have explored the potential integration of machine learning approaches into the data validation process of oracles (Zhao et al., 2022). However, practical applications of these techniques in real-world blockchain oracle environments remain unexplored. Furthermore, while streaming algorithms have shown promise in handling continuous data flows (Iglesias Vázquez et al., 2023; Guha et al., 2016; Tan et al., 2011), there is limited research on their application to blockchain oracle data. This gap is significant given the continuous nature of data provision by blockchain oracles to smart contracts, which aligns with the characteristics of streaming data as described by Tan et al. (2011). This research gap presents a risk, as undetected anomalies in oracle data can lead to significant financial losses and potentially erode trust in DeFi applications. The severity of this risk is underscored by incidents such as the Compound liquidation of November 2020 and the Synthetix incident in June 2019 (Caldarelli & Ellul, 2021; Gu et al., 2021). 30 4. RESEARCH METHODOLOGY This chapter details the methodology for evaluating the anomaly detection techniques on the Ethereum to U.S. Dollar price feed from the Chainlink blockchain oracle. It explains the data retrieval process, the parameters of the utilized anomaly detection algorithms and the experimental steps followed. Additionally,the performance metrics, as well as the software tools used for data processing and algorithm implementation are described. 4.1. EXPERIMENTAL DATA The experimental data is represented by the historical broadcast prices of the Chainlink oracle that was fetched directly from the Ethereum blockchain. To connect to the Ethereum blockchain, the Web3 Python library alongside an Infura endpoint was used. The Web3 library enables interactions with Ethereum's blockchain. Infura provides a gateway to the Ethereum network by offering API access to an Ethereum node, thereby eliminating the need to run a personal node. The contract address of the aggregator contract was then used to establish a connection to the contract on the blockchain and fetch the historical price feed data. Table 4.1 - Dataset Information (Preprocessed) 4.2. ALGORITHM PARAMETERS This section discusses the parameters used for the respective machine learning algorithms. Table 4.2 provides an overview of the anomaly detection methods and their associated parameters, categorized into static and streaming algorithms. 31 Table 4.2 - Anomaly Detection Algorithms and their Parameters SVM: In SVM, the Kernel Type defines the function used to map data into a higherdimensional space, Gamma controls the influence of individual training examples, and Nu regulates the algorithm's sensitivity to outliers. DBSCAN: This algorithm requires the specification of two key parameters: Epsilon, which defines the neighborhood radius, and Minimum Samples, which denotes the minimum number of points needed to form a dense region. K-Means: K-Means clustering necessitates setting the Number of Clusters, which indicates how many clusters the data should be partitioned into, Initialization Method, which determines the starting positions of cluster centroids, Number of Runs for stability, and Maximum Iterations to limit the computational cost. 38 performance evaluation metrics can be used, with Precision, Recall, and F1 score being among the most common ones. Precision measures the proportion of correctly identified anomalies among all instances that are flagged as anomalies. It is calculated as the ratio of true positives to the sum of true positives and false positives. Formula: Where: ■ 𝑇 P (True Positives) is the number of correct predictions that an instance is an anomaly. ■ 𝐹𝑃#(False Positives) is the number of incorrect predictions that a non-anomalous instance is an anomaly. Recall represents the proportion of true anomalies identified from all actual anomalies. It is calculated as the ratio of true positives to the sum of true positives and false negatives. Formula: Where: ■ 𝐹𝑁#(False Negatives) is the number of anomalies that were not detected. F1 score combines Precision and Recall into a unified metric, creating a balanced evaluation of algorithm performance. It ensures a compromise between identifying as many anomalies as possible (Recall) and ensuring that the detections are indeed anomalies (Precision). The F1 score is calculated as the harmonic mean of Precision and Recall: This thesis primarily uses the F1 score, with Recall as a secondary metric. This choice reflects the need to balance different considerations in the context of this kind of applications. A High Recall is crucial to minimize missed anomalies, which could lead to incorrect smart contract executions or financial transactions. However, focusing solely on Recall can result in low Precision, potentially overwhelming the system with false alarms. The F1 score provides a balanced measure, ensuring critical anomalies are caught while minimizing disruptive false alarms. This approach aligns with the broader literature on anomaly detection, where the F1 score is widely recognized as a robust metric for balanced performance evaluation. It is 39 particularly suitable for the sensitive environment of blockchain oracles, where both missed anomalies and false alarms can have significant consequences. By prioritizing the F1 score, this study aims to evaluate anomaly detection algorithms in a way that best reflects the practical utility of blockchain oracles, balancing the need for accurate anomaly detection with the operational requirements of the underlying DeFi systems. This balanced approach ensures that the evaluation process considers both the ability to detect genuine anomalies and the necessity to maintain system efficiency by minimizing false alarms, providing a more comprehensive assessment of each algorithm's performance in the context of blockchain oracle price feed anomaly detection. 4.8. SOFTWARE IMPLEMENTATION The research employed several Python libraries for data analysis and algorithm implementation. Pandas and NumPy were used for data manipulation and preprocessing, while SciPy provided statistical functions. Matplotlib and Seaborn were utilized for data visualization, creating both basic plots and more complex graphical representations. Scikitlearn served as the primary library for machine learning tasks, including feature selection, model training, anomaly detection algorithm implementation, and model evaluation. For specific algorithms not available in Scikit-learn, additional libraries were incorporated. The minisom library provided the implementation for Self-Organizing Maps (SOM). To address anomaly detection with streaming algorithms, the river library was used for implementing Half-Space Trees, and the RRCF library for the Random Cut Forest algorithm. This combination of software tools facilitated the data analysis, algorithm implementation, and performance evaluation processes throughout the study. 40 5. RESULTS To address the research question regarding the impact of extracted features based on common financial indicators, feature selection methods as described in Chapter 4.4, were employed. After applying these methods, the highest-ranking features were identified, as visualized in figure 5.1. Based on these scores, three distinct feature sets were constructed: 1. RSI and ATR, representing the two best-performing indicators 2. RSI, ATR, and ETH/USD Rate, representing the three top features 3. RSI, ATR, ETH/USD Rate, and EMA, encompassing the four highest-ranking features Figure 5.1 - Feature importance and correlation analysis. The grey bars show the feature importance from the decision tree modeling, and the blue bars indicate the correlation coefficients with the anomaly variable. Based on the high scores obtained from the feature selection methods, the RSI and ATR set was chosen for further analysis without additional evaluation. This selection was made directly from the feature importance rankings, reflecting the strong performance of these indicators in the initial assessment. To gain additional insights into how different feature combinations might perform in distinguishing anomalies, Uniform Manifold Approximation and Projection (UMAP) was employed to visualize two of the feature sets into a two-dimensional space. The UMAP visualization allows for a qualitative assessment of how well the chosen features separate anomalous data from normal data in a lower-dimensional space. 41 Figure 5.2 - Umap Projection of the RSI, ATR, ETH/USD Rate feature set, where blue points represent normal data points and red points indicate anomalies. Figure 5.3 - Umap Projection of the RSI, ATR, ETH/USD Rate, EMA feature set, where blue points represent normal data points and red points indicate anomalies. Comparing the two UMAP projections, it appeared that the RSI, ATR, and ETH/USD Rate feature set (Figure 5.2) might be more effective in isolating anomalies. In this projection, the anomalies seemed to be more distinctly clustered and separated from the normal data points, 42 particularly along the edges of the projection. This suggests that this three-feature set could potentially provide better discrimination between normal and anomalous data points. In contrast, the four-feature set including EMA (Figure 5.3) shows a slightly more dispersed distribution of anomalies throughout the projection. While some clustering of anomalies is still visible, the separation between normal and anomalous points appeared less pronounced compared to Figure 5.2. To further enhance this analysis, DBSCAN clustering was employed on top of the UMAP projection of the RSI, ATR, and ETH/USD Rate feature set. Figure 5.4 shows the results of this combined approach. Figure 5.4 - UMAP projection with DBSCAN clustering, where three clusters were identified colored light blue (0), dark blue (1), and orange (2) and the red points representing anomalies. Figure 5.5 - Mean ETH/USD Rate, RSI, and ATR by cluster and anomaly type, with blue representing normal data points and red anomalous data points. 43 In the next step the mean values of the different features per cluster were examined, as visualized in figure 5.5, where the ETH/USD Rate proved to be the least effective feature overall. While it showed a clear distinction in Cluster 0, with anomalies having lower rates than normal data points, Clusters 1 and 2 displayed minimal distinctions. RSI demonstrated improved distinctions than the ETH/USD Rate, with significant deviations between normal and anomalous instances in Clusters 1 and 2, where anomalies had significantly higher RSI values than normal data points. Interestingly, Cluster 0 exhibited an opposite trend with lower RSI for anomalies. ATR emerged as the most effective feature for anomaly detection. It consistently showed higher values for anomalies across all clusters. Following the comprehensive feature analysis, an initial F1 score comparison was conducted for the two most promising feature sets: RSI and ATR, and RSI, ATR, and ETH/USD Rate. Figure 5.6 presents the F1 scores for these two feature sets across different anomaly detection algorithms. The performance varied across different methods, with some algorithms showing improved F1 scores with the inclusion of the ETH/USD Rate, while others perform better with just RSI and ATR. The best-performing feature combinations from each method were then utilized for the final evaluation. Table 5.1 presents a comparison of the best combinations and the originally fetched univariate dataset. This final evaluation includes both F1 scores and recall. Figure 5.6 - Initial F1 score comparison of algorithms and feature sets, with grey representing the F1 score of the RSI, ATR and ETH/USD Rate feature set and blue representing the RSI and ATR feature set. 44 Table 5.1 - Performance metrics of the anomaly detection techniques on the original dataset (univariate) compared to the multivariate datasets, with the best performing combinations in bold. Among the static methods, Isolation Forest and k-NN showed the highest overall performance. Isolation Forest achieved an F1 score of 0.72 on the multivariate dataset, the highest among all methods, including streaming methods. It also achieved a recall of 0.74, indicating a strong balance between precision and recall by identifying most true positives while maintaining a relatively low rate of false alarms. In contrast, k-NN achieved an F1 score of 0.56 on the multivariate dataset, the second highest among static algorithms, with a recall of 0.94—the highest among all static methods—highlighting its high sensitivity in detecting anomalies. However, this high sensitivity comes with a trade-off in precision, potentially flagging more false positives compared to Isolation Forest. A noticeable trend among the static methods is the significantly higher performance of scores achieved on the multivariate dataset compared to the univariate dataset. For example, Isolation Forest's F1 score improved significantly from 0.11 (univariate) to 0.72 (multivariate), while its recall increased from 0.06 to 0.74. Similarly, k-NN improved its F1 score from 0.08 (univariate) to 0.56 (multivariate), and its recall from 0.11 to 0.94. In the streaming methods category, Half Space Trees achieved the best scores F1 score with 0.54 and a recall of 0.54 on the multivariate dataset. SWKNN demonstrated an F1 score of 0.27 with a perfect recall of 1.0. Interestingly, RRCF scored second best in this category but was the only algorithm among both static and streaming approaches that achieved a better F1 score on univariate data. It achieved an F1 score of 0.34 and a recall of 1.0 on the univariate dataset, compared to an F1 score of 0.29 and a recall of 0.86 on the multivariate dataset. Generally, the Streaming algorithms showed a similar pattern of higher F1 scores on multivariate data, with the already explained exception of RRCF. However, the difference is not as pronounced as in the static methods. They generally maintained a higher baseline of F1 scores on univariate data, compared to the static algorithms. For example, Half Space Trees' 45 F1 score improved from 0.34 (univariate) to 0.54 (multivariate). Similarly, SWKNN's F1 score increased from 0.25 (univariate) to 0.27 (multivariate). In terms of recall, two streaming algorithms saw a decrease when moving from univariate to multivariate data: Half Space Trees decreased from 1.0 to 0.54, and RRCF decreased from 1.0 to 0.86. SWKNN's recall remained the same, maintaining a perfect recall of 1.0 for both univariate and multivariate data. It's worth noting that all streaming algorithms exhibited perfect recall (1.0) when applied to univariate data, indicating their strong capability to detect anomalies in less complex datasets. 46 6. CONCLUSION This study investigated the effectiveness of static and streaming machine learning techniques in detecting anomalies within the Ethereum-US Dollar (ETH/USD) exchange rate from the Chainlink blockchain oracle. Additionally, it examined the impact of extracting new features in the form of financial indicators. The findings reveal several key insights for anomaly detection applications in this context. The results demonstrated significant variations in performance across the tested methods, both in terms of F1 score and recall. Isolation Forest emerged as a strong performer, achieving an F1 score of 0.72 and a recall of 0.74. This indicates Isolation Forest's relative effectiveness in identifying anomalies while maintaining a good balance between precision and recall, showing its ability to detect true anomalies while relatively minimizing false alarms. In contrast, the streaming algorithm Half Space Trees achieved an F1 score of 0.54, which represents moderate performance. The comparison between static and streaming methods revealed that static methods like Isolation Forest and k-NN showed significant performance improvements with multivariate data compared to univariate data. This highlights their enhanced capabilities when using richer feature sets. The use of multivariate data allows these models to capture a broader range of relationships within the data, providing a more comprehensive view of the underlying patterns. On the other hand, the streaming algorithms performed notably better on univariate data. This can be attributed to their design, which often prioritizes real-time processing and efficiency over depth of analysis. The complexity of multivariate data can potentially introduce noise and complicate the model's ability to detect anomalies. This was particularly notable for RRCF, where both the F1 score and recall decreased when applied on multivariate data. For Half Space Trees, the transition to higher-dimensional data resulted in an improved F1 score, but at the cost of decreased recall. These observations underscore the importance of balancing multidimensional feature sets with model simplicity for effective implementation of streaming data algorithms. Despite these challenges, the high recall scores of the streaming algorithms on the univariate data are an interesting discovery. This indicates their potential for ensuring that no true anomalies are missed, which is particularly important in financial applications, where unidentified anomalies could cause immense damage to customers. Regardless of these promising results it has to be noted, that models with these scores are not ready for an application in real-life scenarios yet. Future work needs to focus on improving the overall reliability to increase their suitability for practical use. While the features in this thesis were all extracted solely from the exchange rate of Ethereum to US Dollar, future research could explore additional features that may be able to provide more context. Potential features could include the transaction volume, which can indicate market activity levels. Other valuable features might be on-chain metrics like the number of active addresses and the transaction fees. Incorporating a broader range of features could 47 lead to more robust models. However, as previously mentioned, it remains crucial to balance increasing the dimensionality of the data with maintaining model efficiency. Future work could also address the computational efficiency of different methods. This consideration is important for real-time data analysis, where rapid processing is essential for a useful application. A comparative study of computational speeds across different algorithms could provide further insights into their practicality. Lastly, another area of promising research could lie in the application of window sizing techniques to static algorithms, particularly in regard to the top performers like Isolation Forest. This approach could potentially enhance the performance of static methods when processing streaming data. In conclusion, this study has shed a light on the potential use of machine learning techniques in identifying anomalies in blockchain oracle data price feeds. The comparative analysis of static and streaming methods, along with the exploration of feature engineering, has revealed both interesting directions as well as challenges for the application of anomaly detection into blockchain oracles, which, in the past, has generally received limited attention compared to other areas of finance and blockchain security. 54 APPENDIX A 1) 7-Day Moving Average: Calculated as the mean of the ETH/USD Rate over a rolling window of 7 days, multiplied by 24 hours to achieve hourly granularity. This feature aims to smooth short-term fluctuations, highlighting longer-term trends in price movement. Where: ■ Pt is the price at time t. 2) 7-Day Moving Standard Deviation: Represents the standard deviation of the Rate over a 7- day rolling window, aiming to provide a measure of volatility. Formula: 4) Percentage Change: The percentage change in the ETH/USD Rate from one hour to the next, multiplied by 100 to transform it into a percentage. Formula: Where: ■ Pt represents the ETH/USD Rate at the current hour t. ■ Pt−1 is the ETH/USD Rate at the previous hour. 3) Relative Strengh Index (RSI): A momentum oscillator calculated by using the average gains and losses over a 14-hour window. It aims to identify overbought or oversold conditions in the trading of ETH/USD. The RSI is calculated using the following approach: 55 Where RS is the Relative Strength, defined by: 4) Bollinger Bands: Calculated using simple moving average (SMA) of the ETH/USD Rate, plus as well as minus two standard deviations to create upper and lower bands. These bands show the price movement aiming to indicate volatility. Formula: . Where: ■ MA is the Moving Average ■ σ is the standard deviation ■ k is typically set to 2 5) Exponential Moving Average (EMA): Similar to a simple moving average but gives more weight to recent prices, making it more responsive to new information. Formula: Where: ■ N is the number of days in the EMA ■ EMAt−1 is the EMA of the previous period 6) Moving Average Convergence Divergence (MACD): A trend-following momentum indicator showing the relationship between two exponential moving averages. Indicates buy or sell signals. Formula: 56 Where: • EMA12 is the 12-period exponential moving average of the ETH/USD • EMA26 is the 26-period exponential moving average of the ETH/USD Rate. 7) Average True Range (ATR): The Average True Range (ATR) is a technical indicator that aims to measure market volatility by decomposing the entire range of an asset price for a period. The Average True Range is calculated using the following approach: Where: • Hight is the highest price at time t. • Lowt is the lowest price at time t. • Closet−1 is the closing price at time t−1. Information Management School NOVA Information Management School lnstituto Superior de Estatistica e Gestao de lnforma ao Universidade Nova de Lisboa