Lux Docs
Lux Skills Reference

Lux FHE - Fully Homomorphic Encryption

Documentation for Lux FHE - Fully Homomorphic Encryption

Overview

Lux FHE (github.com/luxfi/fhe) is a pure-Go Fully Homomorphic Encryption library and complete FHE ecosystem for the Lux Network. It provides TFHE boolean gate evaluation with programmable bootstrapping, integer arithmetic via radix decomposition, CKKS approximate arithmetic, threshold decryption (t-of-n), lazy carry propagation, SIMD-optimized NTT, and a standalone HTTP daemon (fhed). The monorepo also contains JavaScript SDKs, Solidity contracts, WASM bindings, Python ML integration, Hardhat/Foundry plugins, and 25+ example applications.

Why

FHE enables computation on encrypted data without decryption. On a blockchain, this means smart contracts can process encrypted balances, votes, bids, and analytics while the underlying values remain hidden. Lux FHE is the cryptographic foundation for confidential EVM execution on Lux C-Chain and T-Chain.

Tech Stack

LayerTechnology
Core libraryGo 1.25.5, pure Go (no CGO required)
Lattice primitivesgithub.com/luxfi/lattice/v7 (LWE, RLWE, RGSW, blind rotation, NTT)
ThresholdGo (pkg/threshold/) with LSSS (Shamir) over 256-bit prime field
Cluster discoverygithub.com/luxfi/mdns (mDNS/DNS-SD, zero-config)
Daemonfhed v0.3.0, HTTP API, urfave/cli/v3
JavaScript SDKs@luxfhe/v1-sdk (single-key), @luxfhe/v2-sdk (threshold), TypeScript
Solidity contracts@luxfhe/contracts (FHE.sol, FheOS.sol, IFHE.sol, token/finance/governance)
WASM@luxfhe/wasm (TFHE in browser/Node.js via conditional exports)
KMS bindings@luxfhe/kms (web + node)
Pythonluxfhe package (CKKS context, GPU acceleration via Metal/CUDA)
PluginsHardhat plugin, Remix IDE plugin
TemplatesHardhat, Foundry, Next.js, Nuxt, React, Vue, Scaffold-ETH2, miniapp
PapersLaTeX: bootstrapping optimization, FHE integers, multiparty HE, threshold FHE, threshold RNG

Key Dependencies

PackageVersionPurpose
github.com/luxfi/lattice/v7v7.0.0LWE/RLWE/RGSW primitives, blind rotation, ring operations
github.com/luxfi/mdnsv0.1.0mDNS peer discovery for threshold clusters
github.com/urfave/cli/v3v3.6.2CLI framework for fhed
github.com/google/uuidv1.6.0Session and node IDs

OSS Base

Pure-Go implementation built on github.com/luxfi/lattice (fork of Lattigo lattice library). No upstream TFHE dependency in the Go core -- the boolean FHE scheme is implemented from scratch using lattice primitives. The broader ecosystem (FHEVM, coprocessor, Rust KMS) is based on Zama's toolchain -- see lux/lux-fhevm.md for that layer.

When to use

  • Implementing FHE boolean circuits or integer arithmetic in Go
  • Building a confidential smart contract that needs encrypted types (ebool, euint4..euint256)
  • Running an FHE daemon for encrypt/decrypt/evaluate operations
  • Setting up threshold decryption with mDNS cluster discovery
  • Building a dApp frontend that encrypts user input before sending to chain
  • Writing Solidity contracts using FHE.add(), FHE.sub(), FHE.mul() on encrypted values
  • Machine learning on encrypted data (Python CKKS with luxfhe package)
  • Implementing custom FHE precompiles for the Lux EVM

Hard requirements

  • Go >= 1.25.5 for the core library
  • github.com/luxfi/lattice/v7 -- never use raw Lattigo or any other lattice library
  • github.com/luxfi/mdns for peer discovery (local replace in go.mod: replace github.com/luxfi/mdns => ../mdns)
  • Pure Go mode works with CGO_ENABLED=0; GPU acceleration requires CGO_ENABLED=1 plus github.com/luxfi/gpu
  • Node.js 18+ for JavaScript SDKs
  • Solidity ^0.8.24 for FHE contracts
  • FHE types: FheBool, FheUint4, FheUint8, FheUint16, FheUint32, FheUint64, FheUint128, FheUint160 (Ethereum addresses), FheUint256
  • Never reference Zama, TFHE-rs, or Concrete in the Go core -- those belong to the FHEVM layer

