mariachiacero.com

All You Need to Understand About Blockchain Oracles and Their Functions

Written on

Understanding Blockchain Oracles

The term "oracle" has its roots in ancient Greek, referring to an individual believed to communicate with deities and possess prophetic insights. In the realm of blockchain, oracles are decentralized systems that facilitate the transfer of external information to the blockchain (inbound) and convey blockchain data to the outside world (outbound). They serve as a crucial link between off-chain data and smart contracts. The primary roles of oracles include:

  • Monitoring blockchain networks for off-chain requests from clients or smart contracts.
  • Retrieving data from various off-chain sources like APIs and web servers.
  • Formatting the gathered off-chain data for on-chain readability.
  • Adapting on-chain requests to be compatible with off-chain systems.
  • Validating the retrieved data from external sources using cryptographic methods, such as TLS signatures and zero-knowledge proofs.
  • Performing necessary calculations, such as weighted averages, prior to delivering results to smart contracts.
  • Distributing off-chain outcomes and proofs to smart contracts.

In this discussion, we will explore various facets of oracles, including:

  • The Oracle Problem
  • Different Types of Oracles
  • Architectural Design Considerations for Oracles
  • Notable Oracle Examples
  • Sample Oracle Code (in Solidity)

Let’s dive in!

The Oracle Problem

Blockchains operate as isolated networks with no direct access to external resources, necessitating a third-party infrastructure—an oracle—to act as a bridge between on-chain and off-chain environments. This challenge is commonly known as the Oracle Problem.

So, why are oracles indispensable in blockchain ecosystems?

Virtual machines, which serve as the computational backbone of blockchains, execute code and update the system's state. Achieving consensus among nodes requires synchronized execution. If different nodes yield varying execution results, consensus becomes unattainable.

This is the first rationale for the necessity of oracles. They eliminate randomness or non-deterministic outcomes by incorporating external data into transaction payloads.

Another significant concept within blockchains is smart contracts, which can execute basic code snippets and return binary results. Here are a few examples of smart contract queries:

  • Did the public key holder authenticate the transaction with their private key?
  • Does the public address possess sufficient funds to cover its transaction?
  • Is the transaction type valid within the specified smart contract?

Smart contracts operate on limited information for several reasons:

  • The storage capacity of the ledger is constrained.
  • The computational cost for executing complex calculations is high.
  • Allowing nodes to process all inputs independently complicates consensus.
  • For security and reliability, smart contracts should minimize exposure to external data and off-chain resources.
  • Building scalable solutions with unrestricted operations and data sources is challenging.

These factors underscore the importance of oracles, which handle off-chain calculations, retrieve data, perform computations, and apply necessary transformations outside the blockchain. This approach addresses concerns related to computation, storage, consensus, security, and scalability.

Types of Oracles

Oracles essentially perform off-chain tasks and relay results back to the blockchain. They can be categorized into two main types:

  1. Data Oracles: These oracles focus on transmitting external data into the blockchain. Various design patterns exist within this category:
  • Immediate Read: Supplies data needed for immediate actions, storing it once for direct requests. An example is a university record system.

    • Publish-Subscribe: Offers a broadcast service for subscribers, with data subject to frequent changes, such as an asset price feed.
    • Request-Response: Provides large amounts of data to requesters, typically too extensive for smart contract storage. An example includes the price feed for the top 1000 cryptocurrencies.
  1. Computation Oracles: These oracles execute complex calculations off-chain, transmitting only the results to the blockchain. This alleviates work from the blockchain, saving time and costs. Several implementation methods exist, including:
  • Cloud-based Virtual Machines: Dedicated services in the cloud perform calculations and return results but are not decentralized.

    • Cryptlets: Encrypted units that abstract infrastructure and validate incoming and outgoing messages.
    • Verification Games: Decentralized applications pay for verifiable computations off-chain, relying on the blockchain for rule enforcement.

Oracles' Architecture Design Considerations

How Oracles Deliver Data to Smart Contracts

The process of transferring off-chain data into smart contracts typically involves three key steps:

  1. The oracle gathers data from an off-chain source (e.g., a weather station).
  2. The oracle sends the data to the blockchain using a signed message.
  3. The data is stored in the smart contract for future access.

Once data is stored, other contracts can retrieve it by invoking the oracle's retrieve function or accessing its storage directly.

Ensuring Data Authentication and Integrity

Given that oracles relay data from off-chain sources to the blockchain, maintaining data integrity is paramount. Several strategies exist to ensure authenticity:

  • Authenticity Proofs: Trust is shifted from the oracle and smart contracts to third-party modules, utilizing techniques like digitally signed proofs to verify data before execution.
  • Trusted Execution Environment (TEE): Hardware-based secure units ensure data integrity through various authentication features.

Achieving Decentralization in Oracles

Optimal blockchains prioritize decentralization. Connecting a decentralized network to a centralized oracle can introduce significant issues, such as:

  • A single point of failure.
  • Inaccuracies in data and computations due to corrupted oracles.
  • The immutability of blockchain transactions, which cannot tolerate faulty data.

