# Intro

Privacy engine for AI and Blockchain

<figure><img src="/files/h6NlrqhpBT0O1AJBmaWo" alt=""><figcaption></figcaption></figure>

***

**Fair Math** is building **cryptographic infrastructure** for **privacy‑preserving AI** and **on‑chain finance**.

#### Core products on the Fair Math stack:

* [**FHE Computer** ](/fhe-computer/overview)— a decentralized computing platform designed to perform operations directly on encrypted data using **Fully Homomorphic Encryption (FHE)**. It serves as the foundation for running privacy‑preserving applications and scaling secure computation in both Web2 and Web3 contexts.
* [**Fair Math AI**](https://fairmath.xyz/ai) — privacy‑native rails for running AI models and agents directly on encrypted data, built on a **FHE** optimized for scalable AI workloads.
* [**Fair Math Payments** ](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments)— is a **modular privacy framework** designed to integrate into existing on‑chain financial systems, enabling selective encryption of transactions and balances without requiring changes to the underlying infrastructure.<br>

We are committed to an **open‑source and community‑driven approach**, fostering collaboration between researchers and developers.


# Overview

**Fair Math Payments** is a **flexible privacy framework** for existing on‑chain financial systems.

It introduces a modular architecture that enables developers and organizations to **add privacy controls to their current infrastructure** — wallets, treasury systems, payroll solutions, or DeFi applications — **without requiring**:

* deployment of a new blockchain,
* migration to custom tokens, or
* changes to wallet ownership models.

The framework integrates directly with **existing account infrastructures** (Safe is the first supported integration) and adds a **privacy account layer** on top of standard on‑chain accounts, enabling selective encryption of balances and transaction data.

#### Core Properties

* **Non‑disruptive:** preserves existing wallets, assets, and operational flows.
* **Modular:** privacy features can be activated selectively (e.g. per token, per operation, or per user group).
* **Customizable:** allows fine‑grained privacy policies, from minimal amount‑only encryption to fully confidential transfers.
* **Auditable:** designed with support for accounting, reporting, and regulatory compliance.

***

> 📌 **Demo**\
> As a demonstration of the framework, you can try [**Transfair**](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments/transfair-safe-app) — a privacy extension for Safe accounts that adds encrypted balances and private transfers within the Safe ecosystem.


# Getting started

To start using private balances and transfers with your SAFE account, Install the Transfair App from the Safe Apps interface.

> 👉 For detailed instructions, see [Installing the App](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments/safe-module/installation)

This step connects the Private Safe module to your existing Safe without requiring new keys or a separate wallet.

Below you will find info on how to:

1. [Deposit your encrypted balance](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments/transfair-safe-app/deposit)
2. [Make encrypted transfer](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments/safe-module/transfers)
3. [Withdraw your tokens](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/41/fair-math-payments/safe-module/withdraw)


# Compliance

Fair Math Payments is designed to deliver **privacy without breaking compliance**.

Unlike “black box” privacy tools that obscure all activity, Fair Math Payments introduces a **structured and auditable privacy layer**. This allows companies, financial institutions, and DAOs to implement confidentiality while still meeting **regulatory, accounting, and reporting standards**.

#### &#x20;Key Principles

* **Auditable Encryption:**\
  All encrypted transactions remain **traceable** and can be decrypted by authorized parties (e.g. internal auditors or compliance officers).
* **Selective Disclosure:**\
  Privacy rules can be set so that **certain information remains private to the public**, but can still be **selectively revealed** for audits or legal requirements.
* **Regulatory Alignment:**\
  The framework is designed to support requirements like **KYC/AML reporting, tax filings, and financial audits**without forcing public exposure of all business operations.
* **Enterprise‑ready Policies:**\
  Different departments or workflows can have **different privacy levels** — e.g., payroll might be fully private, while vendor payments are semi‑transparent for tax reporting.

***

**In short:** Fair Math Payments is not just a privacy layer — it’s a **compliance‑aligned privacy framework**, ensuring that businesses can protect sensitive data **and** meet all legal, accounting, and regulatory obligations.


# Key Features

Fair Math Payments is based on two key abstractions:

#### Privacy Zones

Configurable privacy compatible environments that define:

* What metadata is hidden (amounts, senders, timing)
* What performance/cost is expected
* How compliance is handled (audit logs, disclosure rules)

Each zone can be tailored for general use, enterprise-grade flows, or app-specific needs.

#### Privacy Providers

Entities that power zones using one of three models:

* **Trusted** — custodians, issuers, or internal teams
* **Cryptographic** — ZK, MPC, or FHE backends
* **Hybrid** — TEE + proof-based logic

This separation allows privacy to be **modular and composable**, with asset movement and policy enforcement across zones.


# Use cases

#### Payroll Integration

* Encrypt salary payouts
* Maintain auditability
* Use internal or external privacy providers

#### Merchant Acquiring

* Accept private payments from consumers
* Withdraw to public accounts as needed
* Regional or compliance-specific privacy setups

#### Vendor & Supplier Payments

* Keep contract amounts and payout history confidential
* Route encrypted funds across vendors
* Support segmentation by geography or entity type

All use cases are Safe-native, ERC-20-compatible, and interoperable across public and private flows.


# Transfair (for SAFE)

**Transfair** is a **privacy extension** for Safe accounts that adds support for **private balances** and **private transfers** — **without** requiring a new blockchain, a custom token, or changes to your existing infrastructure.

It is built on the **Fair Math Payments Engine** and allows users to **extend their existing Safe accounts** with privacy features in a seamless way.

> ⚠️ **Important**\
> Transfair is currently running in **test mode** (Sepolia testnet). Functionality, performance, and security parameters are still being validated. Use only with test funds.

It integrates directly with your existing Safe and works with **any tokens connected to your account**. All standard Safe features — including **multisig approvals**, **transaction history**, and **owner control** — remain fully supported.

**Transfair** introduces an **encrypted account layer** linked to your existing Safe address. This private account enables:

* **Deposits** from your public Safe balance into a encrypted private balance.
* **Private transfers**, where amounts are encrypted and visible only to the recipient.
* **Public withdrawals** to any Ethereum address, including your own public Safe.


# Installation

To start using Private transactions in SAFE, you need to install Safe App within your existing Safe account. This takes less than a minute.

#### 1. Open your Safe and go to the “Apps” section

Log into your Safe via the [Safe interface](https://app.safe.global/), select the Safe you want to use, and click on the **“Apps”** tab in the left sidebar.

<figure><img src="/files/x3Tp5HDFBhsYvLz3qn2p" alt=""><figcaption></figcaption></figure>

#### 2. Click on “Add Custom Safe App”

Scroll to the bottom of the page and click the button **“Add custom Safe App”**.

<figure><img src="/files/mu8zUbFLlMNtKsunKr9f" alt=""><figcaption></figcaption></figure>

#### 3. Enter the app URL

In the pop-up window, paste the following URL: `https://app.payments.fairmath.xyz`

Then click **“Add”** to save it.

#### 4. Launch the app

<figure><img src="/files/xAcuvkkwoQnXnuRRqCRm" alt=""><figcaption></figcaption></figure>

The Private Safe app will now appear in your Safe's list of custom apps.

Click on it to open the interface. The app will automatically detect your Safe address and initialize your private account.


# Deposit

Private transfers are made from a **private account** (that linked to the main account) that holds an **encrypted balance**.

To be able to make a private transfer, you first need to fund this private account.

You can receive private funds in two ways:

* **Self-funding:** You transfer tokens from your own Safe’s public balance into your private balance.
* **Incoming transfer:** Another user sends you a private transfer to your Safe address.

In this section, we’ll walk through how to fund your private balance **from your own Safe**, using the Private Safe app.

#### Steps to Deposit into Your Private Account

* **Open the Private Safe app** and select the token you want to deposit into your private balance.
* **Click the “Deposit” button** next to the selected token.<br>

  <figure><img src="/files/FZQPgK62TprPVZGEKZfq" alt=""><figcaption></figcaption></figure>
* In the pop-up window, **enter the amount** you want to deposit.<br>

  > The amount will be withdrawn from your public Safe balance and encrypted into your private balance.

<figure><img src="/files/Nib7c8tLXxcRiANLonjk" alt=""><figcaption></figcaption></figure>

* **Follow the instructions** and sign the transaction using the standard Safe multisig flow.
* After the transaction is confirmed and processed, you will see the **updated private balance** for the selected token in the interface.


# Transfers

A **private transfer** sends tokens from your **private SAFE account** to a recipient address, keeping the amount **encrypted on-chain**.

Only the recipient will be able to see the amount and use the funds.

> ⚠️ Note: The recipient may not have have the app installed at the time of the transfer.
>
> The transfer will succeed regardless.
>
> However, to **view and manage** the received funds, the recipient will need to install the app later.

#### Steps to Send a Private Transfer

1. **Select the token** you want to send and click the **“Transfer”** button next to it.<br>

   <figure><img src="/files/eg1lU7gKS8UuWq9dbWRj" alt=""><figcaption></figcaption></figure>
2. **Enter the recipient’s Safe address** and the amount you wish to send.<br>

   <figure><img src="/files/TGp31sWiQ5r6y0mnRB87" alt=""><figcaption></figcaption></figure>
3. Make sure the checkbox **“Send Encrypted (Only recipient will see amount)”** is **enabled**.This ensures that the transfer amount remains private and only the recipient can decrypt it.<br>

   <figure><img src="/files/89Tggb1K8CfJKOmKjOsz" alt=""><figcaption></figcaption></figure>
4. **Follow the on-screen instructions** and sign the transaction using your Safe.
5. Once the transaction is confirmed, the encrypted tokens will be available to the recipient in their private account.


# Withdraw

You can withdraw tokens from your **private Safe account** to **any Ethereum address**, including your own public Safe or an external wallet.

Unlike private transfers, a withdrawal is a **public transaction** — the recipient address and amount will be visible on-chain.

***

#### Steps to Withdraw from Your Private Balance

1. **Select the token** you want to withdraw and click the **“Transfer”** button next to it.<br>

   <figure><img src="/files/6OztUryloVyYsRGBcTbB" alt=""><figcaption></figcaption></figure>
2. **Enter the recipient's address** and the amount you wish to send.
3. Make sure the checkbox **“Send Encrypted (Only recipient will see amount)”** is **disabled**.

   This ensures the transfer is processed as a public withdrawal, not a private transfer.<br>

   <figure><img src="/files/iheMZXyQnzvAReaPKYeD" alt=""><figcaption></figcaption></figure>
4. **Follow the app instructions** and sign the transaction using your Safe.
5. Once confirmed, the tokens will be transferred from your private balance and appear publicly at the recipient address.


# Overview

Fair Math Computer is a decentralized execution environment with heterogeneous execution nodes (actors) designed to perform computations on encrypted data. Its architecture as depicted below is structured into five primary

<figure><img src="/files/lkefZJbHxmZyDF67h1Pj" alt=""><figcaption><p>FHE Computer Architectural Layers</p></figcaption></figure>

{% hint style="info" %}
We explained architecture in more details in our [whitepaper](https://github.com/fairmath/research/blob/main/Decentralized%20FHE%20Computer.pdf)
{% endhint %}

The first three layers form the Decentralized Operating System based on blockchain. The Execution Layer serves as the hardware equivalent, comprising a scalable network of computational nodes, while the Data Layer, implemented as IPFS-based storage, functions as the system’s permanent repository for encrypted and plaintext data.

Our Operating System incorporates core concepts such as applications, processes, threads, and virtual memory, drawing inspiration from UNIX-like systems. This system provides the foundation for application management, resource allocation, and task schedul- ing while maintaining the security and decentralization. We consider each layer in more details in the following subsection.

Our computer has command line interface you can play with: <https://computer.fairmath.xyz>

The ecosystem includes several key components:

* [**Fair Math Computer**](/fhe-computer/overview): A decentralized FHE Computer.
* [**FHERMA**](/fherma):  FHE Challenges Platform.
* [**POLYCIRCUIT**](https://docs.fairmath.xyz/):  FHE components repository.
* fhelanfg: MLIR based FHE Compilerd

The detailed overview of the system can be found in our [Whitepaper](https://github.com/fairmath/research/blob/main/Decentralized%20FHE%20Computer.pdf).

<figure><img src="/files/135PKkALsIbZjuZO3UnI" alt=""><figcaption><p>Fair Math Ecosystem</p></figcaption></figure>


# Hello (CIFAR) world!

We have deployed an application capable of classifying encrypted images from the CIFAR-10 dataset. This page provides instructions on setting up the environment, preparing inputs, running the application, and obtaining the results.

### Prerequisites

* `fairmathd` :&#x20;
  * [Mac OS darwin-amd64 ](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-darwin-amd64.zip)
  * [Mac OS darwin-arm64 ](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-darwin-arm64.zip)
  * [Linux amd64](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-linux-amd64.zip)
  * [Linux arm64](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-linux-arm64.zip)
* `fairmath-cli`  latest release can be downloaded from the [github page](https://github.com/fairmath/fairmath-cli/actions/runs/11970928596)
* FHE Computer web frontend - <https://computer.fairmath.xyz/dashboard>

### Setup

* Unpack and install downloaded `fairmathd` and `fairmath-cli` zip files

### Registration

To run any application on the FHE computer, you need an address on the Fair Math network. If you don’t have one yet, please follow these steps:

1. Run init command:

   ```bash
   $ ./fairmathd init <username> --chain-id fairmath-tn1
   ```

   It will generate config file, by default located at `.fairnet/config/client.toml.`
2. Now we need update the `config` file with the following fields:

   ```bash
   node = "<https://testnet.computer.fairmath.xyz>"
   chain-id = "fairmath-tn1"
   keyring-backend = "test"
   ```
3. Getting a FairMath address:

   ```bash
   $ ./fairmathd keys add <accountname> --keyring-backend=test
   ```

   Note that keyring backend test will store your private key in the open file, never use this option for mainnet
4. You can request tokens from someone or use our [Faucet](https://faucet.fairmath.xyz) to obtain them. Tokens can be transferred between accounts using the following command:

   ```bash
   $ ./fairmathd tx bank send <from address> <to address> 100stake --from <from account> --chain-id testnet --keyring-backend test 
   ```

   You can find the address using the `keys list` command:

   ```bash
   $ ./fairmathd keys list --keyring-backend=test
   - address: fairmath19wjlxxzef8nvlfr63xr9c8vkefmf54awtp8mk0
     name: <accountname>
     pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"A2akCmQrGqdJWMjQw7xqR8I188pI+KVb5z/O+1GTXYbN"}'
     type: local
   ```

   Once you receive tokens you can run an application on FHE computer

### Running Application

1. Each application comes with a configuration file that contains all the necessary information for preparing encrypted inputs. Ath te first step you have to get this config. The name of CIFAR application is `cifar-split.`  To download an  config use the  following command:

   ```bash
   $ ./fairmathd actor app-config cifar-split --grpc-addr=testnet.computer.fairmath.xyz:9090
   ```

   If everything is set up correctly, you will see similar logs:: <br>

   ```
   024/11/25 10:23:27 Download config for the following apps:
   2024/11/25 10:23:27 Name: cifar-split	ID: 12	Author: fairmath19wjlxxzef8nvlfr63xr9c8vkefmf54awtp8mk0
   You can see a message about downloaded configs:
   ```

   ```bash
   Name: cifar-split	ID: 12	Author: fairmath19wjlxxzef8nvlfr63xr9c8vkefmf54awtp8mk0
   ```

2. From the message above, we will need the ID later to run the application. Once this command is executed, an FHE configuration file named `cifar-split-12-fhecfg.json` will be generated with all parameters preconfigured.

3. Based on the configuration file, the `fairmath-cli` will generate all the required keys, cryptocontext and ciphertexts. At this stage, we only need to provide the plaintext value in the `plaintext_value` field. Images from the CIFAR dataset can be represented as a vector of numbers. We have prepared [scripts](https://github.com/fairmath/cifar10-image-convert) that generate the corresponding vector from an image. Now we can put input for our applicaiton in config file in open form to generate cipheretx.\
   In this config you must provide just `plaintext_value` for the `input` object.&#x20;

   Example of input section:

   ```bash
    ...
    "input": {
       "cryptocontext": "ctx",
       "plaintext_value": [132,125,130,143,142,145,148,147,148,136,122,133,142,126,123,134,132,114,120,123,118,136,122,116,107,98,97,104,98,102,97,98,146,156,154,145,139,146,145,143,146,132,120,125,125,120,113,127,134,122,129,135,126,126,117,131,122,100,98,105,103,104,88,85,151,160,165,159,151,160,148,138,146,140,124,137,128,128,118,129,134,127,124,138,134,128,110,108,112,101,104,115,120,115,94,91,148,142,161,160,146,156,152,140,143,148,143,124,131,126,123,125,127,119,107,115,127,123,110,97,100,104,114,122,124,117,107,102,160,159,168,159,131,137,146,143,141,149,125,95,121,121,103,97,106,116,137,142,136,112,105,100,101,109,116,106,92,86,96,99,165,171,173,158,153,163,134,141,142,127,116,121,128,111,107,103,98,105,132,172,190,173,147,116,100,116,118,99,86,77,85,96,156,154,170,156,173,173,145,150,155,140,134,137,134,133,129,126,112,114,97,101,143,189,194,178,141,115,117,100,90,75,81,96,146,141,155,149,167,168,160,153,147,151,156,157,142,144,133,145,152,145,137,123,98,115,123,137,150,111,110,101,89,88,76,85,145,144,155,165,172,170,157,147,140,132,135,140,132,140,147,143,135,127,127,123,108,103,88,71,73,57,62,81,73,81,78,81,154,148,148,176,180,168,156,141,161,156,136,145,138,147,153,144,134,135,130,107,73,88,93,91,81,34,27,60,70,76,82,76,158,161,154,186,197,134,117,141,182,175,140,145,151,160,155,149,127,130,122,115,91,70,64,56,69,61,52,66,79,84,87,79,142,164,186,201,216,108,46,117,187,182,141,130,102,137,159,150,126,118,108,108,98,81,83,58,49,58,68,69,83,90,86,80,134,137,166,191,209,153,99,145,160,153,148,125,122,127,165,142,99,104,130,83,67,63,68,67,52,38,37,74,83,76,75,83,136,125,132,156,177,182,180,190,144,100,130,110,142,162,160,144,131,101,126,105,80,60,53,79,63,44,56,100,77,66,78,92,142,134,123,128,145,163,179,186,154,95,125,120,132,170,164,147,148,123,118,104,86,69,72,108,73,65,105,100,62,61,82,96,143,135,130,120,128,143,149,156,167,146,152,129,137,171,190,163,142,129,119,95,76,49,93,114,68,99,126,88,54,33,55,82,142,132,121,120,127,101,108,120,133,147,149,102,127,175,188,182,157,134,114,109,101,73,119,107,73,130,113,73,43,18,35,69,160,136,109,123,130,93,66,91,98,90,103,92,116,147,154,152,139,128,124,124,104,105,131,99,99,135,94,63,34,17,39,72,181,154,120,123,120,68,40,79,111,105,109,122,129,119,134,133,125,113,111,99,93,129,135,112,135,127,87,64,26,18,48,74,186,174,151,137,119,63,14,41,130,159,127,163,182,133,117,122,118,104,85,71,96,138,136,120,149,113,79,55,17,28,73,72,177,181,160,140,130,91,29,6,43,103,116,156,197,171,109,99,82,69,60,69,118,150,126,121,146,97,67,41,20,56,101,87,172,169,154,128,139,138,84,33,5,27,77,106,157,170,122,83,79,71,68,72,115,167,129,141,140,83,57,30,32,87,112,94,152,142,148,139,152,163,140,114,85,31,25,70,126,128,116,76,87,75,83,67,100,178,150,162,120,72,42,22,51,101,106,95,138,143,152,142,140,160,160,160,182,130,53,93,152,111,90,64,77,77,70,27,92,188,158,153,93,60,27,26,79,110,107,92,134,155,151,132,133,150,158,156,168,210,179,169,148,104,53,34,53,56,41,45,141,186,136,108,77,43,26,62,96,101,112,90,147,152,138,118,139,164,176,182,178,189,173,146,115,65,28,17,31,75,95,144,177,163,113,90,58,29,46,103,111,92,98,97,144,145,130,111,123,131,136,133,165,181,133,99,73,30,18,45,85,133,160,166,159,136,109,76,37,51,95,116,120,102,88,98,140,139,121,114,119,132,125,123,154,155,106,58,36,24,36,99,130,134,148,143,111,98,83,46,45,98,125,135,127,113,94,98,135,128,116,116,122,148,153,180,143,114,107,92,94,91,117,150,142,133,84,92,115,109,53,37,96,131,131,144,120,109,113,102,130,132,114,110,121,141,132,139,150,146,142,136,138,116,139,165,167,165,113,127,130,106,90,84,123,137,132,121,110,119,125,106,130,139,118,122,130,125,125,139,147,134,133,132,138,117,129,164,167,161,146,128,130,127,138,140,134,135,132,119,117,121,116,102,129,136,123,130,123,122,137,132,125,125,126,122,131,124,135,151,146,146,141,139,143,148,134,120,129,127,132,127,120,112,113,106,142,130,133,147,148,151,155,153,154,142,129,137,147,135,133,144,142,126,131,133,125,143,128,128,125,115,114,121,116,120,116,113,155,161,157,150,143,149,151,149,151,139,127,130,130,129,125,137,144,133,139,142,133,135,126,145,140,118,116,122,122,122,107,101,160,165,168,163,154,162,153,142,151,144,129,140,131,136,129,138,142,136,132,143,141,139,122,123,130,119,121,132,138,133,112,107,157,147,163,162,150,161,157,145,149,152,147,126,135,134,134,134,135,128,115,120,136,137,126,115,118,122,132,139,141,134,125,118,169,164,171,162,140,150,157,153,152,157,130,100,128,133,119,107,115,126,147,151,148,132,128,121,119,127,133,123,109,103,113,115,173,175,176,162,168,186,156,160,161,145,128,131,140,128,128,122,116,122,149,188,204,183,155,125,111,130,134,118,104,94,103,113,162,159,175,164,192,202,176,176,183,169,154,153,152,155,153,155,141,141,121,122,153,185,181,172,144,123,131,119,108,93,99,115,147,147,166,162,188,194,189,181,178,184,182,180,165,167,156,169,179,171,163,145,111,117,121,136,154,119,123,119,107,106,94,104,143,154,175,186,193,188,178,171,167,163,165,168,157,163,169,164,159,153,155,147,128,118,100,79,81,67,75,98,91,99,96,100,154,168,181,205,198,175,166,158,180,179,165,171,160,171,178,166,157,163,163,134,97,113,116,106,92,45,39,76,88,94,100,95,165,195,198,219,209,128,114,146,189,188,164,163,165,184,186,176,156,165,162,149,122,101,85,70,83,73,65,83,97,102,104,98,154,204,237,235,226,95,34,117,187,185,158,143,112,160,192,177,151,156,155,145,129,112,101,68,64,71,79,87,103,110,105,99,138,164,207,230,233,158,95,162,171,146,151,145,140,143,189,146,91,127,178,111,83,81,85,74,71,52,36,94,111,101,99,104,135,137,158,194,213,207,196,219,160,95,134,128,160,183,195,169,136,125,160,125,98,76,71,94,89,55,57,126,107,90,101,112,139,136,132,151,175,191,207,214,169,101,142,135,144,193,203,197,185,159,147,127,115,93,94,139,103,70,118,135,88,80,102,117,139,131,127,121,135,156,167,177,182,161,176,147,148,182,197,194,177,170,160,128,109,79,122,155,96,106,154,127,76,45,70,104,138,130,117,109,118,99,112,130,146,162,170,121,143,181,174,187,172,164,155,140,129,103,155,144,89,147,154,108,60,22,46,90,157,138,113,121,128,93,68,95,105,99,111,102,135,168,161,163,145,140,136,134,121,133,173,126,100,165,142,91,46,14,45,92,180,157,127,128,124,73,43,80,117,115,115,135,156,150,156,156,142,126,117,106,113,162,178,128,137,171,135,83,35,19,54,92,184,174,153,140,123,65,14,39,137,177,142,185,214,162,133,143,144,127,106,93,128,177,170,127,165,166,117,69,27,37,83,87,175,179,158,142,134,95,31,3,48,118,133,177,226,202,128,114,100,85,74,89,149,182,143,127,173,145,95,49,30,67,112,100,169,165,148,128,141,141,86,29,4,32,86,116,180,204,145,94,88,79,74,87,138,187,133,151,174,122,75,35,42,98,123,105,149,134,137,132,148,159,136,107,75,23,22,69,145,164,139,83,91,78,85,74,112,190,155,180,155,101,54,28,62,112,117,105,135,133,136,127,127,147,146,145,162,110,40,89,174,148,105,65,79,79,72,25,90,194,175,183,126,80,37,34,90,121,119,103,130,143,133,114,115,131,137,135,144,188,166,171,174,137,57,30,56,58,43,35,125,189,164,146,103,56,36,73,107,112,124,103,137,138,127,108,129,152,162,164,168,191,176,161,137,81,31,18,37,78,92,123,149,155,134,117,71,35,52,115,126,106,112,112,135,134,126,110,120,126,129,125,169,198,149,116,87,36,19,44,88,132,150,143,133,125,119,91,44,55,99,126,134,117,102,113,138,135,123,118,121,131,123,121,160,169,120,68,43,25,34,91,122,126,132,124,94,88,83,50,48,101,128,142,141,126,107,112,136,128,120,122,126,149,152,174,136,110,105,94,96,89,113,136,127,120,65,74,104,102,45,34,97,135,133,150,131,121,124,114,129,130,118,115,122,139,127,129,135,130,129,132,137,113,134,152,154,156,100,112,122,103,83,79,124,139,133,126,119,128,134,116,127,134,119,122,126,118,117,134,139,121,126,128,133,112,121,154,163,162,144,116,121,126,133,137,134,134,131,122,125,129,123,110,126,131,120,125,116,113,126,130,125,120,120,115,123,116,126,144,143,146,140,130,132,143,130,118,127,123,129,129,125,118,118,112,118,108,112,124,125,125,123,126,129,113,97,106,116,104,102,120,114,88,95,102,97,115,98,100,100,93,96,102,91,90,89,93,131,140,135,123,125,135,124,123,127,110,94,99,100,97,91,109,114,98,111,117,105,106,100,120,115,95,97,103,98,95,82,80,136,143,147,143,145,156,135,124,134,126,108,120,110,110,100,107,107,99,103,122,117,113,103,103,105,97,103,112,115,111,90,85,133,125,144,151,134,137,133,120,125,134,132,109,112,105,99,95,89,79,71,89,102,100,102,94,93,99,113,119,121,117,105,96,145,142,152,148,94,80,104,101,100,120,105,68,84,81,60,55,60,61,83,94,85,64,76,88,94,104,114,102,90,90,95,93,146,155,159,135,92,82,66,69,72,72,67,67,72,50,43,44,38,43,74,111,116,94,85,78,72,102,114,95,86,81,86,92,132,137,153,116,95,83,59,54,65,62,55,59,67,56,51,55,40,50,41,50,72,93,98,105,85,88,111,96,92,78,82,96,125,116,115,89,74,67,64,54,55,66,71,74,67,57,44,67,76,74,70,65,33,32,44,70,92,84,108,99,90,90,78,86,123,104,94,91,70,65,59,51,45,40,48,54,52,47,50,61,59,52,50,55,45,39,36,23,26,36,65,82,75,83,80,82,128,94,84,106,82,72,72,54,66,57,47,58,57,56,59,63,57,59,53,48,29,39,43,43,39,18,31,61,72,78,84,77,126,95,104,135,115,63,60,66,86,71,49,59,73,76,72,74,52,60,56,52,38,28,25,20,36,49,54,65,81,86,89,80,105,95,151,167,150,57,11,52,94,80,51,47,30,62,87,81,54,56,52,51,46,41,38,21,24,49,66,63,83,93,89,81,102,96,126,151,150,86,34,66,83,81,72,49,47,50,91,75,31,45,73,38,30,35,34,26,26,24,26,49,65,80,83,84,108,97,90,112,121,107,96,107,79,45,66,36,64,88,95,82,62,44,72,59,41,35,29,40,34,22,31,60,50,67,85,91,113,107,88,90,94,91,98,105,87,36,60,46,55,97,103,87,79,66,66,55,43,39,36,67,40,30,61,52,33,57,84,94,113,109,102,89,85,82,81,80,93,77,78,60,65,91,111,98,78,72,66,38,32,14,47,71,31,51,70,39,26,27,53,80,110,107,98,95,92,58,63,62,67,77,74,40,62,92,97,114,96,76,57,46,57,31,64,60,30,71,58,33,21,13,35,70,127,110,88,99,100,62,41,61,56,36,40,37,57,74,78,90,76,69,66,57,61,59,69,49,45,70,45,36,18,14,41,76,152,128,99,97,91,47,30,64,84,68,60,77,79,56,68,71,61,56,59,45,56,85,75,50,67,63,46,47,19,18,49,77,160,150,128,112,94,46,10,31,109,126,76,116,133,71,54,62,61,56,44,38,64,93,76,44,71,56,43,42,19,28,70,71,152,156,135,119,108,71,19,3,33,71,59,91,130,108,59,52,37,31,30,51,85,87,59,46,70,44,34,29,21,55,97,84,146,142,127,108,116,113,64,24,0,11,42,47,85,104,72,40,37,36,38,60,78,86,56,72,71,37,31,20,31,84,106,89,126,113,118,113,122,129,109,87,62,16,13,28,58,62,61,32,46,39,49,52,60,92,79,102,63,39,26,16,49,96,99,88,112,112,118,106,99,116,121,115,133,90,28,45,81,49,49,35,47,50,45,13,51,108,96,104,51,40,23,24,75,104,99,85,108,123,115,91,85,101,115,102,101,142,114,91,68,52,35,26,42,45,30,24,86,113,82,66,46,35,28,61,91,94,103,83,118,121,109,88,105,123,131,125,112,119,98,70,54,33,17,11,25,62,67,91,100,85,61,50,34,33,46,95,107,88,93,95,117,116,106,89,96,97,94,84,112,125,75,48,39,16,15,29,63,103,109,101,84,63,62,46,20,52,91,108,116,98,83,97,117,115,101,93,93,100,88,82,109,111,67,30,21,16,33,73,92,93,90,82,52,43,46,29,34,87,116,129,123,108,88,95,114,107,97,94,96,118,119,140,98,70,73,74,80,73,97,118,107,98,42,44,68,69,24,27,88,112,118,138,114,103,107,98,108,109,95,85,91,109,99,103,106,101,106,116,116,83,103,133,144,144,82,87,94,77,65,68,109,117,114,110,102,112,117,101,106,114,97,93,96,90,91,111,113,92,100,114,114,81,90,132,146,145,120,93,101,105,113,112,110,117,110,102,108,113,107,95,106,110,97,98,88,89,105,107,98,93,96,103,109,91,100,119,121,124,115,108,115,124,111,92,103,107,109,108,110,102,103,98],
       "public_key": "pk",
       "source": "",
       "type": "ciphertext"
     },
     ...
   ```

4. Now we can execute a command to prepare the data(encrypt input, generate keys etc.), upload it to the Data Layer, and run the application:

   ```bash
   $ ./fairmathd actor start-app 12 ./cifar-split-12-fhecfg.json --keys-dir=/path/to/store/keys --key-generator=/path/to/fairmath-cli --from <accountname> --ipfs 167.235.197.94:5001 --keyring-backend=test
   2024/11/25 10:35:38 application with id <12> has been started under process ID: <38>

   ```

If the execution is successful, you will receive a process ID for your run (e.g., `38` in this example). Additionally, all necessary keys and the cryptocontext will be generated and stored in the directory specified by the `--keys-dir` flag. The secret key and cryptocontext will be required later to decrypt the result.

Once the command completes, an updated configuration file named `./cifar-split-12-fhecfg.updated.json` will be created. For future runs, you can use this updated configuration to avoid re-generating keys. Simply modify the input section in the updated config, and the FHE computer will use the existing keys.

To prevent saving an updated configuration, pass the flag `--save-config=false`. This is especially useful if you are running the application with an already updated config to avoid generating redundant files like `cifar-split-12-fhecfg.updated.updated.json`.

To observe the execution of your app you can go to the [FHE computer terminal](https://computer.fairmath.xyz/dashboard) and run `orders` command

```bash
3os> orders 
```

<figure><img src="/files/EMFaAuuUhc8xM7YElbmt" alt=""><figcaption></figcaption></figure>

There is 3 orders related to the process `38`. Once all of related orders is in `done` status the process considered as finished and you are able to see result.

To see result of the execution you need your account address(you discovered it during step 2 of registration). Run `process` command in the [FHE computer termial](https://computer.fairmath.xyz/dashboard) and observe the

```bash
3os> process user=fairmath19wjlxxzef8nvlfr63xr9c8vkefmf54awtp8mk0
```

<figure><img src="/files/FrkAAqSYqSVtmQz0ewNx" alt=""><figcaption></figcaption></figure>

If everything is ok then Args column will contain ipfs link to the result of computation. In this case it is - `/ipfs/QmQ1LHHuu4TheWvKz1UBy5VXsLWr3EWPUgSsk4xHQRHLcu`. To download it paste the following address in your browser changing ipfs link to yours

`http://167.235.197.94:8080/ipfs/QmQ1LHHuu4TheWvKz1UBy5VXsLWr3EWPUgSsk4xHQRHLcu`

```json
{
    "vars": {
        "%arg0": {
            "basetype": "",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "/home/gsm/.fairmath/fhevm-store/actor-1/.ipfs.QmXR5FDSupU6ZKxxkU95WcywhmAvykLZbNEqtcu2P3M43a"
        },
        "%arg2": {
            "basetype": "i32",
            "is_array": true,
            "is_secret": false,
            "storage": "ipfs",
            "value": "/home/gsm/.fairmath/fhevm-store/actor-1/.ipfs.QmfZhqPFDZmyK4rAxwDH5FTHeQGrJjDFbRJ1WDzW4qpF1P"
        },
        "%mul_key": {
            "basetype": "",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "/home/gsm/.fairmath/fhevm-store/actor-1/.ipfs.QmT4xPQnAkZXR6PGDySaVZ4kBPbHdkVi2TqZgUZdREhfa7"
        },
        "pk": {
            "basetype": "",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "/home/gsm/.fairmath/fhevm-store/actor-1/.ipfs.QmeA4jDooaoR4G2amHtnQKGpRD4eEdfVZSLjARDFF5HJq4"
        }
    }
}
```

Now you have a result, to decrypt it you can use `fairmath-cli`   with secret key and crypto context.

```
fairmath-cli decrypt --cc ./cryptocontext_name --key ./private_key_name --output ./decrypted.txt ./ciphertext_file
```


# Fair Math Actor

This page describes a FairMath actor and its components

## Intro

The [Execution Layer](/fhe-computer/architectural-layers/execution-layer) of Fair Math Computer relies on [**actors**](/fhe-computer/fair-math-actors), which are responsible for executing FHE instriuctions - [tasks](/fhe-computer/operating-system/execution-graph-and-tasks).  Communicating with the orchestration layer actor receives tasks, performs calculation and submits result. Typically actor consists of the following components:

* [`fairmathd`](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/28/overview/fairmath-actors/fair-math-controller) - controller application which is responsible for communication with other parts of a system
* [`fairmath-vm`](https://app.gitbook.com/o/n6hALlBc1Rcd3fH2JvqV/s/mHu1qRdgJeHeQup4pe3R/~/changes/28/overview/fairmath-actors/fair-math-vm) - a virtual machine which is responsible for the execution of FHE app


# Fair Math Controller

`fairmathd` is an executable operating with the FairMath Net. This tool contains plenty of command to communicate with the blockchain infrastructure. See help command of the application to explore all functionality.

This is a central application for the FairMath actor which connects all parts of a system.&#x20;

<figure><img src="/files/Djt6tJ6e8uDqWD29vo0y" alt=""><figcaption></figcaption></figure>

Actor controller receives tasks from FairMath Net, prepare data for VM operating with IPFS and update result of execution. It is configured by a several config files.

Actors config typically located at the `~/.fairmath` directory and looks like this:

```
actor-id: 1
tx:
    owner: "actor-owner"
    gas-adjustment: 1.5
query:
  query-grpc-address: "testnet.computer.fairmath.xyz:9090"
orders:
    acquire-interval: 30s
    main-actor-ping: 1m0s
    backup-actor-ping: 1m0s
    min-price: 0fmth
    backup-min-price: 0fmth
ext-storage:
    ipfs:
      node-url: 167.235.197.94:5001
interpreter:
    path: /home/actor/path/to/vm

```

For correct work there should one more config file with correct parameters: `~/.fairmath/config/client.toml`

The most important sections are

* `query` - grpc address of a validator to perform query requests
* `interpreter.path` - a path to Fairmath Virtual Machine
* `ext-storage.ipfs.node-url` - address of IPFS node, be sure that kubo API is available, controller operates through this API

Its content usually looks like this:

```
# This is a TOML config file.
# For more information, see https://github.com/toml-lang/toml

###############################################################################
###                           Client Configuration                            ###
###############################################################################

# The network chain ID
chain-id = "fairmath-tn1"
# The keyring's backend, where the keys are stored (os|file|kwallet|pass|test|memory)
keyring-backend = "test"
# CLI output format (text|json)
output = "text"
# <host>:<port> to CometBFT RPC interface for this chain
node = "https://testnet.computer.fairmath.xyz"
# Transaction broadcasting mode (sync|async)
broadcast-mode = "sync"

# gRPC server endpoint to which the client will connect.
# It can be overwritten by the --grpc-addr flag in each command.
grpc-address = "https://testnet.computer.fairmath.xyz:9090"
```

* `chain-id` - set the chain id. To operate with fairmath testnet use `fairmath-tn1`&#x20;
* `keyring-backend` - specify key storage backend, use test only for testnet because this backend keep all keys opened with no security.
* `node` - a validator address. You can use FairMath TestNet validators specifying the following URL: `https://testnet.computer.fairmath.xyz:9090`  &#x20;

It is convenient to configure actor as a daemon through `systemd`


# Fair Math VM

FHE Virtual Machine

<figure><img src="/files/Djt6tJ6e8uDqWD29vo0y" alt=""><figcaption></figcaption></figure>

**FairMath Virtual Machine**

The FairMath Virtual Machine (fairmath-vm) is  running on the actor side, responsible for executing instructions received from the [Orchestration Layer](https://docs.fairmath.xyz/) through [Order Book](/fhe-computer/operating-system/order-book).

We have implemented the virtual machine based on **OpenFHE**, but the specification allows actors to implement it using other libraries, providing flexibility to developers.

FMVM executes compiled FHE applications or their parts and returns the execution results. It operates solely with local files, with all necessary data prepared in advance.

#### Required Input Data:

1. **Instructions**: A file containing the instructions to execute.
2. **Execution Context**: A file with precomputed variables (possibly generated on another actor). The execution context allows splitting the application into blocks and running these blocks across multiple actors.

This approach is explained in detail in our Whitepaper.

FMVM requires no additional configuration, making it simple and efficient to use.

### How To Build

* Install CMake 3.22(or above), gcc or clang
* Install OpenMP(this is not necessary but highly recommended)
* Clone vcpkg repo and install binary

```
$ git clone https://github.com/microsoft/vcpkg.git
$ cd vcpkg && ./bootstrap-vcpkg.sh
```

* Add the following env vars

```
$ export VCPKG_ROOT=/path/to/cloned/vcpkg/repo
$ export PATH=$VCPKG_ROOT:$PATH
```

You may also to add these variables to your `.bashrc` file for convenience.

* Clone `fairmath-vm` repository

```
$ git clone https://github.com/fairmath/fairmath-vm
```

* Configure cmake and build the project. You should specify vcpkg path, build type and directory for cmake generated file.

```
$ VCPKG_ROOT=/path/to/cloned/vcpkg/repo BUILD_TYPE=Release BIN_DIR=rel cmake --preset=base && cmake --build BUILD/rel
```

All files will be located in `BUILD` directory. You can omit VCPKG\_ROOT variable if the one was defined previously(e.g. in the `.bashrc` file) Also it is possible to create user defined presets for CMake. Just create the following file in the root of the repository CMakeUserPresets.json:

```
{
    "version": 2,
    "configurePresets": [
      {
        "name": "dbg",
        "inherits": "base",
        "environment": {
          "VCPKG_ROOT": "/path/to/cloned/vcpkg/repo",
          "BUILD_TYPE": "Debug",
          "BIN_DIR": "dbg"
        }
      },
      {
        "name": "rel",
        "inherits": "base",
        "environment": {
          "VCPKG_ROOT": "/path/to/cloned/vcpkg/repo",
          "BUILD_TYPE": "Release",
          "BIN_DIR": "rel"
        }
      }
    ]
}
```

Since that you are able to run the following command to build release configuration

```
$ cmake --preset=rel && cmake --build BUILD/rel
```

Change rel to dbg to build a debug configuration.

The very first build could take a time because of vcpkg will build 3rd party libraries for this project. NExt builds will be mush faster since 3rd party libraries will be already built and cached.

* Installation Run cmake install to gather all binary files related to the build.

```
$ cmake --install BUILD/rel
```

If you are using provided `CMakeUserPresets.json` then build will be installed to the `BUILD/install` directory.


# Setup an Actor

This instruction explain how to be an actor  Fair Math Computer. More details about actors can be found [here](/fhe-computer/fair-math-actors).

Follow provided steps to run your own actor for FHE Computer.

### Prerequisites

1. Get the actor execution file:\
   [Mac OS darwin-amd64 ](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-darwin-amd64.zip)\
   [Mac OS darwin-arm64 ](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-darwin-arm64.zip)\
   [Linux amd64](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-linux-amd64.zip)\
   [Linux arm64](https://fairmath-releases.s3.eu-central-1.amazonaws.com/faimrathd/v0.0.20/fairmathd-linux-arm64.zip)
2. Install fairmath certificate to `/etc/ssl/certs`

{% file src="/files/9TMNiSBMtYHB7qDqSo8p" %}

### Setup&#x20;

1. Create an account in the Fairmath Testnet
   1. Run init command&#x20;

      ```bash
      $ ./fairmathd-linux-amd64 init <username> --chain-id fairmath-tn1
      ```

      Update the `.fairmath/config/client.toml` file with the following fields:

      ```bash
      node = "https://testnet.computer.fairmath.xyz"
      chain-id = "fairmath-tn1"
      keyring-backend = "test"
      ```
   2. Create a Fairmath Net account

      ```bash
      $ ./fairmathd-linux-amd64 keys add <accountname> --keyring-backend=test
      ```

      Note that keyring backend test will store your private key in the open file, never use this option for mainnet
   3. Ask someone to send several tokens for your, it could be done via command

      ```bash
      $ ./fairmathd-linux-amd64 tx bank send <from address> <to address> 100fmth --from <from account> --chain-id fairmath-tn1 --keyring-backend test 
      ```

      You can use `--gas-adjustment` flag or perform transaction in dry-run mode to estimate needed gas value

      Validate your token’s amount:

      ```bash
      $ ./fairmathd-linux-amd64 q bank balances <your address> --chain-id fairmath-tn1
      ```
2. Register actor
   1. Run a transaction to register your actor:

      ```bash
      $ ./fairmathd-linux-amd64 actor register <actorname> --from=<account name or address> --keyring-backend=test
      ```

      `actorname` - is an actor human readable name, just string

      `account name or address` - account name from step 2.b

      if everything is ok then you should see the message like this:

      ```bash
      $ ./fairmathd-linux-amd64 actor register testactor --from=testaccount --keyring-backend=test
      2024/11/04 15:29:10 registration is done: actor 'testactor' is registered under ID: <30>
      ```

      Also an actor config file template will be created in the `~/.faitmath`. Config file name contains actor name and ID, so in the example below it should be `~/.fairmath/testactor-30.yaml` with the following content:

      ```yaml
      actor-id: 30
      tx:
          owner: ""
          gas-adjustment: 1.5
      query:
          query-grpc-address: ""
      orders:
          acquire-interval: 30s
          main-actor-ping: 1m0s
          backup-actor-ping: 1m0s
          min-price: 0fmth
          backup-min-price: 0fmth
      ext-storage:
          ipfs:
              node-url: <http://ipfs/url:8080>
      interpreter:
          path: /path/to/interpreter
      ```

      You have to specify some settings to run actor:

      * `owner` - your account name from step 2.b
      * `query-grpc-address` - grpc address of validator, should be `testnet.computer.fairmath.xyz:9090`
      * `ipfs.node-url` - address for IPFS node, kubo rpc should be available (our IPFS node - `167.235.197.94:5001`)
      * `min-price` and `backup-min-price` - Set the minimum price for which your actor will perform the job.
      * `interpreter` - path to FHE virtual machine

      Also you should add a custom code component which is `18446744073709551615`

      Example of the config:

      ```yaml
      actor-id: 1
      tx:
          owner: "testaccount"
          gas-adjustment: 1.5
      query:
        query-grpc-address: "testnet.computer.fairmath.xyz:9090"
      orders:
          acquire-interval: 30s
          main-actor-ping: 1m0s
          backup-actor-ping: 1m0s
          min-price: 0fmth
          backup-min-price: 0fmth
      ext-storage:
          ipfs:
            node-url: 167.235.197.94:5001
      interpreter:
          path: /home/path/to/vm

      ```
3. Your are ready to run your own actor, please run the command

   ```yaml
   $ ./fairmathd-linux-amd64 actor run <actor config name> --keyring-backend=test 
   ```

   Note that you should NOT specify the full path to the actor config, just place the config file name, e.g. `testactor-30.yaml`. If you see logs then everything is ok:

   ```yaml
   {"level":"warn","time":"2024-11-04T16:00:40+03:00","message":"heavy objects cache could not find the state file(cache will be reset): read cache state: open /home/gsm/yasha/dcomp/fairnet/bin/.actor/fhevm-store/actor-30/h-cache.json: no such file or directory"}
   {"level":"warn","time":"2024-11-04T16:00:50+03:00","message":"failed to acquire order send tx calculate gas: simulate tx: rpc error: code = Unknown desc = rpc error: code = Unknown desc = failed to execute message; message index: 0: acquire order tx: no available orders [cosmos/cosmos-sdk@v0.50.10/baseapp/baseapp.go:1023] with gas used: '36614': unknown request"}
   ```


# Architectural Layers


# Application Layer

The Application Layer is the highest level in our multi-layered architecture. This layer acts as the primary interface for the interaction with the system.

Each application stored at the Application Layer is associated with a security policy that governs its execution. These policies define the conditions under which applications can be accessed and executed. For example, some applications may be publicly available to all users, while others may restrict access to a predefined group of authorized users.


# Orchestration Layer

The Orchestration Layer is a responsible for managing the execution workflow of applications deployed on the system. It coordinates task distribution among actors, creates execution contexts, and ensures that applications are efficiently and securely executed. The orchestration process involves several key phases:

### Application Execution Graph Creation

In the first phase of execution, an application is analyzed and transformed into an execution graph. Each application may define multiple entry points (functions) as its potential starting points. During the application launch, the specific entry point is selected and execution begins from that point.

The execution graph represents the logical flow of the application. The nodes of this graph correspond to blocks of instructions (tasks), which are the fundamental units of execution. Each block is designed to be assigned to actors for processing. A block contains one or more instructions, which are categorized into two types:

**Atomic Instructions:** These are indivisible operations within the system’s Instruc- tion Set Architecture (ISA) that can be executed directly by actors without further decomposition.

**Composite Instructions:** These represent high-level operations that may be expanded into a sequence of atomic instructions during the execution planning phase. For instance, a composite instruction like a polynomial evaluation or matrix multiplication might be unrolled into smaller, atomic operations to optimize execution.

The orchestration layer is responsible for constructing the execution graph. It determines dependencies between the blocks and ensures that the graph adheres to the logical flow of the application. The edges in the graph define the dependencies between blocks, ensuring that the execution proceeds in a consistent and orderly manner. This structure allows the orchestration layer to distribute execution efficiently across available actors, optimizing parallelism and resource utilization. Dependencies between blocks are also captured on Orchestration Layer, enabling efficient scheduling and execution.&#x20;

### Process Creation

Once the execution graph is constructed, the system creates a process for the application, similar to traditional Operating systems. A process is an isolated execution entity that encapsulates all orders (blocks of instructions), data and the associated execution context. This approach ensures isolation between different application runs, providing security and stability for the decentralized environment. The process serves as a container for managing the application’s lifecycle, including task execution, resource management, and context handling. It maintains the state of the execution and acts as a boundary for resource allocation and data flow.

### Task Assignment and Actor Selection.&#x20;

The assignment of tasks to specific actors is managed through a decentralized order book. This mechanism allows actors to compete for tasks based on various factors, such as their capabilities, availability, performance history and cost of the computation. The decentralized order book ensures fairness and transparency in task management.

### Execution and Result Aggregation.&#x20;

Once an actor is assigned an order, it retrieves the associated execution context and begins processing the instructions within the block. Key aspects of this phase include:

* Actors execute instructions based on the provided context, handling both atomic and complex operations.
* Dependent orders in the execution graph are activated as their prerequisites are completed, enabling parallelism and efficient resource utilization.
* The Orchestration Layer monitors task progress and ensures that results are correctly propagated through the graph.

```markup
```


# Verification Layer


# Execution Layer

The Execution Layer is composed of a heterogeneous network of computational nodes, referred to as actors, which are capable of executing instructions defined by the virtual machine. Each actor may support a subset of the available instructions. For example, some actors may specialize in instructions related to a specific encryption scheme, while others may support a single operation, such as ciphertext multiplication.

When registering as an actor, the node specifies the list of instructions it can execute, along with metadata describing its performance characteristics. This information is crucial for task allocation and ensures that actors are matched to tasks that align with their capabilities. Actors also have the flexibility to modify their supported instruction set at any time, enabling them to adapt to changing workloads or optimize for specific tasks.

As described in Section 5.5, during the assignment of an actor to a task(block of instructions), the system considers the actor’s declared capabilities. It ensures that actors are only assigned blocks consisting of instructions they explicitly support. This guarantees efficient and reliable execution, even in a heterogeneous environment with actors of varying specializations.

We discuss actors in more details in section 5.8


# Data Layer

Given the strict limitations and high costs of data storage in blockchain networks like Ethereum, and considering that the volume of ciphertexts and keys for Fully Homomorphic Encryption can reach several gigabytes, we have adopted a strategy to avoid placing such large amounts of data directly on the blockchain. Instead, we utilize IPFS-based external data storage to manage the data. This approach not only addresses the storage limitations and cost inefficiencies but also ensures efficient, scalable, and decentralized data management. On the on-chain side, instead of storing the ciphertexts and keys themselves, we only place commitments and meta-data corresponding to the files located on the external storage. The blockchain serves as a form of a hash table, pointing to the location of the data and ensuring their integrity and authenticity through a system of data commitments. This allows us to optimize the costs of using the blockchain while providing a reliable and scalable infrastructure for working with encrypted data of arbitrary scale. This data storage model makes our platform ideally suited for a wide range of applications requiring high data confidentiality and security.


# ISA

Instruction Set Architecture

[Execution Layer](/fhe-computer/architectural-layers/execution-layer) functions as a multiprocessor, where the computational cores are represented by heterogeneous nodes, referred to as actors. These actors are heterogeneous because they may vary in two key aspects:&#x20;

* the subset of instructions they support
* the specific implementations they use for those

This design provides the flexibility to accommodate a wide range of actors with diverse computational capabilities, enabling scalability and specialization.

The Instruction Set Architecture (ISA) of the FHE Computer defines a canonical set of instructions supported by Execution Layer. The instructions are the part of an executable program, stored on [Application Layer](/fhe-computer/architectural-layers/application-layer) and executed on Execution Layer. Actors in the FHE Computer can implement arbitrary subset of instructions.&#x20;

This approach allows specialization; for instance, some actors may focus exclusively on specific operations, such as encrypted arithmetic for a particular FHE scheme, while others may implement more general-purpose functionality. Importantly, the system guarantees that, for every instruction in the canonical instruction set, there is at least one actor capable of executing it at any given time.

To support this heterogeneous and extensible model, the ISA adopts a declarative approach. Inspired by the [MLIR](https://mlir.llvm.org), instructions are organized into logical groups called dialects, which categorize operations based on their purpose and domain. Each instruction specifies its required inputs and expected outputs but does not prescribe the exact implementation. This abstraction allows actors to optimize execution based on their capabilities while adhering to a standardized interface.

The instruction set is modularly organized into dialects, ensuring clarity, extensibility, and specialization. Each dialect groups a set of related instructions, facilitating straightforward management and seamless extension. Dialects are hierarchically structured, allowing sub-dialects to be nested within parent dialects. This approach supports fine-grained categorization and flexibility in defining operations across various computational domains.

There are 4 top level dialects:&#x20;

* **arith**
* **tensor**
* **fhe**
* **polycircuit**

{% hint style="info" %}
Full list of instructions can be found in [Whitepaper](https://github.com/fairmath/research/blob/main/Decentralized%20FHE%20Computer.pdf).
{% endhint %}

For instance, the top level `fhe` dialect includes sub-dialects such as `fhe.bgv` and `fhe.ckks` which define instructions specific to the BGV and CKKS encryption schemes, respectively. At the meantime `fhe` dialect defines unified data types, such as `RLWECiphertext`, `RLWEPlaintext` that shared across sub-dialects. While different encryption schemes may utilize different encoding techniques, we would like to provide some universal layer for FHE schemes based on the same math problem, like (R)LWE. T


# fhe

`fhe` dialect includes operations for encrypted data computations. This dialect is further divided into subgroups based on the encryption scheme, such as `fhe.bgv` and `fhe.ckks`, allowing tailored operations for each scheme. Within each subgroup, operations like addition, multiplication, and rotations are defined.

### Examples

<pre data-overflow="wrap"><code>//Adds two ciphertexts using the BGV scheme.
%result = fhe.bgv.add %lhs, %rhs, %ctx : (RLWECiphertext, RLWECiphertext, BGVCryptoContext) -> RLWECiphertext

<strong>//Rotates coefficients of a CKKS ciphertext by the specified offset. 
</strong>%rot = fhe.ckks.rotate %ciphertext, %offset, %ctx, %key : (RLWECiphertext, i32, CKKSCryptoContext, RLWEGaloisKey) -> RLWECiphertext

</code></pre>


# arith

The `arith` dialect provides foundational operations for working with basic types. It includes instructions for basic arithmetic, logical operations, and comparisons. This dialect is flat, with no subgroups, and focuses entirely on non-encrypted types.&#x20;

### Examples

```
\\Adds two integers and returns an integer result.
%sum = arith.add %a, %b : (i32) -> i32

\\Compares two 64-bit integers for equality, returning a Boolean result.
%eq = arith.eq %x, %y : (i64) -> bool
```


# tensor

The `tensor` dialect supports operations on multidimensional arrays, commonly used in machine learning and linear algebra computations. While the initial implementation is flat, future versions may include subgroups for specialized tensor operations (e.g., sparse tensors).

### Examples

{% code overflow="wrap" %}

```
//Creates a 1-dimensional tensor of size 
%tensor = tensor.create %shape : (i32) -> tensor<[n]> 

// Performs element-wise addition on two 4x4 tensors.
%result = tensor.add %t1, %t2 : (tensor<[4]x[4]>, tensor<[4]x[4]>) -> tensor<[4]x[4]>
```

{% endcode %}

```
```


# polycircuit

The `polycircuit` dialect provides high-level operations mapped to reusable FHE components, enabling complex computations such as neural network activations and polynomial evaluations. These operations often work across multiple ciphertexts and contexts.

### Examples

{% code overflow="wrap" %}

```clike
//Applies the ReLU activation function to an encrypted input.
%relu_out = polycircuit.relu %ciphertext, %ctx : (RLWECiphertext, Context) -> RLWECiphertext

//Evaluates a polynomial defined by the coefficients on an encrypted input. 
%eval = polycircuit.poly_eval %coeffs, %ciphertext, %ctx : (tensor<[n]>, RLWECiphertext, Context) -> RLWECiphertext
```

{% endcode %}


# Operating System

The operating system of the Fair Math FHE Computer is built on a blockchain infrastructure, providing a decentralized framework for resource management and task allocation. It functions as a distributed scheduler, orchestrating workloads across heterogeneous actors based on their computational capabilities and supported instruction subsets. Leveraging blockchain technology, the system ensures deterministic resource allocation, verifiable exe- cution, and secure state transitions. This approach enables transparent interaction between actors, immutability of task assignments, and seamless integration of new computational nodes into the network.


# Computer State

The computer can be conceptualized as a state machine, with its state evolving deterministically based on transactions recorded on the chain. At any given moment, the computer resides in a well-defined state, characterized by multiple parameters and factors such as:

* **Resource Availability:** The allocation and utilization of computational, memory, and network resources across the decentralized network of actors.
* **Task Queue:** The current set of tasks awaiting execution, their priority levels, and the mapping of tasks to specific actors.
* **Actor States:** The operational status of each actor, including supported instructions, current workloads, and performance metrics.
* **Deployed Applications:** Metadata and configurations for applications running on the computer, including active jobs, required cryptographic keys, and runtime dependencies.
* **Transaction History:** Immutable records of task submissions, resource allocations, and interactions between system components.

  The blockchain acts as the single source of truth, ensuring that the state of the computer evolves in a transparent and tamper-proof manner. Transactions on the chain serve as the triggers for state transitions, which may include deploying new applications, assigning tasks to actors, or reallocating resources.


# Application

An application in the Fair Math Computer consists of two main components:

1. **External Functions** — These are functions that take input and return output. Each function performs a specific sequence of instructions and serves as an entry point to the application. Importantly, these functions cannot directly call other functions within the same application.
2. **Global Variables** — These are variables available throughout the application's execution. They can have various types, such as integers, arrays, or ciphertexts.

By default, the application starts with the **main** function unless another function is explicitly specified. The main function acts as the primary entry point.

When an application is launched, a **process** is created. This process remains active until the application explicitly calls the **exit** function (or is terminated by the operating system). The process manages the application’s state, resources, and execution flow throughout its lifecycle.


# Running Applications

Applications in the Fair Math Computer are triggered through **transactions**, which can perform two types of actions:

1. **Starting a New Application**\
   A transaction can launch a new application by providing its unique identifier and any required input arguments. This creates a new **process** linked to the application. The process starts executing from the specified entry point or the **main** function by default.
2. **Calling a Specific Function**\
   A transaction can directly call an external function within a running application by providing the following details:
   * **Application ID**: Uniquely identifies the target application.
   * **Function Name**: Specifies the function to invoke as the entry point.
   * **Process ID**: Links the call to the correct application process.\
     Input arguments can be passed dynamically, enabling flexible interaction with the application during its execution.


# External Functions

Functions in  applications are strictly external, meaning they can only be invoked through trans- actions from outside the application or by the orchestration layer. Direct function calls from one function to another within the same application are not supported. This design ensures:

* Clear separation of entry points, simplifying execution flow.
* Modular interaction with the application, as each function operates independently. &#x20;
* Improved transparency and security by explicitly restricting internal function calls.


# Interactive APPS

The application model inherently supports the development of interactive applications. By defining multiple external entry points and supporting dynamic invocation of functions, developers can implement applications that:

* Trigger new computations in response to external events.
* Maintain shared state across invocations through global variables V.
* Respond to user input or other asynchronous triggers, enabling dynamic and stateful workflows.


# Execution Graph and Tasks

In the Fair Math Computer, a **task** is the smallest unit of execution managed by the orchestration layer. A task consists of the following components:

1. **Instructions**\
   A task includes an ordered set of instructions that define its operations. This set must not be empty.
2. **Variables**\
   These are the variables used or created by the instructions in the task.
3. **Metadata**\
   Metadata provides additional information about the task, including:
   * **Resource requirements** (e.g., memory or compute power needed).
   * **Estimated complexity** of the task.
   * **Execution constraints**, such as deadlines or specific capabilities required.

A task is valid if it has at least one instruction and all instructions are compatible with the dependencies of the application.


# Atomic and Composite Instructions

Instructions in a task are categorized into two types: **atomic** and **composite**.

1. **Atomic Instructions**\
   These are simple, indivisible operations that can be directly executed by the system’s Instruction Set Architecture (ISA). For example:
   * `arith.mul` (multiplication of two ciphertexts).\
     Atomic instructions require no further breakdown and are ready to be executed as-is.
2. **Composite Instructions**\
   These are higher-level operations that consist of multiple atomic instructions. For example:

   * `polycircuit.relu` (a non-linear activation function).\
     A composite instruction like `RELU` might be implemented as a sequence of comparisons, multiplications, and additions.

   The orchestration layer can **unroll** composite instructions into their atomic components when:

   * No system actor is available to execute the composite instruction directly.
   * Breaking the composite instruction down allows better parallel execution or resource usage.


# Instruction Unrolling

Unrolling involves replacing a composite instruction with its sequence of atomic instructions. For example:

* A composite instruction `I_composite` is expanded into atomic instructions `{I_atomic_1, I_atomic_2, ..., I_atomic_k}`.

This process ensures tasks are executed efficiently by dynamically adjusting their granularity.


# Task Dependencies

Tasks are dependent on one another when one task uses variables modified by another. For example:

* **Task A** modifies a variable.
* **Task B** uses the modified variable from Task A.

In such cases, **Task B** depends on **Task A** and must wait for it to complete before starting. Dependencies help ensure proper execution order and resource management.


# Execution Graph

The breakdown of a function into tasks is represented as a **directed acyclic graph (DAG)**, called the **execution graph**. The graph consists of:

* **Nodes (Tasks):** Each task in the function is a node in the graph.
* **Edges (Dependencies):** Directed edges between tasks represent dependencies, meaning one task must be completed before another can start.

<figure><img src="/files/cI927mMP5w9sAUiSjQyd" alt=""><figcaption><p>Execution graph example</p></figcaption></figure>

Key Features of the Execution Graph

1. **Dynamic Refinement:**\
   The orchestration layer can break tasks into smaller subtasks if needed, allowing for more flexible and efficient scheduling.
2. **Instruction Expansion:**\
   Composite instructions within tasks can be expanded into their atomic components, ensuring they can be executed by available resources.

This adaptability allows the system to optimize task execution based on available resources and workload while maintaining proper dependency order.


# Process

In the Fair Math Computer, a process represents an instance of an application in execution. Processes are ephemeral entities that encapsulate the state, resources, and execution context required to perform computations. They serve as the primary abstraction for managing the execution lifecycle of applications, ensuring isolated, secure, and efficient operations in a decentralized environment.


# Process lifecycle

The lifecycle of a process in the Fair Math Computer includes the following key stages:

1. **Initialization:** A process is created when a user or actor invokes an application. During initialization, the process is assigned a unique identifier and its initial state is constructed based on the application’s configuration file and input arguments.
2. **Execution:** The process executes the instructions defined in the application. Exe- cution is distributed across the network, leveraging the computational resources of heterogeneous actors. The system ensures the correctness and integrity of execution through cryptographic guarantees.
3. **Suspension and Resume:** In cases where a process requires external input or encounters resource constraints, it can be suspended. The process state is serialized and stored securely on the blockchain, allowing it to be resumed later without loss of progress.
4. **Termination:** Once the execution completes, the process is terminated. The final state, including any results, is recorded on the blockchain, and all associated resources are released.


# Resource Allocation and Isolation

Each process operates in a sandboxed environment, ensuring that it cannot interfere with other processes or access unauthorized resources. Resource allocation is managed by the blockchain-based operating system, which dynamically assigns actors and computational capacity to processes based on workload, priority, and availability.

The concept of processes in the Fair Math Computer ensures that applications ex- ecute reliably, securely, and efficiently, forming a robust foundation for decentralized computations.


# Order Book

In the system, the fundamental unit of planning is a task. A task is defined as a set of one or more instructions from the Instruction Set Architecture (ISA). The allocation of tasks to actors is managed at the Orchestration Layer through the order book.

Each task that requires execution is transformed into an order. An order encapsulates the task along with its associated metadata, which specifies the requirements for execution. This metadata includes:

* **Deadline:** The maximum allowable time for task completion.
* **Maximum Reward:** The upper limit of compensation for completing the task.
* **Complexity:** A quantitative measure of the computational resources required for execution.


# Matching Mechanism

Tasks are assigned to actors through an **order book**, which functions similarly to a traditional order matching system in trading platform. Actors submit **bids** based on their available resources and capabilities, and the order book manages the following:

1. **Task Assignment**\
   Matches tasks with actors who submit suitable bids for execution.
2. **Execution Monitoring**\
   Ensures tasks are completed within specified parameters, such as deadlines and complexity limits.
3. **Incentive Structuring**\
   Rewards actors for successfully completing tasks and applies penalties for failing to meet deadlines.

This system enables decentralized, efficient, and scalable workload distribution, while maintaining transparency in actor participation and performance.

####


# Task Complexity

Each task in the system is associated with a **complexity metric**, which quantifies the computational effort required for its execution. The task's complexity is calculated as the sum of the complexities of all its instructions:

* The complexity of a task is determined by adding up the complexity values of its individual instructions.
* This metric helps evaluate and allocate tasks to actors with appropriate resources.


# Instruction Complexity

The complexity of an instruction depends on its type, the input arguments it processes, and the cryptographic parameters influencing its execution. For operations involving encrypted data, the same instruction can have varying complexity based on the input ciphertexts and the cryptographic context.

#### Factors Affecting Instruction Complexity

1. **Input Arguments**\
   The data passed to the instruction, such as ciphertexts, influences complexity.
2. **Cryptographic Parameters**\
   Contextual settings that define the operational environment, including:
   * **Ring Dimension (N):** Determines the size of polynomial arithmetic, affecting computational cost.
   * **Scaling Factor (Δ):** Influences the precision of encrypted computations.
   * **Security Level:** Indicates the cryptographic strength and associated resource requirements.

#### Example: Encrypted Multiplication

For the instruction `fhe.bgv.mult` (multiplication of encrypted values), the complexity is affected by:

* **Ciphertexts:**
  * **Multiplicative Depth (D):** Indicates how many operations have been performed on the ciphertext. Higher depth increases complexity due to relinearization and modulus switching.
* **CryptoContext Parameters:**
  * **Ring Dimension (N):** Governs the cost of polynomial operations.
  * **Scaling Factor (Δ):** Affects the precision and associated computation.

For each instruction there is cost function that evaluates its complexity based on the given input and cryptographic environment.&#x20;


# Task re-Delegation

Actors can re-delegate tasks or parts of tasks back to the order book. This introduces a dynamic and scalable approach to task execution.

For instance, an actor may take on a complex task consisting of several components. During execution, the actor can decide:

* To execute the components locally if it is efficient in terms of time and resources.
* To place some instructions back into the order book if delegation is deemed more cost-effective.

This capability transforms actors into local, partial orchestrators capable of dynamically adapting to changing conditions. If, during task execution, an actor determines that delegating specific instructions to other actors will result in faster or cheaper execution, it can initiate this process. The delegated instructions are returned to the order book, becoming available to other actors.

The detailed process of Application running is depicted below

<figure><img src="/files/KceUZOgbmV0c3m0BWirf" alt=""><figcaption></figcaption></figure>


# Context

The Context is a concept in our Computer model, representing the state of the process. It acts as a container for all relevant data, including variables, their current values, and additional parameters required for executing assigned tasks.

When an actor is assigned a task, the associated context is passed to it. This context includes the current state of all accessible variables and any necessary cryptographic infor- mation, such as keys or the cryptographic context. As the actor executes the instructions, it generates a new context that reflects the updated state. This new context is then submitted to the blockchain, where it updates the global state of the relevant process.

The context serves as the medium through which actors communicate the results of their computations, including intermediate results. Throughout the execution of the application, the context evolves, and a final context is formed and saved once the application completes. While the context itself is stored on the blockchain, it is designed to be lightweight. Large objects, such as arrays and ciphertexts, are stored on external data layers, with the context containing only references (e.g., hashes) to these objects. This design ensures efficiency and scalability.


# Context Structure

#### Context Representation

The **context** in the Fair Math Computer is a JSON-like object that organizes information into the following sections:

1. **`fhe`**\
   Contains cryptographic data, including:
   * Public keys.
   * Rotation keys.
   * Cryptographic contexts.
2. **`args`**\
   Represents command-line-style arguments provided to the application during execution.
3. **`vars`**\
   Describes all variables used in the process. Each variable entry includes:
   * **`id`**: Unique identifier for the variable.
   * **`basetype`**: The base type of the variable (e.g., `i32`).
   * **`is_secret`**: A boolean indicating whether the variable is encrypted.
   * **`is_array`**: A boolean indicating whether the variable is an array.
   * **`storage`**: Specifies where the variable's value is stored (e.g., `local` or `ipfs`).
   * **`value`**: The current value of the variable, either directly or as a reference (e.g., an IPFS hash).

#### Example Context File

Below is an example of context file:

```json
{
    "vars": {
        "%arg0": {
            "basetype": "",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "ipfs.QmXR5FDSupU6ZKxxkU95WcywhmAvykLZbNEqtcu2P3M43a"
        },
        "%arg2": {
            "basetype": "i32",
            "is_array": true,
            "is_secret": false,
            "storage": "ipfs",
            "value": "ipfs.QmfZhqPFDZmyK4rAxwDH5FTHeQGrJjDFbRJ1WDzW4qpF1P"
        },
        "%mul_key": {
            "basetype": "CKKSMulKey",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "ipfs.QmT4xPQnAkZXR6PGDySaVZ4kBPbHdkVi2TqZgUZdREhfa7"
        },
        "pk": {
            "basetype": "CKKSPublicKey",
            "is_array": false,
            "is_secret": false,
            "storage": "ipfs",
            "value": "ipfs.QmeA4jDooaoR4G2amHtnQKGpRD4eEdfVZSLjARDFF5HJq4"
        }
    }
}
```

This structure allows the system to organize and manage cryptographic and process-related information efficiently, ensuring seamless application execution.


# FHE Component Repository

The **Component Repository** is a dynamic library of FHE components that serve as modular building blocks for applications stored on blockchain level. These components are implemented as functions built from ISA instructions, providing high-level abstractions for cryptographic computations, such as `ReLU`, `Sign`, or polynomial evaluation.

#### Key Features of the Component Repository

1. **High-Level Abstraction**\
   Components act like **intrinsics** in traditional computing, offering optimized and reusable functionality while hiding the complexity of their implementation. They allow developers to leverage advanced cryptographic operations without needing deep knowledge of the underlying algorithms.
2. **Integration with `polycircuit` Dialect**\
   Components dynamically form the **`polycircuit` dialect** within the Instruction Set Architecture (ISA). This dialect provides specialized instructions for invoking components, ensuring seamless integration into computational pipelines with flexibility and efficiency.
3. **Composability**\
   Components can call other components within their implementation. For instance, a neural network component may internally use activation functions (e.g., `ReLU`, `Sigmoid`) or pooling operations. This composability simplifies the construction and maintenance of complex algorithms.

#### Incentive Mechanism

To encourage the creation of high-quality, reusable components:

* **Developers are rewarded** when their components are used in applications. A proportional share of the rewards generated by the application's execution is distributed to the component’s creator.
* This mechanism fosters a vibrant ecosystem, motivating developers to contribute and maintain robust components.

#### Repository Management

The repository is managed through the **FHERMA** platform, which:

* **Validates** components for security and compatibility.
* **Benchmarks** them to ensure optimal performance.
* **Version-controls** the components to maintain consistency and reliability.


# Fair Math Actors

The execution layer of Fair Math relies on **actors**, which are responsible for executing tasks. When an application runs, it is broken down into a set of independent tasks $$(T\_1, T\_2, \dots, T\_n)$$ . Each task  $$T\_i$$  is assigned to an actor $$A\_{m,i}$$ for execution.

Blockchain-Level Task Monitoring

At the blockchain level:

* Tasks are **not continuously tracked**.
* Completion is verified **only when deadlines expire**.
* If a task is incomplete by its deadline, the orchestration layer:
  * Reassigns the task.
  * Penalizes the responsible execution pair.

This approach reduces computational overhead and improves scalability.

####


# Task State Monitoring

Directly tracking the state S(A) of an actor during task execution on the blockchain adds unnecessary complexity. To streamline this process:

* **State tracking** is delegated to the actors themselves.
* **Execution Pairs** are introduced to ensure task reliability.


# Execution Pairs

An **execution pair** consists of:

1. **Main Actor** $$A\_{m,i}$$
   * Executes the assigned task $$T\_i$$.
   * Monitors the state of the fallback actor $$A\_{f,i}$$.
2. **Fallback Actor** $$A\_{f,i}$$
   * Monitors the main actor $$A\_{m,i}$$.
   * Takes over if the main actor fails $$S(A\_{m,i}) = \text{failed}$$.
   * Notifies the orchestration layer to assign a new fallback actor.

The state of an actor $$S(A)$$ can either be:

* **Active**: The actor is performing its assigned task.
* **Failed**: The actor is unable to complete the task.

The state of an execution pair $$P\_i$$ is considered **operational** if at least one actor in the pair is active:\
$$\[ S(P\_i) = \text{operational} \iff S(A\_{m,i}) = \text{active} \vee S(A\_{f,i}) = \text{active}. ]$$\
If both actors in the pair fail, the orchestration layer reassigns both roles.


# Rewards and Penalties

For each task $$T\_i$$: Rewards $$R\_i$$ and penalties $$P\_i$$ are distributed between the main actor $$A\_{m,i}$$ and the fallback actor $$A\_{f,i}$$.\
This incentivizes reliability and ensures accountability in the system.


# Ethereum Endpoint

TBD


# CIFAR10 App

We deployed privacy preserving CIFAR recognition as the first APP example.&#x20;

\
[CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) is a widely recognized dataset comprising 60,000 color images of size 32x32 pixels, categorized into 10 classes such as automobiles, airplanes, dogs, etc. This dataset serves as a standard benchmark for machine learning algorithms in computer vision.

The CIFAR10 APP implements a machine learning model capable of efficiently classifying encrypted images without decrypting them.

#### Input

Each image is encoded as a real vector with a dimension of 3072=3x1024. The initial 1024 slots denote the red channel, the subsequent ones denote green, and the final segment denotes blue. Each slot stores value in the range \[0, 255].&#x20;

#### Output

The outcome of the computation is governed by the initial 10 slots in the resultant ciphertext. If the input image belongs to class `i`, then within the first 10 slots of the resultant vector the maximum value will be located in slot `i`.

\ <br>


# FHERMA

https\://fherma.io

FHERMA is a platform for Fully Homomorphic Encryption (FHE) challenges jointly developed by **Fair Math** and the **OpenFHE** teams.

The project's main goal is to develop an open-source library of FHE components. Such a library can significantly simplify application development and accelerate the adoption of FHE. The initial challenges are focused on **Machine Learning** and **Blockchain** applications.

On the platform, there are two types of challenges:

1. **Black Box:** In this type of challenge, participants develop solutions according to the challenge requirements, process encrypted test data, and submit to the platform only the serialized final ciphertext. This type of challenge does not require submitting source code or any other data that reveals the details of the solution itself. The main criterion for evaluating and ranking solutions in this type of challenge is accuracy.
2. **White Box:** It is impossible to evaluate the solution's performance based solely on the ciphertext. While the Black Box type is suitable for many challenges, it is crucial to obtain the most efficient solution from a performance perspective for others. For these, the White Box type is available. Participants must submit their projects' source code to the platform. The platform will compile the project and run tests to measure performance and accuracy. The main criteria for evaluating and ranking solutions in this type of challenge are performance and accuracy. Solutions uploaded to the platform are confidential and unavailable to other participants.

{% embed url="<https://www.ibm.com/blog/ibm-researchers-to-publish-fhe-challenges-on-the-fherma-platform/>" %}

Challenges on [FHERMA](https://fherma.io/) are being solved using one of three languages:

* Go - using [lattigo](https://github.com/tuneinsight/lattigo)
* Python - using [openfhe-python](https://github.com/openfheorg/openfhe-python)
* Rust - using [openfhe-rs](https://crates.io/crates/openfhe)
* C++ - using [openfhe](https://www.openfhe.org/)

We collect winning solutions and put them into the open-source repository [Polycircuit](https://github.com/fairmath/polycircuit). Check out the relevant [documentation page ](https://github.com/fairmath/openfhe-rs/blob/00-docs/gitbook-docs/README%20\(1\).md)to learn more about the collaborative idea behind it.

{% embed url="<https://www.youtube.com/watch?v=Fyu0RJ2bhuI>" %}
Talk about FHERMA and behind
{% endembed %}


# Talks and Podcasts

### Scalable MLIR Based FHE Compiler |  FHE Summit II

{% embed url="<https://youtu.be/9dvVxbxUmGo?si=sJVYXhSBSTsq5IbU>" %}

### FHECon Panel at Token 2049

{% embed url="<https://youtu.be/RX5hnCFYd5E?si=_LYuuGBbvuovFE-H>" %}

### TUM Blockchain Conference 2024

{% embed url="<https://youtu.be/eUEj_bJ_14c?si=8egdraJu1NXg1NRw>" %}

### Verifiable summit 2024

{% embed url="<https://youtu.be/sjK7eM1b_ks?si=3jovPcV7Uo4004NO>" %}

### FHE Summit during ETHCC 2024

{% embed url="<https://youtu.be/cbui8-0QhuI?si=6yT9wi_WRM6ld0yF>" %}

### FHEOnChain talk with Gurgen and Elvira

{% embed url="<https://youtu.be/Fyu0RJ2bhuI?si=RahOS43T_mq60A9j>" %}

### Gurgen’s interview

{% embed url="<https://youtu.be/IiJzZ8dRrcs?si=Uj3tONIhNc4xBDw4>" %}