Quick reference

ItemValue
Go modulegithub.com/luxfi/fhe
Go version1.25.5
fhed version0.3.0
LicenseBSD-3-Clause (core), Lux Ecosystem License 1.2
Local path~/work/luxfhe/
Daemon port8448 (default)
Default paramsPN10QP27 (N=1024, ~128-bit security)
SchemesTFHE (boolean gates), Radix integers (1-256 bit), CKKS (approximate)
Security levels128/192/256-bit classical; 128/192/256-bit post-quantum
Bootstrap methodsAP, GINX, LMKCDEY (fastest, Gaussian secrets)
OpenFHE compatSTD128, STD128Q, STD192, STD192Q, STD256, STD256Q parameter sets

One-file quickstart

package main

    "fmt"
    "github.com/luxfi/fhe"
)

func main() {
    // 1. Setup: create parameters and generate keys
    params, _ := fhe.NewParametersFromLiteral(fhe.PN10QP27)
    kg := fhe.NewKeyGenerator(params)
    sk, _ := kg.GenKeyPair()
    bsk := kg.GenBootstrapKey(sk)

    // 2. Create encryptor, decryptor, evaluator
    enc := fhe.NewEncryptor(params, sk)
    dec := fhe.NewDecryptor(params, sk)
    eval := fhe.NewEvaluator(params, bsk)

    // 3. Encrypt two bits
    ctTrue := enc.Encrypt(true)
    ctFalse := enc.Encrypt(false)

    // 4. Evaluate boolean gates on encrypted data
    ctAnd, _ := eval.AND(ctTrue, ctFalse)
    ctOr, _ := eval.OR(ctTrue, ctFalse)
    ctXor, _ := eval.XOR(ctTrue, ctFalse)
    ctNot := eval.NOT(ctTrue)

    // 5. Decrypt results
    fmt.Println("AND:", dec.Decrypt(ctAnd))   // false
    fmt.Println("OR:", dec.Decrypt(ctOr))     // true
    fmt.Println("XOR:", dec.Decrypt(ctXor))   // true
    fmt.Println("NOT:", dec.Decrypt(ctNot))   // false

    // 6. Integer arithmetic (bitwise approach)
    bwEnc := fhe.NewBitwiseEncryptor(params, sk)
    bwDec := fhe.NewBitwiseDecryptor(params, sk)
    bwEval := fhe.NewBitwiseEvaluator(params, bsk, sk)

    a := bwEnc.EncryptUint64(42, fhe.FheUint8)
    b := bwEnc.EncryptUint64(10, fhe.FheUint8)
    sum, _ := bwEval.Add(a, b)
    fmt.Println("42 + 10 =", bwDec.DecryptUint64(sum)) // 52
}

Core Concepts

Architecture

github.com/luxfi/fhe
├── Core Go Library (package fhe)
│   ├── fhe.go            Parameters, keys, key generation
│   ├── encryptor.go      Boolean encryption (secret key)
│   ├── decryptor.go      Boolean decryption
│   ├── evaluator.go      Boolean gates: AND, OR, XOR, NOT, NAND, NOR, XNOR, MUX, MAJORITY
│   ├── shortint.go       ShortInt (1-4 bit values, LUT-based PBS)
│   ├── integers.go       RadixCiphertext (arbitrary-width integers via radix blocks)
│   ├── integer_ops.go    Comparison, bitwise, shift, select operations on radix integers
│   ├── bitwise_integers.go  BitCiphertext (integers as bit vectors, boolean-circuit approach)
│   ├── lazy_carry.go     LazyCarryInteger (deferred carry propagation, 10-16x PBS reduction)
│   ├── security.go       Security levels (STD128..STD256Q), OpenFHE-compatible params
│   ├── serialization.go  Binary serialization for keys, ciphertexts
│   ├── ntt_simd.go       SIMD-optimized NTT engine (AVX2/AVX-512/NEON)
│   ├── random.go         FheRNG (deterministic encrypted random numbers)
│   ├── threshold_rng.go  ThresholdRNG (threshold network randomness)
│   └── profile.go        CPU/memory/block/mutex profiling (build tag: profile)

├── pkg/threshold/        Threshold FHE (LSSS Shamir secret sharing)
│   ├── keygen.go         Distributed key generation, key shares
│   └── lsss.go           Shamir secret sharing over 256-bit prime field

├── pkg/membership/       Dynamic cluster membership management
│   └── membership.go     Member tracking, quorum detection, change handlers