To mitigate these challenges, Decentralized Oracle Networks (DON) are commonly employed. Key characteristics include:

  • Multiple nodes to eliminate single points of failure.
  • Consensus mechanisms to penalize corrupted nodes, ensuring accuracy in data extraction.

Mitigating Manipulation Attacks

Using oracles poses risks if external data is subject to manipulation. For instance, if a smart contract relies on an oracle for asset pricing, and an attacker manipulates the price feed through a flash loan, the oracle's response may be inaccurate.

To combat this, smart contracts and oracles employ various techniques:

  • Utilizing the median from multiple oracles for enhanced security.
  • Employing weighted average strategies to derive results from various sources.
  • Involving validator nodes to verify data accuracy before submission to smart contracts.

Notable Oracle Examples

Oracles are applied in numerous blockchain projects. Some examples include:

  • Oracles for academic record verification.
  • Oracles for generating random numbers.
  • Oracles for detecting natural disasters like earthquakes.
  • Oracles for exchange rate data.
  • Oracles for capital market insights.
  • Oracles for weather-related information.
  • Oracles for reporting sports game outcomes.
  • Oracles for insurance contract damage verification.
  • Oracles for inter-blockchain events.

In the upcoming sections, we will examine prominent oracle projects in the industry.

Chainlink

Chainlink Decentralized Oracle Network

Chainlink is a decentralized oracle network (DON) that provides essential resources such as network, storage, and computation. The DON comprises multiple nodes, forming a committee responsible for connecting off-chain resources to blockchains. Each node utilizes two primary types of integrated programs:

  • Executables: Decentralized applications ensuring high performance and confidentiality.
  • Adapters: Programs linking the DON to external resources, facilitating data retrieval.

API3

Overview of API3 Mechanics

API3 is an oracle project utilizing decentralized APIs (dAPI) designed to meet the needs of smart contracts. These APIs adhere to best practices in security and data integrity. API providers act as first-party oracles, directly offering services to external contracts, overseen by a decentralized governing entity.

Band Protocol

Overview of Band Protocol Architecture

Band Protocol operates on Bandchain, an oracle blockchain built using Cosmos SDK and Tendermint. It employs Byzantine Fault Tolerance for consensus among block validators. Central to Bandchain are Oracle scripts, which retrieve data from external sources and aggregate it into final results.

Example Contract Using Oracles

Let’s illustrate how to invoke oracles in a smart contract with a practical example taken from a GitHub repository.

Example Contract Using Oracles

To facilitate understanding, consider the following notes on the code:

  1. Import the Chainlink Solidity contract:
  2. Define a contract named APIConsumer that inherits from the ChainlinkClient contract:

contract APIConsumer is ChainlinkClient

  1. Establish three oracle parameters (oracle, jobId, fee) necessary for connecting with the oracle server and utilizing services:

constructor() public {

setPublicChainlinkToken();

oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;

jobId = "29fa9aa13bf1468788b7cc4a500a45b8";

fee = 10 ** 18; // 0.1 LINK

}

  1. Create a function called requestEthereumPrice to fetch the current ETH price:

function requestEthereumPrice() public returns (bytes32 requestId) {

Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);

request.add("path", "id");

emit LogNewAlert('req sent, waiting for resp');

return sendChainlinkRequestTo(oracle, request, fee);

}

  1. The fulfill function receives the response and updates the contract with the fetched price:

function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) {

emit LogNewAlert("fulfill called");

ethereumPrice = _price;

}

You can deploy this contract on test environments like Remix with MetaMask, test its functionality, and eventually implement it on the mainnet.

Disclaimer: This article is for informational purposes only and should not be viewed as financial or legal advice. For major financial decisions, consult a professional. If you enjoy similar content, consider joining Medium through my referral link for unlimited access while supporting your favorite writers.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Optimizing Array Iteration in .NET: A Performance Analysis

Discover the most efficient methods for iterating arrays in .NET, validated through BenchmarkDotNet performance testing.

Effective Strategies for Managing Technical Incidents at Scale

Explore effective strategies for managing technical incidents in software development to minimize downtime and enhance user experience.

The Incredible Journey of Stamatis Moraitis: A Life Beyond Cancer

Discover how Stamatis Moraitis defied cancer expectations and lived a fulfilling life for over 40 years.

Inspiration from a School Bus Driver: Five Life Lessons

Discover five impactful lessons from my kids’ school bus driver that inspire positivity and connection in everyday life.

Unlocking Arnold Schwarzenegger's Timeless Muscle-Building Wisdom

Discover essential muscle-building tips from Arnold Schwarzenegger that anyone can follow for effective results.

Pringles’ Brand Refresh: A New Look for a Classic Favorite

Discover the story behind Pringles' brand refresh and its new design elements in this insightful overview.

Boosting Website Traffic: Our Journey to 10k+ Monthly Visitors

Discover how we increased a client's website traffic by over 10k visitors through a strategic content audit.

The Transformative Potential of Bioprinting in Medicine

Exploring how bioprinting is revolutionizing regenerative medicine, offering personalized solutions for organ transplants and tissue creation.