├── cmd/fhed/             FHE daemon (HTTP server, standard + threshold modes)
├── cmd/crdt/             Encrypted CRDT demo
├── cmd/mediaseal/        Media sealing with FHE
├── cmd/provenance/       Content provenance tracking
├── cmd/seal/             Data sealing utility
├── cmd/stats/            Encrypted statistics computation
├── cmd/vote/             Encrypted voting demo

├── luxfhe/               Python package (CKKS context, GPU acceleration)
│   ├── core/             Context, keys, ciphertext, backend
│   ├── compiler/         Python-to-FHE compiler
│   ├── ml/               ML with FHE
│   └── numpy/            NumPy integration for encrypted arrays

├── js/                   JavaScript SDKs
│   ├── v1-sdk/           @luxfhe/v1-sdk (single-key TFHE, simpler, lower latency)
│   ├── v2-sdk/           @luxfhe/v2-sdk (threshold TFHE, t-of-n decryption)
│   └── permit/           Permit handling utilities

├── packages/             Additional packages
│   ├── kms/              @luxfhe/kms bindings (web + node)
│   ├── wasm/             @luxfhe/wasm TFHE bindings (browser + node)
│   ├── hardhat-*/        Hardhat integration packages
│   └── luxfhejs/         Legacy JS bindings

├── relayer-sdk/          Relayer SDK for FHEVM protocol (TypeScript)
├── sdk/                  Additional SDKs (Python, relayer)
├── wasm/sdk/             WASM SDK for browser-native FHE

├── examples/             25+ reference implementations
│   ├── blind-auction/    Sealed-bid auction (v1)
│   ├── blind-auction-v2/ Threshold sealed-bid auction (v2)
│   ├── confidential-voting/ Private ballot counting
│   ├── erc20-tutorial/   Confidential ERC20 token
│   ├── rps-game/         Rock-paper-scissors (v2, threshold)
│   ├── secret-santa/     Secret Santa assignment (v2)
│   ├── encrypted-crdt/   Encrypted CRDTs
│   ├── data-seal/        Data sealing patterns
│   ├── shadow-governance/ Shadow governance voting
│   ├── content-provenance/ Content authenticity
│   └── ... (15+ more)

├── templates/            Project starters (hardhat, foundry, next, nuxt, react, vue, scaffold-eth)
├── plugins/              Hardhat plugin, Remix IDE plugin
├── mocks/                Mock contracts for testing (Foundry)
├── research/             Research implementations
│   ├── ocp-fhe/          Open Compute Protocol for FHE
│   ├── threshold-paper/  Threshold TFHE benchmarks
│   ├── verifiable-fhe/   Verifiable FHE proofs
│   └── acm-threshold/    ACM threshold paper code
├── papers/               LaTeX papers (5 papers on bootstrapping, integers, multiparty, threshold, RNG)
├── proto/                Protobuf (decryption oracle)
├── docs/                 Documentation (resources, workshop materials)
└── tests/                E2E test suites (fhevm-suite)

Encryption Schemes

TFHE (Boolean) -- The core scheme. Each encrypted bit is an LWE ciphertext. Boolean gates (AND, OR, XOR, etc.) are evaluated via programmable bootstrapping using blind rotation with RGSW keys and test polynomials. Each gate produces a fresh ciphertext with reset noise.

Radix Integers -- Built on top of TFHE. Integers are decomposed into radix blocks (ShortInt, 2 or 4 bits each). Block-level operations use LUT-based programmable bootstrapping. Carry propagation chains blocks together. Supports euint4 through euint256.

Bitwise Integers -- Alternative integer approach using pure boolean circuits. Each integer is a vector of encrypted bits. Operations use ripple-carry adders, multipliers from basic gates. Simpler but more bootstrapping operations.

Lazy Carry Propagation -- Optimization for radix integers. Defers carry propagation across additions, amortizing expensive PBS operations. For euint256 with 8x32-bit limbs: traditional add costs 7 PBS for carry chain; lazy add (up to 16 ops) costs 0 PBS, with 7 PBS amortized on propagation. 10-16x PBS reduction for arithmetic-heavy workloads.

CKKS (Approximate) -- For floating-point operations on encrypted vectors. Available via the Python luxfhe package and the lattice library. Not directly in the Go core boolean FHE.

Parameter Sets

NameN_LWEN_BRQSecurityNotes
PN10QP2710241024~134M~128-bitDefault, good performance
PN11QP5420482048~2^54~128-bitHigher precision
PN9QP28_STD1285121024~2^28128-bit classicalOpenFHE compatible
PN9QP27_STD128Q5121024~2^27128-bit post-quantumOpenFHE compatible

OpenFHE-compatible sets (via SecurityParams): STD128_LMKCDEY, STD128Q_LMKCDEY, STD192_LMKCDEY, STD192Q_LMKCDEY, STD256_LMKCDEY, STD256Q_LMKCDEY. These use Gaussian secrets and LMKCDEY bootstrapping (fastest method).

FHE Types (for EVM integration)

TypeBitsGo constantSolidity
ebool1FheBoolebool
euint44FheUint4euint4
euint88FheUint8euint8
euint1616FheUint16euint16
euint3232FheUint32euint32
euint6464FheUint64euint64
euint128128FheUint128euint128
euint160160FheUint160euint160
euint256256FheUint256euint256

Boolean Gates

All gates operate on encrypted bits. Each gate performs programmable bootstrapping with a gate-specific test polynomial. NOT is free (ciphertext negation, no bootstrap).

GateInputsBootstrapAlgorithm
NOT1NoNegate ciphertext
AND2Yessum + TestPolyAND
OR2Yessum + TestPolyOR
XOR2Yes2*(sum) + TestPolyXOR (OpenFHE-style)
NAND2Yessum + TestPolyNAND
NOR2Yessum + TestPolyNOR
XNOR2Yes2*(sum) + TestPolyXNOR
MUX33x(sel AND a) OR (NOT(sel) AND b)
MAJORITY3Yessum + TestPolyMAJORITY (single bootstrap)
CMPCOMBINE3Yes2*isLess + isEqual + bitLt (single bootstrap)
AND3/OR332xComposed from 2-input gates

Threshold FHE

The pkg/threshold/ package implements t-of-n threshold decryption using LSSS (Linear Secret Sharing Scheme / Shamir's Secret Sharing) over a 256-bit safe prime field.

Key operations:

  • GenerateSharedKey(params, t, n, sessionID) -- Generate FHE keys and split into n shares with threshold t
  • ReshareKey(oldShares, newT, newN, sessionID) -- Reshare to new threshold/parties without regenerating keys
  • MarshalKeyShare / UnmarshalKeyShare -- Serialize key shares

Cluster management (pkg/membership/):

  • Dynamic member join/leave tracking
  • Quorum detection (can we decrypt with current members?)
  • Change handlers for reshare triggers
  • Integrated with mDNS discovery in fhed

FHE Daemon (fhed)

Standalone HTTP server for FHE operations.

# Install
go install github.com/luxfi/fhe/cmd/fhed@latest

# Standard mode
fhed start --http :8448 --params PN10QP27

# Threshold mode with mDNS discovery
fhed start --mode threshold --threshold 2 --discover

# Key generation
fhed keygen --output ./keys
fhed keygen --threshold --t 2 --n 3 --output ./keys

# Reshare
fhed reshare --input ./keys --new-t 3 --new-n 5 --output ./reshared

API endpoints:

EndpointMethodDescription
/healthGETHealth check with params, mode, threshold info
/publickeyGETPublic key (hex-encoded)
/encryptPOSTEncrypt bit, uint32, or uint64
/decryptPOSTDecrypt ciphertext(s)
/evaluatePOSTGate evaluation (and, or, xor, not, nand, nor, xnor, mux, majority, refresh)
/cluster/statusGETCluster state (threshold mode)
/cluster/peersGETDiscovered peers (threshold mode)
/cluster/resharePOSTTrigger reshare (threshold mode)

Solidity Contracts

Canonical FHE contracts live in @luxfi/contracts (at ~/work/lux/standard/contracts/fhe/). Development happens in luxfhe/contracts/ with pnpm sync to copy to the standard location.


contract ConfidentialToken {
    mapping(address => euint32) private _balances;

    function transfer(address to, euint32 amount) external {
        _balances[msg.sender] = FHE.sub(_balances[msg.sender], amount);
        _balances[to] = FHE.add(_balances[to], amount);
    }
}

Contract structure:

  • FHE.sol -- Core operations (add, sub, mul, div, rem, eq, lt, gt, le, ge, and, or, xor, not, shl, shr, select, decrypt, reveal)
  • IFHE.sol -- Types and interface
  • FheOS.sol -- Precompile interface
  • access/ -- Permissioned access control
  • config/ -- Network configuration
  • finance/ -- Vesting, DeFi primitives
  • gateway/ -- Gateway for decryption requests
  • governance/ -- Confidential voting
  • token/ERC20/ -- Confidential ERC20 tokens

Unified FHE API (Decryption Pattern)

// Step 1: Request async decryption
FHE.decrypt(encryptedValue);

// Step 2: Get result when ready
bool result = FHE.reveal(encryptedValue);         // Reverts if not ready
(bool result, bool ready) = FHE.revealSafe(encryptedValue);  // Safe version

JavaScript SDK Usage


const client = await createFheClient({
    provider: window.ethereum,
    networkUrl: 'https://fhe.lux.network'
})

// Encrypt
const encrypted = await client.encrypt_uint32(42)

// Send to contract...

v1-sdk vs v2-sdk:

  • v1: Single encryption key, key holder decrypts, lower latency, trusted environments
  • v2: Distributed key shares (t-of-n), network consensus decryption, no single point of trust, public DeFi

Native luxd Integration

Target architecture for FHE native to luxd:

luxd (--dev mode)
├── C-Chain (EVM)
│   └── FHE Precompiles (precompiles/fhe/)
│       FHEAdd, FHESub, FHEMul, FHEDiv, FHERem
│       FHEEq, FHELt, FHEGt, FHELe, FHEGe
│       FHEAnd, FHEOr, FHEXor, FHENot
│       TrivialEncrypt, VerifyCiphertext
│       Decrypt, Reencrypt

└── T-Chain (ThresholdVM)
    └── FHE RPC Service (vms/thresholdvm/fhe/)
        GetPublicParams, RegisterCiphertext
        RequestDecrypt / GetDecryptResult
        CreatePermit / VerifyPermit

Performance

OperationLatency (PN10QP27)
TFHE gate (AND/OR)~10ms
TFHE bootstrap~50ms
TFHE NOTfree (no bootstrap)
CKKS Add<1ms
CKKS Multiply~5ms
NTT N=2^16 (GPU)~1ms
Lazy carry add (euint256, amortized)~0 PBS per add

Troubleshooting

Build fails with lattice import errors -- The go.mod has replace github.com/luxfi/mdns => ../mdns. Ensure the mdns repo exists at the sibling path. For CI, remove the replace directive and use tagged versions.

CGO_ENABLED=0 errors -- The core library works in pure Go mode. GPU acceleration (ntt_simd.go, Metal/CUDA) requires CGO_ENABLED=1. Tests with //go:build !cgo tag verify pure-Go functionality.

Parameter set confusion -- PN10QP27 is the default and recommended for most uses. Use PN9QP28_STD128 only when you need OpenFHE-compatible parameters for benchmarking. PN11QP54 provides higher precision but is slower.

Threshold mode "not enough parties" -- The daemon requires at least threshold ready members before decryption. Check /cluster/status for current member count. Ensure mDNS discovery is working (same network, --discover flag).

JavaScript SDK "cannot find module" -- Use @luxfhe/v2-sdk for threshold mode, @luxfhe/v1-sdk for single-key. Do not mix. Install with pnpm add @luxfhe/v2-sdk.

Solidity compilation errors -- FHE contracts require Solidity ^0.8.24. Use @luxfi/contracts (canonical location), not @luxfhe/contracts (development). Run pnpm sync in luxfhe/contracts/ to update the canonical location.

Key serialization incompatibility -- Keys are serialized with Go's encoding/gob. They are not compatible across different parameter sets. Always regenerate keys when changing parameters.

  • lux/lux-fhevm.md -- FHEVM: the full-stack confidential smart contract framework (Rust coprocessor, gateway contracts, protocol contracts, test suite). Uses Zama's tfhe crate for actual FHE computation. This skill (lux-fhe) covers the Go core library and ecosystem; lux-fhevm covers the EVM integration layer with the off-chain coprocessor architecture.
  • lux/lux-lattice.md -- Underlying lattice cryptography (BFV, BGV, CKKS, RLWE, RGSW schemes)
  • lux/lux-crypto.md -- Other cryptographic primitives
  • lux/lux-evm.md -- EVM with FHE precompile support
  • lux/lux-gpu.md -- GPU acceleration (Metal, CUDA) for NTT and polynomial operations
  • lux/lux-threshold.md -- Threshold cryptography patterns
  • lux/lux-mpc.md -- Multi-party computation

Last Updated: 2026-03-13

On this page