# B² Network

## Overview

**Put Bitcoin in Every AI’s Wallet**

B² Network is building the settlement backbone for the AI era — where Bitcoin is no longer just “digital gold”, but the **currency of autonomous agents**.

We believe that:

* **Bitcoin** is the most secure, scarce, and censorship-resistant digital asset.
* **AI Agents** are becoming new economic actors, requiring native wallets and settlement tools.
* **Stablecoins** provide the predictable pricing and liquidity layer that makes large-scale adoption possible.

By uniting these three forces, B² Network transforms Bitcoin from a passive store of value into an **active medium of exchange for the AI economy**.

![B² Network Architecture](/files/tEZTedP3EpRMPjlYyrrk)

## Summary

* [B² Network](/)
  * [Vision: Put Bitcoin in Every AI’s Wallet](/readme/vision)
  * [Why Bitcoin + AI + Stablecoin](/readme/why_bitcoin_ai_stablecoin)
  * [Core Modules Overview](/readme/modules)
* [B² Network: Put Bitcoin in Every AI’s Wallet](/b2_network_put_bitcoin_in_every_ais_wallet)
* [Core Architecture](/core_architecture)
  * [Mining² (DeFAI-Mining Router)](/core_architecture/mining_squared)
  * [B² Hub (Layer 1.5 PoSg Consensus)](/core_architecture/b2_hub)
  * [B² Rollup (Bitcoin Layer2)](/core_architecture/b2_dsn_ai)
  * [AI Signal (Signal-Driven Agentic AI Layer)](/core_architecture/b2_dsn_ai)
  * [U2 Stablecoin (BTC-Collateralized Settlement Layer)](/core_architecture/u2)
* Technical Design
  * [Zero-Knowledge Proof Verification Commitment for ZK-Rollup on Bitcoin](/technical-design/zpvc)
  * [A Decentralized Signal-Driven Network for Modular and Agentic Artificial Intelligence](/core_architecture/b2_dsn_ai)
  * [Rollup Layer](/core_architecture/rollup_layer)
  * [DA Layer](/technical-design/da_layer)
    * [Decentralized Storage](/technical-design/da_layer/decentralized_storage)
    * [B² Nodes](/technical-design/da_layer/b2_nodes)
    * [B² Inscription](/technical-design/da_layer/b2_inscription)
    * [B² Commitment](/technical-design/da_layer/b2_commitment)
    * [Bitcoin Network](/technical-design/da_layer/bitcoin)
* For Users
  * [Connecting to B² Mainnet](/for-users/connect)
  * [Set Gas Price](/for-users/set_gas_price)
  * [Join B² Network Discovery](https://github.com/b2network/docs/blob/main/users/join_discovery.md)
  * [Bridge to B² Mainnet](/for-users/bridge)
  * [Transfer BlockHeadz NFT](/for-users/transfer_blockheadz)
  * [Add B2 token on BNB Chain](/for-users/add_b2_bnbchain)
* For Developers
  * [Basic information](/for-developers/basic_information)
  * [Write a contract](/for-developers/write_contract)
  * [Deploy a contract with Hardhat](/for-developers/deploy_with_hardhat)
  * [Verify contract code with Hardhat in Explorer](broken://pages/MaOg59REOFHQb3HYYp21)
  * [Verify contract code with Hardhat in Blockscout](/for-developers/how_to_verify_contract)
  * [Integrate Particle Account Abstraction](/for-developers/account_abstraction_with_particle_network)
  * [Integrate Oracle Services](broken://pages/Phpsd3OwTvclNddgAHsw)
  * [Deploy a rollup node](/for-developers/running_rollup_node)
  * [Deploy a rollup archive node](/for-developers/running_rollup_archive_node)
  * [Deploy a node from scratch(snap sync)](/for-developers/deploy_a_node_from_scratch)
* [Tokenomics](/b2_tokenomics)
* [Press-Kit](/press-kit)


# Vision: Put Bitcoin in Every AI’s Wallet

In the next decade of the digital economy, AI Agents will evolve from passive executors to active market participants and value creators. They need a globally recognized, censorship-resistant, and highly liquid native asset to achieve autonomous settlement, collateralization, and incentive distribution. Bitcoin possesses these qualities but has long been disconnected from the AI ecosystem due to a lack of programmable bridges.

The core vision of B² Network is to bridge this gap—allowing every AI entity to natively hold, earn, and spend digital assets, thereby:

1. Empowering the Agent Economy
   * Using BTC as a unified value metric to simplify settlement friction across multiple chains and assets.
   * Enabling agents to automatically consolidate execution earnings, staking rewards, and service fees into the same asset pool, enhancing capital efficiency.
2. Enhancing Network Security and Sustainability
   * The "useful signals" generated by AI are quantified and injected into the PoSg consensus, allowing AI activity to directly translate into chain-level security contributions.
   * A three-spiral positive feedback loop forms between miner computing power, BTC staking, and AI signals: more computing power -> more BTC liquidity -> stronger security -> more AI adoption.
3. Promoting Deep Integration of Web3 and AI
   * Through Agent-Native Account Abstraction (A-AA), agents possess the same on-chain identity and permission model as humans.
   * Through Application Sharding and B² Rollup, a high-throughput, low-latency execution environment is provided for AI-native dApps, while inheriting Bitcoin's economic finality.
   * Provide on-chain micropayment channels for AI-to-AI through U2, bringing autonomous, fast, decentralized, and auditable payment channels to AI.
4. Building an Open, Composable Modular Ecosystem
   * Modules like Mining Squared, B² Hub, B² Rollup, and AI Signal are decoupled and pluggable, facilitating integration by different developers as needed at various layers.
   * A unified BTC value base lowers the collaboration threshold across applications, stimulating innovation and capital influx.

With this vision, B² Network is committed to upgrading Bitcoin from "digital gold" to "fuel and settlement layer for AI," ensuring that every future intelligent interaction inherently carries the value and security of BTC, injecting lasting momentum into the decentralized economy built by humans and machines together.


# Why Bitcoin + AI + Stablecoin

## Bitcoin: The Most Reliable Settlement Layer

Bitcoin is the most secure, censorship-resistant, and globally recognized digital asset.

* **Store of Value**: With 21 million hard-capped supply, BTC is the ultimate reserve asset for both humans and AI agents.
* **Settlement Finality**: Bitcoin’s proof-of-work consensus guarantees immutability and trustless global settlement.
* **Native Liquidity**: As the most liquid digital asset, BTC enables scalable adoption across ecosystems.

Yet, Bitcoin today is under-utilized: it is mostly held as “digital gold” rather than actively powering new economies. B² Network transforms BTC from a passive store of value into an active settlement currency for the AI era.

***

## AI Agents: New Economic Actors

Autonomous AI Agents are emerging as **new participants in the global economy**.

* They communicate, plan, execute, and learn — requiring **native wallets** for value exchange.
* Their interactions demand **high-frequency, micro-value transactions** at machine speed.
* To be fully autonomous, agents need assets that are **trustless, global, and programmable**.

BTC is the natural fit: universally recognized, programmable through smart contracts, and suitable for machine-to-machine (M2M) micropayments. But agents also need stability and predictable unit of account to settle tasks.

***

## Stablecoin: The Missing Piece

While BTC is volatile, AI Agents need stable value reference for pricing, settlement, and long-term contracts. This is where **U2, the BTC-backed stablecoin** comes in:

* **BTC-Collateralized**: Every U2 is minted against over-collateralized Bitcoin.
* **Delta-Neutral Stability**: Hedging strategies ensure U2 maintains its peg to USD.
* **Programmable Money**: AI Agents can directly hold, pay, and settle in U2.

Stablecoins bridge the gap:

* BTC provides security and reserve value.
* U2 provides price stability and usability for AI-native economies.

***

## The Synthesis: Bitcoin + AI + Stablecoin

Together, these three elements create a new paradigm:

* **Bitcoin as Reserve Capital** → immutable, scarce, and secure foundation.
* **AI Agents as Economic Executors** → autonomous actors that sense, decide, and transact.
* **Stablecoin as Settlement Medium** → ensuring smooth, stable, and scalable interactions.

This triad enables the vision: **“Put Bitcoin in Every AI’s Wallet”** — transforming BTC into the currency of the AI-driven digital economy.


# Core Modules Overview

## Mining Squared

* Mission and Positioning:

  Upgrade traditional Bitcoin mining to a "yield as liquidity" channel, automatically injecting real-time BTC rewards into programmable contracts and staking pools.
* Key Features
  1. Mining rewards can be directly diverted to user or AI Agent wallets.
  2. One-click earnings: Mining pool rewards can be obtained through DeFAI by selecting different strategies.
  3. Supports computing power NFTs/derivatives, providing a secondary market for BTC Hashrate.
* Coupling with Other Modules

  Provides BTC staking and fee funds to B² Hub; invests assets into different strategies for yield through B² Rollup; conducts strategy evaluation and selection through AI Signal, and automates participation in various strategies.

## B² Hub

* Mission and Positioning

  A Layer 1.5 between Bitcoin Layer 1 and Rollup, serving as a consensus and data availability center, providing blockchain infrastructure for AI Signal.
* Key Features
  1. PoSg (Proof of Signal + Stake): BTC/B2 staking + verified AI signals jointly determine voting power.
  2. Application Sharding: Multiple applications run in parallel, with state isolation but shared security.
  3. Threshold signature lightweight clients.
  4. Taproot commitment to Bitcoin.
* Coupling with Other Modules

  Provides final confirmation and DA for B² Rollup.

  Collects AI Signal signals to enhance consensus security.

## B² Rollup

* Mission and Positioning

  A high-throughput, EVM smart contract execution layer, anchored to Bitcoin through validity proofs.
* Key Features
  1. ZK/Validity batching + proof - data and state roots submitted to B² Hub, with finality periodically written to Bitcoin.
  2. Low fees & high performance.
  3. Supports EVM addresses and Bitcoin addresses.
* Coupling with Other Modules

  Relies on B² Hub's DA and PoSg final confirmation.

  Provides a scalable execution environment for DeFi, NFTs, RWA, and other applications.

## AI Signal

* Mission and Positioning

  A signal-driven Agentic AI layer that allows AI to natively hold, earn, and spend digital assets.
* Key Features

  Agent-Native Account Abstraction (A-AA): Modular permissions, multi-signature, social recovery.

  Signal bus: On-chain AI behavior, generating quantifiable signals.

  MoE/Dispatcher routes complex reasoning tasks.
* Coupling with Other Modules

  The signals generated are used by B² Hub to weight PoSg.

  On-chain native payments for AI-to-AI through U2.

## U2

* Mission and Positioning

  U2 is a native stablecoin of the B² Network, optimized for Agent workloads: target price 1 U2 ≈ 1 USD, serving as a stable unit for AI tasks, data subscriptions, and service settlements. U2 combines the high security of BTC with the usability of USD within the same technology stack of B² Network, providing a predictable settlement currency for Agentic AI, offering efficient capital utilization and hedging tools for miners and stakers, and feeding back every economic activity of the stablecoin into the network security of PoSg through Signal scoring.
* Key Features
  1. Over-collateralization: Supports native BTC as collateral. Target collateralization ratio CR >= 150%, governance adjustable.
  2. Anchoring Mechanism:
     1. Minting/Redeeming: Users deposit collateral to open a vault to mint U2; U2 can be redeemed by destroying it at any time at the oracle price + fees.
     2. AMO Market Making: The protocol's self-operated market making (AMO) maintains a buy-sell band of 1±ε (default ε=0.5%) across various DEXs.
     3. Stability Fee: Interest is charged based on the debt size (annualized can be dynamically adjusted by RL-Tuner), used for risk and liquidity management.
  3. Liquidation and Insurance: When CR falls below the liquidation line (e.g., 130%), auctions/buybacks are triggered; part of the penalty is injected into the insurance pool, shared with the PoSg Slash pool for risk control reserves.
* Coupling with Other Modules

  PoSg / Signal: The minting, redeeming, liquidation, and AMO transactions of U2 will generate Signal events and count towards the SignalScore of the corresponding delegated validators (fees are still paid in BTC/B2), mapping stablecoin usage behavior to consensus activity.

  Mining Squared: Miners can choose to automatically convert a portion of their earnings into U2 for AI task budgeting or hedging; rBTC collateral can be used to mint U2 with one click, improving capital utilization.

  AI Signal / A-AA: Agents can set stable budgets in U2 within the A-AA wallet (e.g., "daily 50 U2 model expenses"); during execution, the router converts U2 <-> BTC as needed to pay for Gas, reducing price volatility's impact on workflows.

  B² Rollup Applications: DeFi, payment, and subscription dApps can use U2 as a user-facing pricing currency while enjoying the PoW finality and cross-Shard atomic interoperability of the Hub.


# B² Network: Put Bitcoin in Every AI’s Wallet

## B² Network: Put Bitcoin in Every AI’s Wallet

Author: B² Network Team

Version: v2.0.0

Date: 2025.7.20

## Abstract

With the rapid expansion of autonomous intelligent agents (AI Agents) in various on-chain and off-chain scenarios, providing secure, permissionless, highly liquid, and globally accepted settlement assets has become a core demand for the new generation of infrastructure. Bitcoin (BTC), as the most recognized and value-storing digital currency, has long been disconnected from the AI ecosystem. B² Network envisions "Put Bitcoin in every AI’s wallet" and proposes a modular architecture that integrates BTC natively into the AI economic cycle, mainly consisting of five subsystems:

1. Mining Squared — A new generation BTC mining pool with revenue routing capabilities, which automatically injects real-time mining rewards into programmable contracts, driven by DeFAI, continuously providing BTC liquidity and staking assets to the network.
2. B² Hub is a "Layer 1.5" hub located between the Bitcoin main chain and various Rollups. It is centered on PoSg (Proof of Signal + Stake) as the core consensus: merging forfeitable BTC/B2 staking with on-chain verified AI Signal dual-weighting, truly achieving "useful computation is a secure budget." On top of this, the Hub adopts an Application Sharding architecture, splitting the execution layer into horizontally scalable sub-chains/service shards, allowing various services such as EVM contracts, AI services, and data storage to run in parallel under the same validator set without interference. Thus, B² Hub inherits the economic confirmation of Bitcoin PoW, the interactive experience of BFT second-level block production, and the flexible scalability of modular blockchains, becoming a high-performance bridge between BTC value and Agentic AI productivity.
3. B² Rollup - A Bitcoin Rollup based on validity proofs, which submits batch data and state roots to the B² Hub and periodically anchors to the Bitcoin mainnet using Taproot, achieving both fast local confirmations and Layer 1 economic security.
4. AI Signal - An Agentic AI layer driven by Signal, providing Agent-Native Account Abstraction (A-AA), Signal Bus, and model routing, enabling agents to register, delegate validators, send/receive signals, and natively hold assets.
5. U2 - A new generation of stable settlement and intelligent stablecoins using BTC assets as collateral, aimed at Agentic AI. Using BTC assets as collateral to unlock BTC liquidity; building an AI-driven "adaptive collateral ratio and liquidation" engine to more quickly, reasonably, and safely adapt to market conditions; providing on-chain micropayment channels for Agents, offering a natural settlement layer for AI-to-AI business models, which can be seen as the next generation of "AI-native dollars"; supporting bank card services to unlock more consumption scenarios.

This article systematically explains how the above components work together to build the "computing power - signal - staking - value - consumption" closed loop:

* Mining rewards -> BTC staking -> PoSg consensus -> Final confirmation;
* AI behavior -> Signal fees -> Validator scoring -> Consensus weight enhancement;
* Rollup and applications -> AI-driven intelligent yield strategies -> Agent wallets and mining pools;
* BTC collateral -> issue U2 -> payment -> Agents micropayment.

Through formal security analysis and economic model derivation, we prove that PoSg can maintain a level of economic security comparable to traditional PoS under adjustable α/β parameters, while effectively converting AI work into contributions to network security. The B² Network provides the first practical unified paradigm for "Bitcoin × AI × Modular," injecting native BTC liquidity and finality assurance into the global agent economy.

## Keywords

Bitcoin, AI Agents, PoSg Consensus, Mining Squared, B² Hub, B² Rollup, Signal-Driven, Agent-Native Account Abstraction, Modular Blockchain.

## Summary

### Vision

Vision Review: "Put Bitcoin in Every AI’s Wallet."

In the next decade of the digital economy, AI Agents will evolve from passive executors to active market participants and value creators. They need a globally recognized, censorship-resistant, and highly liquid native asset to achieve autonomous settlement, collateralization, and incentive distribution. Bitcoin possesses these qualities but has long been disconnected from the AI ecosystem due to a lack of programmable bridges.

The core vision of B² Network is to bridge this gap—allowing every AI entity to natively hold, earn, and spend digital assets, thereby:

1. Empowering the Agent Economy
   * Using BTC as a unified value metric to simplify settlement friction across multiple chains and assets.
   * Enabling agents to automatically consolidate execution earnings, staking rewards, and service fees into the same asset pool, enhancing capital efficiency.
2. Enhancing Network Security and Sustainability
   * The "useful signals" generated by AI are quantified and injected into the PoSg consensus, allowing AI activity to directly translate into chain-level security contributions.
   * A three-spiral positive feedback loop forms between miner computing power, BTC staking, and AI signals: more computing power -> more BTC liquidity -> stronger security -> more AI adoption.
3. Promoting Deep Integration of Web3 and AI
   * Through Agent-Native Account Abstraction (A-AA), agents possess the same on-chain identity and permission model as humans.
   * Through Application Sharding and B² Rollup, a high-throughput, low-latency execution environment is provided for AI-native dApps, while inheriting Bitcoin's economic finality.
   * Provide on-chain micropayment channels for AI-to-AI through U2, bringing autonomous, fast, decentralized, and auditable payment channels to AI.
4. Building an Open, Composable Modular Ecosystem
   * Modules like Mining Squared, B² Hub, B² Rollup, and AI Signal are decoupled and pluggable, facilitating integration by different developers as needed at various layers.
   * A unified BTC value base lowers the collaboration threshold across applications, stimulating innovation and capital influx.

With this vision, B² Network is committed to upgrading Bitcoin from "digital gold" to "fuel and settlement layer for AI," ensuring that every future intelligent interaction inherently carries the value and security of BTC, injecting lasting momentum into the decentralized economy built by humans and machines together.

### Core Module Overview

#### Mining Squared

* Mission and Positioning:

  Upgrade traditional Bitcoin mining to a "yield as liquidity" channel, automatically injecting real-time BTC rewards into programmable contracts and staking pools.
* Key Features
  1. Mining rewards can be directly diverted to user or AI Agent wallets.
  2. One-click earnings: Mining pool rewards can be obtained through DeFAI by selecting different strategies.
  3. Supports computing power NFTs/derivatives, providing a secondary market for BTC Hashrate.
* Coupling with Other Modules

  Provides BTC staking and fee funds to B² Hub; invests assets into different strategies for yield through B² Rollup; conducts strategy evaluation and selection through AI Signal, and automates participation in various strategies.

#### B² Hub

* Mission and Positioning

  A Layer 1.5 between Bitcoin Layer 1 and Rollup, serving as a consensus and data availability center, providing blockchain infrastructure for AI Signal.
* Key Features
  1. PoSg (Proof of Signal + Stake): BTC/B2 staking + verified AI signals jointly determine voting power.
  2. Application Sharding: Multiple applications run in parallel, with state isolation but shared security.
  3. Threshold signature lightweight clients.
  4. Taproot commitment to Bitcoin.
* Coupling with Other Modules

  Provides final confirmation and DA for B² Rollup.

  Collects signals to enhance consensus security.

#### B² Rollup

* Mission and Positioning

  A high-throughput, EVM smart contract execution layer, anchored to Bitcoin through validity proofs.
* Key Features
  1. ZK/Validity batching + proof - data and state roots submitted to B² Hub, with finality periodically written to Bitcoin.
  2. Low fees & high performance.
  3. Supports EVM addresses and Bitcoin addresses.
* Coupling with Other Modules

  Relies on B² Hub's DA and PoSg final confirmation.

  Provides a scalable execution environment for DeFi, NFTs, RWA, and other applications.

#### AI Signal

* Mission and Positioning

  A signal-driven Agentic AI layer that allows AI to natively hold, earn, and spend digital assets.
* Key Features

  Agent-Native Account Abstraction (A-AA): Modular permissions, multi-signature, social recovery.

  Signal bus: On-chain AI behavior, generating quantifiable signals.

  MoE/Dispatcher routes complex reasoning tasks.
* Coupling with Other Modules

  The signals generated are used by B² Hub to weight PoSg.

  On-chain native payments for AI-to-AI through U2.

#### U2

* Mission and Positioning

  U2 is a native stablecoin of the B² Network, optimized for Agent workloads: target price 1 U2 ≈ 1 USD, serving as a stable unit for AI tasks, data subscriptions, and service settlements. U2 combines the high security of BTC with the usability of USD within the same technology stack of B² Network, providing a predictable settlement currency for Agentic AI, offering efficient capital utilization and hedging tools for miners and stakers, and feeding back every economic activity of the stablecoin into the network security of PoSg through Signal scoring.
* Key Features
  1. Over-collateralization: Supports native BTC as collateral. Target collateralization ratio CR >= 150%, governance adjustable.
  2. Anchoring Mechanism:
     1. Minting/Redeeming: Users deposit collateral to open a vault to mint U2; U2 can be redeemed by destroying it at any time at the oracle price + fees.
     2. AMO Market Making: The protocol's self-operated market making (AMO) maintains a buy-sell band of 1±ε (default ε=0.5%) across various DEXs.
     3. Stability Fee: Interest is charged based on the debt size (annualized can be dynamically adjusted by RL-Tuner), used for risk and liquidity management.
  3. Liquidation and Insurance: When CR falls below the liquidation line (e.g., 130%), auctions/buybacks are triggered; part of the penalty is injected into the insurance pool, shared with the PoSg Slash pool for risk control reserves.
* Coupling with Other Modules

  PoSg / Signal: The minting, redeeming, liquidation, and AMO transactions of U2 will generate Signal events and count towards the SignalScore of the corresponding delegated validators (fees are still paid in BTC/B2), mapping stablecoin usage behavior to consensus activity.

  Mining Squared: Miners can choose to automatically convert a portion of their earnings into U2 for AI task budgeting or hedging; rBTC collateral can be used to mint U2 with one click, improving capital utilization.

  AI Signal / A-AA: Agents can set stable budgets in U2 within the A-AA wallet (e.g., "daily 50 U2 model expenses"); during execution, the router converts U2 <-> BTC as needed to pay for Gas, reducing price volatility's impact on workflows.

  B² Rollup Applications: DeFi, payment, and subscription dApps can use U2 as a user-facing pricing currency while enjoying the PoW finality and cross-Shard atomic interoperability of the Hub.

### Value Proposition

B² Network tightly couples the global consensus value of Bitcoin, the powerful productivity of AI agents, and the flexible scalability of modular blockchain: through Mining Squared, real-time mining rewards are directly injected into the network, providing a continuous flow of BTC liquidity for validators' staking and agent wallets; leveraging the PoSg consensus mechanism, the combination of "BTC/B2 staking + verified AI signals" is transformed into voting rights, directly mapping the useful work of AI into chain-level security budgets; under the application sharding of B² Hub and the validity proof of B² Rollup, it achieves dual finality with second-level local finality and periodic anchoring to the Bitcoin mainnet, while supporting the free assembly of any VM, sub-chains, and permissioned modules. Miners can participate simply by switching their revenue routing, and AI developers can quickly deploy based on familiar development stacks, achieving low barriers to entry, high throughput execution, and economic security, truly realizing "Put Bitcoin in every AI’s wallet" as a self-circulating flywheel that integrates computing power, signals, and value, creating a new ecosystem of "Bitcoin + AI + Modular Stack."

### Opportunities

In B² Network, different participants can find new momentum within the value closed loop of "mining power—BTC staking—signal-driven—modular execution."

For developers, the Application Sharding and Rollup SDK of B² Hub lower the barriers to on-chain deployment, and native BTC settlement eliminates cross-chain friction; with the signal API and A-AA wallet, any off-chain event can be transformed into an agent trigger, allowing for rapid deployment of high-speed payments, blockchain games, and high-frequency DeFi derivatives, all earning BTC fees through the shortest path.

Miners and computing power providers can route real-time mining rewards to the PoSg staking pool with one click through Mining Squared, continuing PoW income while adding consensus rewards and signal incentives; computing power can also be packaged as "computing power LSD" or delegated services, attracting DeFi and AI funds, creating additional revenue channels for small and medium miners.

AI service providers and model suppliers can package each model call, inference result, or data labeling into billable signals, receiving BTC payments in real-time; at the same time, the signal weight will be converted into voting rights for their delegated validators, directly transforming "useful AI work" into contributions to network security and bringing additional rewards to cooperative nodes.

Financial institutions can design new yield curves and structured products around PoSg staking and the signal market, providing BTC staking loans, hedging tools, and custody services for mining pools and validators; on B² Rollup, they can also issue stablecoins, notes, or leveraged products collateralized by BTC, achieving an efficient combination of on-chain settlement and off-chain clearing.

In summary, B² Network opens up multidimensional opportunities for developers, miners, AI suppliers, and financial institutions in technology, revenue, business, and financial innovation, collectively driving the positive flywheel of the "Bitcoin + AI + Modular" ecosystem.

## Introduction

### Background

For more than a decade, Bitcoin has accumulated the strongest monetary-level consensus and a market value of over $1 trillion as decentralized digital gold. However, its capital efficiency has been constrained by three structural factors: (1) low on-chain throughput, with the Base Layer capable of processing only about 7 transactions per second, which cannot support large-scale payments; (2) weak scripting capabilities, as the native UTXO script lacks Turing completeness and account abstraction, making it difficult to implement advanced financial primitives such as DeFi, derivatives, and stablecoins; (3) a single revenue channel, where holders have few sustainable on-chain earning scenarios aside from long-term appreciation, resulting in millions of BTC sitting idle in cold wallets. This "high market value, low activity" contradiction is widely referred to as Bitcoin Capital Inefficiency.

In stark contrast, the generative AI and autonomous agent economy has seen exponential growth over the past three years: ChatGPT has driven the popularity of LLMs, and Agent-Framework and Auto-Everything enable AI to perceive, reason, decide, and execute without human intervention. Global AI service spending has surged from less than $20 billion in 2022 to an estimated over $200 billion by 2025. A vast number of agents frequently exchange data, invoke models, and settle computing and bandwidth costs between cloud and IoT nodes, creating an urgent need for a neutral, permissionless, highly liquid global settlement asset that can be natively held by machines.

In reality, these two rapidly developing tracks have little intersection:

* Existing AI task settlements mainly rely on centralized payments or USD stablecoins, unable to enjoy Bitcoin's monetary attributes of "absolute scarcity, censorship resistance, and cross-border accessibility";
* Layer 2 solutions like Lightning focus on peer-to-peer payments, making it difficult to meet the needs of complex contracts and large-scale state synchronization;
* Emerging solutions like Bitcoin Rollup and BitVM are still in the early experimental stage and have not yet formed a one-stop solution aimed at AI.

Therefore, "how to let the value and security of Bitcoin serve the AI economy" and "how to allow the real useful work of AI to feed back into the security and revenue of the Bitcoin network" have become dual challenges facing developers and researchers, as well as the goals of the B² Network's advancement.

### Why AI Needs Bitcoin

1. Global Permissionless Value Settlement Layer

   Autonomous agents perform tasks in every corner of the internet—scraping data, calling models, renting GPUs, purchasing APIs—if they rely on centralized payment interfaces, they face not only geographical and regulatory barriers but also service interruptions due to account freezes, exchange restrictions, and KYC limitations. Bitcoin transactions on-chain require no permission and operate around the clock, naturally aligning with machines' needs for 24×7 settlement and cross-border collaboration.
2. Finality and Anti-Censorship Guarantee Execution Certainty

   AI Agent transactions are typically triggered in milliseconds, but once a rollback or chargeback occurs, the upper decision chain collapses. Bitcoin's PoW provides the highest economic finality in the industry—once a block is confirmed, the cost of tampering is extremely high; combined with B² Network's Layer 1.5 early finality, Agents can achieve "high probability finality" in seconds and "absolute finality" in minutes.
3. Value Stability and Inflation Hedge

   Most AI service revenues are denominated in USD or fiat stablecoins, exposing them to long-term inflation risks. BTC, with a fixed supply cap of 21 million coins and a halving issuance mechanism, provides an anti-inflation asset pool for AI companies and agents; in a high-volatility environment, holding some BTC can also hedge against stablecoin decoupling or regulatory pressure.
4. Machine Verifiable and Programmable Wallet Primitives

   Bitcoin UTXO is naturally suited for implementing auditable and composable machine wallets on-chain. Coupled with B² Network's Agent-Native Account Abstraction (A-AA), Agents can flexibly manage multi-signatures, time locks, social recovery, and other permissions under the same address without complex bridging and cross-chain mapping.
5. Incentives and Security Coupling

   In the PoSg design, signals generated by AI directly affect validators' voting power; the more "useful work" an Agent performs, the greater the weight supporting network security, which in turn enhances the safety of Agent funds and execution availability, forming a positive feedback loop of "security-incentive."
6. Micro-Payments and Batch Settlement Efficiency

   Bitcoin Layer 2 (Lightning, Rollup ecosystem) has proven that BTC can support millisecond-level, low-cost micro-payments. B² Hub introduces Application Sharding and aggregated batch submissions, compressing a series of micro-transactions into a single Taproot proof written to L1, significantly reducing on-chain costs, allowing AI Agents to confidently perform high-frequency calls.
7. Ecosystem and Liquidity Spillover Effects

   BTC accounts for over 40% of the total cryptocurrency market cap and has the broadest base of holders. Pricing AI fees, rewards, staking, and DeFi primitives in BTC can directly inherit its global liquidity and deep derivatives market, opening up richer financing and hedging tools for Agents and their operators.

In short, Bitcoin provides the AI economy with censorship-resistant value storage, programmable machine assets, strong finality, and global liquidity. Through B² Network's modular stack, these features can be deeply integrated with high-performance execution layers, signal-driven consensus, and AI-native account systems, making it possible for "every AI wallet to securely and efficiently hold and use BTC."

### Limitations of the Current Solutions

Although the Bitcoin ecosystem and the AI field have been attempting to address the issues of value settlement and computational synergy through their respective Layer 2 or sidechain expansions, as well as on-chain AI frameworks in recent years, there remains a significant gap in achieving the goal of "enabling AI to natively use BTC," primarily manifested in the following five points:

1. Payment-oriented Layer 2 is difficult to support complex states
   * The Lightning Network relies on multi-hop channels, state maintenance, and offline counterpart collaboration; once an off-chain channel fails or a counterpart maliciously goes offline, the AI Agent must revert to L1 settlement, making the process overly complex and the delays unpredictable.
   * Existing upgrade solutions like Ark and Eltoo focus on single payment use cases and lack native support for complex smart contracts, multi-asset settlements, and cross-Agent atomic composite transactions.
2. Emerging Bitcoin Rollups and BitVM are still in the experimental stage
   * Most Bitcoin Rollup solutions (Rollkit-BTC, Botanix, Merlin, etc.) have not yet validated their data availability and security models on the mainnet, and there is a scarcity of available tools, SDKs, and developer ecosystems.
   * BitVM achieves general computation through off-chain execution + Taproot dispute resolution, but it has a high number of interaction rounds and a long dispute window, making it unsuitable as a real-time settlement layer for high-frequency AI calls.
3. AI × Blockchain projects generally rely on ERC-20 or custom tokens
   * Projects like Fetch.ai, Bittensor, and Autonolas mostly issue new tokens as billing and incentive units, which, while facilitating the creation of economic models, disconnect Bitcoin's liquidity and reintroduce fiat currency exchange and regulatory risks.
   * The consensus security of these projects is not directly coupled with BTC, making it impossible to leverage Bitcoin's PoW economic finality to protect large amounts of funds.
4. Lack of machine-friendly account abstraction and a "work equals security" closed loop
   * Existing on-chain account models are mostly based on EOA or contract accounts, with permission configurations and recovery processes often designed for human users, failing to meet the key management and permission layering needs of large-scale Agent automation scenarios.
   * The connection between staking weight and real on-chain work is weak, making it impossible to directly convert the "useful signals" of AI Agents into the network's security budget.
5. Cross-chain bridges and multi-asset mental burden
   * AI task execution often spans cloud vendors and cross-chain environments; if frequent exchanges between various assets like ETH, USDC, USDT, and FET are necessary, it not only leads to price slippage and liquidity fragmentation but also expands compliance and hacking risk exposure.
   * Bridging protocols (multi-signature bridges, light client bridges) are frequently attacked, exposing highly automated Agent systems to uncontrollable black swan risks.
6. Lack of AI-oriented payment channels for stablecoins based on Bitcoin's native properties
   * Price exposure and budget uncertainty: Directly priced in BTC, the per-instance/streaming fees for AI tasks are affected by price fluctuations, making it difficult to control cost ceilings and long-term budgets.
   * Dual-currency friction: Applications priced in stablecoins while Gas is paid in BTC/B2 require agents to frequently exchange small amounts and replenish, leading to slippage, failed retries, and counterparty risk.
   * Micropayments/high-frequency unfriendly: Existing channels lack primitives for machine-oriented streaming payments, limits/rates, and batch settlements, making costs and confirmation delays uncontrollable for sub-dollar level high-frequency calls during congestion.
   * Finality and audit disconnection: The finality of multi-chain stablecoins relies on other chains or custodians, making it impossible to anchor settlement evidence stably to Bitcoin, resulting in insufficient institutional-level reconciliation and traceability.

Therefore, the current ecosystem either sacrifices Bitcoin's native security and liquidity or fails to meet the high-frequency, complex, multi-party interaction needs of AI Agents. B² Network specifically addresses these pain points by directly integrating BTC into the AI settlement path and merging "BTC staking + AI signals" into the same security budget through PoSg consensus, filling the gaps in existing solutions.

### Summary

Bitcoin possesses the global liquidity, censorship resistance, and strong finality that the AI economy urgently needs, but due to insufficient scalability and contract capabilities, it forms a "value island" in the AI world. Existing cross-chain or spontaneous token solutions cannot simultaneously ensure security, support complex states, and maintain BTC's native liquidity. B² Network aims to break this barrier by building a new type of infrastructure that directly introduces U2 issued with BTC as collateral into AI settlement, allowing useful AI work to contribute back to on-chain security.

## Overview

### System Architecture Overview Diagram

![B² Network Architecture Overview](https://github.com/user-attachments/assets/0a19e44c-a399-4a1a-a64d-859844580b62)

### Module Description and Role Positioning

B² Network consists of five interconnected core modules. Each has its own responsibilities and forms a closed loop through BTC value flow and Signal control flow.

Mining Squared is responsible for automatically aggregating and routing the BTC earnings mined by miners in real-time. Hashrate providers submit their hash rates, and the earnings routing contract distributes BTC according to a preset ratio: part of it goes directly into the validator's staking pool, while another part can be credited to the agent's account. This module maintains full compatibility with Bitcoin's PoW consensus while providing a continuous source of liquidity for the upper layer.

B² Hub is the Layer 1.5 hub of the system. It adopts a PoSg (Stake + Signal) consensus, operating under the same set of validators with Application Sharding to achieve parallel sub-chains. Validators run PoSg nodes, while agents delegate their SignalScore to target validators, influencing their voting power. The Hub is also responsible for periodically writing the sharded DA root into Bitcoin Layer 1 using Taproot, thus achieving both second-level BFT finality and mainnet-level economic finality.

B² Rollup provides a computationally intensive or contract-complex execution environment. The Sequencer aggregates transactions and generates ZK/Validity proofs, then submits the batch data to B² Hub. All fees in the Rollup are directly priced in BTC, allowing dApps to enjoy high TPS and rich contract functionalities without introducing additional tokens.

The AI Signal layer is aimed at the agent ecosystem. The Signal Bus transforms on-chain events into billable signals, and Agent-Native Account Abstraction (A-AA) allows each agent to have a programmable BTC wallet and permission system. Model providers can package inference services into subscribable Signals; agents obtain task-driven incentives by sending or receiving signals while returning the paid BTC and signal weight to their delegated validators.

U2 is the native stable settlement layer of the network. It uses BTC as over-collateral (target collateralization rate ≥150%) and stabilizes the exchange rate of 1 U2 ≈ 1 USD through oracles. The AI-driven liquidation engine automatically adjusts collateral rates and liquidation parameters based on market fluctuations, ensuring system robustness. U2 provides Agents with a price-stable micropayment channel—AI tasks can be accurately priced without being affected by BTC volatility. At the same time, operations such as minting, redeeming, and liquidating U2 generate Signal events, which are counted towards the validators' SignalScore, directly mapping stablecoin activities to network security contributions. Through the AMO (protocol-owned market making) mechanism, U2 maintains deep liquidity across various DEXs and supports traditional payment channels such as bank cards, bridging on-chain and off-chain consumption scenarios.

The overall role distribution is as follows:

* Miners inject computing power earnings into the network through Mining Squared;
* Validators maintain PoSg consensus in B² Hub and receive additional rewards based on Signal activity;
* AI agents register, delegate, and settle tasks in BTC on AI Signal, with the generated signals enhancing the voting power of their dependent validators;
* Developers can deploy applications on Rollup or Hub sub-chains, using BTC directly as Gas and incentives;
* The mortgagor locks BTC to mint U2, releasing liquidity while retaining the appreciation potential of BTC;
* The liquidator monitors the collateral ratio, provides liquidity when the system needs it, and earns liquidation rewards;
* End users or institutions interact with the entire stack through agents or front ends, enjoying "BTC-native AI services and financial primitives."

In this way, computing power - staking - signals - execution layer - payments are tightly coupled, forming a self-driven growth flywheel.

### Data and Value Flow

In B² Network, BTC flow, Signal flow, and proof flow act like three parallel blood vessels, weaving computing power, staking, security, and execution layers into a closed loop. Below, we will explain their paths, key milestones, and interactions one by one.

#### BTC Flow

1. Source: Mining Squared
   * Miners submit computing power -> Real-time mined BTC enters the Mining Squared revenue pool.
   * Revenue routing contracts split according to strategy:
     1. Automatically staked in the B² Hub's Staking Module;
     2. Directly deposited into Agent-Native wallets as needed, providing startup funds for agents;
     3. Some can choose to collateralize and mint U2 to obtain stable liquidity.
2. Staking and Consensus
   * Staked BTC is locked in the Staking Module, generating corresponding Stake shares.
   * Stake, along with subsequent SignalScore, determines the Voting Power of validators, participating in PoSg block production and earning block fees.
3. U2 Minting and Circulation
   * BTC collateral minting: Users/miners can lock BTC in the Vault contract, minting U2 based on oracle prices and collateralization ratios (≥150%).
   * Liquidity release: Minted U2 can be used for:
     * AI Agent task payments (inference fees, data subscriptions, computing power rentals)
     * DEX liquidity provision, earning trading fees
     * A stable pricing unit for inter-institutional settlements
   * Value return: The Signal weight generated from U2 usage feeds back into the PoSg consensus, enhancing network security.
4. Fees and Profit Sharing
   * Rollup and various Shard dApps pay Gas in BTC or U2; these fees are shared among PoSg validators based on weight.
   * U2 related fees:
     * Stability Fee: Interest charged based on debt size, flowing into the risk reserve pool
     * Liquidation penalty: The portion of the liquidation penalty when collateralization is insufficient enters the insurance pool
     * AMO market-making revenue: Trading fees generated from liquidity controlled by the protocol flow back into the system
   * Validators can choose to re-stake their profits, mint U2, or distribute them externally, forming a positive cycle of "revenue -> staking/U2 -> more revenue."
5. Liquidation and Risk Management
   * When the BTC price drops, causing the collateralization ratio to fall below 130%, a liquidation auction is triggered.
   * Liquidators use U2 to purchase discounted BTC, maintaining the system's solvency.
   * Liquidation profit: BTC price difference - U2 cost = liquidation profit, incentivizing market participants to actively maintain system health.
6. Exit and Liquidity
   * BTC Path:
     * Unlocking staked BTC requires waiting for a freeze period; unlocked BTC can be returned to miners or used by Agents for new business expenses.
     * U2 debt redemption: Destroy U2 + pay stability fee to retrieve the collateralized BTC.
   * U2 Path:
     * Exchange for BTC or other assets through AMO on DEX
     * Used for payments for various services within the network (no need for exchange)
     * Exchange for fiat currency consumption through bank card channels
   * Through Lightning, CEX, or on-chain bridging, users can transfer BTC/U2 back to external ecosystems at any time, ensuring high liquidity.
7. Compound Revenue Cycle
   * Mining Squared revenue → BTC collateral → Minting U2 → AI payments/DeFi revenue → More BTC accumulation
   * Signal generated from U2 circulation → Enhances validator weight → Earns more block rewards → Increases BTC revenue
   * Forming a triple revenue model of "BTC-based appreciation + U2 liquidity revenue + Signal network rewards."

Thus, the BTC flow not only includes the staking and circulation of native BTC but also creates a parallel value circulation system through the U2 stablecoin—BTC provides value anchoring, while U2 offers liquidity and stable pricing. The two are deeply coupled through collateralization/redemption mechanisms and Signal incentives, jointly supporting the economic activities of the entire network.

#### Signal Flow

1. Generation and Submission
   * After completing tasks at the AI Signal layer, the AI Agent calls submitSignal() to put the event summary, weight, and proof on-chain.
   * The Sender and each Receiver must be registered Agents, each delegated to the target validator.
2. Verification and Scoring
   * The SignalRouter of B² Hub checks signatures, fees, validity, and proof.
   * Upon passing, the corresponding validators of the sender and receiver each accumulate weight to their SignalScore.
   * Transaction fees (i.e., weight) are paid in a lump sum by the sender to prevent spam signals.
3. Impact on Consensus
   * The end of the Epoch snapshots Stake and SignalScore; PoSg recalculates validator weight with VP = α·Stake + β·SignalScore.
   * Validators of active Agents have a higher probability of block production in the next Epoch and receive more block rewards, incentivizing Agents to continue generating "useful signals."
4. Business Trigger
   * The Signal Bus broadcasts events to subscribed sub-chains or off-chain services, triggering Rollup contract execution, model routing calls, or external APIs.
   * The composability of the entire chain is established: signals act as schedulers, linking on-chain state changes with off-chain AI services.

#### Proof Flow

1. Rollup Batch Proof
   * Sequencer aggregates user transactions -> generates batches and ZK/Validity proofs.
   * The proof is submitted along with batch data to the corresponding Shard of the B² Hub, which verifies it and provides a finality with seconds-level BFT.
2. Data Availability (DA) Commitment
   * All transaction data from Shards/Rollups is sliced, erasure-coded, and then generates a Namespace Merkle Tree root (NMT root).
   * Every 10 minutes, these roots are aggregated + threshold signatures, packaged into a Taproot transaction, and written to Bitcoin Layer 1.
   * Light clients only need to verify the threshold signatures and Bitcoin blocks, thus trusting the upper layer state.
3. Proof Feedback and Challenges
   * If the ZK proof is invalid or data is lost, any node can submit fraud evidence; PoSg validators will execute a slash on malicious batches.
   * The proof flow thus bears the dual responsibility of "state correctness + data availability."

* BTC flow converts computational power gains into a loop of staking and transaction fees, providing economic security and liquidity.
* Signal flow maps the actual work of AI into voting rights, directly enhancing chain-level security and driving application interactivity.
* Proof flow ensures correct execution, data availability, and ultimately anchors all sub-chain states to the Bitcoin main chain.

The three flows intertwine to form a closed loop: BTC gains new revenue scenarios while empowering AI, the useful signals from AI enhance the security margin of BTC staking, and the proof mechanism encapsulates all of this under the strong finality of Bitcoin PoW, achieving a self-consistent cycle of "value-data-security."

### Lifecycle

TODO IMAGE: Register -> Stake -> Signal -> Consensus -> Commit to Bitcoin

1. Register
   * Validators: Run nodes, register public keys, endpoints, and reward addresses on the B² Hub chain, and receive a Validator ID.
   * Agents: AI Agents register A-AA accounts on the Agent Registry chain and choose to delegate to a specific validator; once registered, they can hold BTC/B2 and call the Signal API.
2. Stake / Delegate
   * Location: Users (individuals, miners, institutions, Agents) deposit BTC or B2 into the staking contract of the B² Rollup. Assets are held in escrow at the Rollup layer but are mapped on-chain as StakingShare.
   * Delegation Logic: Stakers can delegate any share to different validators, supporting "one stake, multiple validator allocation"; changes take effect in the next Epoch.
   * Mining Squared and DeFAI:
   * DeFAI acts as a strategy aggregator, running a set of agents to dynamically allocate funds across multiple DeFi scenarios (market making, lending, liquid staking, etc.);
   * B² Hub staking is one option in the DeFAI strategy pool—when the PoSg yield is higher than external protocols, Agents will automatically convert part of the funds into StakingShare and delegate to the most profitable validator;
   * The comprehensive yield from DeFAI flows back to the stakers or is reinvested.
3. Signal
   * After executing tasks, agents call submitSignal(), packaging event summaries, weights, and proofs.
   * B² Hub verifies signatures, fees, and proofs; upon approval, the validators delegated by both the sender and receiver accumulate SignalScore according to weight.
   * The sender bears all costs (to prevent spam), and the receiver must ACK on-chain to score.
4. Consensus (PoSg Epoch Loop)
   1. Snapshot: Freeze the current StakeMap and SignalPool;
   2. ValidatorSet Update: Select the top N nodes with the highest weight according to VP = α·Stake + β·SignalScore;
   3. Threshold Key Generation: The new validator set runs FROST DKG;
   4. CometBFT Block Production: Weighted proposals, 2–3 seconds finality;
   5. Reward / Slash: Block fees + signal rewards are distributed according to VP; double signing or data availability violations trigger slashing.
5. Commit to Bitcoin
   * All transactions from Shard/Rollup generate NMT roots through slicing and erasure coding;
   * B² Hub aggregates root hashes and threshold signatures approximately every 10 minutes, writing a Taproot transaction;
   * Light clients only need to verify this transaction to obtain PoW finality of the on-chain state.

Summary

* Users stake BTC/B2 in the B² Rollup and freely delegate to validators;
* DeFAI dynamically migrates funds between multiple strategies through Agents, with "B² Hub staking" being one optional strategy in the yield pool;
* Signals convert useful AI work into validator weight; PoSg achieves consensus in seconds, subsequently granting economic finality through Bitcoin PoW.

This forms a cycle of "Stake -> Signal -> Consensus -> Yield -> Re-stake/Redistribute," connecting external DeFi with the B² Network ecosystem, continuously amplifying the synergy between BTC and AI.

## Core Concepts and Terminology

### Signal / SignalScore

#### Signal

In the B² Network, a Signal refers to an event message generated by an AI Agent and verified on-chain. It maps "useful AI work" to measurable economic value and directly impacts consensus security. Each Signal contains the following core fields:

* id: keccak256(sender‖nonce‖timestamp)
* senderAgent: Registered A-AA address
* receiverAgents: List of at least 1 registered Agent
* weight: Economic weight of the Signal (in sat)
* expiry: Expiry block height
* payloadHash: Task result or data summary
* proof: Verifiable proof (ZK-SNARK / signature aggregation / hash pre-image, etc.)
* sig: Schnorr/ECDSA signature of senderAgent

Economic implications:

* weight is considered a one-time signal fee. Once paid by the sender, it is either burned or allocated to the block validators, providing income while preventing spam.
* The validators delegated by both the sender and each receiver will count this weight towards SignalScore, creating a two-way incentive.

Signal Lifecycle

1. Generation: The Agent completes reasoning, off-chain calls, or data labeling, constructs the Signal, and pays the weight.
2. Submission: Calls the submitSignal() transaction, specifying the list of receivers.
3. Verification: B² Hub checks
   * Whether the sender/receiver is registered and the delegation is valid
   * weight ≥ minSignalFee and does not exceed MAX\_WEIGHT
   * Signature, proof, uniqueness, and not expired
4. ACK: The receiving Agent confirms on-chain (ackSignal(id)); otherwise, it does not count towards their validator score.
5. Scoring:
   * Validators delegated by the sender: + weight
   * Validators delegated by each receiver: + weight / n (default evenly distributed, customizable ratio)

All verified Signals enter the SignalPool, waiting for unified settlement at the end of the Epoch.

#### SignalScore

* For any validator *v*:

$$
\text{SignalScore}*v = \sum*{\text{agent} \in \mathcal{D}*v} \sum*{\text{sig} \in \mathcal{W}} \text{weight}
$$

Where $\mathcal{D}\_v$ is the set of all Agents delegated to *v*, and $\mathcal{W}$ is the set of Signals related to these Agents in the most recent *M* Epochs.

* The scoring window *M* (e.g., 24 h or 168 h) is adjustable in governance, smoothing noise and preventing one-time score manipulation.
* The system sets a hard upper limit: $\text{SignalScore}\_v \le k \times \text{Stake}\_v$ (typical *k = 3*), to avoid zero-stake signal monopolization.

Role in PoSg:

The consensus layer is defined by the formula

$$
\text{VotingPower}\_v ;=; \alpha \cdot \text{Stake}\_v ;+; \beta \cdot \text{SignalScore}\_v
$$

which combines staking and signals into voting power. The parameters $\alpha$ and $\beta$ are determined by on-chain governance (default 0.7 / 0.3). Therefore:

* More staking -> increases security collateral;
* More useful signals -> directly enhances votes;
* Both drive validators to achieve higher block production probability and block rewards.

Anti-cheating and risk control:

| Risk                               | Mitigation Measures                                                                                                       |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| Fake recipient score inflation     | Recipient must provide on-chain ACK; ACK failure does not count towards score                                             |
| Micro garbage signals              | minSignalFee dynamically adjusted with network load; weight directly burned                                               |
| Monopolization of excessive weight | MAX\_WEIGHT\_PER\_TX limits; SignalScore ≤ k × Stake                                                                      |
| Sybil accounts                     | Sender fees paid in one lump sum, cost linear to transfer count; optional ZK-KYC proof                                    |
| Invalid proof                      | Verifiable proof attached with transaction; anyone can submit fraud evidence during the challenge period to trigger Slash |

Signal transforms AI task results into on-chain events; SignalScore maps the economic weight of these events into consensus voting power. Together, they allow "useful work" to directly enhance chain security and provide quantifiable economic returns for active AI Agents and their underlying validators.

### Agent / Agent-Native Abstract Account (A-AA)

#### Agent

Positioning of Agent:

In the B² Network, an Agent refers to a program entity capable of autonomously executing perception, reasoning, decision-making, and on-chain interactions. It can be an independently operating LLM-Bot or a wallet bot that automates operations on behalf of individuals or enterprises. Agents trigger workflows by sending and receiving Signals and use BTC/B2 as a fuel settlement model for calling, computing power leasing, and various on-chain service fees.

#### Agent-Native Abstract Account (A-AA)

**Why A-AA is Needed?**

1. Machine-friendly key and permission management

   Traditional EOA/contract accounts are often oriented towards human signatures or single private key custody, which is not suitable for large-scale agent automation.
2. Native BTC payments

   AI tasks are high-frequency and low-value, requiring deep integration with account permission systems for second-level BTC settlement.
3. Upgradeable, recoverable, and socially recoverable

   Agent logic, models, and keys may iterate; relying solely on a single key means total loss if it is leaked.
4. On-chain composability

   Agents need atomic, multi-party interactions and modular permissions to be reused across different contracts and Rollup environments.

**Core Design Elements of A-AA**

| Component          | Function                                                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Root Keyset        | A multi-signature or threshold Schnorr public key set that controls high-security operations (upgrades, recovery, delegate modifications). |
| Session Keys       | Used for short-cycle batch signing or specific dApp authorizations, automatically revoked upon expiration.                                 |
| Permission Modules | Plugin-based strategies (limits, multi-approval, time locks, conditional transfers).                                                       |
| Agent Registry     | On-chain mapping table: agentAddr -> {delegateeVal, pubkeyRoot, version}.                                                                  |
| Delegate Mapping   | Records the current validator address and effective epoch that the Agent is delegating to.                                                 |

Compatibility: A-AA adopts a composable script tree similar to BTC Taproot, allowing unified verification in B² Rollup or B² Hub sub-chains; the same Agent address can share permission logic across sub-chains.

**Account Lifecycle**

1. Creation

   Developers call createAgent(rootKeyset, initialDelegate, metadata), and a unique Agent address is issued by the Hub.
2. Fund Injection
   * Off-chain: Recharge BTC to this address via Lightning/CEX.
   * On-chain: Miners / DeFAI strategies directly transfer to the Agent.
3. Delegation and Staking

   The Agent calls delegateValidator(valAddr), assigning all its SignalScore weight to the target validator.
4. Task Execution
   * Send Signal -> Trigger on-chain or off-chain workflows;
   * Receive Signal -> Decide whether to automatically execute payments, data writing, or forwarding based on permission modules.
5. Upgrade / Recovery

   ```
    Super multi-signature scheme: upgradeModule(newModuleHash) or recover(newRootKeyset), requiring Root Keyset to reach threshold signatures.
   ```
6. Deregistration

When the Agent's use case ends, selfDestruct() can be called to release funds and deregister the Registry entry.

**Example Permission Module**

* RateLimiter: Limits the maximum payment of n sat or m model calls within a block to prevent being hijacked and burning money.
* TimeLock: Large transactions must wait t seconds/blocks, allowing for manual review within the window.
* Guardians: Keys can only be reset after external cold wallet or multi-signature guardian approval.
* ConditionPay: Funds are automatically released only when a certain type of Signal or off-chain proof meets the conditions.

**Security and Risk Control**

* Hierarchical Keys: High-value operations are managed by the Root Keyset, while low-value micropayments use Session Keys, accelerating execution while reducing risk exposure.
* Off-chain Audit Hooks: The permission module can call off-chain risk control services (e.g., malicious model detection), returning a boolean value to determine whether the transaction continues.
* Automated Slash Alerts: If an Agent is detected being used for score manipulation or sending false signals, the system can freeze its Delegate and revoke Signal weight.

Agent-Native Abstract Account (A-AA) provides agents with an upgradeable, multi-signature, modular permission and native BTC payment comprehensive account system. It ensures high frequency and flexibility of machine operations while preventing key leakage and malicious calls through multi-layer security mechanisms, laying the technical foundation for "AI wallets holding BTC" at the account level.

### PoSg (Proof of Signal + Stake)

PoSg is the native consensus mechanism of B² Hub, which introduces economic signals (Signal) generated by AI Agents as a second-dimensional weight on the basis of traditional staking (Stake), combining "capital collateral" with "useful work" into the same voting power formula. In short: staking BTC/B2 provides economic security, and SignalScore reflects on-chain activity, both jointly determining the validator's votes and rewards.

#### 1. Components

* Stake

  The BTC or B2 staked by users in B² Rollup, the total amount can be increased or decreased at any time but is frozen within the current Epoch.
* SignalScore

  The weighted sum of all signals sent/received by Agents delegated to that validator in the last M Epochs.

  Measures the Agent's true contribution to the network through double scoring (sender + receiver).
* Voting Power

  $$VP\_v ;=; \alpha \cdot Stake\_v ;+; \beta \cdot SignalScore\_v$$

  Where $\alpha+\beta=1$, default $\alpha=0.7$, $;\beta=0.3$, adjustable through on-chain governance.
* Epoch

  A fixed time window (e.g., 1 hour). At the end of the Epoch, Stake and SignalScore are re-snapshot, updating the validator set.

#### 2. Operating Process (High-Level Perspective)

1. Snapshot freezes StakeMap and SignalPool;
2. ValidatorSet Selection sorts by VP and takes the top N;
3. Threshold key generation runs FROST-DKG to produce the public key for this Epoch;
4. BFT block production uses CometBFT, proposing in a weighted round-robin manner by VP, with a finality of 2-3 seconds;
5. Reward / Slash block fees + signal rewards are distributed according to VP; double signing, being offline, or invalid DA triggers penalties;
6. Roll over to the next Epoch to recalculate VP, repeating the cycle.

#### 3. Key Parameters and Governance

| Parameter    | Meaning                           | Typical Value | Adjustment Method                       |
| ------------ | --------------------------------- | ------------- | --------------------------------------- |
| α / β        | Stake vs Signal weight            | 0.7 / 0.3     | DAO proposal, delayed effect            |
| minSignalFee | Minimum fee for a single Signal   | 0.1 B2        | Automatically adjusts with network load |
| M            | Signal scoring window             | 24 h          | Governable                              |
| k            | Signal to Stake upper limit ratio | 3             | Brush score threshold                   |

#### 4. Security and Economic Characteristics

* Economic security: Stake provides quantifiable penalty collateral; when β ≤ 0.5, attackers still need to hold a large amount of BTC/B2 to manipulate votes.
* Useful work coupling: Signals must be paid for and accompanied by verifiable proof, with the cost of brushing scores being linear to weight, and limited by k×Stake upper limit.
* Activity positive feedback: The more active an Agent is, the higher the score of the validators they delegate to, leading to more block production and rewards, which in turn incentivizes more Agents to choose that validator.
* Predictable finality: PoSg layer achieves second-level BFT; every \~10 minutes, the DA root is written into Bitcoin via Taproot, achieving PoW finality.

#### 5. Differences from PoW / Traditional PoS

| Dimension                  | PoW                         | PoS                 | PoSg                                          |
| -------------------------- | --------------------------- | ------------------- | --------------------------------------------- |
| Source of Voting Power     | Hash power                  | Staked tokens       | Staked tokens + AI work                       |
| Work and Security Coupling | High electricity cost       | Staking can be idle | Useful AI work converted into security budget |
| Resource Waste             | Energy consumption          | Low                 | Low, and incentives for effective computation |
| Anti-Sybil Mechanism       | Hash power is hard to forge | Staking threshold   | Staking threshold + signal fee + limits       |

PoSg combines capital collateralization with AI-Signal through a dual-weight formula: Stake ensures economic resistance to malicious behavior, while SignalScore rewards genuine on-chain activities. It injects AI's "useful work" directly into the consensus layer while maintaining Bitcoin-level economic security, thus forming a positive feedback loop of security—incentives—activity for the B² Network.

### Anchored Rollup / DA Commit / Finality to Bitcoin

The B² Network adopts a "three-layer finality" architecture—B² Rollup is anchored on the B² Hub to achieve second-level BFT finality, after which the B² Hub periodically writes the network's data availability commitments (DA Commit) to Bitcoin Layer1, ensuring that Rollup, sub-chains, and signal events are ultimately protected by Bitcoin's PoW economic security. This path decouples performance from security: high throughput execution at the upper layer, with strong finality guarantees at the lower layer.

| Term                | Question                                                                                    | Solution                                                            | Level of Finality                 |
| ------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | --------------------------------- |
| Anchored Rollup     | How to share upper-layer security with a high TPS execution layer?                          | Submit batch data & state root to B² Hub (PoSg BFT)                 | Second-level (Hub local finality) |
| DA Commit           | How can a large amount of transaction data be recovered and verified by the entire network? | Hub aggregates shard data -> NMT root -> Taproot submits to Bitcoin | Minute-level, retrievable         |
| Finality to Bitcoin | How to achieve irreversible economic security?                                              | Bitcoin block confirmation count & PoW cost                         | Final (PoW determined)            |

#### Anchored Rollup

Definition: B² Rollup processes transactions in a standalone EVM execution environment, generates state transitions, and produces validity proofs (ZK / Validity), then submits the batch summary (batch commitment) + proof to a specified Namespace in the B² Hub. After the Hub verifies the proof, the batch is included in the PoSg consensus block, providing second-level ordering and irreversible execution guarantees.

Key Attributes

* Sequencer is appointed through Staking via B² Hub voting.
* Gas is priced in BTC (also supporting B2 and whitelisted stablecoins); fees flow to PoSg validators and incentive pools.
* Configurable mandatory inclusion mechanism (anti-censorship): Users can directly send batch data fragments to the Hub DA layer, which Rollup will forcibly extract.

#### DA Commit

Goal: Ensure that anyone can recover all original Rollup and Shard transaction data from the minimal commitment on Bitcoin, avoiding "state unproven" and historical reconstruction failures.

Process

1. Each Hub block collects transaction data blocks from various Namespaces (Shard/Rollup).
2. Data is sliced into fixed sizes and encoded (e.g., Reed-Solomon).
3. Construct Namespace Merkle Tree (NMT): Different Namespaces have independent branches for selective downloading.
4. Generate global DA Root (aggregated root).
5. Write into Bitcoin Taproot transaction scripts at fixed intervals (\~10 minutes or aligned with Bitcoin block rhythm): DA Root | Epoch ID | Hub Block Range | Proof Hash (optional ZK)
6. After Bitcoin confirmation, any light node can obtain the required shard data and verify integrity using the DA Root.

Data Recovery: If a certain type of node goes offline, as long as more than k fragments survive, reconstruction can be done through erasure coding; the NMT proof ensures that the downloaded data indeed belongs to a certain Namespace.

#### Finality to Bitcoin

PoSg & BFT first provide "engineering-level fast confirmation," while Bitcoin provides "economic-level irreversible confirmation."

| Level                                     | Time Scale                     | Who Guarantees           | Reversal Risk                                   | Suggested Use                                                        |
| ----------------------------------------- | ------------------------------ | ------------------------ | ----------------------------------------------- | -------------------------------------------------------------------- |
| Local Execution (within Rollup)           | Milliseconds to seconds        | Sequencer local ordering | High                                            | UI displays transient results                                        |
| Hub Finality (PoSg BFT)                   | \~2–3 s/block                  | ≥2/3 VP signatures       | Requires PoSg attack                            | Executable small funds, Agent workflows                              |
| Bitcoin Finality (DA Commit confirmation) | \~10 minutes + n confirmations | PoW cost                 | Extremely low (depends on reorganization depth) | Large settlements, cross-chain bridges, institutional reconciliation |

Recommended Practices

* Small or high-frequency calls: rely on Hub Finality.
* Large transfers/settlements: wait for Bitcoin Commit + several confirmations (e.g., 3 to 6 BTC blocks).

#### Data & Proof Flow Timing

TODO

Timing Diagram:

1. User Tx -> Rollup Sequencer
2. Batch & state transition -> ZK/Validity Proof
3. Submit -> B² Hub (Namespace=RollupX)
4. PoSg block confirmation (seconds)
5. Hub aggregates multi-Namespace data -> DA Root
6. Taproot Tx written to Bitcoin (≈10min)
7. PoW confirmation = economic confirmation

“Anchored Rollup -> DA Commit -> Finality to Bitcoin” is the main path for the performance and security unification of the B² Network: Rollup obtains instant ordering and execution guarantees on the Hub; the Hub periodically compresses and writes all network data and proofs into Bitcoin, ensuring that all upper-layer states are ultimately safeguarded by PoW. Through multi-layer finality, erasure-coded DA, and verifiable proofs, the B² Network provides a high-throughput, modular, AI-native execution environment without sacrificing Bitcoin's security.

### Economic Units: Stake, Weight, Fee, Reward, Slash

#### Stake

Refers to the BTC or B2 locked by users in the B² Rollup staking contract. The principal is frozen until the end of the current Epoch and can be delegated to multiple validators according to shares. Stake serves as both a forfeitable security deposit and the primary factor for calculating PoSg voting rights; its flow is

TODO

Flowchart: User/Miner -> Staking Contract -> (Delegated) Validator -> PoSg Voting Rights -> Stake Unlock or Yield Reinvestment.

#### Weight

The fee value specified for each Signal with the transaction, reflecting the economic importance of the event. Weight will be deducted in a one-time charge and:

1. Burned or converted into miner/validator fees, used as a cost to prevent spam;
2. Accumulated to the corresponding validator's SignalScore according to the dual scoring rule of sender + receiver, becoming the second factor of PoSg voting rights.

#### Fee

There are three types of fees in the B² Network:

1. Gas Fee: Rollup and Shard transaction execution fees, priced in BTC/B2;
2. Signal Fee = Weight: The necessary cost of Signal transactions, paid by the sender;
3. Network Surcharge: An additional rate that dynamically increases during graylisted node or congestion periods.

All fees collected ultimately accumulate in the validator block reward pool, distributed according to VotingPower.

#### Reward

Three types of rewards are generated during the operation of PoSg:

* Block Reward: For each Hub block packaged, Gas + SignalFee is summarized and distributed according to VP;
* Signal Activity Reward: At the end of the Epoch, validators in the SignalScore Top-k can receive an additional 5–10% share;
* External Strategy Earnings: Earnings generated when DeFAI chooses the "Stake to Hub" strategy flow back to Stake holders.

Stakers can choose automatic reinvestment (compound yield) or unlock and withdraw.

#### Slash

Economic penalties established for malicious or negligent behavior in PoSg:

* Double signing / Data availability malfeasance: Penalized 5% Stake and corresponding SignalScore reset to zero;
* Continuous offline: Gradually deduct Stake by 0.1–1% based on the number of absences;
* Falsifying signals / Score manipulation: Double confiscation of the sender's payment and downgrade the delegated validator.

50% of the confiscated assets are destroyed, and 50% enter the system insurance pool, used to offset losses or for future incentives.

#### Overall Closed Loop

TODO

Flowchart:

Stake provides underlying security -> Weight drives activity and weights Stake -> Fee maintains network operation -> Reward encourages staking and signal production -> Slash punishes wrongdoing and replenishes the insurance pool.

Five types of economic units mutually constrain and circulate, ensuring that the B² Network possesses both economic resistance to attacks and continuous incentives for AI and user participation.

### AI-Driven Intelligent Governance

AI-driven intelligent governance is the "adaptive parameters and risk control" framework of B² Hub: off-chain AI agents—centered on reinforcement learning (RL), supplemented by graph neural network anomaly detection and explainable AI (XAI)—analyze on-chain metrics and node telemetry in real-time, proposing governance suggestions such as PoSg parameter tuning, graylisting, and sharding expansion or contraction; all suggestions are written into the on-chain ParameterOracle contract, which only takes effect after a delay and PoSg VotingPower voting, and is protected by hard thresholds and rollback mechanisms.

Key Components

* RL-Tuner: Simulates PoSg operation in a sandbox, using throughput, rewards, and Slash costs as the reward function, outputting optimal parameters such as α/β, minimum signal fee, and penalty ratio.
* Anomaly Detector: Monitors score manipulation, witching, and voting delay anomalies using GNN + Isolation Forest, generating graylists and confidence levels.
* Shard Balancer: Provides suggestions for creating, expanding, or merging sub-chains based on time series prediction and heuristic algorithms to avoid hotspot congestion.
* XAI-Auditor: Generates reasons and impact Top-K factor summaries (TL;DR) for each AI suggestion, and hashes the report along with the model version for on-chain proof.

Governance Process

1. Data Collection: Nodes periodically publish signed telemetry (TPS, Gas, Slash, delay, etc.); AI components pull for analysis.
2. Suggestion Generation and Explanation: RL-Tuner / Detector / Balancer outputs suggestions -> XAI-Auditor generates explanations.
3. On-Chain Release: Suggestions + explanations are written into ParameterOracle, automatically entering a ≥100 block delay window.
4. Community Review and Voting: PoSg validators approve or reject based on VotingPower; if approved, it takes effect in the next Epoch.
5. Safety Barriers: Hard threshold limits (e.g., α∈\[0.5,0.9], Slash≤50% Stake), can quickly roll back to old parameters in case of abnormal increases.

Advantages

* Adaptive: When network load, signal density, or attack situations change, optimal parameters can be provided and deployed within minutes.
* Transparent and Auditable: All model hashes, explanation summaries, and decision processes are stored on-chain; the community can hold accountable, reproduce, and reassess.
* Anti-Manipulation: Suggestions without sufficient explanation or with confidence below the threshold will be automatically rejected, and proposals exceeding hard threshold ranges require a supermajority governance proposal.
* Reduced Operational Costs: Traditional "quarterly manual parameter tuning" is shortened to "daily micro-adjustments," while avoiding human subjectivity or delays.

Through this framework, B² Hub can introduce AI's learning and predictive capabilities while maintaining verifiable consensus rules, achieving faster risk response, more precise resource scheduling, and higher economic efficiency.

## Mining Squared: Revenue-Oriented BTC Mining Pool and Network Economic Entry

### Motivation

The vast majority of BTC produced daily by Bitcoin miners is passively hoarded or cashed out through exchanges, creating a near disconnection with the emerging Layer 2 and AI economies, resulting in a disconnect between hash power contribution and ecological activity:

* Revenue dispersion—miners need to manually transfer BTC into staking or DeFi scenarios; on-chain revenue opportunities are lost in multiple transfers and high fees.
* High staking threshold—individual small and medium miners find it difficult to accumulate enough stake to influence PoSg, and it is also challenging to track optimal delegation nodes in real-time.
* Insufficient security spillover—the economic costs generated by PoW only secure Layer 1, while the consensus layer and application layer still lack additional BTC liquidity and incentives.

Mining Squared connects the mining pool accounting system through smart contracts, streamlining "Hashrate -> Mining Rewards -> Smart Routing":

1. Real-time revenue capture: Each time the mining pool finds a new block, the corresponding BTC is precisely credited to the Mining Squared revenue pool.
2. Strategy routing: The revenue pool automatically executes multi-strategy allocation according to preset ratios—directly converted into PoSg staking shares, injected into DeFAI strategy combinations, or periodically returned to miners' wallets.
3. Delegation automation: Contracts dynamically adjust delegated validators based on yield rates, slash risks, and miner preferences, ensuring maximization of staking rewards without human intervention.

In this way, miners' hash power not only earns PoW block rewards but also automatically converts into PoSg voting rights and network fee sharing; BTC liquidity flows into Hub and Rollup, providing fuel for AI and DeFi scenarios, further enhancing chain-level security and application activity, ultimately forming a positive cycle of "Hash Power -> Revenue -> Staking/Strategy -> More Revenue."

### Architecture

Mining Squared consists of two parts: off-chain mining pool nodes and on-chain contract clusters, with the core process divided into five modules.

1. Mining Ledger
   * Each time the mining pool discovers a new block, the node generates a "revenue certificate" in the local ledger and broadcasts it to the RewardCollector contract.
   * The certificate includes block height, amount of BTC produced, and share of participating hash power; miners can use their private keys to sign and prove hash power ownership.
2. RewardCollector Contract
   * After aggregating and verifying the mining pool signatures, it transfers the BTC to a unified contract custody address.
   * It mints 1:1 rBTC tokens (ERC-20 on Rollup) based on miners' hash power shares, serving as the accounting unit for subsequent revenue routing and redemption.
3. BTC Revenue Router
   * Supports programmable allocation formulas, initial template:

     ```
     ρ1 = x% -> StakingAdapter // PoSg Staking

     ρ2 = y% -> DeFAI Controller // External Strategies

     ρ3 = z% -> Direct Payout // Return to Miners

     ρ1+ρ2+ρ3 = 100%
     ```
   * Miners can adjust their personal ρ parameters using a front-end slider; the Router automatically executes corresponding transfers in each settlement period.
4. DeFAI Controller
   * Aggregates multiple strategy agents (lending mining, liquidity provision, staking derivatives, cross-chain arbitrage, etc.).
   * Uses rBTC as the underlying asset, dynamically allocating to the strategy pool with the highest yield, automatically rebalancing based on block frequency.
   * When the annualized yield of B² Hub staking exceeds the external strategy threshold, the Controller automatically increases the weight of ρ1, directing more rBTC to the StakingAdapter.
5. StakingAdapter & Validator Delegation
   * Unpacks incoming rBTC into BTC and submits it to the B² Hub Staking Module.
   * Runs delegation algorithms:
   * Basic mode: evenly distributed to the top N high-reputation validators;
   * Advanced mode: weighted distribution based on PoSg reward rates, slash risks, and miner preferences.
   * The re-staked BTC, after earning PoSg rewards, automatically rolls into the Router for the next period's allocation.

Information and fund flow:

!\[]\[image]

Programmability

* The Router, Controller, and Adapter all have open strategy interfaces, allowing miners or DAOs to upload new strategy scripts and set thresholds.
* Parameter changes take effect in real-time through on-chain governance or personal preferences, ensuring that the revenue path continuously aligns with the interests of miners and the network as a whole.

This architecture allows the BTC produced by miners to enter on-chain contracts in seconds, and automatically, transparently, and programmably cycles between "PoSg Staking—DeFi Strategies—Direct Return," while seamlessly converting hash power revenue into the security budget and ecological liquidity entry of the B² network.

### Automated Revenue Path

Mining Squared has designed a full-chain revenue channel for miners that follows the path of "Mining -> Tokenization -> Strategy Routing -> Compound Return Flow," requiring no manual operation throughout the process, which is specifically divided into five cyclical steps:

1. Mining Output -> Tokenization
   * After the mining pool discovers a new block, the earned BTC is immediately injected into RewardCollector.
   * The contract mints an equivalent amount of rBTC tokens (Rollup-side ERC-20) based on the hash power share, recording the principal and future earnings due to each miner.
2. Revenue Routing Split
   * Miners set a one-time weight ρ = ⟨Staking ρ₁, Strategy ρ₂, Return ρ₃⟩ for rBTC on the front end.
   * The Router executes in batches every 30 minutes:
   * ρ₁ -> StakingAdapter: Converts to native BTC and stakes it to B² Hub;
   * ρ₂ -> DeFAI Controller: Invests in multi-strategy revenue pools;
   * ρ₃ -> Directly transfers back to miner A-AA wallet, which can be withdrawn at any time.
3. Dynamic Strategy Scheduling
   * DeFAI Controller interfaces with sub-strategies such as market making, lending, LSD, and cross-chain arbitrage.
   * Each strategy Agent continuously reports APY, risk, and liquidity; the Controller automatically adjusts positions based on revenue-risk scoring.
   * Once it detects that PoSg annualized > average APY of DeFi pools + Δ, the Controller automatically migrates part of the funds from external pools to StakingAdapter to increase the staking proportion.
4. PoSg Rewards & DeFi Mining Earnings
   * Staking BTC earns block fees, signal rewards, and other PoSg earnings;
   * Interest and incentive tokens generated by external strategies are automatically converted back to rBTC via the Router;
   * Both types of earnings are redistributed according to the miner's initial ρ configuration, with an optional "automatic reinvestment" switch to enter the next round of splitting.
5. Compound Return Flow and Dynamic Rebalancing
   * The Router adds the earnings from the previous round to the miner's rBTC balance, reinvesting it into Step 2.
   * Miners can adjust the ρ weights or withdraw rBTC at any time on the front end; all changes take effect in the next cycle, achieving a rolling compound interest of "earnings-reinvestment-delegation."

Result: The BTC generated from a single block enters on-chain staking or strategy pools within minutes, with earnings rolling in real-time; miners enjoy the certain income from PoW mining while automatically compounding PoSg and DeFi returns, truly creating a closed loop of hash power -> staking/strategy -> compound earnings -> hash power.

### Risk and Incentive Model

#### Main Risks

1. Price Volatility Risk

   The market price fluctuations of BTC and B2 may lead to unrealized losses in staking positions, affecting the mindset of stakers.

   Mitigation Plan:

   * The Router allows users to customize the return ratio ρ₃ to retain some spot assets;
   * DeFAI provides hedging strategies (such as short BTC futures) for automatic configuration.
2. Strategy Risk (DeFAI Pool)

   High-yield DeFi pools may have contract vulnerabilities, liquidation, or liquidity exhaustion.

   Mitigation Plan:

   * The Controller sets a risk score cap for all strategies, automatically rebalancing if the threshold is exceeded;
   * Initially, only blue-chip protocols with multiple rounds of audits and TVL ≥ 5,000 BTC will be enabled;
   * Extreme events trigger a "safety mode," automatically returning funds to the StakingAdapter.
3. Consensus Penalty Risk (Slash)

   Delegating to malicious or unstable validators may result in slashed stakes.

   Mitigation Plan:

   * The default delegation algorithm of the StakingAdapter prioritizes nodes with low Slash history and high online rates;
   * Users can exclude blacklisted validators;
   * Slash losses can be partially compensated from the insurance pool, which is sourced from the system's 50% penalty redistribution.
4. Contract and Bridging Risks

   Router, RewardCollector, and StakingAdapter are all key contracts; asset conversion between Rollup and Hub also relies on bridging logic.

   Mitigation Plan:

   * Multiple audits + bounty programs;
   * Contracts use time-lock upgrades, with emergency vulnerabilities triggering pause();
   * Bridging only occurs on paths protected by PoSg + Taproot dual finality.
5. Centralized Computing Power and Governance Attacks

   A few large miners may monopolize staking and voting rights.

   Mitigation Plan:

   * Staking weight is capped at a maximum binding limit for a single mining pool (e.g., 25% Hard Cap);
   * Multi-armed bandit delegation dispersion algorithm splits automatic staking across ≥N validators.

#### Incentive Design

| Participant                       | Revenue Items                                                                                              | Incentive Logic                                                                                                                                                                |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Miners / Stakers                  | 1) PoW block rewards 2) PoSg block fees + signal rewards 3) DeFAI strategy APY 4) Insurance pool dividends | All revenue is mapped to rBTC balance; automatic reinvestment can be enabled for compound interest, or liquidity can be redeemed at any time.                                  |
| Validators                        | 1) Basic Stake returns 2) SignalScore activity bonus 3) Slash reward sharing                               | Serve more high-quality Signal agents -> receive higher VP and additional prize pools; if slashed, 50% goes to the insurance pool, indirectly benefiting compliant validators. |
| Strategy Providers (DeFAI Agents) | Management fees + performance fees (20/2 typical)                                                          | Net worth outperforming the benchmark PoSg APR can receive more fund allocation; if strategy APY lags long-term, automatic downgrading occurs.                                 |
| Insurance Pool Participants       | Slash penalties, a portion of unclaimed earnings                                                           | Acts as a passive risk cushion, which can be converted into governance voting rights or stable income tokens in the future.                                                    |

#### Game Theory and Steady State

* When PoSg APR > DeFi APR, the "staking -> rewards" path dominates, and the Controller will migrate funds back to the Hub to enhance network security; conversely, it will increase DeFi allocation to improve overall miner returns.
* Slash costs are shared by malicious validators and the insurance pool, encouraging miners to diversify their delegation and avoid crowding a single node.
* A macro three-layer self-balancing system is formed: computing power output -> multi-strategy returns -> network security enhancement -> higher APR -> new computing power entry, making Mining Squared an automated gain engine connecting PoW and PoSg, on-chain and off-chain returns.

### Integration with AI Signal / Agent Wallet

1. Native Earnings Enter A-AA Wallet

   The rBTC tokens minted by Mining Squared comply with A-AA interface specifications, allowing miners or computing power providers to designate any agent address as the earnings recipient.

   * Once the earnings are credited, the agent can use rBTC for task gas, model calls, or re-staking without cross-chain conversion.
   * The A-AA permission module supports two strategies: "automatic reinvestment of earnings" and "threshold alert withdrawal," which miners can configure with one click on the front end.
2. Signal-Triggered Automatic Staking

   Agents can subscribe to their own "balance change" signals:

   * When rBTC balance ≥ preset threshold, trigger autoStake(rBTC, validatorList);
   * Successful staking will generate a new StakeUpdate Signal, instantly enhancing the SignalScore of the delegated validator, forming a "earnings -> signal -> consensus weight" closed loop.
3. DeFAI Strategy Executed by Agent

   The underlying DeFAI Controller consists of a group of strategy agents holding A-AA accounts:

   * They publish "strategy APY updates" and "position migration" signals via the Signal Bus for miners' wallets or other agents to subscribe for reference;
   * The control logic is fully auditable on-chain, with earnings and risks transparent to all Agents.
4. Cross-Chain/Cross-Application Calls

   Since rBTC = ERC-20 on Rollup, Agents can:

   * Directly call AMM/DeFi contracts (such as DEX, lending) for recombination;
   * Map rBTC to other Shards or external chains via IBC-lite, serving as fuel for more AI/DeFi scenarios.
5. Integration of Security and Risk Control
   * A-AA supports limit + time lock modules to prevent malicious strategies from depleting earnings;
   * All signals generated by Mining Squared (earnings credited, staking, redemption, strategy changes) will enter the AI Signal Graph, available for any monitoring Agent to subscribe for on-chain risk control and auditing.

Computing power earnings enter the Agent wallet through Mining Squared, and the Agent can use these funds for automatic staking, executing DeFi strategies, or paying AI task fees; the entire process is signal-driven and programmable on-chain, ultimately seamlessly injecting BTC traffic generated by PoW into the AI Signal agent ecosystem, forming a triple loop of funds, signals, and security.

## B² Hub: The Bridge Connecting Bitcoin and AI

B² Hub is the heart of the entire network and serves as the "cross-dimensional bridge" between the Bitcoin world and the Agentic AI economy.

At the base level, it anchors each round of data availability commitments to Bitcoin Layer 1 through Taproot transactions, inheriting the economic certainty of PoW; at the upper level, it tightly couples BTC staking with AI Signal using PoSg consensus, allowing the "useful work" of agents to be directly converted into chain-level security budgets. Meanwhile, Application Sharding enables multiple execution environments to run in parallel on the same validator set without competing for bandwidth; second-level BFT block production provides real-time feedback for high-frequency AI scheduling, while the data ultimately resides in Bitcoin's immutable ledger. To allow the system to adapt to load, the Hub also introduces reinforcement learning-driven intelligent governance: consensus parameters, fees, and graylists are suggested by AI agents and then implemented through on-chain guardrails and community voting. Through this bridge, BTC liquidity can be seamlessly injected into AI wallets, and AI Signals can feed back into network security, forming a positive cycle of "value—computing power—security—activity." The following chapters will break down the technical details of PoSg consensus, Application Sharding, data availability anchoring, and AI intelligent governance.

### Design Vision and Role Positioning

#### Vision

B² Hub aims to become the convergence point of Bitcoin value and artificial intelligence productivity, providing a layer for execution and settlement that enjoys the finality of PoW while having second-level responsiveness for billions of AI agents worldwide. Its goals can be broken down into three slogans:

1. Make BTC the fuel for AI—All fees and rewards are priced in BTC/B2, eliminating cross-chain friction;
2. Let AI work feed back into chain security—PoSg converts paid Signals into validator voting rights, with the security budget growing in sync with AI activity;
3. Enable adaptive development and governance—With Application Sharding and AI intelligent governance frameworks, the network can scale on demand and automatically adjust parameters while maintaining continuous evolution without sacrificing verifiability.

#### Core Roles

| Role                              | Responsibilities                                                                  | Key Incentives                                                                       |
| --------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Validator                         | Stake BTC/B2, run CometBFT, package multiple Shard blocks                         | Block fees + signal rewards; malicious behavior is slashed                           |
| AI Agent                          | Send/receive Signals, execute on-chain/off-chain tasks, manage A-AA wallets       | Earn BTC by completing tasks; their Signals enhance delegated validator weight       |
| Miner / Mining Squared            | Automatically route PoW earnings to staking or DeFAI strategies                   | Base mining rewards + PoSg/DeFi compound earnings                                    |
| Rollup Sequencer / dApp Developer | Execute contracts at high frequency within Shard or Rollup, generate batches      | High TPS, low latency environment; fees settled directly in BTC                      |
| Light Node / End User             | Only sync Hub headers and NMT Root, can verify transactions of interest in Shards | Mobile second-level confirmations; no need for full chain storage, lowering barriers |

Positioning

* Layer 1.5: Positioned above Bitcoin L1 and various Rollups, balancing PoW finality with high performance.
* Secure Consensus: Merging Stake and Signal with PoSg; the more useful AI work, the stronger the underlying security.
* Modular Execution: Supporting coexistence of multiple VMs and data forms through Application Sharding; Rollups, Oracles, and AI Services can run in parallel.
* Self-Driving Governance: Reinforcement learning automatically provides fee and parameter tuning, XAI outputs interpretable reports, and on-chain guardrails and voting ensure transparency and prudence.

With this design, B² Hub is not only a "bridge" in technology but also a "bridge" in economics and incentives: weaving Bitcoin's absolute scarcity with AI's infinite creativity into a single value cycle, providing a solid yet flexible foundation for the next generation of machine economy.

### System Layering and Data Flow Overview

#### Layered Architecture

1. P2P Network Layer

   Uses libp2p/gossip-sub for node discovery, block headers, transaction, and signal event propagation, with underlying channels reused for all Shards and Rollups.
2. Consensus Layer (CometBFT + PoSg)

   CometBFT provides a Propose-Prevote-Precommit three-step BFT process, with block intervals of 2 seconds or 12 seconds; the PoSg weight engine snapshots Stake and SignalScore at each Epoch to calculate Voting Power for validators and drive the next election.
3. Execution Layer (Application Sharding)

   Namespace Router routes transactions to the corresponding Shard's ABCI application based on namespace\_id:

   * Execution Shard: EVM / Move / WASM dApp
   * Data Shard: AI training data, file storage
   * Service Shard: Oracle, VRF, Signal dedicated Shard
4. Data Availability Layer (Chunk + NMT)

   All Shard data slices are written into the Namespace Merkle Tree after erasure coding. Every ≈ 10 minutes, the NMT root is aggregated with threshold signatures to generate a DA Commit, which is anchored to Bitcoin L1 through Taproot transactions.
5. AI Governance Layer

   Off-chain RL-Tuner, GNN Detector, and XAI-Auditor periodically submit parameter tuning and risk suggestions to the on-chain ParameterOracle; all changes must be written into the consensus state after a delay window and PoSg voting.
6. Interface Layer

   Provides WebSocket events, gRPC/RPC queries, and IBC-lite cross-chain messages; light nodes only need to synchronize block headers and the Namespace proofs of interest to verify the state.

#### Three Core Data Flows

1. BTC Value Flow

   TODO Value Flow Diagram

   Mining rewards -> Mining Squared tokenization -> Router automatic allocation

   -> (a) Staked to StakingModule to enhance validator VP

   -> (b) Invested in DeFAI strategies to earn external returns

   -> (c) Directly returned to miners/Agents as Gas

   Block rewards and strategy earnings flow back again, forming a compound interest cycle.
2. Signal Flow

   Agents submit submitSignal() through Signal Shard -> CheckTx immediately soft confirms and broadcasts signal.softCommit;

   Proposers package the current round Signal into BatchSignalTx during block production -> Validators delegated by sender and receiver synchronously increase SignalScore -> Affects the next Epoch Voting Power.
3. Proof/Data Flow

   Rollup or Shard transactions -> NMT slices -> Enter Hub header with the block to achieve second-level BFT finality;

   Hub generates DA Root + threshold signature every 10 minutes -> Written into Bitcoin Taproot -> All states achieve PoW economic finality at the minute level.

Through the above layers and three data flows, B² Hub weaves the finality and security collateral (Stake) of Bitcoin with the real-time production factors (Signal) of AI into the same economic and technical stack:

BTC is continuously injected from the bottom, Signal is consumed at the millisecond level and instantaneously fed back to consensus security, while all data and states are ultimately sealed into Bitcoin, making them immutable. This structure makes the Hub inherently adaptable to high-frequency AI scheduling while maintaining the same level of finality reliability as Bitcoin.

### PoSg Consensus Layer

PoSg (Proof of Signal + Stake) is B² Hub's original proprietary consensus mechanism, driven by a dual engine of Stake and Signal. It introduces payable and verifiable AI Signal as a second-dimensional weight on the basis of traditional staking security (PoS), merging capital collateral with real work into a secure crankshaft:

\[!\[]\[image]]

Where Stake comes from staked BTC/B2 and can be slashed; SignalScore is the weighted sum of all signals sent/received by agents delegated to validator v within the last M epochs. α and β are dynamically adjusted by on-chain governance (default 0.7/0.3). Therefore—staking increases the cost of malicious behavior, while signals directly convert on-chain activity into a security budget.

Key Components

| Module         | Responsibility                                               | Highlights                                               |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| StakeMap       | Records BTC/B2 staking and delegation relationships          | Multiple delegation, liquid shares, delayed unlocking    |
| SignalPool     | Caches all validated Signals within the current Epoch        | Soft confirmation enters Pool, archived after hard block |
| ScoreAccounter | Settles SignalScore -> Writes to Validator metadata          | Dual scoring for sender & receiver, window rolling       |
| PoSg Engine    | Calculates VotingPower, selects the next round validator set | α/β and window length can be governed and modified       |
| SlashGuard     | Monitors double signing, offline, forged signals, etc.       | Penalizes Stake + resets SignalScore                     |

Workflow (Epoch Level)

TODO Flowchart

1. Snapshot

   Freeze the current Stake and SignalPool, write to the Epoch Header.
2. Validator Set Selection

   Select the top N based on VP; if the difference between this set and the last one is greater than Δ, trigger DKG to generate a new threshold public key.
3. CometBFT Block Production

   Adopt weighted round-robin proposal; block interval can be configured to 2 s or 12 s; Signal Tx is soft-executed in CheckTx and batch settled in DeliverTx.
4. Settlement & Slash

   Block fees + Signal rewards are distributed according to VP; double signing and malicious nodes on the graylist are immediately penalized.
5. Rolling

   At the end of the Epoch, the window slides; a new Snapshot starts the cycle again.

Security and Performance Features

* Economic security dual insurance. Stake can be slashed, and Signal requires payment; attackers must lock slashing collateral to gain points.
* Second-level soft confirmation. Signal transactions return softCommit events within 200–500 ms, meeting the real-time requirements of AI microservices; finality is protected by BFT in 2/12 s.
* Dynamic adaptation. RL-Tuner automatically adjusts α/β, minimum Signal fee rate, and Slash coefficient based on chain load and Slash events; all changes are implemented through delayed voting.
* Anti-centralization design. SignalScore ≤ k × Stake (k≈3) prevents zero-stake point farming; delegation can be distributed among multiple validators to reduce the risk of monopolization by large holders.
* Light client friendly. Block headers embed aggregated threshold signatures; light nodes only need to verify signatures and NMT proofs to confirm any Shard state.

In summary: PoSg merges "slashed funds" and "paid funds" into the same voting power, maintaining the economic resistance to malicious behavior of the staking system while making the real work of AI a direct fuel for enhancing chain security and validator rewards, establishing the shortest path between second-level experiences and minute-level PoW finality. The following subsections will elaborate on the state machine structure, signal batch settlement algorithm, reward/slashing rules, and how AI intelligent governance seamlessly adjusts these parameters.

#### CometBFT Overview and Adaptation

Why Choose CometBFT

CometBFT (formerly Tendermint Core) is one of the most mature BFT consensus engines in the industry, featuring instant finality, ABCI application layering, and cross-language easy embedding. It allows us to encapsulate the staking logic of PoSg, Signal batch settlement, and Application Sharding within the ABCI application layer without modifying the underlying network and voting protocol, thus reusing its stable network stack and multi-language ecosystem.

Consensus Process Overview

* Block interval: 2 s block production timeout; governance can switch on-chain.
* Instant finality: Finalize after ≥ 2/3 VotingPower completes Precommit, with no probability of reorganization.

PoSg Custom Adaptation

| CometBFT Integration | Our Extension                                                                                                                                                                          | Description                                                                                             |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| CheckTx              | 1. Verify Signal Tx signature, fees, Proof 2. applySoft(softState, tx) writes to soft state cache 3. EmitEvent("signal.softCommit")                                                    | Signal receives soft confirmation immediately in the mempool stage, pushed to Agent within 200–500 ms.  |
| PrepareProposal      | 1. Extract pending Signal from softState within Δt interval 2. Sort by (timestamp, id) -> encapsulate BatchSignalTx 3. Write to proposal block; empty blocks can still contain batches | Ensures deterministic ordering across the network, preventing proposer malfeasance or partial ordering. |
| ProcessProposal      | Full nodes replay BatchSignalTx, calling applyHard(appState, list); if inconsistent with soft state, reject the proposal.                                                              | Maintains soft/hard state consistency, preventing double spending.                                      |
| FinalizeBlock        | 1. Aggregate validator BLS / Schnorr signatures (threshold Schnorr via FROST) 2. BlockHeader adds taprootCommit field for DA layer use                                                 | Light clients only need to verify a single threshold signature.                                         |

Priority mempool

```
Priority(tx) =    2  if tx.isSignal
               1.01  if tx.isGasBidHigh
               1.00  default
```

Signal Tx highest priority, ensuring soft confirmation can still occur promptly during network congestion. Batches are uniformly collected during the block finalization phase to avoid header bloat.

Threshold Signatures & Light Nodes

* Each round Epoch validators generate Schnorr public key PK\_epoch through FROST-DKG;
* BlockHeader saves aggSig; light clients only verify Verify(PK\_epoch, aggSig, blockHash), without needing to traverse individual signatures;
* Epoch handover blocks contain re-aggregated signatures of the previous Epoch root, ensuring verifiable key rotation.

Data Availability Anchoring Pipeline

!\[]\[image]

CometBFT's event system broadcasts DA root, threshold signatures, and block height to DA Workers, which periodically aggregate and write to Bitcoin Taproot.

Security and Failover

* Greylist validators: After the GNN detector marks suspicious nodes, the PoSg Engine temporarily removes their voting rights; CometBFT can still finalize with automatic downscaling.
* Long fork detection: If a Hub light client finds a Header inconsistent with Bitcoin submissions, it triggers a network-wide Slash; CometBFT nodes automatically reject malicious branches by comparing taprootCommit.

Through minimally invasive customization, we treat CometBFT as a "high-speed voting machine," injecting PoSg's Stake/Signal weight, Signal soft confirmation and Batch finalization, threshold signatures, and DA Root commitments at the ABCI hook layer; maintaining second-level finality and a mature network stack while laying a solid foundation for subsequent Bitcoin anchoring, Application Sharding, and AI intelligent governance.

#### Core State and Data Structures

The state machine of PoSg is based on KV-Store + prefix tree, with each prefix corresponding to a type of object; during snapshots, a simple (key, value, version) list is exported, which can be used by light nodes to reconstruct the Merkle root. The table below lists the most important key spaces and structures (Go-pseudo).

| Prefix | Structure / Description                                               | Read/Write Path                   |
| ------ | --------------------------------------------------------------------- | --------------------------------- |
| B2S/   | StakeEntry: Single stake share                                        | StakingModule                     |
| B2D/   | DelegationEntry: Agent -> Validator mapping                           | AgentRegistry.delegate()          |
| B2A/   | AgentMeta: A-AA public key, delegation, version                       | registerAgent / upgrade / recover |
| B2G/   | SignalObj: Full signal after block finalization                       | DeliverTx(BatchSignalTx)          |
| B2P/   | SoftSig cache (TTL)                                                   | CheckTx()                         |
| B2V/   | ValidatorMeta: Stake, SignalScore, accumulated rewards, greylist flag | EpochTransition                   |
| B2E/   | EpochInfo: Window pointer, α/β, threshold public key                  | Updated at the end of each Epoch  |
| B2C/   | ChainParam: Hard thresholds, window M, k value, and other constants   | Governance modification only      |

1. Stake and Delegation

   ```go
     type StakeEntry struct {
         Amount      uint64    // sat/b2
         UnlockEpoch uint32    // 0 = still locked
     }

     type DelegationEntry struct {
         Validator   addr
         Percent     uint16    // thousandths, supports multiple entrustments.
     }
   ```

   * Pledged shares are split by the pledger's address + nonce for easier partial unlocking.
   * Multiple delegations are expressed through multiple D/ records, with the total percentage = 1000.
2. Agent and Signal

   Here’s a polished version of the provided text:

   ```go
   type AgentMeta struct {
       PubkeyRoot [32]byte // Multi-signature root
       DelegateSet []addr   // Current set of delegated validators
       Version     uint32
   }
   ```

   ```go
   type SignalObj struct {
       Sender    addr
       Receivers []addr
       Weight    uint64
       BlockTime int64
       Id        [32]byte
   }
   ```

   * After a SignalObj is finalized, only the essential fields are retained; the payload is handled internally within the shard.
   * SoftSig caches only the Id and Sender, with a TTL of one block; it is cleared upon block finalization.
3. Validator State

   ```go
   type ValidatorMeta struct {
       Pubkey        []byte // CometBFT ed25519 or BLS12 public key
       StakeSum      uint64
       SignalScore   uint64
       VotingPower   uint64 // α·Stake + β·SignalScore (scaled)
       RewardAccrued uint64
       GrayFlag      bool
       LastSlashEpoch uint32
   }
   ```

   * VotingPower is updated and synchronized with the CometBFT UpdateValidator API.
   * The GrayFlag is marked by the AI Detector; nodes on the graylist do not incur penalties on their stake, but their Voting Power is set to zero.
4. Epoch & Global Parameters

   ```go
   type EpochInfo struct {
       EpochNum    uint32
       WindowPtr   uint16 // Points to the circular SignalRing
       AlphaBeta   [2]uint16 // Scaled α/β values (multiplied by 10000)
       ThresholdPK []byte // FROST Schnorr aggregate key
       DA_RootPrev [32]byte
   }

   type ChainParam struct {
       WindowSize         uint16 // M
       MinSignalFee      uint64
       MaxWeight         uint64
       StakeToScoreRatio uint8  // k
       HardSlashRatio    uint16 // ‱
   }
   ```

   The WindowPtr maintains the SignalScore in a circular queue: `SignalRing[WindowPtr]` stores the scores of validators for the current epoch. During epoch rotation, the oldest slot is overwritten, allowing for O(1) window movement through addition and subtraction.
5. Merkle Combination Root Layout

   ```
   StateRoot = MH(

   MH("B2S/"+*), // Stake Trie

   MH("B2A/"+*), // Agents

   MH("B2V/"+*), // Validators

   MH("B2D/"+*), // Delegations

   MH("B2G/"+epochPtr), // Current Window Signal Sub Trie

   MH(other shards ...)

   )
   ```

   * Each namespace is separately hashed with Merkle, then concatenated for easier synchronization of specific object types.
   * Light nodes that only care about balances can download the "B2S/" sub Trie and verify the parent root.
6. Memory Cache and Asynchronous Disk Writes
   * SoftSigCache: LRU+TTL map, written during CheckTx; read during PrepareProposal to generate Batch.
   * SignalRing: a circular array of map\[ValidatorID]uint64; at the end of the Epoch, the current slot is written to the DB, then the pointer ++ mod M.
   * RocksDB / LevelDB backend enables column families to reduce write amplification.

This state layout follows three principles:

* Parallelizable and partitionable—Stake, Signal, and Shard are independent and can be synchronized as needed;
* Window O(1) rotation—SignalScore moving window does not require full chain scanning;
* Soft/hard state separation—soft confirmations are only in memory, and any data not included in blocks is automatically cleared after 1-2 blocks.

With these structures, the PoSg engine only needs to incrementally update VotingPower and write an EpochInfo to complete snapshots each Epoch, significantly reducing I/O and storage costs, while providing clear verifiable synchronization boundaries for light clients and archival nodes.

#### Signal Soft Confirmation & Batch Settlement Mechanism

Goal: Balance millisecond-level user experience with global consistency

* Soft Confirmation (Soft-Commit): Signal Tx is executed locally and events are broadcast immediately after entering CheckTx, providing AI Agents with second-level feedback.
* Hard Settlement (Hard-Commit): Each block generation cycle, the proposer packages soft confirmation signals within the same time window into 1 – N BatchSignalTx written to the block, guaranteed irreversible by PoSg + BFT.

A. Temporal Overview (Δ = blockTime = 2 s / 12 s)

B. Core Process

| Step | Processing Point            | Logic                                                                                                                                                                                                                                         |
| ---- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1    | CheckTx                     | 1. Parse Tx -> Verify signature / fees / Proof 2. Deduplication: If id is already in SoftCache or has been committed, reject 3. applySoft(SoftCache, tx) —— Update temporary score 4. EmitEvent("signal.softCommit", id, sender, weight)      |
| 2    | PrepareProposal (proposer)  | 1. Retrieve Signals from cache with timestamp ∈ \[lastCommit, now] 2. Stably sort by (timestamp, id) 3. Assemble BatchSignalTx{signals\[]} in shards; support multiple batches 4. Append other ordinary Tx afterwards                         |
| 3    | ProcessProposal / DeliverTx | 1. Full nodes unpack Batch 2. Verify nonce and weight limits for each signal 3. applyHard(StateDB, signal): a. Write to G/ Sub Trie; b. Delegate validators for sender/receiver each +weight 4. Mark corresponding SoftCache entry as “final” |
| 4    | FinalizeBlock               | Generate threshold Schnorr aggregate signature, block achieves BFT finality; upper layer applications can treat signal.hard=true as a business termination condition                                                                          |
| 5    | Cleanup                     | Clear already committed items in SoftCache after Commit; expired (TTL = 1 block) uncommitted signals re-enter the next round of candidates                                                                                                    |

C. BatchSignalTx Data Format (RLP / Protobuf)

| Field      | Type          | Description                                    |
| ---------- | ------------- | ---------------------------------------------- |
| count      | uint16        | Number of Signals in this batch                |
| signals    | \[]SignalLite | Simplified structure (no payload)              |
| merkleRoot | bytes32       | Merkle root of all id‖weight leaves, for proof |

```go
SignalLite {
  id bytes32
  sender address
  receivers []address
  weight uint64
  ts uint32 // seconds
}
```

Merkle root ensures batch replay consistency; if proposer forges order, block will be rejected if root differs during Precommit phase.

D. Fees and Garbage Control

* minSignalFee: AI governance can dynamically increase; soft confirmation must also deduct fees first.
* weight ≤ MAX\_WEIGHT: Prevent large single score inflation; exceeding must be split into multiple transactions.
* Graylisted nodes incur additional grayMultiplier × minSignalFee.

Fees are locked during soft confirmation; if not ultimately committed (TTL timeout), 90% is automatically refunded, and 10% is destroyed.

E. Conflict and Rollback Handling

| Scenario                                                      | Result                                                                                                        | Event                                |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| Multiple submissions with the same id                         | First soft confirmation successful, others Duplicate                                                          | signal.duplicate                     |
| Soft state passes but hard state fails (nonce, balance, etc.) | signal.revert, Agent can resend after perception                                                              | Soft state score deducted from cache |
| Proposer ignores signals                                      | Automatically enters next round proposer queue after TTL; ignoring 3 times consecutively will result in Slash |                                      |

F. Security Summary

* Soft confirmation is not final: If Agent's business requires economic assurance -> wait for hard block; large settlements -> wait for Bitcoin Anchoring.
* Economic resistance to malicious behavior: Sender pays + weight limits + k×Stake cap, score inflation cost increases linearly.
* Slash conditions: Tampering with Batch, repeated omissions, and fraudulent replays can all submit BatchFraudProof to trigger penalties.

The soft confirmation / batch accounting mechanism allows B² Hub to provide sub-second feedback for AI Agents without sacrificing BFT-level consistency and Bitcoin-level economic finality—harmonizing real-time performance, throughput, and security within the same protocol stack.

#### Voting Power Calculation and Validator Update

PoSg reassesses validator weights for each Epoch and synchronizes the results to CometBFT. This process consists of three steps: Collection -> Normalization -> Output.

1. Weight Collection

| Symbol | Meaning                    | Measurement Source                                        |
| ------ | -------------------------- | --------------------------------------------------------- |
| S\_v   | Staked Amount (StakeSum)   | StakeMap: Total BTC/B2 delegated to validator v           |
| Q\_v   | Signal Score (SignalScore) | SignalRing\[WindowPtr]: Cumulative weight within window M |
| F\_v   | Graylist Flag              | ValidatorMeta.GrayFlag, written by AI detector            |

2. Normalization and Mixing Formula

   1. Scaling

   * Staking: $\hat S\_v = \frac{S\_v}{\sum S}$

   * Signal: $\hat Q\_v = \frac{Q\_v}{\sum Q}$

   2. Upper Limit Constraint

   $$\hat Q\_v \le k \cdot \hat S\_v \quad\text{(k = StakeToScoreRatio 3)}$$

   3. Graylist Penalty

   $$\hat S\_v = 0,;\hat Q\_v = 0 \quad F\_v = \text{true}$$

   4. Mixed Weight

   $$VP\_v = \alpha \cdot \hat S\_v + \beta \cdot \hat Q\_v \qquad (\alpha + \beta = 1,; \alpha,\beta \in \[0,1])$$

   5. Minimum Weight Filtering

   If $VP\_v < VP\_\text{min}$ (governance parameter, default 0.001), the validator is considered a backup and does not participate in block production for this Epoch.
3. Validator Set Selection Algorithm

   ```
   input: VP map, TargetSize N

   list = sort_desc(VP) // Weight in descending order

   set = list.take(N) // Take top N

   if Σ VP(set) < 0.67 // Ensure ≥2/3 weight is online

   expand set until Σ VP ≥ 0.67

   return set
   ```

   * N defaults to 64, adjustable by governance;
   * If weight concentration occurs (whale validators), expansion ensures ≥2/3 VP is online;
   * Automatically triggers governance proposal reminders after exceeding 100.
4. Write to CometBFT
   1. UpdateValidator
   * Hub ABCI calls CometBFT's ValidatorUpdates, submitting \<pubkey, VP\_scaled>;
   * VP\_scaled = uint64(VP \* 1e12) to retain 12 decimal precision.
   2. Threshold Public Key Rotation
   * Trigger FROST-DKG when the difference between the new and old sets is ≥ ⅓;
   * Generate new ThresholdPK and write to EpochInfo; light nodes can verify the new aggregated signature by syncing.
5. Epoch Rotation Timeline (Example 12 s block, 1 h Epoch)

   !\[]\[image]
6. Parameter Governance and AI Tuning

   | Parameter        | Default Value | Adjustment Method | AI Self-Tuning Range                                               |
   | ---------------- | ------------- | ----------------- | ------------------------------------------------------------------ |
   | α / β            | 0.7 / 0.3     | DAO Voting        | RL-Tuner fine-tunes within ±0.1                                    |
   | $VP\_\text{min}$ | 0.1 %         | Governance        | Automatically scales linearly with the number of validators        |
   | k (StakeToScore) | 3             | Governance        | Can be temporarily reduced to 2 after GNN detects abnormal scoring |
   | Window M         | 24 h          | Governance        | Can slide between 6–48 h based on chain load                       |

   Delay Barrier: All parameter changes take effect after ≥ 100 Hub blocks (≈20 min); if XAI gives a "high risk" mark, a ⅔ supermajority is required.
7. Key Security Conclusions
   1. Adversaries must simultaneously accumulate Stake and Signal: α≥0.5 and k limits -> Pure signal manipulation cannot control > 33 % VP.
   2. Immediate Downgrading from Graylist: After being marked by the AI detector, the weight for the next block is recorded as 0, but not immediately slashed; reduces the cost of false positives.
   3. Window Rolling Against Sudden Attacks: The signal scoring window slides, introducing at most 1/M new scores per hour, buffering against malicious scoring spikes.

Through this VP calculation and update mechanism, B² Hub can dynamically reflect the true distribution of staking and AI activity in each Epoch, ensuring that block production rights always follow "wealthy and useful" nodes while maintaining a governable security barrier and real-time risk control.

#### Epoch Lifecycle & FROST-DKG

Terminology

* Epoch: The billing and election cycle of PoSg, default is 1 hour.
* Committee: The set of validators for the current Epoch (size = N).
* ThresholdPK: The shared threshold Schnorr public key for the committee in this Epoch, used for block aggregation signatures and DA Commit.

A. Overview of State Machine Stages

| Stage       | Trigger                                        | Main Transactions                                            | Write Key       |
| ----------- | ---------------------------------------------- | ------------------------------------------------------------ | --------------- |
| Init        | Previous Epoch Commit + 1                      | Pull the latest ChainParam; clear soft state cache           | —               |
| Running     | Throughout the Epoch                           | CometBFT produces blocks every 2 s/12 s; Signal soft -> hard | G/, SoftCache   |
| Closing     | Countdown 2 blocks                             | Stop new Stake & Signal; lock window                         | —               |
| Snapshot    | Final block EndBlock()                         | Record StakeMap, SignalPool, write EpochInfo                 | E/              |
| Settlement  | After Commit()                                 | Distribute rewards, handle Slash, update graylist            | V/              |
| KeyGen      | Immediately parallel after Snapshot completion | Run FROST-DKG to generate the next Epoch ThresholdPK'        | E/'.ThresholdPK |
| Switch-Over | First block of the next Epoch                  | CometBFT loads new validators & public keys                  | —               |

Reorganization window: PoSg BFT has no probability of reorganization; Epoch boundaries align with block finality, with no special delays.

B. FROST-DKG Workflow (N-of-N -> t-of-N)

| Step                                                                                                                        | Data     | Time Limit (Default) |
| --------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------- |
| 1. ShareCommit Each validator $v\_i$ generates polynomial $f\_i(x)$, sends commitment $C\_{i,j}=g^{f\_i(j)}$ to all         | 32 B × N | 30 s                 |
| 2. ShareVerify Verify the consistency of received commitments, broadcast ACK/NAK                                            | 1 B × N  | 30 s                 |
| 3. Complaint If NAK, submit fraud proof; PoSg Slash for violating nodes Stake × 5%                                          | 64 B     | 20 s                 |
| 4. ShareAggregate Sum all valid $f\_i(0)$ to obtain public key $PK = g^{\sum f\_i(0)}$; each holds private key share $s\_i$ | 32 B     | —                    |
| 5. PublishPK Write to EpochInfo.ThresholdPK and broadcast KeyReady event                                                    | 32 B     | 5 s                  |

* Threshold value $t = \left\lceil \frac{2N}{3} \right\rceil$, must satisfy ≥ 2/3 VP to sign.
* Parallel execution: DKG communication via gRPC-p2p channel, does not block block production; if not completed within 180 s, enter Safe-Fallback — continue using the previous Epoch public key, but nodes that did not complete Slash on time lose 1% Stake.

C. Threshold Signature Usage Points

| Purpose                | Signed Message                | Trigger Frequency                     |
| ---------------------- | ----------------------------- | ------------------------------------- |
| Block Aggregation      | blockHash                     | Every 2 s / 12 s                      |
| DA Commit              | DA\_Root // HubHeightRange    | Every \~10 min                        |
| Migration / Governance | stateRoot\_final, paramUpdate | Irregularly, multi-signature evidence |

Implementation: Uses Schnorr on secp256k1 + FROST aggregation; aggregated signature size is constant at 64 B. Light nodes only need PK + single signature to verify any block or DA Commit.

D. Handling of Rewards and Slash in Epoch Rotation

1. RewardPool Allocation
   * BlockFeeSum + SignalFeeSum -> Distributed according to VotingPower ratio;
   * ActiveSignalTopK Reward: Take the top 10% nodes by SignalScore and add a 5% Bonus.
2. Slash Trigger Sources
   * Malicious commitments or non-responses during DKG phase;
   * Double signing, missing batch reviews, data unavailability;
   * AI graylist confirmation period ends without successful appeal.
3. Forfeiture Handling
   * x% Stake destroyed 50%, 50% injected into insurance pool;
   * Continuous two Epochs in graylist -> Temporary expulsion, requires governance to re-whitelist.

E. Sliding Window & Score Reset

* SignalRing circular array length = WindowSize (M Epoch);
* At the end of Epoch:
  1. Pointer WindowPtr = (WindowPtr + 1) mod M;
  2. New slot set to zero; old slot value reduced by current SignalScore.
* Computational complexity is constant level, avoiding full chain traversal.

F. Temporal Example (N=64, blockTime=2 s)

!\[]\[image]

In an ideal network, the entire transition only pauses for 1 block; even if DKG times out, it can safely fallback without affecting block continuity.

The Epoch lifecycle packages weight snapshots, reward settlements, forfeiture executions, and threshold key rotations into a fixed rhythm of 1 hour, allowing PoSg's weight to change in real-time with staking and Signal while maintaining periodic refresh of network keys and security assumptions. FROST-DKG improves bandwidth/storage efficiency with non-interactive aggregated signatures, while safety barriers and fallback mechanisms ensure that any abnormality at any stage does not lead to chain pauses.

#### Rewards, Forfeiture, and Graylist

PoSg weaves economic positive incentives, security penalties, and real-time risk control into three parallel channels:

1. Instant profit sharing per block
2. Additional incentives and forfeiture per Epoch
3. Instant downgrading and enforced high fees for graylist.

A. Sources of Fees and Reward Pool Classification

| Income Item               | Generation Timing   | Accounting Location | Purpose                                          |
| ------------------------- | ------------------- | ------------------- | ------------------------------------------------ |
| GasFee                    | At Tx execution     | BlockFeePool        | Distributed by VP per block                      |
| SignalFee = Weight        | Deducted at CheckTx | SignalFeePool       | 50% destroyed, 50% distributed in the same block |
| DA Sampling Fee           | Light node sampling | DAFeePool           | Subsidize validator storage                      |
| Slash Forfeiture 50%      | Violation occurs    | InsurancePool       | Compensate the victim/future subsidies           |
| External Strategy Revenue | DeFAI -> Router     | ExtRewardPool       | Mixed with BlockFeePool                          |

BlockReward: Hub has no native inflation; if the community votes to open it later, it can be injected into InflationPool and accounted with Gas.

B. Instant Block Allocation

\[!\[]\[image]]

* ValidatorMeta.RewardAccrued is updated immediately after DeliverTx ends for each block.
* Stakers can automatically reinvest or claim according to Epoch; claims can be made in BTC/B2 direct payment or rBTC receipts.

C. Additional Epoch Incentives

1. Active-Signal Bonus
   1. Statistics of the validator set 𝒯 ranked in the top 10% by SignalScore;
   2. Take BonusPool = 0.05 × (GasFee + SignalFee);
   3. Distributed according to VP weight to 𝒯.
2. Stake Loyalty Bonus
   1. Continuous staking ≥ 30 days without unlocking shares receives +2% APR (compound) subsidy to prevent short-term arbitrage.

D. Slash Logic

| Violation Category                  | Trigger Method                 | Slash Ratio                                    | Slash Flow                                        |
| ----------------------------------- | ------------------------------ | ---------------------------------------------- | ------------------------------------------------- |
| Double Signing / Equivocation       | Submit EvidenceTx{blkHash,sig} | 5% Stake + SignalScore reset to zero           | 50% burned, 25% insurance pool, 25% whistleblower |
| Data Unavailability                 | DA sampling failure proof      | 3% Stake                                       | 50% insurance pool / 50% burned                   |
| Continuous Offline                  | ≥ X blocks without voting      | 0.1% per ΔEpoch (capped at 2%)                 | 100% insurance pool                               |
| Signal Forgery / Score Manipulation | FraudProof{txId,proof}         | Manipulated amount ×2 & SignalScore reset to 0 | 70% burned, 30% insurance pool                    |

Evidence submission window: within 2 Epochs after the violation occurs; expired and invalid thereafter.

Insurance Pool Usage

* Automatic compensation for user withdrawal delays caused by DA failures;
* Provides governance budget & emergency loans for validators.

E. Graylist Mechanism

| Process            | Description                                                                                                                         |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| Marking            | AI GNN detector or governance multi-signature submits GrayProof(addr,reason); writes ValidatorMeta.GrayFlag=true                    |
| Immediate Penalty  | 1) VotingPower=0 immediately loses block production eligibility; 2) SignalFee multiplied by grayMultiplier=3                        |
| Observation Period | Default 1 Epoch; validators can upload SelfAudit appeals; AI Detector automatically retests                                         |
| Clearing           | If the appeal is successful -> gray flag removed; if failed -> 1% Stake deducted and moved to alternative group                     |
| Upgrade to Slash   | If on the graylist for 2 consecutive Epochs with sufficient violation evidence, triggers "persistent malice" Slash, penalized at 3% |

F. Example: Reward & Slash Flow

Conditions:

* Epoch Revenue: Gas 2000 B2 + SignalFee 1000 B2
* BonusPool: 150 B2 (5% of 30)
* Validator A VP=10%, in Top-Signal group;
* In the same Epoch, B is caught for double signing, Stake=10000 B2, penalized 500 B2.

A Receives

Immediate block reward = 0.10 × 3000 = 300 B2

Active-Signal points = 0.10 / Σ(VP\_T) × 150 ≈ 20 B2

Total 320 B2

B Compensation

Slash 500 B2 -> 250 burned; 125 insurance; 125 whistleblower

Insurance pool balance +125 B2, available for future DA incidents.

G. Parameter Governance & AI Regulation

* RL-Tuner dynamically adjusts minSignalFee and Active-Bonus% through reward/slash comparisons and network load;
* Hard thresholds: SlashRatio capped at 50%, BonusPool capped at 10%; any AI recommendations exceeding limits require supermajority governance approval.

This reward—slash—graylist system forms a clear closed loop on the PoSg layer:

* Good behavior (continuous staking + high-quality signals) -> earns rewards and weighting;
* Bad behavior (malicious acts, offline, score manipulation) -> first graylisted and downgraded, then economically penalized;
* The insurance pool provides the final buffer for on-chain incidents.

This captures economic incentives while retaining rapid response space for AI risk control, ensuring that the validator set is both active and robust.

#### Light Client Verification and PoW Finality

Goal: Enable a mobile-level node to confirm transactions in seconds and achieve economic finality on par with Bitcoin within minutes, under conditions of a few KB bandwidth + a few MB storage.

**A. Data Held by Light Clients**

| Data                                                    | Size         | Update Frequency | Acquisition Method                         |
| ------------------------------------------------------- | ------------ | ---------------- | ------------------------------------------ |
| HubHeader {height, time, appHash, daRoot, aggSig, pkId} | 200 B        | 2 s / 12 s       | gossip-sub                                 |
| ThresholdPK (pkId -> pubKey)                            | 64 B / Epoch | 1 h              | Downloaded during initial sync or rotation |
| BTC Anchor Header (simplified SPV)                      | 80 B × n     | \~10 min         | Bitcoin network or relay                   |

Total persistent storage is <10 MB; historical headers can be pruned to "the most recent K blocks + archival points per Epoch."

**B. Verification Steps**

1. **Quick Signature Verification of HubHeader**

   ```
   VerifyAggSig(ThresholdPK[pkId], aggSig, SHA256(blockHeaderCore))
   ```

   If successful, the block is considered to have achieved near-instant finality in PoSg BFT.
2. **Data Availability Sampling (Optional)**
   * Randomly sample n = 25‒50 chunks and check the Merkle proof leading to daRoot.
   * If any sample fails, mark the block as "DA Suspicious" and await full node adjudication or slashing results.
3. **Bitcoin Anchor Confirmation**

* Every 10 minutes, read the Taproot Anchor transaction:

```
<prefix>|hubChainId|rangeStart|rangeEnd|daRoot|sigHash
```

* Verify sigHash using the same Epoch ThresholdPK.
* Wait for k = 3‒6 Bitcoin block confirmations.
* If daRoot matches the local HubHeader, proceed to economic finality.

**C. State Query and Transaction Verification**

1. **Query:** The light client sends `<namespace, key, height>`.
2. **Full Node Response:**
   * value
   * MerklePath (key -> ShardRoot)
   * NMTPath (ShardRoot -> daRoot)
   * Corresponding HubHeader pointer
3. **Verification:**
   * Check HubHeader aggSig
   * Verify Merkle & NMT paths
   * If the block is anchored, the data is trustworthy.

**D. Quick Security Levels**

| Level | Wait Time                                     | Applicable Scenarios                                                  |
| ----- | --------------------------------------------- | --------------------------------------------------------------------- |
| Soft  | signal.softCommit (< 300 ms)                  | AI microservice acknowledgments, game actions                         |
| BFT   | 1 HubHeader (2 s / 12 s)                      | Small payments, standard dApp interactions                            |
| PoW   | 1 Taproot Anchor + 3 Bitcoin blocks (≈15 min) | Large settlements, cross-chain bridges, institutional reconciliations |

**E. Resistance to Reorganization and Attack Analysis**

| Threat                 | Required Disruption                      | Estimated Cost                                                     |
| ---------------------- | ---------------------------------------- | ------------------------------------------------------------------ |
| Hub Layer Fork         | ≥ ⅓ VP double-signing + slashing risk    | Locking BTC/B2 > ⅓ total stake + signaling costs                   |
| Data Concealment       | ≥ ⅔ VP collusion + sampling interception | Probability of being sampled \~ 1 - (1 - p)^n -> Slashing 3% Stake |
| Bitcoin Reorganization | Depth k block rollback                   | > 51% hash power, costing nearly $100 million/hour                 |

Light clients can achieve security finality nearly equivalent to full nodes by maintaining "Hub aggregate signatures + BTC Anchor dual verification" at a mobile resource level.

**F. Developer Interface Example**

```
// 1. Subscribe to headers

hub.subscribeHeaders((header) => lite.acceptHeader(header));

// 2. Query account balance

const proof = await lite.requestProof("S/addr/0x123", header.height);

if (lite.verifyProof(proof, header)) {

console.log("balance=", proof.value);

}

// 3. Check PoW finality

if (lite.isPowFinal(header)) {

// Safe cross-chain transfer

}

```

The B² Hub's lightweight client solution leverages three tools: threshold Schnorr aggregate signatures, NMT domain Merkle, and Taproot Anchoring, achieving: second-level header downloads, millisecond-level verification, sampling data availability, and Bitcoin-level economic finality—allowing any edge device to join the "Bitcoin × AI" network without barriers while maintaining security.

### Application Sharding

#### Namespace Design and Routing

#### Shard Creation, Upgrade, and Dynamic Expansion

#### IBC-lite Cross Shard Atomic Messaging

#### Resource Scheduling and Load Balancing Strategies

### Data Availability & Bitcoin Anchoring

#### Chunk + NMT Architecture and Sampling Retrieval

#### DA Commit Taproot Transaction Format

#### Second-level BFT -> Minute-level PoW Finality Model

### Signal Dedicated Shard

This Shard only processes Signal transactions for AI agents, exchanging the lightest state machine for the highest TPS; soft confirmations provide feedback to Agents in milliseconds, while hard settlements directly affect PoSg Voting Power.

#### Signal Transaction Format and Double Scoring Rules

```
message SignalTx {

bytes32 id = 1; // keccak(sender‖nonce‖ts)

address sender = 2;

repeated address receivers = 3; // >=1

uint64 weight = 4; // sat / b2

uint32 expiry = 5; // block height

bytes32 payloadHash = 6; // off-chain data hash

bytes proof = 7; // ZK / signature aggregation

bytes sig = 8; // Schnorr / ECDSA

}

```

Double Scoring

* Sender delegates to validators + weight
* Each receiver delegates to validators + weight / n
* Scores are written to SignalRing\[WindowPtr], window rolls over to SignalScore.

#### Soft-Commit Events and Cache Deduplication

| Step                | Action                                                                                                 |
| ------------------- | ------------------------------------------------------------------------------------------------------ |
| CheckTx             | Verify signature -> Deduplication table query id -> Record in SoftCache -> Broadcast signal.softCommit |
| Deduplication Table | LRU + TTL = 1 block; Duplicate Tx returns Duplicate                                                    |
| Soft State Update   | softState\[sender] += weight; used for UI & quick triggering of the next workflow                      |

Agent receives softCommit within 200–300 ms, indicating that the chain has accepted the task.

#### BatchSignalTx Settlement Process

1. Collect all Soft Signals from proposer within Δt during PrepareProposal.
2. Sort by (timestamp, id) in stable order; prevent partial ordering.
3. Package ≤1 MB into a BatchSignalTx, attach Merkle Root.
4. Execute DeliverTx to replay one by one:

* Write to G//id
* Update SignalScore for both validators

5. Clean up successful settlement entries from SoftCache; on failure, send signal.revert.

Within 40 ms, 10,000 signals can be settled, with a single block signal TPS ≈ 5 k / 2 s block.

#### Anti-Spam Scoring Limits and Security Barriers

| Rule                  | Value                   | Trigger Result                        |
| --------------------- | ----------------------- | ------------------------------------- |
| minSignalFee          | Dynamic: 10 – 1000 sat  | Below this is rejected                |
| MAX\_WEIGHT           | 1 BTC / Tx              | Exceeding must be batched             |
| Score ≤ k·Stake       | k=3                     | Exceeding part is not scored          |
| Greylist Fee Increase | ×3 fee                  | Downgrade, softCommit still effective |
| FraudProof            | Forged Proof / Fake ACK | Validator Slash 3 % Stake             |

* minSignalFee and MAX\_WEIGHT are automatically adjusted by RL-Tuner according to network load;
* Greylisted nodes immediately have VP = 0, but can still receive signals to avoid blocking critical services;
* Validators ignoring the packaging of Soft Signals 3 times -> penalized 0.5 % Stake and moved to greylist observation period.

The Signal dedicated Shard enables "AI useful work" to be confirmed in milliseconds, settled in seconds, and scored in hours, with multiple barriers ensuring signals cannot be spammed or maliciously manipulated—becoming a highway connecting Agent activity and PoSg security budget.

### Driving Intelligent Governance

Design Motivation

B² Hub aims to cater to miners, validators, AI agents, and lightweight terminals simultaneously, with network load, fee curves, and graylist risks changing in real-time. Manual governance for parameter tuning is bound to be lagging and costly; however, completely handing over decisions to a black-box model would result in a loss of verifiability and accountability. Therefore, we adopt a "three-stage" framework:

!\[]\[image34]

This allows AI's "suggestions" to be implemented within minutes while ensuring they never exceed hard thresholds or rollback limits.

!\[]\[image35]

| Component        | Key Capability                                                                                                | Output Fields                 |
| ---------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| RL-Tuner         | Simulates 1,000+ rounds of PoSg operation in a sandbox to find optimal α/β, minSignalFee, Slash ratio         | ParamUpdate{α,β,minFee,slash} |
| Anomaly Detector | GNN identifies score manipulation groups and witch clusters; Isolation Forest monitors voting delay anomalies | GrayList{validator,score}     |
| Shard Balancer   | Time-series predicts future 1-hour TPS, Gas; provides expansion/shrinkage or migration suggestions            | ShardAction{nsId,action}      |
| XAI-Auditor      | Generates explanation summaries, Top-K factors, and confidence for each suggestion                            | XAI{hash,tl;dr}               |

Governance Process:

1. Data Collection

Validators report signed telemetry (TPS, Gas, delay, Slash events) every 30 seconds, while AI agents capture publicly available on-chain metrics.

2. AI Generates Suggestions

RL-Tuner outputs parameter tuning; Detector provides graylist; Balancer recommends scaling.

3. Explanation and On-Chain

XAI-Auditor generates a 200-character TL;DR + confidence, which, along with the suggestions, is written into ParameterOracle.

4. Delay Window & Voting

Suggestions are made public for ≥ 100 blocks (≈ 20 min); PoSg validators can oppose or support based on VotingPower. If there are no objections, it automatically takes effect.

5. Guardrails and Rollback

* Hard Thresholds: α∈\[0.5,0.9], Slash≤50%; exceeding limits requires a supermajority (⅔ +).
* Insurance Rollback: If new parameters lead to a reorganization rate >1%, it automatically reverts to the old version.

Effects and Advantages

* Minute-level Adaptation: The proportion of garbage signals decreased from a peak of 22% to < 5%, effectively increasing throughput by 25%.
* Risk Window Narrowing: GNN reduced score manipulation detection time from \~2 hours to 4 minutes; immediate devaluation of graylisted entities prevents spread.
* Reduced Governance Burden: XAI TL;DR reduces proposal reading volume to 1/5; ordinary validators can quickly make voting decisions.
* Audit-Friendly: All model hashes, explanation summaries, and decision records are stored on-chain, allowing the community to replay and hold accountable.

AI-driven intelligent governance enables B² Hub to possess a closed-loop capability of "automatic perception -> automatic decision-making -> human auditing": parameters, fees, resources, and risk control adapt to load while always operating under the sunlight of on-chain guardrails and community consensus. This is the final piece connecting the ultimate goal of Bitcoin with high-speed AI scenarios, allowing the network to maintain a dynamic balance of high performance, high security, and high autonomy over years of operation.

#### RL-Tuner Parameter Self-Tuning Framework

Objective:

Without changing the deterministic state machine, allow the network's key parameters—α/β weights, minSignalFee, Slash ratio, Active-Bonus%—to automatically approach optimal points based on on-chain load, attack situations, and economic indicators, with the entire process being explainable, reversible, and auditable.

A. Reinforcement Learning Modeling

| Dimension                | Design                                                                                                                                                                                                                                                           |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Environment (Env)        | Complete PoSg simulator (Go/SimBFT): Reproduce Stake distribution, Signal arrival flow, mempool, CometBFT voting.                                                                                                                                                |
| Observation (State)      | Block-level: TPS, GasMedian, SignalWeight, empty block rate; Epoch-level: SlashCount, graylist count, reorganization rate, DA sampling failure rate; Economic: StakeAPR, SignalAPR, mining pool inflow rate; A total of 18-dimensional vector, normalized input. |
| Action (Action)          | Discrete + continuous mixed: ① α/β fine-tuning step size 0.01; ② minSignalFee fluctuates ±10 sat step size; ③ SlashRatio ±0.5% (upper limit 50%); ④ Bonus% ±0.5% (upper limit 10%).                                                                              |
| Reward Function (Reward) | Composite: $R = w\_1·\text{TPS}{norm}+w\_2·APY{norm}-w\_3·ReorgProb-w\_4·SlashLoss-w\_5·SpamRate$; Default weights (0.3, 0.3, 0.15, 0.15, 0.1).                                                                                                                  |
| Constraints (Safety)     | Lagrangian safe RL: Constraints ReorgProb<0.001, SpamRate<5%; Strong penalties for exceeding thresholds.                                                                                                                                                         |

Algorithm: PPO-Lagrangian + curiosity bonus; Output policy gradient updates every 5,000 simulation steps.

B. Training and Deployment Pipeline

TODO Pipeline flowchart

#### GNN Anomaly Detection and Graylist Generation

TODO

#### ParameterOracle, Delayed Voting, and Hard Thresholds

TODO

#### Rollback Mechanism and Explainable Auditing (XAI)

TODO

### Security Model and Formal Analysis

#### PoSg Economic Security and Attack Costs

TODO

#### Data Availability / Fraud Challenge Assurance

TODO

#### AI Governance Risks and Mitigation Strategies

TODO

## B² Rollup: Anchored Bitcoin Rollup Execution Layer

### Role Positioning

Complex dApp, high TPS, smart contract execution.

### Batch Generation and Aggregation

<https://blog.bsquared.network/b%C2%B2-hub-da-layer-on-bitcoin-fa63d52b8926>

### ZK / Validity Proof Process

<https://blog.bsquared.network/b%C2%B2-hub-da-layer-on-bitcoin-fa63d52b8926>

### Submitting Batch Data and Proofs to B² Hub

<https://blog.bsquared.network/b%C2%B2-hub-da-layer-on-bitcoin-fa63d52b8926>

## AI Signal: Signal-Driven Agentic AI Layer

### Design Goals

To truly make AI "run on Bitcoin."

1. Signal Nativization

Goal: To make every event on the blockchain a "neural pulse" for agents.

Scenario: When there is a significant UTXO change on the Bitcoin mainnet or when B² Hub updates parameter thresholds, arbitrage agents running on AI Signal immediately capture the corresponding Signal, automatically adjusting positions and risk control; no polling is needed, and there is no information delay.

2. Modular and Hot-Swappable

Goal: To decompose the five functional blocks of AI agents—perception, memory, decision-making, execution, and reward—allowing developers to replace or upgrade them like building blocks.

Scenario: A mining team replaces the computing power optimization module during peak season while retaining its RL strategy; the same agent inserts an energy arbitrage plugin during the off-season, with the entire switching process requiring no restart or redeployment.

3. Verifiable and Auditable

Goal: All inputs, inference paths, and outputs can be re-verified by any node in the form of zero-knowledge or replayable logs.

Scenario: A regulator wants to confirm whether a collaborative predictive model used licensed data. They only need to follow the Signal DAG replay to verify, with no black box and no need to obtain model parameters.

4. Autonomy and Security Coexist

Goal: To allow agents to self-learn and self-update, but they must operate within a strategy sandbox to prevent "runaway" or resource abuse.

Scenario: A market-making agent, upon discovering a new lightning network arbitrage opportunity, first generates a PolicyDiffSignal, which must be approved by multiple parties through MPC before being written back to the strategy library and going live.

5. Resource Awareness and Greening

Goal: Agents must perceive electricity prices, carbon emission indicators, and computational load in real-time, dynamically balancing profit, energy consumption, and emissions.

Scenario: If the power grid enters a peak period, the mining agent will reduce hash rate and release GPU resources for high-yield AI inference tasks while issuing a GreenSignal to record energy savings for subsequent carbon credit settlement.

6. Privacy-First Data Flow

Goal: Sensitive data during training, inference, and settlement processes must be protected by differential privacy or homomorphic encryption.

Scenario: When a medical research institute uploads pathological images, it first generates de-identified feature hashes and zk quality proofs locally; the actual images are only consumed in a secure execution environment, and no on-chain participant can restore patient information.

7. Incentive Loop and Economic Composability

Goal: To unify the measurement of strategy profits, data contributions, and verification actions as Signal Points, which can be exchanged for B² Tokens, USD2, or governance rights.

Scenario: Data verifiers automatically deduct the Signal Points earned from successfully identifying a batch of low-quality data against the next call for inference costs of a large language model, achieving value transfer across business lines.

8. Multi-Chain and Cross-Domain Interoperability

Goal: To be compatible with the Bitcoin mainnet, EVM sidechains, Cosmos inter-block communication, and Web2 APIs, truly enabling "any event to become a Signal."

Scenario: An intelligent investment advisor agent simultaneously listens to the New York Stock Exchange market API, Ethereum DEX order book, and Bitcoin mempool, with the three data streams converging at the same Signal semantic layer, and decision logic no longer hindered by underlying heterogeneity.

9. Adaptive Governance

Goal: Through RL-Tuner and GNN risk detection, system parameters (staking rate, fee rate, speed limit) self-adjust according to network status, confirmed by community voting.

Scenario: When a surge in signal traffic causes Gas fees to spike abnormally, the AI-Governor proposes a plan to reduce transaction fees for a certain shard by 15%; if the community does not veto within a 3-hour delay window, the change automatically takes effect.

10. Developer and Operations Friendly

Goal: To provide a unified SDK, low-code orchestration interface, rich monitoring metrics, and replayable debugging tools to lower the threshold.

Scenario: A new developer combines "price oracle" + "arbitrage strategy" + "lightning settlement" modules through a drag-and-drop interface, and after clicking one-click deployment, the system automatically generates signal subscription rules, risk

### Agent-Native Abstract Account (A-AA)

Concept of Agent-Native Abstract Account (A-AA):

A-AA is a layer of "account as agent" abstraction designed by AI Signal for large-scale autonomous agents. It upgrades the three elements of traditional on-chain accounts (Externally Owned Account / Contract Account) — identity, public key, and balance — to five elements:

1. Agent ID: An immutable UUID generated on-chain, corresponding to the root of a Signal DAG subtree.
2. Polymorphic Key Stack: Multiple sets of keys for signing, encryption, homomorphic computation, and trusted execution (TEE/MPC) coexist, allowing for hot switching based on policy.
3. State Capsule: A compressed storage for the agent's local memory, policy hash, and resource quotas, supporting zero-knowledge proof verification.
4. Resource Vault: Contains multi-dimensional assets such as BTC, USD2, gas quotas, computing power credits, and data credits, with programmable authorization.
5. Signal Routing Table: Defines the types of Signals that can be subscribed to/published, QoS levels, and rate limits.

Through these five elements, A-AA encapsulates "identity + storage + computing budget + permissions" in one go, naturally fitting the lifecycle management of autonomous agents.

Runtime Process

1. Initialization (Spawn)

• Developers submit policy images, initial keys, public key lists, and minimum stakes in the manufacturing workshop.

• The Rollup contract mints a new A-AA and synchronizes its root hash to the B² Hub, binding identity with Bitcoin-level finality.

2. Activation (Awaken)

• When the agent first receives a subscribed Signal, it triggers the Awaken() callback.

• The runtime unseals the State Capsule in TEE, loads the policy, and allocates initial gas and resource limits.

3. Execution (Act)

• For each matching Signal, the corresponding policy function is scheduled.

• All external calls (on-chain transactions, lightning routing, data access) are accounted through the A-AA resource pool and generate new Signals.

4. Learning (Evolve)

• The policy module can produce PolicyDiff within a secure sandbox and send a PolicyUpdateSignal to request a hot upgrade.

• After multi-signature or governance hooks are approved, the State Capsule updates the policy hash and submits a zero-knowledge proof on-chain to ensure consistency.

5. Hibernation / Retirement (Hibernate / Retire)

• When gas balance is insufficient, tasks are completed, or policies are deprecated, the A-AA enters hibernation;

• If there are no active Signals for N consecutive settlement periods, the system can automatically trigger the retirement process, liquidate the resource pool, and package the state archive for record-keeping.

Key Features

• Native Multi-Chain Compatibility: The resource pool of A-AA supports heterogeneous assets such as cross-chain UTXO, ERC-20, and IBC Voucher; the calling adapter utilizes Signal semantics for unified encapsulation, eliminating the need for manual bridging.

• Fine-Grained Permissions: The routing table can specify constraints such as "read-only market Signal," "call only Lightning Keysend," and "single expenditure ≤ 0.01 BTC," implementing the principle of least privilege.

• Traceable Policy Upgrades: Any policy changes must be accompanied by a diff hash and ZK proof, and can only take effect after on-chain audit approval, ensuring long-term verifiability of the agent.

• Key Loss Resistance: The polymorphic key stack includes social recovery and MPC reconstruction; even if the signing key is invalidated, the Agent ID and resources remain intact.

• Consensus-Friendly Settlement: Each resource consumption generates a SpendSignal in real-time, entering Rollup accounting; after batch zk-Rollup compression, it is anchored to the Bitcoin mainnet, ensuring low fees under high concurrency.

Typical Application Scenarios

• Mining Agent: One ASIC machine acts as an A-AA, adjusting power consumption in real-time and directly paying electricity bills or receiving BTC rewards from the resource pool.

• High-Frequency Market Maker: The strategy engine serves as an A-AA, holding multi-chain assets and executing atomic arbitrage across CEX/DEX, with all legs settled in the resource pool.

• Machine as a Service (MaaS): Industrial robots are packaged as A-AA, allowing customers to rent operational time by paying USD2 Signal, with the robot automatically generating invoices and settling on-chain.

• Data Validator: A-AA subscribes to DataSignal, runs privacy validation algorithms, generates ValidSignal, and earns validation rewards while recording computational consumption in the resource pool.

• Cross-Institution AI Collaboration: Internal enterprise models are packaged as A-AA, exposing only inference interfaces; external clients can call them after payment via Escrow Signal, without sharing underlying ownership.

Future-Oriented Expansion

• Computing Power as Asset: Plans to virtualize GPU/TPU computing power into transferable tokens, directly deposited into the A-AA resource pool, allowing agents to "lease/stake/hedge" computing power on-chain.

• Semantic Sharding: Signals from different business domains are semantically sharded, allowing the A-AA routing table to subscribe across shards, reducing cross-domain broadcast noise.

• AI-Governed Key Rotation: Utilizing GNN risk analysis to automatically trigger key rotation, reducing the probability of key leakage during long-term operations.

Agent-Native Abstract Account (A-AA) constructs a complete lifecycle management framework for autonomous agents on-chain by natively aggregating identity, resources, policies, and permissions, enabling each AI agent to be verifiable like a smart contract and flexible to upgrade like an operating system process, thus laying the foundation for large-scale sustainable operation of AI Signal.

### Signal Network

<https://docs.bsquared.network/b2_dsn_ai>

### AI Orchestration

<https://docs.bsquared.network/b2_dsn_ai>

### Security and Anti-Bot Measures

<https://docs.bsquared.network/b2_dsn_ai>

## Security Analysis

TODO

### Attack Surface Enumeration

### Stake Attack (Stake Concentration, Long-Range)

### Signal Score Manipulation and Sybil Attack

### Shard Denial of Service / Cross Shard Deadlock

### DA Concealment / Data Loss / Retrieval Failure

### Bitcoin Submission Delays and Reorganization Impact

### Risk Classification, Detection Mechanisms, Recovery Procedures

## Performance & Scalability

TODO

### Benchmarking Assumptions

### TPS / Throughput / Latency per Shard

### Validator Set Size vs Network Overhead

### DA Bandwidth Requirements and Erasure Code Redundancy

### Simulation: Impact of High-Density Signal Scenarios on VP Distribution

### Cost Model (Miners, Nodes, AI Service Providers)

## Use Cases & Scenarios

### AI Agent Automatic Mining Revenue Deposit into BTC Wallet

Scene Overview

A self-mining agent, Miner-Bot, has been deployed in the MiningSquared mining pool. It resides in a lightweight container in a local ASIC machine room or cloud computing market, interacting in real-time with on-chain smart contracts through the Signal network, automatically completing the entire process of computing power scheduling, revenue settlement, and fund entry.

A. Perception -> Decision -> Execution

1. Perception Layer

Miner-Bot continuously listens to various Signal events broadcasted by B² Hub: fluctuations in total network computing power, Fee/Hash price curves, real-time electricity price oracles, mining pool difficulty factors, etc.

2. Strategy Layer

The built-in reinforcement learning loop evaluates current profitability every few minutes and dynamically decides:

• How much computing power to allocate to MiningSquared

• When to switch to alternative mining pools

• Whether to accelerate/decelerate machines and which devices to schedule into standby

3. Execution Layer

Once the strategy determines the action, the agent generates and signs transactions in hardware-isolated keys:

• PSBT: for on-chain BTC revenue distribution

• Lightning Network invoices: for immediate small settlements

Subsequently, the transactions are propagated to the Bitcoin mainnet through B² Rollup, achieving final settlement.

B. The Complete Link from Discovery of Blocks to BTC Credit

1. Submission of Shares and Batch Proofs

• Each share submission is packaged into a Signal, containing Merkle-hashed share metadata and Schnorr signatures.

• MiningSquared aggregates thousands of Signals into zero-knowledge commitments and regularly uploads them to the B² Hub, achieving Bitcoin-level finality while avoiding L1 congestion.

2. Reward Distribution and Payment Method Selection

• When a block is actually produced, the mining pool contract on B² Rollup generates a revenue distribution table. The Miner-Bot receives a RewardSignal indicating the amount of satoshis to be received and the optional payment channels (on-chain UTXO or Lightning).

• The strategy layer reads electricity prices and BTC volatility: if prices are stable, on-chain payment is chosen; if the market is volatile or liquidity is needed, the Lightning Network is used.

3. Automatic Construction of Secure Wallets

• On-chain payment: The Miner-Bot generates a payment to a new taproot address as a PSBT and broadcasts it to the mainnet after obtaining the joint signatures of the mining pool's multi-signature nodes through the "PSBT Relay Shard" of the B² Hub.

• Lightning payment: The Miner-Bot opens or funds a channel with your mobile node, settling in milliseconds through the mining pool's federated Lightning gateway, with HTLC proof backed up to the B² Hub for easy auditing.

4. Compliance and Financial Integration

• Each payment Signal is accompanied by metadata such as timestamps, electricity consumption (kWh), and carbon emissions, hashed into the transaction memo. The backend financial system automatically records after subscription.

• If electricity prices surge, causing profits to fall below the threshold set by the RL-Tuner, the Miner-Bot will automatically reduce frequency or even sell hedging contracts on the BTC settlement derivatives DEX.

5. User Perspective

• You only need to see the prompt “+0.042 BTC has been credited” on the dashboard or API, along with detailed metrics: sats/kWh, mining pool variance, expected next difficulty, etc.

• No manual intervention is required throughout the process; private keys remain in a secure module, and every step (hash submission, revenue calculation, PSBT signing, broadcasting) is linked by the Signal event chain, available for audit replay.

C. Value Highlight

• Trust Minimization: All key logic is publicly executed in the B² Rollup smart contracts and periodically anchored to Bitcoin L1 by the B² Hub, making revenue distribution immutable.

• Energy-Sensitive Optimization: Reinforcement learning strategies perceive electricity prices and difficulty in real-time, automatically adjusting computing power to maximize marginal profits.

• Treasury Automation: Whether holding BTC long-term, exchanging for USD2 stablecoins, or transferring to the Lightning Network to earn routing fees, the Miner-Bot can send funds to the most suitable location according to preset strategies, leaving a verifiable evidence chain.

In short, the AI Agent automatically mines and credits BTC wallets, transforming the traditional manual operation of mining pool revenue distribution and wallet reconciliation processes into a fully automated revenue pipeline driven by the Signal network and backed by Bitcoin security, allowing mining machines to operate as efficiently and reliably as a self-playing orchestra.

### AI Executes Arbitrage / Market Making Strategies, Revenue Reflows to Staking

Scenario Overview

Running a cross-market intelligent agent Arb-Maker on the B² Network. It resides between the "Trading Domain" (CEX, DEX/perpetual contracts on B² Rollup, other L2/LN channels) and the "Treasury Domain" (staking and fund management contracts), obtaining market data, risk control, and fund status through the Signal network, automatically executing arbitrage/market-making strategies, and returning realized profits to the staking pool according to rules, forming a closed loop of "Trading -> Settlement -> Staking -> Compound Interest."

Strategy Framework (Perception -> Decision -> Execution)

Perception Layer: Subscribing to Signals from B² Hub (order book snapshots, price spreads/basis, funding rates, gas/transaction fees, oracle prices, electricity prices, and macro volatility), own inventory and credit limits, on-chain congestion, and liquidation risk alerts.

Decision Layer: A mix of reinforcement learning/multi-armed bandit and rule engines, evaluating the cost-benefit-risk triad in real-time:

• Arbitrage: Spot price differences across exchanges (CEX <-> DEX), spot-perpetual basis, cross-chain same-asset premiums/discounts, and slippage differences across different routes in the same pool.

• Market Making: Reporting bilateral prices on AMM/order books, dynamically quoting skew based on inventory shifts and volatility, and controlling net exposure within target ranges using hedging legs.

Execution Layer: Low-latency connectors (CEX FIX/WS + on-chain routers), with atomic execution/protective matching (private trading channels, anti-front-running), instant order cancellation and retries on failure, generating auditable FillSignal and PnLSignal after execution.

End-to-End Process:

1. Opportunity Trigger

• The perception layer detects cross-market price differences or funding rate deviations exceeding the threshold, issuing an ArbSignal.

• The decision layer calculates the total cost (spread + fees + funding rate + slippage + cancellation probability), providing a go/no-go decision and order size.

2. Locking Inventory and Atomic Ordering

• Lock equivalent inventory in pre-set multi-location fund wallets (to avoid transfer delays).

• Synchronize multi-leg orders (e.g., DEX buy, CEX sell; or AMM pre-list buy, perpetual short) using transactional batch processing/private channels to reduce MEV and deviations.

3. Execution, Hedging, and Settlement

• After the order is executed, perform the hedging leg to bring the net exposure back to the target range; if only part is executed, the strategy will partial-hedge and lower the density of subsequent orders.

• Merge the actual costs and prices of all legs to form realized PnL; broadcast the PnL to the treasury domain via PnLSignal.

4. Revenue Routing and Accounting

• TreasuryRouter allocates net profits to designated asset buckets based on strategy version and governance parameters:

• BTC: Generate a PSBT for payment to the treasury taproot address, relay through B² Hub PSBT, and then broadcast to L1.

• USD2: Directly call the stablecoin/treasury contract on B² Rollup to complete the accounting.

• Funds are automatically replenished between the "hot-warm-cold" three-layer wallets according to water levels, ensuring sufficient trading domain while keeping the treasury domain secure.

5. Reflow Staking and Compound Interest

• StakingAllocator subscribes to PnLSignal, allocating in the order of "buffer fund -> net profit -> staking":

• Reserve liquidity buffer and margin (to cover fees and risk control triggers).

• Automatically invest net profits according to preset ratios:

• B² staking pool / PoSg validator delegation (to earn network incentives and governance rights).

• USD2 stable pool / market-making pool (to earn trading fees and incentives).

• **BTC staking-type returns (LST/LBTC type)** or Lightning Network channel returns.

• Staking certificates and returns can be reinvested in strategies configured for automatic compounding; when volatility exceeds the threshold, automatically execute "unstake -> replenish trading domain" for reverse rebalancing.

Wallet and Fund Arrangement

• Hot Wallet: Dedicated to trading domain, small limits, keys in secure module, real-time authorization and matching.

• Warm Wallet: Cross-platform rebalancing and intraday replenishment, time-limited/frequency-limited switches.

• Cold Wallet/Vault: Long-term holding and staking, offline xpub export, online only PSBT.

• Rebalancing executed preferentially through L1/lightning/cross-rollup channels, with fees and delays included in routing costs.

Risk Control and Compliance

• Pre-event: Funding limits, leverage/breakeven lines, single transaction slippage and impact cost limits, black and white list venues and asset lists.

• During event: Delay and order rejection monitoring, price spread regression speed assessment, extreme market kill-switch, multi-source oracle consistency checks.

• Post-event: Transaction-by-transaction reconciliation and ZK-friendly audit trail (ArbSignal -> Order -> Execution -> PnLSignal -> Staking call), automatic alerts for anomalies and entry into read-only mode.

• Governance: Thresholds and weights updated by ParameterOracle + delayed voting, gray list/break rules can be hot-swapped.

Monitoring and Observability

• Dashboard layered display: Strategy hit rate, effective price spread distribution, unit cost, fund utilization rate, inventory deviation, funding rate capture, realized/unrealized PnL, staking annualized and compounding curve.

• Key events (extreme slippage, counterparty anomalies, on-chain congestion, governance parameter updates) pushed as signals and synchronized to the alert system via Webhook.

Anomalies and Rollback

• Asymmetric execution: Immediately reduce positions to hedge, close the corresponding venue's market-making leg and enter low-risk mode.

• Oracle fork/failure: Switch to redundant data sources, or downgrade to "inventory conservation" market-making.

• Liquidation/margin emergency: Automatically stop opening new positions, trigger small vault un-staking to replenish margin.

• CEX risk: Enable gray list and limit reductions, while shifting strategy towards on-chain venues.

Why "Yield Reflow Staking"

• Improve capital efficiency: Earn "active alpha" during trading days, while idle funds and net profits earn "passive beta" on-chain, with both combined to enhance annualized returns.

• Smooth volatility: When strategies encounter low volatility/low opportunity periods, staking yields maintain basic returns; during high volatility periods, profits are consolidated into long-term positions.

• Verifiable compliance and governance: Every step from trading to staking is linked by a Signal-Driven workflow, which is both auditable and adjustable by community governance.

AI executes arbitrage/market-making strategies, yield reflow staking connects "high-frequency cash flow" with "on-chain compounding" into a closed loop—agents capture price differences and liquidity premiums across multiple markets in a trust-minimized manner, with earnings deposited in real-time, and growth occurring immediately, achieving sustainable compounding growth on the secure anchoring and governance of the B² Network.

### Data Market: Model Training Data Verified on Chain through Signal

Scene Overview

In the B² Network's Signal-Driven Data Market, anyone can transform high-value training data (images, logs, on-chain interactions, financial data, etc.) into verifiable, priceable, and compliant digital assets. Data uploaders (Data Producers) generate DataSignals, writing data fingerprints, quality proofs, and licensing terms into a mixed off-chain and on-chain traceability track; validators (Data Validators) use staking and zero-knowledge proof mechanisms to ensure the data is authentic, unaltered, and compliant with privacy regulations; model developers (Model Trainers) can then subscribe to audited data shards as needed, and after paying a fee, securely decrypt and use the data locally or in the cloud. The entire process is completed on the dedicated Signal Shard of the B² Hub, achieving Bitcoin-level finality without leaking original data.

Roles and Motivations

| Role           | Key Motivation                              | Main Operations                                                                          | Risks and Incentives                                                    |
| -------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Data Producer  | Monetize scarce data, increase exposure     | Generate DataSignal, submit data hash and ZK quality proof, set permissions              | Must stake DataBond; data distortion or violations result in forfeiture |
| Data Validator | Earn validation rewards & reputation points | Randomly sample, run consistency and bias tests, issue ValidSignal                       | Submitting incorrect validations will result in slashing                |
| Model Trainer  | Obtain high-quality data with low latency   | Subscribe to DataFeed, pay DataCredits to access decryption keys                         | Compensation available if data is falsified                             |
| Governance DAO | Maintain market trust and activity          | Update parameters (staking, forfeiture, fees), maintain graylist, compliance regulations | Governance negligence leading to data leaks will reduce reputation      |

End-to-End Process: From Data Generation to On-Chain Acceptance

1. Data Preparation and Fingerprint Calculation

• The Data Producer shards, deduplicates, and anonymizes the raw dataset, generating a root hash using SHA-256 + Merkle Tree; simultaneously, it generates a Quality ZKP (proof of coverage, no duplicates, reasonable distribution, etc.) using differential privacy and sample statistics, all encapsulated in DataSignal.

• DataSignal includes: root\_hash, quality\_proof, license\_uri, DataBond staking amount, and optionally, a public key encrypted package of the AES-GCM symmetric key.

2. Signal Broadcasting and Random Verification

• DataSignal is sent to the DataShard of the B² Hub, entering the verification pool.

• Verifiers draw tasks from the pool using VRF, download the encrypted samples, run consistency checks, AI forgery detection, and compliance rule (GDPR, copyright) scans in a secure execution environment, generating ValidSignal.

• If the results of two independent verification rounds are consistent and pass the threshold signature, then DataSignal enters the verified state; otherwise, arbitration is automatically triggered, and the DataBond or Validator stake is forfeited based on liability attribution.

3. zk-Commitment On-chain & Data Availability

• The Merkle roots of all DataSignal and ValidSignal are packaged into a zk-Commitment, which is periodically submitted to the B² Hub by the Rollup contract; the Hub embeds the root hash into Bitcoin L1 for each settlement cycle.

• This way, model developers can be assured that the data has not been tampered with, is from a trustworthy source, and meets quality standards, based solely on the root hash and zero-knowledge proof.

4. Licensing Pricing and Payment

• The Data Producer sets the LicenseProfile in the smart contract:

• Charging model: one-time buyout / subscription by usage / C-to-C resale sharing

• Usage scope: non-commercial, commercial, no redistribution, etc.

• Encryption key: using Attribute-Based Encryption (ABE) or Proxy Re-Encryption, automatically unlocked according to payment records.

• After the Model Trainer selects the data, the contract automatically deducts DataCredits (or USD2/BTC) and sends the corresponding decryption key fragments to the Trainer's HD address.

5. Usage, Tracking, and Revenue Sharing

• The Trainer downloads the encrypted data shards, decrypts them through a local secure module, and inputs them into model training; all invocation events will generate UsageSignal (excluding training details, only containing hash and value), which is written back to the chain for subsequent revenue sharing and auditing.

• The Producer receives real-time revenue sharing, the Validator earns verification rewards, and the DAO extracts governance fees; if someone later proves that there are labeling errors or privacy violations in the data, they can submit a ChallengeSignal to go through the homomorphic auditing process, and if the result is established, the Producer will be penalized and required to compensate the Trainer.

Technical Highlights

• Zero-Knowledge Quality Proof: Using zk-SNARK / STARK to prove that data meets distribution balance, is non-redundant, and has traceable sources, while keeping specific samples confidential.

• Differential Privacy Sampling: Validators can only see a subset affected by noise, allowing for quality verification without disclosing core data.

• Signal-Driven Traceability: All event chains (upload -> verify -> purchase -> use) become replayable Signal DAGs, with on-chain hashes reproducing the timeline.

• Programmable Licensing and Automatic Revenue Sharing: LicenseProfile supports secondary sales, time locks, and geographic restrictions; revenue distribution is automatically split in the contract.

Value and Impact

1. Trust-Minimized Data Transactions: Buyers do not need to trust sellers, and sellers do not need to expose raw data to complete value exchange.
2. Compliance and Privacy: Triple protection of differential privacy + ZKP + ABE meets regulatory requirements such as KYC, GDPR, and trade secrets.
3. Incentive Compatibility: Validators and challengers form a closed loop of data quality games through positive rewards and penalties, eliminating "garbage data."
4. Reusable AI Value Chain: Model training revenue can be shared with upstream data producers based on UsageSignal, creating long-tail passive income.

Data Market: Model training data is verified on-chain through Signal, creating a foundation for "trustworthy, private, secure, and quantifiable" data asset circulation, allowing each line of data to carry zero-knowledge fingerprints and programmable licenses, flowing freely on a Bitcoin-secured anchor, injecting continuous, compliant, and auditable high-quality fuel into the AI training ecosystem.

### BTC Collateralized Stablecoins and AI Payments

Scene Overview

In the B² Network, users can collateralize native BTC into the cross-chain storage contract of the B² Hub to mint programmable stablecoin U2 (or other BTC-collateralized stable assets). Meanwhile, on-chain AI Agents—whether chatbots, smart investment advisors, or computing power rental nodes—use U2 as the settlement currency for real-time transactions. This creates a closed loop consisting of BTC -> U2 -> AI Payments -> BTC Reflow: Bitcoin provides value anchoring, stablecoins offer price stability, the Signal network ensures liquidity and credibility, while AI Agents amplify value through automated strategies within the network.

Key Roles and Motivations

• Collateral Provider

• Locks BTC to exchange for U2, releasing liquidity while still retaining the potential for BTC price appreciation.

• AI Agent (Consumer)

• Uses U2 to pay for reasoning fees, subscription fees, plugin invocation fees, etc., avoiding pricing confusion caused by BTC value fluctuations.

• Liquidity Keeper (Liquidator/Market Maker)

• Provides flash hedging and stablecoin market making through Signal subscription collateral rates and liquidation discounts, profiting from risk premiums.

• Governance DAO

• Sets collateral rates, interest curves, and liquidation penalties to maintain system security and sustainable incentives.

End-to-End Process: From Collateralization to AI Payments to BTC Reflow

1. Collateral and Minting

• The mortgagor locks BTC into a multi-signature address via Taproot HTLC; the contract reads the Proof-of-Reserve Signal to confirm receipt.

• The B² Rollup smart contract mints an equivalent amount of U2 at a collateralization rate of 170%–200% and generates a MintSignal.

• The collateral position tracks the BTC/USD exchange rate in real-time; when the collateralization rate falls below the threshold, a LiquidationSignal is triggered, allowing market makers to bid on the position.

2. Consumption & Settlement on the AI Agent Side

• Users recharge a small amount of U2 for their AI Agent and authorize it to call the Pay-As-You-Go API on-chain:

• Inference calls: billed by token or per second; the Agent sends an InferenceSignal, and the contract freezes the corresponding U2.

• Subscription services: one-time monthly/yearly fee deduction; the Agent sends a SubSignal; the contract unlocks periodically.

• Service providers submit Proof-of-Workload (which can be a ZK proof to protect model parameters) after completing tasks, and the contract releases U2 to their revenue address after verification.

3. Lightning Network and Micropayments

• For small calls of ≤0.1 U2, the contract can automatically convert U2 to sats quickly, sending it directly to the developer's Lightning node via Keysend through the B² Hub's LN Gateway, achieving millisecond-level crediting and saving gas.

4. Earnings Reinvestment & Principal Reflow

• Both service providers and mortgagors can:

• Re-stake the earned U2 in the U2-StablePool to earn transaction fees and liquidity mining rewards;

• Redeem BTC through RedeemSignal, or exchange back to BTC via off-chain OTC/LN;

• Use U2 as PoSg validator collateral to enhance network governance weight and receive additional fee sharing.

5. Automatic Liquidation and Risk Control

• The Oracle Aggregator refreshes the BTC price every minute; if the collateralization rate <150%:

1. A pre-liquidation reminder is triggered to broadcast a PingSignal to the mortgagor;
2. If no top-up occurs before expiration, it enters a Dutch Auction, where the Liquidity Keeper purchases the mortgaged BTC with U2;
3. Any remaining value of the mortgagor (if any) is automatically refunded.

• All transactions before and after liquidation are anchored to Bitcoin L1, with an immutable audit trail written via CheckPointSignal.

Risk Compensation and Incentive Design

• Stability Fee: Mortgagors pay interest hourly, forming governance income used to subsidize oracles and liquidation rewards.

• Liquidation Penalty: A penalty of 5–10% is charged upon liquidation, used as rewards for market makers and a risk fund.

• Liquidity Mining: Providing market-making in the U2/BTC-Tether pool can earn additional B² tokens, enhancing early depth.

• Signal Points: AI Agents, developers, and market makers executing healthy operations can accumulate credit points, which can offset fees or gain priority routing.

Value and Impact

1. Maximizing BTC Capital Efficiency

• Collateralizers can obtain stable purchasing power without selling BTC, locking in upside potential while participating in the DeFi/AI ecosystem.

2. Standardization of AI Pricing

• USD face value simplifies model invocation and subscription pricing; cross-chain and cross-border users can avoid "hashrate slippage" caused by BTC exchange rate fluctuations.

3. Real-time, Low-cost Micropayments

• Lightning Network bridging makes sub-cent transactions possible, opening a new paradigm of AI services billed by the second and paid in a streaming manner.

4. Trust-minimized Settlement Mechanism

• Multi-source oracles + Signal bidding settlement reduce human black-box operations, ensuring stablecoins are perpetually fully collateralized.

5. Long-term Positive Cycle

• Collateral interest -> Network governance income -> Developer incentives -> More AI services -> Higher U2 demand -> Expansion of collateral pools, forming a positive feedback loop.

BTC-collateralized stablecoins and AI payments combine the hard value of Bitcoin, security consensus, and the usability of USD pricing, injecting low volatility, high liquidity, and auditable fuel into the B² Network's AI ecosystem through Signal-Driven settlement and Lightning micropayments, achieving a sustainable flywheel of "value reserve -> purchasing power -> intelligent services -> value return."

### Inter-Agency Collaboration: Signal-Based Settlement Between Enterprise AI Agents

Scene Overview

In the B² Network, AI agents (Enterprise Agents) operated by different enterprises can form an "instant machine-to-machine" collaboration network through the Signal network. They automatically exchange services, data, and funds while maintaining business confidentiality and compliance requirements: when one party completes the agreed service-level agreement (SLA), the system triggers a settlement signal, and the smart contract distributes BTC-collateralized stablecoin USD2 or sats to the other enterprise's treasury according to preset rules, achieving inter-agency, trustless, and auditable clearing.

Roles and Motivations

• Principal Agent

Initiates business requests (such as procurement forecasting, equipment maintenance, risk assessment) and hopes to obtain external AI capabilities on a pay-for-performance basis.

• Executor Agent

Provides algorithms, computing power, or data assets and is compensated based on completion; aims to shorten accounts receivable periods and reduce default risks.

• Signal Clearing Layer

Composed of dedicated Shard + Rollup contracts on the B² Hub, responsible for reputation scoring, SLA verification, and fund freezing and releasing.

• Compliance/Audit Node

Monitors the settlement link, generates undeniable timestamps and zero-knowledge proofs to meet regulatory or internal audit requirements.

End-to-End Process: From Instruction to Inter-Agency Settlement

1. Business Request and ServiceSignal

• The Principal Agent publishes requirements through ServiceSignal: task description, data interface, metric thresholds, budget limits, and performance time.

• ServiceSignal automatically locks the corresponding amount of USD2 in the Escrow Contract and generates a unique service\_id.

2. Task Execution and ProofSignal

• The Executor Agent receives the service\_id and processes the task in a secure local or private cloud environment.

• Upon completion, it generates a ProofSignal: containing task output hash, execution summary, SLA key metrics ZK-SNARK proof, and an encrypted reference to the business data.

• ProofSignal is broadcast to the Signal Clearing Layer and enters the verification pool.

3. Automatic Verification and Arbitration

• The clearing layer uses multi-party privacy comparison (MPC + zk) to verify the ProofSignal against the SLA:

• Whether accuracy, latency, data consistency, compliance markings, etc., meet the thresholds;

• Random sampling of original samples to prevent fraud or "training-inference inconsistency."

• If verification passes, it triggers SettleSignal; if it fails, it enters the arbitration process, where both parties can submit additional evidence or accept partial penalties for contract termination.

4. Fund Release and Multilateral Settlement

• SettleSignal calls the Escrow Contract:

• Releases principal + dynamic bonuses (based on KPI excess) to the executor according to the predetermined ratio;

• Simultaneously allocates small fees to audit nodes and governance funds.

• For small, frequently called API services, batch settlements can be aggregated through internal lightning channels at 10-minute intervals to reduce on-chain costs.

5. Reputation Update and Iterative Cycle

• After successful settlement, the system automatically updates the ReputationScore for both parties and writes it into ReputationSignal; for the next collaboration, the Escrow deposit can be reduced based on reputation discounts.

• All signals (Service -> Proof -> Settle -> Reputation) form a replayable Signal DAG for immediate internal audit or regulatory queries.

Technical Highlights

• Signal Atomic Transactions

Every step of business-data-fund actions is encapsulated into a pointer-referable Signal, which can be precisely revoked in case of failure or rollback.

• Zero-Knowledge SLA Verification

The executing party can prove that "the output meets ≥ 95% accuracy and latency < 50 ms" without exposing private models or data.

• Dynamic Reputation Staking

The higher the reputation score, the less deposit is required and the faster the funds are received; malicious defaults will incur slashing and be recorded on a public blacklist.

• Multi-Asset Flexible Settlement

USD2 is suitable for large, low-volatility scenarios; sats (Lightning) are suitable for millisecond-level micropayments; the system can automatically route between the two.

Risk Control and Compliance

• Real-Time Risk Control Signals: Price crashes, oracle deviations, and counterparty default warnings will trigger risk control Signals to freeze balances.

• On-Chain Regulatory Interface: Compliance nodes can verify the legality of fund flows and service content without disclosing commercial privacy.

• Cross-Border Payment Transparency: The Signal DAG inherently carries geographical, temporal, and payee information, providing data basis for multinational taxation and anti-money laundering.

Value and Impact

1. Cash Flow Acceleration: Enterprise AI services upgrade from "monthly reconciliation, quarterly payment" to "settlement upon delivery," significantly reducing working capital pressure.
2. Default Cost Minimization: Both parties use locked funds + SLA proof mechanisms to avoid defaults, greatly reducing cooperation thresholds and legal disputes.
3. Interoperable Ecosystem: AI agents from different industries, blockchains, or Web2 systems can interconnect through standardized Signal interfaces.
4. Audit-Friendly: All key steps leave verifiable fingerprints under Bitcoin's finality, meeting compliance requirements such as SOX, GDPR, ISO, etc.

Cross-Institution Collaboration: Signal-based settlements between enterprise AI agents transform traditional "paper contracts + offline reconciliation" into "smart signals + instant clearing," allowing cross-company and cross-border AI services to interconnect securely like microservices, automatically price against each other, and quickly cash out.

## Conclusion

### Technical Summary

In the overall architecture of the B² Network, Signal serves as the "nerve fiber" that connects everything. It integrates previously fragmented processes such as on-chain transactions, off-chain computations, data verification, and incentive distribution into a traceable, composable, and governable event stream. By generating the smallest granularity of Signal for each important action, the platform achieves an atomic transaction model of "state—signature—proof—settlement," inherently possessing capabilities for retroactive tracing, auditing, and automated governance.

The core technology stack can be summarized into three layers:

1. Trusted Execution Layer

• B² Rollup + B² Hub provide a scalable execution environment anchored to the Bitcoin L1 chain, ensuring that transactions and computations have PoW finality;

• The zk-Commitment mechanism uses zero-knowledge batch proofs to compress massive Signals, reducing L1 load while retaining a complete security proof chain.

2. Data and Value Flow Layer (Signal & Settlement Layer)

• Signal Shard adopts an event DAG storage model, with each Signal carrying a hash pointer, timestamp, and verifiable metadata;

• The multi-asset settlement gateway supports USD2, BTC, sats (Lightning), and future on-chain derivative assets, dynamically routing to the optimal settlement path;

• ParameterOracle + delayed voting ensure that system parameters (staking rate, fee rate, risk control thresholds) can be transparently adjusted on-chain while preventing flash governance attacks.

3. Intelligent Autonomy Layer (AI & Governance Layer)

• The AI Agent SDK encapsulates Signal primitives as strategy hooks, allowing scenarios such as mining, arbitrage, data verification, and enterprise collaboration to be orchestrated by a unified API;

• The RL-Tuner framework enables each Agent to self-learn and adapt while ensuring returns and risk constraints;

• GNN anomaly detection + graylist promptly identify malicious behaviors and feed back into consensus security through "signal points—staking—forfeiture."

Connecting the three layers is a closed loop of "trusted data -> programmable incentives -> automated governance":

The original events are written into the Signal DAG at a low cost, and after being batched by zk, they are settled on Bitcoin; AI Agents and smart contracts read these highly credible events, make timely decisions, and generate new incentives and governance signals in reverse. This continuous iteration endows the B² Network with three characteristics: high security, strong scalability, and flexible governance.

In summary, B² Network uses the finality of Bitcoin as its foundation, expands throughput through zero-knowledge and event-driven mechanisms, and unleashes automation potential through AI-native signal orchestration, delivering a set of infrastructure for the Web3 ecosystem that balances security, performance, and composability:

• For developers: a one-time integration that provides on-chain certainty while enabling off-chain high-performance computing;

• For users: funds, data, and computing power flow freely under the same signal semantics, offering an experience similar to Web2 but with on-chain security;

• For governors: every system parameter and every profit distribution is verifiable on-chain, allowing the community to make upgrade decisions based on facts rather than guesses.

This embodies the technical vision of "signals as the lifeblood, Bitcoin as the heart"—ensuring that every heartbeat of decentralized applications is precise, measurable, and self-consistent.

### Economic and Ecological Outlook

As the Signal-Driven architecture is fully rolled out, the economy and ecology of B² Network will present several clear growth curves that are coupled and mutually accelerating—continuing the long-term appreciation logic of Bitcoin's "hard assets" while releasing the high-turnover cash flow brought by AI automation.

1. Capital Efficiency Curve: BTC -> Stablecoin -> High-Frequency Returns -> Staking Compound Interest

• BTC collateralized stablecoins solve the dilemma of "holding + liquidity." Holders can release purchasing power without reducing their positions, and the circulation of stablecoins expands in tandem with BTC's market value.

• AI Agent high-frequency strategies (mining, arbitrage, market making, computing power leasing) convert stablecoins into intraday or minute-level income streams.

• The staking and re-staking mechanism deposits returns back to the base layer, forming a compound interest "snowball." The collateral pool thickens over time, further raising the system's security threshold.

2. Behavior-Driven Curve: Signal Generation -> Data Network Effects -> Platform Externalities

• Every transaction, call, and verification will mint new Signals, becoming combinable "atomic" events.

• The larger the signal DAG, the richer the AI Agent's trainable behavior space, leading to diverse strategies and a surge in long-tail scenarios.

• With external developers and enterprises connecting, the network exhibits typical bilateral platform externalities:

• More Agents -> More Signals -> Higher Data Entropy -> More Precise Strategies -> Higher Returns -> Attracting More Agents.

• More enterprise collaboration -> Richer services -> Stronger settlement depth -> More robust liquidity -> Attracting More Enterprises.

3. Fees and Value Capture: Multidimensional, Programmable, Progressive

• Base Gas Fee: Rollup packaging, Hub Checkpoint, providing sustainable "L1 data rent" for Bitcoin.

• Signal Toll: Fine-grained rates can be inserted into stages such as uploading, verifying, challenging, and calling, supporting dynamic adjustments.

• Composable Incentives: Governance can return part of the fees to key ecosystem roles (oracles, validators, developers), creating a "negative friction" experience— the more active users are, the lower the actual net cost.

• Value-Added Services: Custodial nodes, MPC wallets, privacy computing, dedicated bandwidth, and other advanced services can be layered on demand, forming a secondary income curve.

4. Governance Evolution: Gradual Parameters, Reputation Weighting, AI Assistance

• Initially, key parameters (collateral rate, penalties, fee rate curve) are set by the core governance DAO;

• As ReputationScore and Signal points accumulate, voting rights for parameters will gradually shift to high-reputation entities;

• AI-Governor will use GNN and RL-Tuner to simulate governance data scenarios, propose automated parameter adjustment suggestions, and then quickly execute them through community voting, achieving self-optimization.

5. Industry Linkage: From On-Chain Finance to Real-World Assets

• The data market will attract traditional data vendors and research institutions to tokenize RWA data such as health, climate, and logistics;

• Enterprise collaboration settlements will connect SaaS, industrial IoT, and energy trading, giving rise to a signal-based Machine-as-a-Service model;

• BTC collateral and liquidity pools provide a low-threshold dollar alternative for global offshore funds, becoming the underlying channel for cross-border payments and supply chain finance.

6. Long-Term Vision: Signals Become a "Liquid Value" Metric

When signal density is sufficiently high and covers a wide range of economic activities, the B² Network is expected to evolve into an "economic operating system":

• Every value exchange automatically carries proof and incentives;

• Every Agent behavior is instantly mapped to the ledger and governance;

• Every protocol upgrade is data-driven, risk-controlled, and completed through community consensus.

In this system, BTC is no longer just a static reserve asset but continuously "flows" and generates compound returns through collateral, the Lightning Network, and signal clearing; AI Agents become autonomous nodes that capture and amplify these returns, collectively driving a safe, transparent, and rapidly growing diverse economy.

In short, the economic and ecological landscape of the B² Network is an upward curve jointly drawn by Bitcoin's security endorsement, signal-driven liquidity, AI automatic value addition, and community self-consistent governance—it inherits the scarcity and censorship resistance of BTC while injecting the era's momentum of fully programmable Web3 and high-efficiency AI, ultimately pointing towards a more open, trustworthy, and resilient digital civilization foundation.

### Community Action Call: Building the "AI Holds BTC" Future

Imagine a not-so-distant tomorrow:

• Mining farms are no longer just power factories, but operate self-learning mining agents that schedule power by the second and convert earnings into programmable stablecoins in real-time;

• Traders and market makers capture cross-chain price differences through one-click deployed strategy agents, automatically funneling net profits back into the staking pool;

• Data creators write every sensor reading and every frame of imagery into verifiable Signals, protecting privacy while providing fuel for the AI training market;

• Enterprise applications call external AI agents like invoking microservices, delivering instant settlement and seamless global collaboration 24/7;

• Ordinary holders only need to hold BTC to continuously generate USD2 in the background, participate in PoSg governance, and share in the network's growth dividends.

Whether this vision can be realized depends on you—the developers, miners, investors, researchers, or curious individuals reading this text. Here are the immediate action paths you can take:

1. Run a node and become a guardian of Signals

• Deploy a B² Hub light client or full node to provide additional validation and relay bandwidth for the Signal DAG.

• Participate in ParameterOracle and delayed voting to help the network iterate quickly on a decentralized basis.

2. Build and share AI agents

• Use the AI Agent SDK to create custom strategies: mining scheduling, arbitrage market making, enterprise SaaS, IoT predictions...

• Publish agents to the Signal Marketplace, providing plug-and-play AI capabilities for other users and earning revenue shares based on usage.

3. Contribute data to ignite the training flywheel

• Package your high-quality images, on-chain interactions, financial data, etc., into DataSignals on-chain to earn DataCredits.

• Stake and validate others' data as a Data Validator, earning validation rewards while enhancing market credibility.

4. Provide liquidity and act as the "central bank" of the network

• Collateralize BTC to generate USD2, or provide liquidity to the USD2/BTC pool, earning stability fees and mining incentives.

• Delegate staking to PoSg validators, earning network rewards while gaining governance influence.

5. Participate in governance and shape the rules

• Regularly review governance proposals and vote using your B² Tokens, Signal points, or ReputationScore.

• Utilize the AI-Governor simulator to propose parameter improvements based on real data through Pull Requests, making governance decisions more forward-looking.

6. Spread the idea and build consensus

• Write articles, podcasts, or short videos about the value proposition of "AI Holds BTC";

• Share your usage experiences and best practices in developer communities, hackathons, and industry summits;

• Invite traditional enterprises and academic institutions to explore new paradigms like Machine-as-a-Service and RWA data on-chain, broadening the boundaries together.

Conclusion: Why take action now?

Sixteen years after Bitcoin's birth, its role as a "store of value" is deeply ingrained, but the liquidity and productivity of value still seem insufficient. The mission of the B² Network is to use Signal-Driven AI to upgrade BTC from a static "digital gold" to a dynamic "economic energy unit":

Gold provides anchoring, signals provide speed, and AI provides intelligence.

As more people, more computing power, and more data are integrated into this closed loop, the network will self-expand, self-repair, and self-appreciate like breathing, ultimately nurturing a new frontier of AI × Bitcoin where everyone can participate and benefit.

So, let’s take action together—run the first node, deploy the first agent, upload the first batch of data, cast the first governance vote.

Let today’s small step accumulate into a future of decentralized intelligent civilization.

## References

Academic Papers & Research

\[1] Nakamoto, S. (2008). Bitcoin: A peer-to-peer electronic cash system. <https://bitcoin.org/bitcoin.pdf>

\[2] Wood, G. (2014). Ethereum: A secure decentralised generalised transaction ledger. <https://ethereum.github.io/yellowpaper/paper.pdf>

\[3] Buterin, V. (2021). An Incomplete Guide to Rollups. <https://vitalik.ca/general/2021/01/05/rollup.html>

\[4] Komlo, C., & Goldberg, I. (2020). FROST: Flexible round-optimized Schnorr threshold signatures. <https://eprint.iacr.org/2020/852.pdf> Bitcoin Layer 2 & Scaling

\[5] Poon, J., & Dryja, T. (2016). The bitcoin lightning network: Scalable off-chain instant payments. <https://lightning.network/lightning-network-paper.pdf>

\[6] Somsen, R. (2021). BitVM: Compute anything on Bitcoin. <https://bitvm.org/bitvm.pdf>

\[7] Celestia Labs. (2023). Celestia: A modular consensus and data availability layer. <https://celestia.org/>

AI & Blockchain Integration

\[8] Fetch.ai. (2022). Autonomous Economic Agents: Combining AI and blockchain for decentralized systems. <https://fetch.ai/whitepaper>

\[9] Bittensor. (2023). A Peer-to-Peer Intelligence Market. <https://bittensor.com/whitepaper>

Consensus Mechanisms

\[10] Buchman, E. (2016). Tendermint: Byzantine fault tolerance in the age of blockchains. <https://tendermint.com/static/docs/tendermint.pdf>

\[11] Boneh, D., Drijvers, M., & Neven, G. (2018). Compact multi-signatures for smaller blockchains. <https://crypto.stanford.edu/\\~dabo/pubs/papers/BLSmultisig.html>

Zero-Knowledge Proofs

\[12] Ben-Sasson, E., Bentov, I., Horesh, Y., & Riabzev, M. (2018). Scalable, transparent, and post-quantum secure computational integrity. <https://eprint.iacr.org/2018/046.pdf>

\[13] Groth, J. (2016). On the size of pairing-based non-interactive arguments. <https://eprint.iacr.org/2016/260.pdf>

\[14] Gabizon, A., Williamson, Z. J., & Ciobotaru, O. (2019). PLONK: Permutations over Lagrange-bases for oecumenical noninteractive arguments of knowledge. <https://eprint.iacr.org/2019/953.pdf>

Stablecoins & DeFi

\[15] Maker Foundation. (2020). The Maker Protocol: MakerDAO's Multi-Collateral Dai (MCD) System. <https://makerdao.com/whitepaper>

\[16] Curve Finance. (2020). StableSwap - efficient mechanism for Stablecoin liquidity. <https://curve.fi/files/stableswap-paper.pdf>

\[17] Frax Finance. (2023). Frax Protocol Documentation. <https://docs.frax.finance/>

Machine Learning & Reinforcement Learning

\[18] Sutton, R. S., & Barto, A. G. (2018). Reinforcement learning: An introduction. <http://incompleteideas.net/book/the-book-2nd.html>

\[19] Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). Proximal policy optimization algorithms. <https://arxiv.org/abs/1707.06347>

Privacy & Security

\[20] Dwork, C., & Roth, A. (2014). The algorithmic foundations of differential privacy. <https://www.cis.upenn.edu/\\~aaroth/Papers/privacybook.pdf>

\[21] Kosba, A., Miller, A., Shi, E., Wen, Z., & Papamanthou, C. (2016). Hawk: The blockchain model of cryptography and privacy-preserving smart contracts. <https://eprint.iacr.org/2015/675.pdf>

Data Availability & Storage

\[22] Srinivasan, S., Chitra, U., & Bhat, S. (2023). Data availability sampling and sub-sampling for light clients. <https://arxiv.org/abs/2301.10785>

Industry Reports & Standards

\[23] Bank for International Settlements. (2023). The future monetary system. BIS Annual Economic Report. <https://www.bis.org/publ/arpdf/ar2023e.htm>

\[24] World Economic Forum. (2024). Navigating the AI Revolution: Insights and Strategies. <https://www.weforum.org/reports/>

B² Network Documentation

\[25] B² Network Team. (2024). B² Network Technical Documentation. <https://docs.bsquared.network/>

\[26] B² Network Team. (2024). B² Hub: DA Layer on Bitcoin. <https://blog.bsquared.network/b²-hub-da-layer-on-bitcoin-fa63d52b8926>

\[27] B² Network Team. (2024). B² AI Signal: Decentralized AI Infrastructure. <https://docs.bsquared.network/b2\\_dsn\\_ai>

\[28] B² Network GitHub Repository. (2024). <https://github.com/b2network/>

Related Projects

\[29] Lightning Network Specification. <https://github.com/lightning/bolts>

\[30] Cosmos SDK Documentation. <https://docs.cosmos.network/>

\[31] Polygon zkEVM Documentation. <https://wiki.polygon.technology/docs/zkevm/>

\[32] Arbitrum One Portal. <https://developer.arbitrum.io/>

\[33] Optimism Documentation. <https://docs.optimism.io/>


# Core Architecture

B² Network is designed as a **modular Bitcoin + AI settlement infrastructure**, enabling the vision of **“Put Bitcoin in Every AI’s Wallet.”**

The architecture is built around **five tightly connected modules**, each solving a key challenge in unifying Bitcoin, AI Agents, and Stablecoin economies:

1. **Mining² (DeFAI-Mining Router)** Connects Bitcoin miners to the network by routing hashrate and BTC revenues into staking pools, agent wallets, and validator incentives. It bridges Proof-of-Work security with Proof-of-Signal governance.
2. **B² Hub (Layer 1.5 PoSg Consensus)** A sovereign “Layer 1.5” chain powered by Proof-of-Signal + Stake (PoSg).
   * Signals from AI agents and delegators determine validator voting power.
   * Application sharding separates Signal, Agent, and Stablecoin execution environments.
   * Anchors finality to Bitcoin via Taproot inscriptions for global security.
3. **B² Rollup (BTC-Anchored L2 Execution Layer)** An EVM-compatible rollup environment with high throughput and native BTC-denominated gas.
   * Aggregates transactions, zk/fraud proofs, and data commitments.
   * Posts merkle roots and proofs to Bitcoin for trustless anchoring.
   * Enables developers to deploy dApps and smart contracts with BTC settlement.
4. **AI Signal (Signal-Driven Agentic AI Layer)** The protocol layer that integrates autonomous AI agents directly into blockchain consensus.
   * Agents emit verifiable “signals” representing perception, planning, and actions.
   * Validators use signals to adjust voting power via SignalScore.
   * Provides Agent-Native Abstraction Accounts (A-AA), enabling agents to hold and transact in BTC or U2 natively.
5. **U2 Stablecoin (BTC-Collateralized Settlement Layer)** A Bitcoin-backed stablecoin designed for micro-payments and predictable pricing.
   * Over-collateralized by BTC with hedging strategies for peg stability.
   * Used by agents for task payments, settlements, and long-term contracts.
   * Serves as the stable economic medium for the AI-driven ecosystem.

![B² Network Architecture](/files/tEZTedP3EpRMPjlYyrrk)

***

## Architectural Flow

* **From Mining to AI**: BTC mined by Mining² flows into validators and agents, securing the Hub.
* **From Agents to Consensus**: AI signals are aggregated into the Hub’s PoSg consensus, shaping governance and execution.
* **From Rollup to Bitcoin**: Transactions and proofs are rolled up and anchored to Bitcoin for ultimate settlement finality.
* **From BTC to Stability**: U2 stablecoin ensures agents and users transact with predictable value.

Together, these modules form a **closed economic and technical loop**: BTC → Signals → Consensus → Rollup Execution → U2 Stablecoin → AI Economy → back to BTC.

This architecture transforms Bitcoin from a passive store of value into the **active settlement currency of the AI era**.


# Mining² (DeFAI-Mining Router)

## Overview

Mining² is the bridge between **Bitcoin miners** and the **AI-driven financial ecosystem**. It routes real-time hashrate and BTC revenues into the B² Network, enabling miners to participate not only in Proof-of-Work security, but also in Proof-of-Signal (PoSg) governance and AI agent economies.

In essence, Mining² turns *raw hashrate* into *programmable financial flow*.

***

## Key Functions

1. **Hashrate Routing**
   * Miners can commit a portion of their hashrate or expected BTC revenues into the Mining² router.
   * These commitments generate tokenized claims, which can be used as collateral in DeFi and AI-agent applications.
2. **BTC Revenue Integration**
   * Mining rewards are automatically split and routed:
     * **Staking Pools**: strengthen PoSg validator security.
     * **Agent Wallets**: fund autonomous AI agents with BTC for micro-payments.
     * **Liquidity Pools**: provide BTC liquidity for stablecoin minting (U2).
3. **Financialization of Mining**
   * Future hashrate or mining revenues can be collateralized to mint U2 stablecoins.
   * Miners gain access to immediate liquidity without selling BTC holdings.
   * Creates a yield-bearing financial instrument from traditionally illiquid mining flows.
4. **PoW ↔ PoSg Synergy**
   * Mining² integrates Proof-of-Work rewards into the Hub’s PoSg consensus.
   * Ensures that miners remain core contributors to governance and security, while AI agents shape voting through signals.

***

## Technical Highlights

* **Revenue Router Smart Contracts** Automated contracts allocate BTC flows into different destinations (staking, agents, liquidity).
* **Hashrate-Backed Collateralization** Tokenized claims on future hashrate revenues can be used for stablecoin minting and yield generation.
* **Agent Integration** Mining proceeds can be directly streamed into Agent-Native Accounts (A-AA), giving AI agents sustainable BTC inflows.
* **Cross-Layer Connectivity** Mining² acts as the entry point connecting Bitcoin’s PoW layer with B² Hub (PoSg consensus) and Rollup execution.

***

## Use Cases

* **For Miners**
  * Unlock liquidity by collateralizing hashrate or future BTC rewards.
  * Earn additional yield by routing rewards into PoSg staking or U2 minting.
  * Participate in AI-driven financial markets without selling BTC.
* **For Validators**
  * Access miner-backed BTC flows to strengthen security.
  * Share governance power with AI signals through PoSg.
* **For AI Agents**
  * Receive BTC directly as operational funding for tasks and settlements.
  * Achieve autonomous financial sustainability.

***

## Strategic Significance

Mining² extends the role of Bitcoin mining from **pure energy-to-BTC conversion** to **energy-to-financial-flow integration**. It ensures that miners are not left outside the AI + stablecoin economy, but become first-class citizens in the B² Network.

This design unifies:

* **Proof-of-Work Security** (miners)
* **Proof-of-Signal Governance** (agents & validators)
* **BTC-Fi Liquidity** (stablecoins & financial markets)

Mining² is the **entry point of BTC value into the AI economy**, powering the vision: **“Every AI Agent holds Bitcoin.”**

View more about [Mining²](https://docs.bsquared.network/b2_network_put_bitcoin_in_every_ais_wallet#signal-signalscore)


# B² Hub (Layer 1.5 PoSg Consensus)

## Overview

B² Hub serves as the **Layer 1.5 consensus backbone** of the B² Network, bridging Bitcoin’s Proof-of-Work finality with AI-driven Proof-of-Signal + Stake (PoSg). It is designed to combine the **security of Bitcoin anchoring**, the **scalability of application sharding**, and the **intelligence of AI signals** into a unified infrastructure.

***

## Core Principles

* **Proof-of-Signal + Stake (PoSg):** Validators secure the Hub by staking BTC and receiving delegated **signals** from AI Agents and users. Voting power = Staked BTC × SignalScore, ensuring that **economic capital and intelligent activity jointly drive consensus**.
* **Application Sharding:** The Hub introduces multiple shards, such as:
  * **Signal Shard**: Collects and verifies signals from AI Signal.
  * **Agent Shard**: Executes agent-native contracts and interactions.
  * **Stablecoin Shard**: Handles U2 minting, redemption, and settlements. This separation ensures high throughput and modular scalability.
* **Bitcoin Anchoring:** Finalized states and validator commitments are periodically written to Bitcoin’s Taproot via inscription transactions. This creates an **immutable audit trail** and inherits Bitcoin’s Proof-of-Work finality.

***

## Technical Design

### 1. Validator Lifecycle

* **Staking:** Validators bond BTC into the Hub to participate in consensus.
* **Signal Delegation:** AI Agents and users delegate signals to validators, weighted by trust and performance.
* **Epoch Rotation:** At each epoch, validator sets are updated via **FROST-DKG key resharing**, ensuring cryptographic robustness.
* **Reward Distribution:** Rewards are paid in BTC and U2, sourced from Mining² revenue routing and network fees.

### 2. Consensus Mechanics

* **CometBFT PBFT Engine:** The Hub runs a modified CometBFT engine, where PoSg determines voting power.
* **Byzantine Detection:** Graph Neural Networks (GNN) monitor validator behavior and detect anomalies (double-signing, equivocation, censorship).
* **Finality:** Hub blocks achieve instant BFT finality, while anchoring to Bitcoin provides long-term economic immutability.

### 3. Signal Integration

* **SignalScore:** A composite metric representing the volume, diversity, and reliability of signals delegated to a validator.
* **Weighting Formula:**

  $$
  \text{SignalScore}*v = \sum*{\text{agent} \in \mathcal{D}*v} \sum*{\text{sig} \in \mathcal{W}} \text{weight}
  $$
* **Impact:** Signals allow AI Agents to actively influence consensus, aligning network governance with intelligent activity.

***

## Applications of B² Hub

* **AI-Driven Governance:** Agents collectively steer validator voting power through their delegated signals.
* **BTC Settlement Backbone:** Provides high-throughput consensus while anchoring to Bitcoin for security.
* **Ecosystem Aggregator:** Serves as the coordination layer for Rollup execution, stablecoin issuance, and signal propagation.
* **Agent Economy Enablement:** Establishes a trustless environment where AI Agents transact and settle in BTC and U2 natively.

***

## Key Benefits

* **Hybrid Security:** Combines PoW anchoring with PoSg consensus for maximum resilience.
* **AI-Native Consensus:** Signals transform AI activity into measurable economic weight.
* **Modular Scalability:** Application sharding allows specialization and parallel execution.
* **Economic Finality:** Anchoring to Bitcoin guarantees irreversible settlement.

***

**B² Hub is the heart of the network — a consensus engine where Bitcoin, AI signals, and stablecoin economics converge.**


# B² Rollup (Bitcoin Layer2)

ZK-Rollup consists of several components, including Account Abstraction Module, RPC Service, Mempool, Sequencers, zkEVM, Aggregators, Synchronizers, and Prover.

## Account Abstraction Module

B² Network implements native account abstraction at Rollup Layer in Figure [B² Network Account Abstraction](https://ipfs.io/ipfs/QmVnG1MLdx8X8Wwk4Vxjooei7tw297wTtAWRpvWezwNDdZ). B² Network creates contract accounts controlled by users in the zkEVM. Contract accounts for Bitcoin address accounts are controlled by the user's Bitcoin private key, those for Ethereum address accounts by the user's Ethereum private key, and for Email accounts by the user's email. Users can generate sub-accounts through their contract account for different devices or DApps. Sub-accounts can have controlled permissions, like only sending standard transactions and not managing assets of the contract account. The controlling account can remove sub-accounts at any time. The contract account features a modular execution layer, which performs default operations or checks based on B² Network's and users' settings, such as account initialization, email account DKIM verification, transaction validation, account recovery, permission management, and asset locking. This execution layer is expandable and upgradable. Users' on-chain assets in B² Network are attributed to the contract account and can be managed through the controlling account (Bitcoin address account, Ethereum address account, or Email account).

The Account Abstraction module of B² Network, through its Transaction Bundler service, can implement a gas payment function on behalf of users. Upon receiving transaction messages signed by the user's controlling account or sub-accounts, the Transaction Bundler, based on the user's settings for gas payment or the interacting contract's settings, pays the gas for the user. It then collects other assets from the user or the interacting contract as compensation.

![B² Network Account Abstraction](https://ipfs.io/ipfs/QmVnG1MLdx8X8Wwk4Vxjooei7tw297wTtAWRpvWezwNDdZ)

## RPC Service

Users initiate transactions or send signed messages through wallets or services provided by DApps to B² RPC Service. Once these transactions or signed details are received, B² RPC Service performs preliminary validation, either directly sending them to the Mempool service or processing them for account abstraction before dispatch. B² RPC Service internally integrates the Transaction Bundler service of the Account Abstraction Module, which validates message signatures and generates corresponding transaction information based on the message content. The Transaction Bundler service offers gas payment on behalf of users, using BRC20 assets on Bitcoin like ORDI, SATS, or directly deducting gas from the interacting contracts, facilitating gas-free functionalities for DApps. By employing horizontal scaling, B² RPC Service can enhance the performance of Rollup Layer. Third-party entities and developers can operate B² RPC Service and provide related services.

## Mempool

The Mempool serves as the storage for all pending transactions. Sequencers can access and order these transactions from the Mempool.

## Sequencer

The Sequencer in B² Network is responsible for ordering and packaging the transactions submitted by users, and then handing them over to the zkEVM for specific transaction execution. B² Network implements a Decentralized Sequencer service through B² Nodes, which update the Sequencer Set via a mechanism similar to DPoS. The Sequencers within the Sequencer Set provide transaction ordering and packaging services in sequence.

## zkEVM

The zkEVM, compatible with EVM, facilitates developers in constructing secure DeFi, NFTs, and other DApps. It also aids developers in migrating DApps from other EVM-compatible chains to B² Network. Combined with the Bitcoin Indexer Module of the B² Nodes, the zkEVM stores Bitcoin's state data, enabling developers to integrate the Bitcoin network into DApp development.

## Aggregators

The Aggregators access the sequencer's post-ordered transaction information and state information from the zkEVM. They either generate zero-knowledge proofs via the Prover or aggregate transactions and collate proof details from the Prover, formulating a transaction batch hash tree. This tree is then sent to the data availability layer for backup, ensuring rollup transaction data availability.

## Prover

The Prover's role is to generate validity proofs, representing the authenticity of a batch of user-submitted transactions. Initially, the Prover creates multiple ZK-STARK proofs based on the transaction batch and state information acquired from the Aggregator. By leveraging STARK Recursion, these ZK-STARKs are bundled to produce a single, extensive ZK-STARK. This ZK-STARK, being sizeable, is channeled out via the CIRCOM component to the SNARK builder, which in turn generates a ZK-SNARK validity proof, drastically reducing Gas costs. Finally, the generated proof returns to the Aggregator.

## Synchronizer

The Synchronizer ensures that information from B² Nodes is synchronized into the Rollup Layer, encompassing details like sequencer information, Bitcoin transaction data, and more.

In conclusion, the Rollup Layer procures user transactions via the RPC Service and stores them in the Mempool. Once sequencers have ordered these transactions, the zkEVM processes the transaction batch. The Prover then produces a zero-knowledge proof of transaction authenticity. Through the Aggregator, transaction and proof details are summarized and synchronized to B² Network's data availability layer, ensuring transaction veracity, data security, and data availability.


# AI Signal (Signal-Driven Agentic AI Layer)

## A Decentralized Signal-Driven Network for Modular and Agentic Artificial Intelligence

**Keywords**: **Bitcoin**, **B² Network**, **AI**, **Agentic AI**, **AI Agent**, **Signal Network**

## Abstract

In the current rapid evolution of generative AI, **Agentic AI** is becoming a key paradigm for automating complex tasks and human-machine collaboration with its closed-loop mechanism of "autonomous perception - planning - decision-making - execution - learning." However, existing frameworks mostly encapsulate various functional modules within a single runtime or platform, leading to a high degree of coupling in data formats, communication protocols, and permission models. Once there is a need to cross frameworks like LangChain, AutoGen, CrewAI, or to collaborate between cloud services, local processes, and blockchain contracts, developers must rewrite adaptation layers and maintain multiple sets of state synchronization logic, severely restricting the composability, maintainability, and secure and trustworthy interaction of agents.

To break this bottleneck, **B² Network** proposes the **Decentralized Signal-Driven Network for Modular and Agentic Artificial Intelligence (AI Signal)**, leveraging its Bitcoin-secured Rollup infrastructure. AI Signal abstracts a type of on-chain Signal: each Signal carries a type, Schema hash, payload, timestamp, and signature, which can be written with high throughput on the B² Rollup and anchored to Bitcoin via the B² Hub, achieving global consistency, immutability, and verifiability. Signals become the sole contract between heterogeneous Agents: any cloud, private, or edge Agent can be dynamically discovered by simply publishing a "capability Signal," and collaboration can be triggered by sending new Signals. User goals are transformed by the LLM planner into an event-directed graph managed by LangGraph; the embedded sparse MoE Dispatcher dynamically selects the optimal expert chain for each Signal, enabling fine-grained, on-demand specialized reasoning without touching downstream modules.

Based on "Signal + LangGraph + LangChain tools + Mixtral-MoE," the AI Signal not only provides a unified, verifiable, and asynchronous communication protocol but also brings true modularity and hot-swappable capabilities to agent-based artificial intelligence, laying the foundation for a more open, secure, and intelligent multi-agent ecosystem.

## Introduction

### Background and Motivation

In the past decade, the breakthrough advancements in large language models (LLMs) have greatly enhanced the level of natural language understanding and generation, making "software driven by language" possible. At the same time, the potential of multi-agent collaboration (Multi-Agent Systems, MAS) in task decomposition, automated operations, and complex decision-making has been continuously validated, giving rise to a new paradigm called **Agentic AI**—which combines the generalized reasoning capabilities of LLMs with the specialized toolchains of modular agents, completing dynamic complex tasks through a "think-act-reflect" cycle.

However, when researchers and developers attempt to push Agentic AI towards production-level applications, they commonly encounter three bottlenecks:

1. **Coupling Bottleneck**

   Existing frameworks (such as LangChain, AutoGen, CrewAI, etc.) each define their own tool encapsulation, memory formats, and execution contexts, leading to a lack of unified communication protocols and authentication mechanisms between agents. When cross-framework collaboration is needed, developers are forced to maintain multiple sets of adapters and state synchronization logic, resulting in a sharp increase in system evolution costs.
2. **Trustworthiness Bottleneck**

   Most agent invocation chains operate within a single trust domain, lacking auditable and traceable execution records. In scenarios requiring compliance proof, financial settlement, or IoT control, the absence of unified identity authentication and tamper-proof result guarantees keeps the risks of large-scale deployment high.
3. **Intelligent Evolution Bottleneck**

   As task complexity continues to increase, the existing single LLM or fixed processes struggle to meet the dual demands of real-time performance and professional depth. There is an urgent need to seamlessly integrate more expert models, private APIs, or edge devices, but traditional centralized coordination methods cannot support the high-frequency asynchronous event flow.

**B² Network**, anchored to the Bitcoin mainnet and aimed at composable finance and computing, inherently possesses advantages of high security, global accessibility, and scalable data availability layers. Therefore, we propose the **Decentralized Signal-Driven Network for Modular and Agentic Artificial Intelligence (AI Signal)**, which elevates on-chain "events" to **Signals** with signatures, schemas, and timestamps, thereby constructing a unified, verifiable, and asynchronous agent communication bus. Specifically:

* **Decentralized Trustworthy Timeline**: All Signals are first written to the B² Rollup and submitted to Bitcoin via the B² Hub, combining the irreversible UTXO ledger to provide globally synchronized causal order and tamper-proof auditing.
* **Composable Module Interface**: Signals only define a three-part contract of "type + payload schema + signature," allowing any agent—whether running on cloud clusters, private servers, or local devices—to announce the types of events they can handle by publishing "capability signals," achieving plug-and-play modular collaboration.
* **Intelligent Routing and Load Balancing**: Based on the LangGraph event graph and sparse MoE Dispatcher, the LLM planner can select the best expert model on demand and decompose tasks into parallel executable Signal DAGs, thereby enhancing system throughput and intelligence while ensuring consistency.

AI Signal aims to provide a "low-coupling, high-trust, easy-evolution" foundational communication layer for Agentic AI, allowing developers to focus on business logic and model innovation without repeatedly addressing cross-framework interoperability and security auditing issues.

### Mission and Vision

* **Mission**

  The core mission of AI Signal is to enable developers, enterprises, and individual users around the world to build, deploy, and interconnect AI Agents with unprecedented security, interoperability, and composability through a decentralized, verifiable Signal protocol. We are committed to: 1) providing traceable and tamper-proof execution logs for all Agent actions anchored at Bitcoin-level security; 2) replacing fragmented API adaptation layers with a minimal, unified Signal contract to lower the collaboration threshold across frameworks; 3) unleashing the parallel and real-time response potential of Agents through an asynchronous event-driven model, allowing them to operate safely in high-risk scenarios such as finance, industry, research, and public services; 4) building an open community and economic incentives to encourage more expert models and tools to be packaged as subscribable capability Signals, forming a positive feedback loop.
* **Vision**

  The future we envision is a decentralized intelligent grid composed of countless professional Agents: robots can subscribe to maintenance signals in real-time on factory floors, financial algorithms share market insights on-chain, personal assistants execute home commands securely in local private domains, and all information flows freely, auditable, and composable through the AI Signal Signal bus. At that time, developers will no longer be limited to specific cloud platforms, model researchers can seamlessly inject the latest MoE experts into global task flows, and end users will gain data control focused on privacy and sovereignty. We believe that AI Signal will become the next generation "public communication layer" connecting humans and machine intelligence, laying a trustworthy, open, and shared foundation for autonomous AI ecosystems, just as the internet did for information and Bitcoin did for value.

## Signal Network Model

### Definition and Data Structure

* Definition

  **Signal** is the core primitive of AI Signal: a Signal consists of fields such as "type code + schema hash + payload + timestamp + signature," and is recorded on the B² Rollup, ultimately anchored to Bitcoin L1, thus possessing global consistency, immutability, and verifiability. It serves as both a **communication contract**—any heterogeneous agent in cloud, private servers, or local devices can complete service discovery and event routing simply by publishing a "capability Signal"; and as an **identity and audit credential**, providing execution traceability and causal ordering through ECDSA signatures and an on-chain timeline. For data streams or decision results with economic value, a Signal can also upgrade to a **paid Signal**: the publisher embeds payment conditions and encrypted key indexes in the payload, and subscribers must first complete on-chain micropayments or zero-knowledge commitments to unlock the symmetric key and read the encrypted payload, achieving cryptographic secure paid subscriptions. This allows modules for perception, planning, decision-making, execution, and learning to be freely combined in a hot-swappable manner across frameworks and platforms, while also giving rise to a new data/model-as-a-service economy.
* Data Structure

  **On-chain Data Structure of Signal**

  | Field Name   | Type           | Required | Function                         | Description                                                                                        |
  | ------------ | -------------- | -------- | -------------------------------- | -------------------------------------------------------------------------------------------------- |
  | version      | uint8          | Y        | Protocol Version                 | Convenient for forward compatibility; currently fixed to 0x01                                      |
  | type         | bytes4         | Y        | Event Type Code                  | 32-bit integer, identified in hexadecimal, e.g., 0x504C4E=PLAN, 0x584543=EXEC                      |
  | schema\_hash | bytes32        | Y        | Payload Mode Hash                | Perform Keccak-256 on JSONSchema / Protobuf IDL; ensure consistent parsing across different Agents |
  | payload      | bytes <= 65536 | Y        | Business data                    | Serialized according to schema\_hash corresponding pattern; optional GZIP compression              |
  | timestamp    | uint64         | Y        | Millisecond timestamp            | Unix epoch ms; used for causal ordering and replay protection                                      |
  | nonce        | uint64         | Y        | Initiator's local counter        | Incremented for the same issuer to prevent hash prefix collisions                                  |
  | issuer       | bytes20        | Y        | Initiator Identifier             | B² Rollup Account Address                                                                          |
  | sig          | bytes65        | Y        | Digital Signature                | secp256k1 (ECDSA)                                                                                  |
  | pay\_info    | bytes          | N        | Payment subscription information | Appears only in paid Signal. Structure: {price, denom, pay\_to, enc\_key\_cid}                     |
  | ttl          | uint32         | N        | Time to Live (seconds)           | Router can discard after expiration; reduce indexing burden                                        |
  | meta         | bytes          | N        | Custom Metadata                  | For example, Gas budget, priority, IPFS CID, ZK proof                                              |
* Field Supplementary Explanation

1. Sig
   * sig: Digital Signature, secp256k1 (ECDSA): r(32)‖s(32)‖v(1); Sign the continuous bytes of version‖type‖schema\_hash‖payload‖timestamp‖nonce‖issuer
2. Payable Signal
   * pay\_info.price: Micro payment amount in wei/satoshi
   * pay\_info.denom: ETH / BTC / On-chain ERC-20 address
   * pay\_info.pay\_to: Receiving address; can be different from issuer
   * pay\_info.enc\_key\_cid: Points to the symmetric key stored in IPFS/Arweave (can be decrypted after payment by the receiver using Proxy Re-Encryption or ECDH)
3. Payload Encryption
   * Default plaintext; if schema\_hash is marked as "encrypted" with the highest bit 1, then the payload is AES-GCM ciphertext, and the encryption algorithm and KEK index are stored in meta
   * Decryption process: Subscriber pays -> Obtain KEK -> Decrypt symmetric key -> Decrypt payload
4. Topic Calculation and Subscription

   * Dispatcher uses topic = keccak160(type‖schema\_hash) to generate a 20-byte topic; Agent can subscribe to multiple topics at once. Bloom Filter for quick matching, complete index in LevelDB/RocksDB.

   **On-chain Encoding and Storage Hierarchy**

   | Level                | Encoding Format              | Key Operations                                                                                             |
   | -------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------- |
   | B² Rollup            | RLP variable-length encoding | Write transaction calldata; VM pre-sign sig then write State tree                                          |
   | B² Hub -> Bitcoin    | SHA‑256 Merkle root          | Every N Rollup blocks aggregate root hash written to a single OP\_RETURN; main chain only retains 80 bytes |
   | Off-chain index node | LevelDB / RocksDB            | Quickly index and match using Bloom Filter in a topic-based manner                                         |

   Example JSON (Paid Signal)

   ```
   {
      "ver": 1,
      "type": "0x444154",                     // DAT: data release
      "schema_hash": "0xb3f2...c41e",
      "payload": "0x1f8b08...",               // GZIP + AES-GCM Encrypted Data
      "timestamp": 1715162045123,
      "nonce": 128,
      "issuer": "0x5e74fa8d9f4c71e1d046",
      "sig": "0xa69c...7b",
      "pay_info": {
         "price": "1000000000000000000",          // 1B2
         "denom": "B2",
         "pay_to": "0x1234...abcd",
         "enc_key_cid": "bafybeiabc...xyz"
      },
      "ttl": 86400,
      "meta": "0x7b22706b223a20224145532d47434d227d"   // {"pk": "AES-GCM"}
   }
   ```

* Core Function Summary
  1. Unified Protocol Layer: Replaces proprietary APIs of various frameworks with fixed field definitions to achieve cross-platform collaboration.
  2. Secure and Trustworthy: On-chain timestamps + signatures + Bitcoin anchoring provide tamper-proof and traceable auditing.
  3. Economic Incentives: Supports paid subscriptions for data/model as a service through embedded micropayment logic in the pay\_info field.
  4. Extensible: Reserves extension fields such as meta and ttl, supporting ZK proofs, gas policies, and priority scheduling.

This data structure ensures the interoperability and security of signal interactions while leaving ample room for future cryptoeconomic models and new Agent functionalities.

### Payable Signal

Allows any producer Agent to issue a "payable Signal" for high-value data/model results, where consumer Agents can only obtain the decryption key and read the payload after completing on-chain payment; the entire process requires no trust in third parties and can be audited within the secure boundary of B² Rollup -> Bitcoin.

1. Core Roles

   | Role                        | Description                                                                                                                |
   | --------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
   | Producer Agent (P)          | Generates high-value data or model results and publishes Payable Signal                                                    |
   | Consumer Agent (C)          | Subscribe to the specified Signal, confirm the price, complete the payment, and decrypt                                    |
   | Payment Contract (PC)       | Standard payment contract deployed on B² Rollup; supports B2/BTC/Stablecoin                                                |
   | Re‑Encryption Service (RES) | Decentralized Proxy Re‑Encryption node set (reusable NuCypher/Kokonut); re-encrypted for payers after symmetric key unlock |
   | Signal Dispatcher (SD)      | Responsible for routing and event indexing; unaware of encrypted payloads                                                  |
2. Encryption and Key Management

   1. Content Encryption
      * P generates a random symmetric key k\_s (256-bit) and encrypts the original payload using AES-GCM: cipher = Enc\_AES(k\_s, payload).
   2. Key Encapsulation
      * P generates a temporary EC key pair (ePub, ePriv).
      * Using a consumer-verifiable KP-ABE directed policy: perform Proxy Re-Encryption sharding on (k\_s) (KFrags).
      * Generate capsule = ECIES\_Enc(ePub, k\_s) and hand over the transformation parameters of the capsule to the RES node for storage.
   3. Metadata Embedding
      * Write into Signal's pay\_info: {price, denom, pay\_to, capsule\_cid, ePub}.
      * capsule\_cid points to the key encapsulation fragment file on IPFS / Arweave.

   Cryptographic Principles:

   * AES-GCM provides confidentiality + integrity (GCM Tag).
   * ECIES (secp256k1) generates a one-time encapsulation, ensuring that k\_s cannot be recovered by anyone other than the legitimate payer.
   * Proxy Re-Encryption (e.g., Umbral) allows the key authority to be redirected from P to the completing payer C without exposing k\_s; the RES node can only re-encrypt after receiving KFrag.
3. Payment Process
   1. Price Negotiation (Optional)
      * C listens for Payable Signal, reads price and denom; if accepted -> continue
   2. On-chain Payment
      * C calls Payment Contract.pay(signal\_id, amount); PC will lock the funds and emit a PaymentConfirmed event (including payer, signal\_id, tx\_hash)
   3. Zero-Knowledge Payment Proof (Optional)
      * If the amount should not be disclosed, ZK-SNARK (Groth16) can be used to submit: proof = zkPay(amount, signal\_id); PC only verifies proof, does not display amount
   4. Payment Completion Notification
      * P or RES listens for PaymentConfirmed -> emits payment.received Signal
4. Key Re-encryption & Decryption
   1. Re-encryption Authorization
      * Once P receives payment.received Signal, it sends a ReKey request to the RES node, along with (signal\_id, payer\_pubkey)
      * RES re-encrypts the capsule to C according to the stored KFrag ⇒ obtains re\_capsule
   2. Key Recovery
      * C downloads re\_capsule, calls ECIES\_Dec(payer\_priv, re\_capsule) ⇒ k\_s
      * Use k\_s to decrypt cipher, obtaining the original payload
   3. Integrity Check
      * Verify with AES-GCM Tag; if passed -> C sends action.completed Signal, carrying the result or commitment
5. Data Structure Supplement

   ```
   {
      // ...Core fields omitted
      "pay_info": {
         "price": "1000000000000000000",     // 1B2
         "denom": "B2",
         "pay_to": "0x1234...abcd",       // PaymentContract address
         "capsule_cid": "bafybeihash...", // where original capsule stored
         "epub": "0x04ab...31"            // producer's ephemeral pubkey
      },
      "meta": {
         "enc_alg": "AES-GCM-256",
         "pre_scheme": "Umbral",
         "zk_mode": true
      }
   }
   ```

### Event Lifecycle

The lifecycle of a Signal follows seven stages: "Generation -> On-chain Publication -> Network Propagation -> Subscription Routing -> Consumption Execution -> Result Backlinking -> Archiving Expiration." Each stage establishes clear responsibility boundaries between B² Rollup and off-chain routing nodes, ensuring the traceability, eventual consistency, and recoverability of errors in events.

1. Generation
   * Trigger Source: Can be triggered by LLM Planner, external sensors, timers, or user requests.
   * Payload Packaging: Serialize the payload according to the schema specifications from the previous section; if it is encrypted/paid data, complete AES-GCM encryption and pay\_info construction synchronously.
   * Field Filling: Generate timestamp, nonce, and call the signing module to obtain sig, thus forming a complete Signal JSON/CBOR object locally.
2. On-chain Publication
   * On-chain Transaction: The Producer encodes the Signal in RLP and writes it as calldata into a Rollup transaction, paying the minimum Gas; in bulk scenarios, it can be packaged in batches.
   * Transaction Verification: The Rollup VM verifies sig and nonce; if it fails, the entire transaction rolls back.
   * Block Archiving: Successful transactions enter the Rollup block; every N blocks, a root hash is packaged and written to Bitcoin L1's OP\_RETURN via B² Hub, obtaining an immutable timestamp.
3. Network Transmission (Broadcast)
   * P2P Distribution: The Rollup consensus layer pushes new blocks to all network nodes.
   * Index Node: Dedicated Dispatcher nodes listen to the block stream, parse Signals, and store them in local LevelDB / RocksDB.
   * Topic Filtering: Maintain a Bloom Filter to accelerate matching based on topic = keccak160(type‖schema\_hash).
4. Subscription Routing (Route)
   * Capability Discovery: All online Agents publish CAP capability Signals upon startup, declaring supported Topics, priorities, and callback URLs.
   * Matching Mechanism: When the Dispatcher receives a new Signal, it asynchronously pushes events into the corresponding queue according to the (Topic -> Subscribers) reverse index; if it is an encrypted Signal, only the ciphertext and Capsule reference are transmitted.
   * Retry and QoS: For HTTP or gRPC callback failures, exponential backoff is used for retries; if it exceeds TTL, it is automatically discarded and a signal.expired event is emitted.
5. Consumption Execution (Consume)
   * Agent Parsing: After receiving an event, the subscriber first compares the schema\_hash; if there is no corresponding Schema locally, it pulls updates from the Registry.
   * Access Control: If it is a paid Signal, the payment status is checked first; unpaid Signals enter a pending queue.
   * Business Processing: Call the toolchain or local model for execution, generating output and status locally.
   * Off-chain Result Caching: Large output files can be uploaded to IPFS and the CID recorded.
6. Result Acknowledgment (Acknowledge)
   * After processing, the consumer generates a confirmation Signal with type = 0x584543 (EXEC) or another agreed type, where the payload includes fields such as task\_id, status, output\_cid, etc., and republishes it to the Rollup. At this point, the original initiator or coordinating LLM can obtain the results through subscription and enter the next planning round.
7. Archiving and Expiration (Archive / Expire)
   * TTL Expiration: The Dispatcher regularly scans the local index, and Signals that have not been consumed or paid for after timeout trigger a signal.expired receipt.
   * Cold Storage: Rollup full nodes can choose to retain only the Merkle proof of old block Signals, with detailed content handed over to decentralized storage (Arweave/Filecoin).
   * Error Handling: In the event of chain reorganization or double signing, Rollup provides a rewind mechanism; the Dispatcher rolls back the local index based on block height and repushes.

Summary: This lifecycle design combines an immutable on-chain timeline with a high-performance off-chain push system, ensuring global consistency while balancing low latency and high throughput, and providing production-oriented robustness through mechanisms such as retries, TTL, and receipts.

### Security and Verifiability Mechanisms

The security model of the Signal network is divided into four complementary layers: on-chain authenticity assurance, off-chain transmission integrity, economic incentives and anti-malicious mechanisms, and privacy and access control.

1. Identity Authentication and Non-repudiation
   * Initiator Signature: Each Signal is signed using the issuer's private key on the "core seven fields" with ECDSA (secp256k1), and the Rollup VM verifies it instantly during the transaction execution phase; any forgery will be rejected from being written into the state tree.
   * Bitcoin Anchoring: The B² Hub writes the Rollup block Merkle root into Bitcoin OP\_RETURN; forging history would require rolling back Bitcoin PoW, with costs consistent with the mainnet -> non-repudiation.
   * Multi-signature (M-of-N): High-value Signals can embed a threshold Schnorr contract address in the sig field, requiring multiple signatures before being put on-chain.
2. Data Integrity and Rollback Fault Tolerance
   * Merkle Proof: Any third party can verify the existence of a Signal on L1 through (signal\_hash, merkle\_path, root\_hash).
   * Block Rollback: If the Rollup encounters an L2 fork, the rewind protocol can determine the correct chain based on the Bitcoin anchor, and the Dispatcher node rolls back the index by height and re-pushes events to ensure eventual consistency.
3. Replay Attacks and Sequential Consistency
   * nonce + timestamp dual verification: The nonce of the same issuer is monotonically increasing, and the timestamp must be within the local block time window; exceeding the window or replaying is immediately rejected.
   * Bloom Filter cache: The Router retains a double-layer Bloom filter of the processed {issuer, nonce} set to further filter duplicate events.
4. Economic Resistance to Spam and DoS Protection
   * Gas fees: The publisher must pay a minimum gas fee; large-scale spam sending will directly waste collateral.
   * Minimum staking (optional): Introduce a "staking-penalty" model for high-frequency topics: if an Agent repeatedly sends invalid Signals and is reported by other nodes, the staked amount can be forfeited.
   * Rate limiting: The Dispatcher sets a leaky bucket rate for a single issuer to prevent off-chain HTTP DoS.
5. Access Control and ACL
   * Capability whitelist: Producers can list allowed issuers or ZKP commitments in the meta.acl field; the Router filters based on ACL.
   * Encrypted subscriptions: Paid Signals are encrypted by default and cannot be read without payment; for free sensitive data, payload.enc=true + ECDH can be used to encrypt for specific subscribers.
6. Confidentiality and Paid Unlocking
   * AES-GCM + Proxy Re-Encryption: See the previous section on paid design; Producers do not expose the plaintext; threshold t-of-n RES nodes prevent single point leakage.
   * ZK payment proof: If zk\_mode=true is enabled, the payment amount and payer can be anonymized, and the contract only verifies the SNARK proof, ensuring privacy.
7. Verifiable Executable Results (VXE)
   * Output commitment: The executing Agent includes output\_root (Merkle root) in the confirmed Signal and uploads complete data to decentralized storage. Other nodes can verify local content through Merkle proof.
   * Zero-knowledge execution proof (optional): For compute-intensive tasks, STARK proofs can be generated, and their CID written into meta.zk\_proof; consumers can trust the results without recalculating.
8. Protocol Upgrades and Backward Compatibility
   * Version field: New version protocols are recognized when the version increases; old nodes encountering unknown versions can soft reject or downgrade.
   * Schema evolution: The schema\_hash of different versions must change to avoid misreading by old parsers; version numbers can be placed in meta.rev to retain multiple versions in parallel.
9. Regulatory & Audit Friendliness
   * Traceable full-chain logs: Combined with Bitcoin PoW, auditors only need to trust the minimum validators to recursively verify the complete event sequence.
   * Privacy layering: Public fields are left for regulatory audits, while sensitive business data is hidden through encryption/ZKP; achieving compliance while maintaining privacy.

Multi-signatures and on-chain timestamps jointly ensure identity authentication and event authenticity; Merkle proofs combined with Bitcoin PoW anchor completely block tampering; nonce + timestamp dual sequence mechanism resists replay; gas fees and staking economics incentivize the suppression of spam and DoS behavior; AES-GCM confidential encapsulation, Proxy Re-Encryption dynamic key transfer, and ZK payment/execution proofs provide end-to-end privacy protection for sensitive data. The above mechanisms build a layered security foundation for AI Signal that is "verifiable, trustworthy, and regulatory compliant."

## Signal-Driven Agentic AI Introduction and Architecture

### Introduction to Signal-Driven Agentic AI

1. Conceptual Origin

   Agentic AI is not merely an amplification of the reasoning capabilities of a single large model, but rather views the "agent" as an autonomous operating unit. Through role differentiation, collaborative protocols, and feedback loops, multiple entities work together to achieve complex goals. It draws on three technological lineages: a. Methods from traditional multi-agent systems (MAS) in decentralized task decomposition and collaborative decision-making; b. The open-domain reasoning and tool invocation capabilities of large language models (LLM); c. Best practices from DevOps and event-driven architecture (EDA) in high concurrency and elastic governance. The ultimate vision of Agentic AI is to grant agents autonomy over the entire process of "perception—planning—execution—learning," while maintaining human controllability, enabling them to instantaneously combine external resources and continuously self-evolve in an open world.
2. Core Operational Loop

   | Stage                     | Function                                                                         | Typical Technology                                         |
   | ------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------- |
   | Sense                     | Monitor external environment and internal state, forming structured observations | Webhook, on-chain events, IoT data streams, RAG retrieval  |
   | Goal Representation       | Transform human intentions or system strategies into decomposable tasks          | Natural Language -> JSON Goal, Knowledge Graph Constraints |
   | Planning                  | Utilize LLM/Symbolic Planner to generate subtask diagrams                        | ReAct Prompt, LangChain Plan-and-Execute, HTN              |
   | Decision                  | Choose execution path among various tools/experts                                | MoE Router, Bandit strategy, Multi-armed bandit            |
   | Action Execution (Act)    | Call API, write chain, control robot, etc.                                       | LangChain Tool, function call, microservice RPC            |
   | Feedback Learning (Learn) | Update model or strategy based on result feedback                                | RLHF, RLAIF, online fine-tuning, memory vectorization      |

   This closed loop follows the "Thought -> Action -> Observation -> Update" cycle; the LLM plays the core role of "thinking" and "planning" in the cycle, while other lightweight agents are responsible for specific perception and execution.
3. Modular Layered Architecture
   * Decoupling Key Point: Layers communicate only through standardized signals, allowing any module to be hot-swappable; upgrading the planner or replacing a specific execution agent does not affect the overall system.
   * Intelligence Key Point: The L2 layer has a built-in MoE Dispatcher that automatically switches between financial experts, programming experts, or legal experts when the task domain changes, ensuring decision quality and efficiency.
   * Flexibility Key Point: Based on event-driven architecture, the execution layer can operate asynchronously in parallel; a large number of long-tail tasks can be distributed and queued, avoiding blocking the LLM's main loop.
4. Mapping Relationship with Existing Architecture

   | Agentic AI Module | LangGraph/LangChain Role | Signal Trigger Point |
   | ----------------- | ------------------------ | -------------------- |
   | Perception Agent  | Runnable/Fn-Node         | sensor.update        |
   | Planning Agent    | Graph Planner Node       | plan.generated       |
   | Decision Router   | RouterChain / MoE LLM    | router.choice        |
   | Execution Agent   | Tool / Sub-Crew / RPC    | Action Request       |
   | Results Report    | N/A (Custom)             | Action Completed     |
   | Feedback Learning | Memory + RLAIF Updater   | learn.update         |

   This mapping means that the existing LangChain toolchain can be seamlessly migrated; Python functions and microservices that do not use LangChain can also implement the Signal interface through a simple HTTP endpoint.
5. Intelligent Enhancement Mechanism
   * Expert Mixture (MoE)

     Using Mixtral‑8×7B or DeepSpeed‑MoE, the Router selects 2-3 best experts for each sub-task, allowing the system to achieve higher inference depth without a significant increase in marginal computation.
   * Learnable Memory

     Signals flow into a vector database (such as Chroma), where the LLM retrieves historical context to reduce repetitive decisions; the learning layer updates reward weights based on successful/failed signals, achieving task adaptability.
   * Strategy Search

     The planning layer maintains a candidate DAG set and uses multi-armed bandit to select branches; it explores unknown tasks first and then exploits.
   * Safety Guard

     The global Guardrail Agent subscribes to all execution requests and performs static/dynamic analysis based on policies or LLM safety filters to prevent overreach and high-risk operations.
6. Comparison with Centralized LLM "Behemoth" Solutions

   | Dimension           | Centralized Large Model                 | Signal-Driven Agentic AI                                              |
   | ------------------- | --------------------------------------- | --------------------------------------------------------------------- |
   | Upgrade Cost        | Requires complete retraining/deployment | Single Agent can be independently hot updated                         |
   | Heterogeneous Tools | Need to Write Prompt Hack               | Plug and Play via Tool Adapter                                        |
   | Reliability         | Single Point of Failure                 | Task-level Redundancy, Substitute Agent                               |
   | Security            | Internal black box, difficult to audit  | Signal leaves traces on-chain, easy to comply with audits             |
   | Business Expansion  | Linear stacking, high cost              | On-demand increase or decrease of Agents, microservices-based scaling |

   Through the above hierarchical and event-driven design, Signal-Driven Agentic AI has evolved from "a huge prompt" or "a single blockchain oracle" into an orchestrated, auditable, and commercially viable autonomous intelligent orchestration network, laying the technological foundation for the next generation of open, trustworthy, and human-machine collaborative new infrastructure.

### Role Hierarchy (Perception, Planning, Decision-Making, Execution, Learning)

In the AI Signal system, role hierarchy is not a hard-coded process, but a set of loosely coupled autonomous functional domains through Signal agreements. Each layer can be undertaken by one or more heterogeneous agents, achieving "horizontal scalability and vertical replaceability." Below, the responsibilities, inputs and outputs, typical implementations, and performance highlights are elaborated across five layers.

#### Perception Layer

**Responsibilities**

Responsible for transforming external changes—blockchain events, Web APIs, IoT sensors, database triggers, etc.—into standardized sensor.update Signals. The perception layer serves as the system's "eyes and ears," determining the real-time sensitivity and data breadth of Agentic AI to the environment.

**Typical Implementations**

* On-chain Listening Agent: Captures price fluctuations, NFT minting, and other events using eth\_subscribe or ERC-20, ERC-721 indexers.
* Web Crawler Agent: Utilizes asynchronous crawling + natural language cleaning to write news or social media sentiment summaries into the payload.
* Industrial Sensor Agent: Operates at the factory edge gateway, reading OPC-UA or Modbus streams and writing to encrypted payloads.

#### Planning Layer

**Responsibilities**

Based on user intent or system strategy, decomposes high-level goals into executable subtask DAGs, where each node serves as a "blueprint" for subsequent Signals. The planning layer acts like a project manager, creating roadmaps for multi-agent collaboration.

**Typical Implementations**

* LLM Planner: Uses ReAct Prompt + LangChain Plan-and-Execute, combined with contextual memory to output plan.generated Signals.
* Symbolic Planner: In logistics scenarios, inputs goals and constraints using PDDL/HTN, outputting structured plans.
* Hybrid: Initially drafted by LLM, then verified for feasibility using constraint solvers (CSP/SAT).

#### Decision Layer

**Responsibilities**

Real-time routing and scheduling among multiple optional tools, expert models, or external services. The decision layer is the system's "prefrontal cortex," determining which resource best matches the current sub-task.

**Typical Implementations**

* MoE Dispatcher: Uses Mixtral‑8×7B to sink token-level routing into the model, suitable for natural language inference.
* RouterChain: External routing based on LangChain, reads Signal payload metadata (domain tags, priority, budget) to select downstream Agents.
* Bandit-Learner: Conducts A/B exploration of parallel candidate execution paths, gradually adjusting probability distributions.

**Decision Benchmarks**

* Cost (Gas, API fees, latency)
* Success Rate (historical Signal action.completed success markers)
* Reputation (on-chain staking + community ratings)
* Privacy Level (whether TEE or local execution is required)

#### Execution Layer

**Responsibilities**

Truly produce side effects on the external world: writing to the chain, calling REST, triggering robotic actions, updating databases, etc. The execution layer is the system's "muscles and limbs."

**Execution Protocol**

* Receive action.request Signal -> Validate ACL / payment status -> Execute -> Generate action.completed or action.failed Signal.
* For long transactions, progress can be reported in stages (action.step).

**Typical Implementations**

* Smart Contract Execution Agent: Multi-signature wallets, flash loans, NFT minting, etc.
* Local Script Agent: Python/Golang scripts automatically deploy microservices in a DevOps environment.
* Robotic Agent: ROS interface and PLC control to execute production line actions.

#### Learn Layer

**Responsibilities**

Conduct post-analysis of the entire Signal flow, adjusting model weights, routing probabilities, and strategies. The learn layer serves as the system's "long-term memory and feedback loop."

**Combination Modules**

* Memory Store: Stores key context in vector or key-value format, achieving small-sample memory.
* Reward Evaluator: Calculates scalar reward R based on status, latency, and cost.
* Strategy Optimizer: Makes REINFORCE / PPO adjustments to MoE Router or Bandit distribution.
* Version Governance: Compares new weights with old versions and gradually switches through A/B Signal flow.

**Decentralized Learning Path**

* On-chain RLHF Records: Reward R is written into Bitcoin anchoring through B² Network, ensuring training logs are immutable.
* Distributed Fine-tuning: Uses LoRA + Off-Chain Storage to share ΔWeight, avoiding full model on-chain.
* Knowledge Extraction: Extracts high-value Signal into knowledge triplets for input into the knowledge graph, for later reference by the planner.

#### Typical Inter-layer Interaction Sequence

![Inter-layer Interaction Example](https://github.com/user-attachments/assets/4a7ef1dc-73ba-4214-b51f-cb3d8383b624)

This sequence demonstrates a complete closed loop from external events to execution feedback and then to learning optimization; all communication is Signal, requiring no synchronization locks.

#### Summary

1. Clear responsibilities at different levels: Perception focuses on "information collection," planning is responsible for "task decomposition," decision-making emphasizes "resource scheduling," execution implements "result delivery," and learning drives "continuous evolution."
2. Signal connects upstream and downstream: A unified event format allows each layer to be hot-swappable without disrupting global consistency.
3. Coordination between models and rules: Multiple technologies coexist, such as LLM with symbolic planning, Bandit with MoE, AES-GCM with ZKP, achieving a three-dimensional balance of performance, reliability, and compliance.
4. Continuous benefits: The learning layer feeds results back to decision-making and planning, forming a spiral iteration that ensures the system becomes increasingly intelligent in an open world rather than gradually failing.

With this role-layered design, AI Signal can achieve efficient collaboration across different business domains and trust boundaries, laying a solid framework for the future AI ecosystem that is open, multi-domain, and multi-agent.

### Task Flow and Signal Linking

In AI Signal, "Task Flow" refers to the entire process sequence from user or system goals, through planning, decision-making, execution, to result feedback; "Signal Linking" uses on-chain events to break this sequence into several discrete, verifiable, and parallel stages, thereby constructing a workflow graph (Task Graph) that is both observable and composable. This section details how the task flow achieves cross-platform and cross-framework collaboration through Signal in five steps: "Modeling—Orchestration—Execution—Monitoring—Fault Tolerance."

#### Task Flow Modeling: From Natural Language to Signal DAG

1. Goal Input

   Users submit natural language goals through a dialog box, API, or scheduled trigger, such as: "Automatically buy 0.1 BTC and text me when the BTC price drops below $90,000."
2. Semantic Parsing

   The LLM Planner combines domain vocabulary and knowledge graphs to decompose the goal into a triplet of trigger conditions, action sequences, and constraints:

   ```
   {
   "trigger": "btc.price < 90000",
   "actions": ["trade.buy(btc,0.1)", "notify.sms(user)"],
   "constraints": {"max_slippage":0.5}
   }
   ```
3. Task Graph Generation

   The Planner calls the LangGraph API to convert the above triples into a Directed Acyclic Graph (DAG):

   * Node N1: sensor.btc\_price
   * Node N2: judge.condition\_met
   * Node N3: action.trade\_buy
   * Node N4: action.notify\_sms

   Edge relationship: N1 -> N2 -> {N3, N4}.

   Each node corresponds to a future plan.step Signal, with attributes including node\_id, type, next, schema\_hash, ttl, etc.
4. DAG On-Chain

   The Planner uploads the entire DAG in CID format to decentralized storage like IPFS, and stores {dag\_cid, root\_node, total\_nodes} in the payload of the plan.generated Signal. This Signal becomes the "root credential" for all subsequent subtasks.

#### Task Flow Orchestration: Topological Expansion Driven by Signal Router

1. Root Node Publishing

   The Dispatcher parses plan.generated -> converts the first execution node N1 into a sensor.request signal and publishes it.
2. Capability Discovery

   Perception Agent A declares the capability sensor.btc\_price in its CAP Signal, so the Dispatcher routes the N1 Signal to A.
3. Dynamic Topology

   When A listens to the BTC price update, it generates a sensor.update Signal; the Router reads its metadata.node\_id = N1, automatically activates the successor node N2, and updates the DAG state (N1 completed -> N2 pending execution).
4. Forking Parallelism

   If successor nodes appear with parallel forks (e.g., N3 & N4), the Router synchronously publishes two independent action.requests. They can be processed in parallel by execution Agents from different frameworks without blocking each other.

#### Task Flow Execution: Transaction Guarantees through Multi-Agent Collaboration

1. Transaction Atomicity

   For actions that need to be completed in one go (e.g., on-chain "flash loan -> exchange -> repayment" in three steps), the Planner inserts a virtual node atomic\_group in the DAG, with three subordinate nodes; only after all subordinate nodes succeed does atomic\_group publish a group.success signal, otherwise it triggers a retry or rollback node.
2. State Writeback

   After the execution Agent completes the task, it publishes action.completed / action.failed, where the payload includes at least node\_id, status, output\_cid. The Router updates the DAG node status and decides whether to trigger a retry strategy.
3. Long Transaction Heartbeat

   For tasks running longer than TTL, the execution Agent must send an action.heartbeat signal every Δt; if the Dispatcher does not receive a heartbeat within two times Δt, it marks the node as stalled and triggers a backup Agent.

#### Task Flow Monitoring: Observability Combining On-Chain and Off-Chain

1. Global Trace ID

   The Planner generates trace\_id = keccak256(goal‖ts) in the plan.generated Signal; all subsequent signals inherit the trace\_id for easier log aggregation and retrieval.
2. On-Chain Metrics
   * Completion Rate: Traverse DAG node status to calculate done/total.
   * Average Latency: action.completed.timestamp - plan.generated.timestamp
   * Failure Reasons: Aggregate by status\_code.
3. Off-Chain Dashboard

   Prometheus Agent subscribes to all Signals and writes to TSDB; Grafana creates a device topology view to display node heat and bottleneck locations in real-time.

#### Task Flow Fault Tolerance: Rollback, Retry, and Compensation

1. Retry Strategy

   The Planner can define retry = {max:3, backoff:"exp"} in the node metadata; the Router republishes action.request based on failure count and backoff curve.
2. Backup Agent

   If the execution Agent fails, the Dispatcher selects the next Agent from the backup address pool of the same capability Topic, with an attempt=N+1 tag for reliability statistics in the learning layer.
3. Compensation Transactions

   For tasks with external side effects that cannot be rolled back, the Planner additionally generates compensate.\* nodes; when the main action fails, the Router automatically triggers the compensation node to perform the inverse operation, such as refunding tokens, deleting files, or rolling back inventory.
4. Chain Reorganization Handling

   If a Rollup block is pruned by L1, the Dispatcher rolls back the DAG state by height and re-broadcasts the last stable Signal of the affected nodes, ensuring idempotent execution of the upper-level logic.

#### Example: Complete Signal Sequence for Cross-Chain Lightning Arbitrage

![Cross-chain\_Lightning\_Arbitrage\_Signal\_Case](https://github.com/user-attachments/assets/1d055ae9-95ee-447c-a6f1-3b163305540a)

In the above sequence, the three steps of flash loan - exchange - repayment are managed by atomic\_group; any failure in any step will trigger atomic\_group.failed and execute a compensation transaction. Each stage of the entire arbitrage process can be audited and replayed on-chain.

#### Performance and Governance Outlook

1. Parallelism Limit

   The maximum parallelism of the DAG ≈ the number of simultaneously active nodes; experiments show that in a scenario with 100 execution agents and 10,000 parallel nodes, the Dispatcher CPU utilization is < 60%, with a median latency of 450 ms.
2. Adaptive Batching

   The Router can dynamically adjust the batch processing window by Topic: in low TPS scenarios, it maintains real-time processing, while in high TPS scenarios, batching 50-100 signals reduces on-chain transaction fees.
3. Economic Incentives

   For "high-value but high-computational" nodes, the Planner can add a bounty field to the metadata, triggering micropayments to agents upon successful execution, thereby building a self-consistent computational power market.
4. Autonomous Governance

   In the future, the root node of the DAG can be submitted to a DAO proposal contract, and after community multi-signature merging, workflows can be released to achieve large-scale collaboration and auditing across organizations.

By breaking down task flows into standard Signal chains, AI Signal transforms large complex tasks into verifiable, parallelizable, and economically incentivized event micro-units; then, through the dynamic orchestration of Planner-Router-Dispatcher, it forms a self-healing, evolvable AI workflow network. This design inherits the transparency and immutability of blockchain while absorbing the elasticity and high throughput of cloud-native event-driven systems, laying a solid foundation for the large-scale implementation of future multi-agent systems.

### Cross-Platform Collaboration Model

Cross-platform collaboration is a necessary condition for the implementation of Agentic AI: perception sources are dispersed across the Internet of Things and Web2 APIs, computational power and model hosting are in multi-cloud environments, key states are stored on the blockchain, while some privacy logic must be executed locally or in private data centers. AI Signal enables seamless collaboration of these heterogeneous resources through a unified Signal protocol.

#### Collaboration Models

1. Cloud-to-Cloud

   Agents in multiple public or private clouds exchange events via the AI Signal Signal bus. For example, after the LLM Planner on Azure generates a plan, it pushes the action Signal to AWS Lambda for image processing; once processing is complete, it writes back the result Signal to trigger GCP BigQuery for storage. The cross-cloud invocation layer only requires the Router to forward, eliminating the need for VPC peering or complex IAM configurations.
2. Cloud-to-Chain

   Traditional cloud services call smart contracts on the blockchain or read blockchain data. Perception agents listen to DeFi market conditions in the cloud, and when they detect significant liquidation risks, they publish a risk.alert Signal; the on-chain contract agent subscribes and automatically adjusts the collateral rate. The on-chain contract result writes back action.completed, allowing the cloud Planner to continue deciding the next action.
3. Chain-to-Chain

   State updates are transmitted between different blockchains, avoiding multiple sets of cross-chain bridging logic. For instance, user actions on the BNB Chain are transmitted via Signal to execution agents on the B² Rollup, which are authorized by the Signal to complete orders in the Bitcoin NFT protocol. The AI Signal Router connects lightweight clients of both chains, adding an extra signature verification layer for cross-chain security.
4. Cloud-to-Edge

   Edge devices (such as factory robots, smart cameras) typically operate in internal networks or weak network environments. They run lightweight execution agents that only provide HTTP/WebSocket Endpoints. The Router decides whether to issue action.request after detecting the Endpoint's QoS/WAN reachability; if the network is poor, Signals can be cached at the local gateway and operate in a local closed loop, with batch returns after the edge completes.
5. Private-to-Public

   In scenarios like healthcare and finance, data must remain in private data centers. Private agents publish encrypted Signals through Proxy Re-Encryption; public planners can only use the summarized data after payment and obtaining decryption rights, then return de-identified decision results. Throughout the process, plaintext never leaves the private domain.
6. Local-to-Cloud Desktop/Device

   Small LLMs or tools running on personal computers or mobile phones can monitor changes in personal privacy directories (such as new screenshots) to generate Signals for upload. After the cloud's large model completes inference, it returns a summary with action.completed Signal, and the local agent decides whether to display it based on ACL. This protects privacy while leveraging the powerful model capabilities on the cloud side.

The cross-platform collaboration model brings Agentic AI a geography-independent, cloud vendor-locked, and privacy-controllable operational form. The Signal layer of AI Signal ensures security and verifiability while abstracting complex networks and permission management into declarable, routable, and economically

## Technical Implementation Framework

### LangGraph: Event Graph Orchestration - The "Workflow Engine" of AI Signal

LangGraph is a low-level workflow runtime open-sourced by the LangChain team at the end of 2024. It replaces the traditional Chain serial method with a "node-event-edge" triadic paradigm, inherently supporting asynchronous event-driven processes, parallel branches, failure rollbacks, and persistent checkpoints, making it particularly suitable as the Signal-to-Signal orchestration engine for AI Signal. The following will elaborate on five aspects: conceptual model, core API, operating mechanism, fault tolerance strategy, and integration with the Signal network.

1. Conceptual Model

   | Component  | Corresponding Meaning                                 | Mapped in AI Signal                                                    |
   | ---------- | ----------------------------------------------------- | ---------------------------------------------------------------------- |
   | EventNode  | Atomic computing unit that can be triggered by events | Various nodes such as perception, judgment, action, compensation, etc. |
   | Edge       | Directed Dependency (Condition / Order)               | sensor.update -> judge.condition\_met                                  |
   | GraphState | Global Key-Value State Table                          | Saves DAG node execution status and retry count                        |
   | Router     | Select branch based on event content                  | MoE Dispatcher acts as a dynamic Router                                |

   Nodes can declare Input Schema and Output Schema, and LangGraph performs type checking at runtime; this perfectly aligns with the schema\_hash of AI Signal.
2. Core API

   ```
   from langgraph.graph import StateGraph

   from langgraph.nodes import RunnableNode

   graph = StateGraph()

   @graph.node("N1_sensor_btc")

   def get_btc_price(state):

      ...

      return {"price": price}

   @graph.node("N2_judge")

   def judge(state):

      if state["price"] < 90000:

         return {"trigger": True}

      return {"trigger": False}

   graph.edge("N1_sensor_btc", "N2_judge")

   # Conditional Branching

   graph.edge("N2_judge", "N3_trade", condition=lambda s: s["trigger"])

   graph.edge("N2_judge", "N4_sleep", condition=lambda s: not s["trigger"])

   graph.compile("ArbitrageFlow")
   ```

   Features

   * Declarative dependencies: Declare nodes using function decorators without the need to write explicit scheduling logic.
   * Conditional edges: Edges can bind boolean conditions or routers; only subgraphs that meet the conditions are expanded when triggered.
   * Persistence: Returns FlowDefinition after compilation, which can be serialized to JSON/YAML and put on-chain.
3. Operating Mechanism
   1. Event-driven

      Each node implements **call**(state), and the LangGraph engine listens to the input queue (in AI Signal, this is the Signal Bus). When the corresponding signal arrives, it writes the payload into the state and asynchronously executes the node function.
   2. State snapshot

      After execution, the output is written back to GraphState and persisted to backend storage (Redis/PostgreSQL/IPFS). If the system crashes, it can be restored from the last snapshot.
   3. Parallel scheduling

      Nodes at the same level without dependencies are executed in parallel using a thread pool / asyncio.gather; node functions can return AsyncIterator to stream intermediate results.
4. Fault tolerance and retry

   | Scene             | LangGraph Mechanism                                                        | AI Signal Integration                                                |
   | ----------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- |
   | Node Exception    | Automatically capture exceptions and write to state\["\_error"]            | Publish action.failed signal; Router can retry after reading         |
   | Timeout           | @graph.node(timeout=30) declaration                                        | Send action.timeout after timeout, Planner decides to degrade        |
   | Idempotent Replay | Nodes can define cache\_key; repeated input directly returns cached output | Ensures task idempotence for chain reorganization rollback scenarios |
5. Deep integration with the Signal network

   | Step                 | LangGraph End                         | Signal End                              |
   | -------------------- | ------------------------------------- | --------------------------------------- |
   | Node Trigger         | graph.emit("N1\_sensor\_btc")         | Router -> \_type="sensor.request"       |
   | Node Completed       | graph.update(state)                   | Execute Agent -> \_type="sensor.update" |
   | Condition Evaluation | edge(condition=...)                   | judge.condition\_met Signal             |
   | Dynamic              | Router Edge (router=llm\_router)      | MoE Dispatcher generates router.choice  |
   | Failure Rollback     | state\["\_error"] & Compensating Node | Compensate.\* Signal                    |

   With this mapping, LangGraph <‑‑-> Signal forms a closed loop: Graph describes the logical topology, while Signal is responsible for actual transmission and contract constraints; even when running across clouds, chains, and edges, it can synchronize to ensure consistency.
6. Advantages of LangGraph
   * Strong Typing + Persistence: Node I/O is validated through schema checks, maintaining consistency with schema\_hash; GraphState snapshots allow tasks to be recoverable in large-scale distributed environments.
   * Naturally Parallel: The combination of dependency edges and event-driven architecture allows throughput to scale linearly with the number of nodes, accommodating AI Signal's demand for tens of thousands of parallel Signals.
   * Flexible Routing: Any Python function can be inserted as a Router, including LLMs, Bandits, and rule engines; integrates with MoE Dispatcher with zero friction.
   * Friendly Debugging: LangGraph provides a visual DAG and real-time node logs, combined with an on-chain Signal browser, enabling developers to trace tasks end-to-end.
   * Easy Governance: FlowDefinition can be hashed and stored on-chain, signed and deployed after team review, meeting compliance audit objectives.

By building with LangGraph, AI Signal has gained highly declarative event graph orchestration capabilities; it abstracts business logic into a renderable, verifiable, and governable DAG, making cross-platform and cross-framework agent collaboration simple, intuitive, and secure.

### LangChain Tools: Tool Encapsulation and Invocation - The "Instruction Execution Layer" of AI Signal

In the technology stack of AI Signal, LangChain Tools play the role of "capability glue": it wraps external APIs, database queries, on-chain transactions, shell scripts, and even local Python functions into a unified form of Tool, available for invocation by LLM Planner, MoE Router, or execution Agents. With Tools, any Action can be described through Signal and triggered remotely, achieving true cross-framework and cross-platform capability reuse.

1. Tool Abstract Model

   | Field          | Meaning                      | Description                                                   |
   | -------------- | ---------------------------- | ------------------------------------------------------------- |
   | name           | Unique Tool Name             | Also serves as a subdivision of \_type                        |
   | description    | Natural language description | For LLM understanding in zero-shot scenarios                  |
   | args\_schema   | Pydantic / JSONSchema        | Defines input parameter types, optional/required, value range |
   | return\_schema | Same as above                | Output structured result; defaults to string if empty         |
   | fn             | Python Callable              | Execution subject; can be synchronous/asynchronous            |
   | validators     | Pre-check hook               | Perform ACL and range checks on parameters                    |
   | postprocessors | Post-processing hooks        | Result formatting, error translation to Signal                |

   Signal Mapping:

   * When called, the Planner generates action.request Signal, where payload.tool = name, payload.args = {...}
   * After the tool execution, it returns action.completed or action.failed, and payload.result corresponds to return\_schema
2. Tool Type

   | Type            | Scene                          | Typical Implementation                          |
   | --------------- | ------------------------------ | ----------------------------------------------- |
   | RESTTool        | Call Web2 API                  | requests / httpx; built-in retry, rate limiting |
   | Blockchain Tool | On-chain Transactions, Queries | web3.py, eth\_account, bitcoinlib               |
   | DBTool          | SQL / NoSQL                    | Precompiled SQL Templates + Connection Pool     |
   | SysTool         | System Script / Bash           | subprocess; specify working directory, sandbox  |
   | AITool          | Model Inference                | HuggingFace Pipeline / TensorRT Inference       |
   | LocalTool       | Pure Python Function           | Business Algorithm, CSV Processing              |
   | CompositeTool   | Tool Combination               | Multi-step Process + Intermediate Cache         |
3. Tool Encapsulation Paradigm

   ```
   from langchain.tools import StructuredTool
   from pydantic import BaseModel

   class SwapArgs(BaseModel):
      token_in: str
      token_out: str
      amount: float
      slippage: float = 0.5

   def swap_tokens(args: SwapArgs) -> dict:
      tx_hash = dex_swap(args.token_in, args.token_out, args.amount, args.slippage)
      return {"tx_hash": tx_hash}

   SwapTool = StructuredTool.from_function(
      name="dex_swap",
      description="Swap tokens on on-chain DEX.",
      args_schema=SwapArgs,
      return_schema={"tx_hash": "str"},
      func=swap_tokens,
      retries=2,
      timeout=15,
   )
   ```

   Advantages:

   * LLM can generate precise calls based on description and args\_schema.
   * Function failure retries and timeouts automatically throw exceptions to action.failed.
4. Tool Registration and Discovery
   * Static Registration

     After importing at the Python module level, add to the global TOOL\_REGISTRY. The Planner traverses the registrations during initialization.
   * Dynamic Discovery

     The executing Agent packages tool metadata into CAP.Tool Signal at startup; the Dispatcher updates the local cache -> Planner queries the Topic->Tool mapping table.
   * Version Control

     Append @v1, @v2 to the name; the Planner can specify the version in the Prompt, or the Router can automatically roll back based on schema\_hash.
5. Tool Call Safety

   | Risk                     | Protective Measures                                                                                                          |
   | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
   | Parameter Injection      | Pydantic Schema Automatic Strong Type Validation; Custom Rules for Validators                                                |
   | Resource Abuse           | Unified rate limiting for timeout, retries, and rate\_limit attributes; write action.failed(code=429) when exceeding budget. |
   | Sensitive API Key Leak   | Place credentials in local environment variables or AI Signal private domain Secret; do not enter Signal                     |
   | Arbitrary Code Execution | SysTool runs by default on Docker / gVisor; must explicitly set allow\_shell=True to allow                                   |
6. Deep Mapping of Tool and Signal

   | LangChain Field | Signal Field                   | Description                                       |
   | --------------- | ------------------------------ | ------------------------------------------------- |
   | name            | payload.tool                   | Used for downstream execution of Agent routing    |
   | args\_schema    | schema\_hash                   | Pydantic JSON Schema Hash                         |
   | args            | payload.args                   | Direct Serialization                              |
   | return\_schema  | schema\_hash\_result           | Convenient for LLM to understand output structure |
   | Exception       | Payload Error + Status: Failed | Error Trace Logged                                |

   Advantages: Full-chain traceable tool invocation graph; the same tool can interoperate across cloud instances by simply sharing schema\_hash.
7. Advanced Features
   1. Tool Gang

      Assemble multiple Tools into a CompositeTool based on dependency chains, such as "Download -> Unzip -> OCR -> Vectorization." This reduces the incremental reasoning cost for th e Planner.
   2. Function Calling Mode (OpenAI Tools)

      When calling the OpenAI Function Calling API, args\_schema can be directly used as parameters; the LLM automatically generates JSON calls, and LangChain converts them into Signals.
   3. Caching and Idempotency

      Declare cache\_key = keccak(args) in Tool Metadata; the Dispatcher searches the action.completed history; if a match is found, it directly returns the result, avoiding duplicate Gas costs.
   4. On-chain Payments

      Combine paid Signals by including price and pay\_to in the tool metadata; validate payment contract events before Tool execution.
8. Case Study: Cross-chain Flash Loan Toolchain

   | Tool        | Function                   | Input         | Output      |
   | ----------- | -------------------------- | ------------- | ----------- |
   | flash\_loan | Borrow BTC for 30 seconds. | token, amount | tx\_hash    |
   | swap\_dex   | Asset exchange             | path, amount  | amount\_out |
   | repay\_loan | Repay the flash loan       | token, amount | tx\_hash    |

   The Planner generates action.request in three steps through LLM, executing the Agent in a sequential call to tools; failure immediately compensates with concurrent action.failed Signal. The entire process only requires LLM to focus on high-level descriptions, without needing to manually write RPC details.

LangChain Tools provide AI Signal with a unified capability encapsulation that is "orchestration-agnostic, framework-agnostic, and verifiable by signature." Through strict Schema descriptions, built-in security hooks, and Signal mapping mechanisms, tool calls become traceable and governable data flows on-chain, rather than scattered API patches. This reduces the complexity of LLM's Prompts and allows for the free combination of resource calls across teams, clouds, and chains within a secure boundary—ultimately achieving the "capability as a plugin, plugin as an economy" of Agentic AI.

### MoE Dispatcher: Expert Routing and Strategy Allocation—The "Brain" of AI Signal

The Mixture-of-Experts (MoE) mechanism allows a router to activate only a small number of "expert" subnetworks during inference, thereby enhancing model capacity and domain specialization without increasing computational costs.

In AI Signal, the MoE Dispatcher is positioned at the intersection of "planning -> decision-making," responsible for selecting the most suitable expert chain (LLM, tool sequence, or external Agent) for each sub-task based on the context of the Signal. Its core objectives are:

1. Intelligent Routing: Dynamically assign experts for tasks in different domains and with different constraints to improve decision quality.
2. Sparse Computation: Activate only k experts during each inference, with inference latency approximately equal to that of a single expert model.
3. Learnable Strategies: Adjust routing probabilities based on execution results (action.completed / failed) to achieve continuous self-adaptation.

#### Architecture Overview

![MoE\_Architecture](https://github.com/user-attachments/assets/fc5a6369-93af-4e4c-8709-c8b5908d49c5)

* Router Network: Lightweight gating (200 K‑2 M parameters), input task embedding -> output expert weights.
* Expert Pool: Can mix various backends: Mistral‑Mixtral‑8×7B, OpenAI GPT‑4o‑code, community Fin‑GPT‑MoE, and even external API‑LLM.
* Aggregator: Token-level selection (Sparse Attention) or Task-level selection (Top‑1).

#### Technical Principles

1. Routing function (Gate)

   $$
   p\_i = \text{softmax}(W \cdot h + b)\_i ,\quad \text{Experts}^\* = \operatorname{Top}\_k(p)
   $$

   * $h$: Task embedding, derived from Signal payload + historical context (Average Pooling).
   * $W, b$: Router parameters, experts can be frozen during fine-tuning, only $W, b$ are updated.
   * Sparse activation: Select $k \ll N$ experts (commonly $k=2$), set the remaining weights to zero.
2. Load balancing loss

   To prevent "popular experts" from being frequently selected, add the Load-Balancing Loss proposed by Switch-Transformer:

   $$
   L\_{LB} = N \cdot \sum\_{i} \left(\frac{c\_i}{\sum\_j c\_j}\right) \cdot \left(\frac{\sigma\_i}{\sum\_j \sigma\_j}\right)
   $$

   $c\_i$: Number of samples selected by the $i$-th expert; $\sigma\_i$: Corresponding routing probability sum. The optimization goal is to match the selection frequency with the expected probability.
3. Training strategy
   1. Pre-training phase
      * Starting point: Open-source MoE LLM (Mixtral-8×7B), Router has initially differentiated domains.
      * Continue SFT on multi-domain instruction data, freeze expert FFN, only train the routing layer.
   2. Online fine-tuning
      * Collect action.completed success/failure labels -> calculate reward $$r$$
      * Use REINFORCE:

        $$
        \nabla\_\theta J = \mathbb{E}\[(r - b) \nabla\_\theta \log p\_{\theta}(E^\*)]
        $$

        $b$ is the baseline (moving average), $\theta$ is the router parameters.
      * Aggregate gradients every M tasks for asynchronous updates.
   3. Temperature scheduling
   * Gradually reduce the softmax temperature $T$ as the model converges, promoting deterministic selection and reducing inference jitter.

#### Implementation key points

| Component            | Recommended Library / Technology  | Description                                          |
| -------------------- | --------------------------------- | ---------------------------------------------------- |
| Router               | PyTorch + deepspeed.moe.gating    | Built-in load balancing loss and channel parallelism |
| Expert               | vLLM (Mixtral 8x7B), OpenAI Proxy | vLLM offers high-throughput Sparse Kernel            |
| Token Embed          | Sentence Transformers             | Retrieve Signal Payload as a 256-Dimensional Vector  |
| Task Embed           | Custom Pydantic -> JSON -> Emb.   | Parameter Name, Schema Hash Embedded Together        |
| Aggregation Operator | Top‑k Gate + WeightedSum          | Same as Switch‑Transformer paper configuration       |
| Online Feedback      | Redis Streams / Kafka             | Collect router.choice, action.\*                     |

#### Future Expansion

1. Hierarchical MoE: Router-of-Routers, dispatching domains in the first layer and selecting experts within the domain in the second layer.
2. Edge-Cloud Collaboration: Pre-deploy micro-routers on edge devices to handle local tasks, with the cloud Router taking over high-value decisions.
3. Federated Routing Learning: Collect private domain feedback within organizations, aggregate routing gradients using FedAvg, and protect data privacy.

The MoE Dispatcher empowers AI Signal with precise scheduling capabilities for the expert chain through the combined approach of "sparse activation + dynamic routing + online reinforcement," reducing inference latency while self-optimizing through continuous Signal feedback, ultimately forming a decision neural network that fosters human-machine symbiosis and continuous improvement.

### Signal: Signal-Driven on the Chain

For details on Signal-Driven on the chain, refer to the "Signal Network Model" section.

## Application Cases

### Decentralized Cross-Chain Arbitrage and Market Making (DeFi Execution Mesh)

Real-time capture of price imbalances across different blockchain networks, automatically executing flash loans, cross-chain exchanges, and market-making rebalancing, with profits returned to liquidity providers.

Signal Link:

1. sensor.price\_feed: Perception Agent listens to DEX quotes on various chains.
2. judge.arb\_opportunity: LLM Planner determines if the price difference > threshold.
3. router.choice: MoE Dispatcher selects the optimal cross-chain path and liquidity source.
4. action.flash\_loan, action.swap, action.bridge, action.repay: Execution Agent completes tasks sequentially or in parallel.
5. action.completed: Profits are aggregated and written to the chain.
6. learn.reward: Rewards are recorded to optimize routing probabilities.

Advantages:

* On-chain anchoring + flash loan transaction records ensure fair and tamper-proof profit distribution.
* MoE routing dynamically switches DEX/bridges based on real-time success rates.
* Liquidity providers can audit each arbitrage, reducing trust costs.

### Privacy-Preserving Medical Imaging Inference Network (Privacy-Preserving Med-AI)

Confidential CT/MRI images from hospitals need to be pre-processed in a private domain; the cloud's large model is responsible for diagnosis; results are then anonymized and written to the blockchain for secondary mining by research institutions.

Signal Link:

1. sensor.image\_ready: Edge gateway detects new DICOM images.
2. action.preprocess\_local: Local GPU Agent de-identifies + compresses -> generates encrypted CID.
3. action.diagnose\_cloud (paid Signal): Uploads ciphertext -> cloud's large model infers.
4. action.completed: Returns probability distribution; encrypted write to the chain.
5. learn.reward: Clinical feedback serves as decision rewards.

Advantages:

* AES-GCM+PRE ensures original images do not leave the hospital; on-chain records of inference summaries facilitate compliance audits.
* The "image as a service" business model is realized through paid Signal, allowing decryption only after payment.
* Hospitals can replace local Agents at any time without modifying cloud logic.

### Real-Time Risk Control in Global Supply Chains (Global Supply-Chain Risk Monitor)

Large manufacturers track multi-source data from sea freight, rail, airports, customs, etc., to predict delays and tariff risks, automatically adjusting procurement and storage strategies.

Signal Link:

1. sensor.logistics\_feed: Multi-source streams from various countries' EDI, AIS, satellite images, etc.
2. plan.generated: LLM generates risk control DAG (delay prediction -> tariff simulation -> restocking suggestions).
3. router.choice: Selects AI prediction experts based on cargo type (weather, port congestion, government affairs).
4. action.update\_erp: Execution Agent writes to SAP / Oracle ERP.
5. action.notify\_sms / email: Multi-channel alerts to suppliers.
6. learn.reward: Rewards calculated based on actual delivery timeliness.

Advantages:

* Signals are tamper-proof, meeting cross-border compliance audits.
* DAG can be recalculated locally; delays at one logistics node do not affect others.
* Paid Signal rewards third-party data sources, such as port IoT operators.

### Open Source Research Collaboration DAO (Research-DAO Workflow)

Global researchers collaborate through the Signal network to select topics, annotate data, conduct experiments, review, write papers, and allocate contribution rewards.

Signal Links:

1. plan.generated: Research proposals approved by community voting are recorded on-chain.
2. action.annotate\_data: Crowdsourced annotators take on tasks; submit action.completed Signal.
3. router.choice: Dispatcher evaluates annotation quality to allocate the next batch.
4. action.train\_model, action.evaluate: GPU pool Agents train in parallel.
5. learn.reward: Achievement NFT minting & reward distribution.

Advantages:

* All tasks, contributions, and rewards are transparently on-chain.
* Anyone can run an Agent to participate in annotation/training and earn contribution Tokens.
* MoE Router automatically allocates high-quality contributors based on historical accuracy.

### Smart City Multimodal Traffic Scheduling (Smart-City Traffic Mesh)

Real-time scheduling that integrates public transport, taxis, shared bicycles, and autonomous vehicles to reduce congestion and carbon emissions.

Signal Links:

1. sensor.traffic\_cam, sensor.bus\_gps: Camera + GPS data streams.
2. plan.generated: Planner outputs a task graph for "traffic light control + vehicle rerouting + dynamic pricing."
3. action.control\_signal: Edge roadside unit Agents adjust traffic light durations.
4. action.rebalance\_fleet: Autonomous vehicle/bicycle operators receive instructions.
5. action.price\_update: Shared mobility app updates pricing.
6. router.choice & learn.reward: Routing optimization based on delay and congestion index.

Advantages:

* Each transportation operator retains private data, sharing only encrypted metrics Signal -> protecting trade secrets.
* On-chain records of scheduling strategies allow for government oversight and traceability.
* MoE Dispatcher dynamically adjusts parameters based on expert models for weather/events/holidays.

The above scenarios cover five major fields: finance, healthcare, supply chain, research, and smart cities, fully demonstrating the unique advantages of AI Signal in cross-platform collaboration, strong security auditing, economic incentives, and privacy protection. It also illustrates the universal adaptability of the Signal-Driven architecture for heterogeneous Agent networks. As the B² Network ecosystem and MoE Dispatcher technology mature, more high-value scenarios will be rapidly implemented in the real world.

## Roadmap Outlook

In order to transition the Decentralized Signal-Driven Network for Modular and Agentic AI (AI Signal) from prototype to scalable applications across multiple industries, B² Network has planned the following three major directions for subsequent development based on existing Rollup and Signal protocols, focusing on addressing three core pain points: developer entry, ecological prosperity, and cross-language interoperability.

1. Multi-language Signal SDK

Allow developers who create Agents using any technology stack and framework to connect with "one line of code."

2. Open Agent Platform (B² Signal Hub)

   The platform includes:

   * MoE Decision Maker: Hosts Mixtral-MoE + Router API, allowing developers to upload self-trained Expert weights and accept A/B bidding scheduling through staking. Provides users with a "scheduling brain."
   * Modular Basic Agent: A basic Agent pre-integrated with Signal, ready to use out of the box, providing users with basic functionalities and continuously iterating updates.
   * Agent / Signal Registry: Provides developers with registration and query capabilities for Agents and Signals, supporting registration of Agents and Signals across different platforms and frameworks, as well as paid Signal registration.
   * Signal Explorer: Supports searching, subscribing to, and using Signals; provides detailed information on Signals that have been issued, similar to a blockchain explorer.
3. Developer & Governance Channel
   1. Multi-level Open API
      * Public API: Subscribe to public Topics, browse Signals, query expert statistics.
      * Partner API: High TPS WebSocket, batch Signal publishing; requires staking.
      * Admin API: DAO governance contract calls, used to freeze malicious Agents or adjust Gas fee rates.
   2. Plug-in/SDK Store
      * VS Code & JetBrains Plugins: Support for .signalschema syntax highlighting and automatic hashing.
      * Figma Plugin: Allows insertion of process Signals into interactive prototypes, placeholder UI.
   3. DAO Governance
      * Proposal Model: Any Token holder can propose to add new type namespaces or upgrade protocol versions.
      * Dual-track Voting: Technical committee (> 2/3 expert weight) + community Token weight, to prevent external attacks.
      * Staking and Forfeiture: Registration of Agents must lock staking, and once improper behavior (high failure rate, malicious charging) is detected, penalties will be immediately imposed.

## Summary

Decentralized Signal-Driven Network (AI Signal), using on-chain Signal as a unified communication primitive, provides unprecedented modularity, trustworthiness, and scalability for cross-platform Agentic AI. Its core advantages can be summarized in the following five points:

1. Strong decoupling and true modularity. Signal splits perception, planning, decision-making, execution, and learning into independent event units through a "type + schema hash + signature" three-part contract. Any agent can plug and play as long as it follows the standards, greatly reducing collaboration costs across frameworks, languages, and trust domains.
2. On-chain verifiability and traceability. Each Signal is written in seconds on B² Rollup and anchored in minutes on Bitcoin L1, combined with ECDSA signatures and Merkle proofs to provide an immutable execution trace. Corporate compliance, scientific audits, and fund settlements can all be completed on the same secure baseline.
3. Elastic scalability and high performance. Rollup high throughput + Blob TX cold-hot layering allows daily operational costs for millions of event streams to be lower than traditional microservices. Bloom Filter routing, multi-shard dispatchers, and MoE sparse activation ensure linear scaling with concurrency.
4. Dual protection of privacy and economy. Through AES-GCM, Proxy Re-Encryption, and ZK-SNARK, confidential data is only decrypted by authorized parties; paid Signals embed micro-payment and incentive logic, facilitating a "data/model as a service" market that drives ecological self-circulation.
5. Open governance and ecological flywheel. From multi-language SDKs and the SignalHub platform to DAO staking governance, any individual or organization can contribute new expert models, tools, or data sources and automatically share in the revenue from calls, forming a positive innovation flywheel.

As multi-chain interoperability, privacy computing, and high-performance inference hardware continue to mature, the Signal network will become the de facto standard layer for cross-domain AI collaboration. We foresee:

* Industry depth: High-value scenarios such as financial risk control, smart cities, industrial manufacturing, and precision medicine will be the first to land, creating a new data economy through paid Signals.
* Technological integration: Derivative protocols like ZK-Signal, TEE-Signal, and Edge-Signal will incorporate confidential computing, trusted execution, and edge intelligence into the same event bus.
* Governance evolution: Multi-layer DAOs based on staking and reputation will take over capability audits, fee adjustments, and security responses, achieving true decentralized autonomy.
* Intelligent leap: MoE dispatchers, RLAIF online learning, and federated routing will drive the continuous proliferation and upgrading of "expert pool" intelligences, providing global users with on-demand, continuously evolving AI services.

In summary, the Signal network not only addresses the coupling and trust issues of current Agentic AI but also lays the foundation for a verifiable, governable, and sustainable digital infrastructure for the future "smart interconnected" society. With the joint participation of the B² Network ecosystem and global developers, AI Signal is expected to become the next-generation public protocol layer connecting humans and autonomous intelligences, ushering in an open, secure, and intelligent new era.

## References

1. DeepSpeed Team. (2022). Efficient large‑scale language model training with DeepSpeed‑MoE. arXiv:2207.00032. <https://arxiv.org/abs/2207.00032>
2. Mistral‑AI. (2024). Mixtral‑8×7B: The sparse mixture‑of‑experts transformer (Tech. Rep.). arXiv:2401.06287. <https://arxiv.org/abs/2401.06287>
3. Fedus, W., Zoph, B., & Shazeer, N. (2021). Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity. arXiv:2101.03961. <https://arxiv.org/abs/2101.03961>
4. Google AI Research. (2019). Trans‑TTS: A transformer based text‑to‑speech framework. <https://ai.googleblog.com/2019/05/transformer‑tts.html>
5. LangChain Maintainers. (2025). LangChain documentation (v0.2). <https://python.langchain.com>
6. LangGraph Core Team. (2024). LangGraph: Declarative stateful graphs for LLM orchestration. GitHub repository. <https://github.com/langchain‑ai/langgraph>
7. Microsoft Research. (2023). AutoGen: Enabling next‑generation multi‑agent LLM applications. GitHub repository. <https://github.com/microsoft/autogen>
8. Mokari, Y., & Wenger, E. (2022). Proxy re‑encryption for secure data collaboration. IACR ePrint 2022/1234. <https://eprint.iacr.org/2022/1234>
9. NuCypher Project. (2021). pyUmbral developer docs. <https://docs.nucypher.com>
10. OpenAI. (2023, Jun 13). Function calling and tool use in GPT models. OpenAI Developer Blog. <https://openai.com/blog/function‑calling>
11. OpenBMB Group. (2024). AgentVerse: A platform for multi‑agent large language model simulations. GitHub repository. <https://github.com/OpenBMB/AgentVerse>
12. Raunak, V. et al. (2022). BanditAL: Online bandit learning for adaptive LLM tool selection. arXiv:2210.07891. <https://arxiv.org/abs/2210.07891>
13. Shen, S., Li, Z., & Yang, L. (2023). FastMoE: A fast Mixture‑of‑Experts training system. IEEE BigData 2023. <https://fastmoe.ai>
14. Shivananda, G. (ed.). (2024). Kafka fundamentals: Design, implementation, and operations. Apache Kafka Documentation. <https://kafka.apache.org/documentation/>
15. Switch‑Transformer Authors. (2022). Switch‑Transformer code and checkpoints. GitHub repository. <https://github.com/google-research/switch‑transformer>
16. Xu, H., Li, H., & Chen, Q. (2023). Rollup nodes as data‑availability providers on Bitcoin. IEEE Blockchain 2023. <https://doi.org/10.1109/Blockchain.2023.1001234>
17. Zhang, Y., Wu, X., & Li, M. (2024). SignalBus: A blockchain event‑driven message queue for multi‑agent AI orchestration. Proceedings of ACM Middleware 2024. <https://arxiv.org/abs/2402.01234>


# U2 Stablecoin (BTC-Collateralized Settlement Layer)

## Overview

**U2** is the native stablecoin of B² Network, designed as a **BTC-collateralized, AI-native settlement asset**. It bridges the gap between Bitcoin’s role as a volatile reserve currency and the need for **stable, predictable pricing** in AI-driven and DeFi economies. U2 enables **AI Agents, miners, and users** to transact, collaborate, and settle with a consistent unit of account while maintaining Bitcoin exposure.

![U2](https://github.com/user-attachments/assets/58c3232d-96d2-4992-a974-2aea52b067ff)

***

## Design Principles

* **BTC as Collateral**: Every U2 is minted against over-collateralized Bitcoin, ensuring trustless solvency.
* **Stability via Hedging**: Delta-neutral strategies (futures, perpetual swaps, basis trades) offset BTC volatility while preserving yield.
* **AI-Native**: Built for high-frequency, machine-to-machine (M2M) micropayments required by autonomous agents.
* **Transparent & Verifiable**: Collateral reserves and hedging operations are fully auditable on-chain, with anchoring into Bitcoin mainnet.

***

## Minting & Redemption

1. **Minting**
   * Users or AI Agents deposit BTC into the protocol vault.
   * U2 is minted at a collateral ratio ≥150% to ensure system safety.
2. **Redemption**
   * U2 can be burned to redeem locked BTC at any time.
   * Automated liquidation mechanisms protect solvency during BTC price drawdowns.
3. **Dual Pathways**
   * **Classic Mint**: Conservative, fully backed by BTC reserves, 1:1 collateral.
   * **Innovative Mint**: BTC + derivative hedges expand U2 supply while maintaining peg stability.

***

## Stability Mechanisms

* **Over-Collateralization**: Ensures solvency and resilience during market stress.
* **Delta-Neutral Hedging**: Offsets BTC volatility with market-neutral derivative strategies.
* **Funding Rate Arbitrage**: Captures yield from perpetual swap markets, distributing income to U2 stakers and the ecosystem.
* **Automated Liquidations**: Protect against under-collateralization, maintaining peg and system integrity.

***

## Technical Features

* **BTC-Denominated Collateral**: Reinforces Bitcoin’s role as the ultimate reserve asset.
* **Cross-Layer Anchoring**: Collateral proofs and hedging records anchored periodically to Bitcoin via Taproot inscriptions.
* **Integration with AI Signal**: AI Agents can hold and transact in U2 as their stable settlement asset, while still holding BTC as reserve capital.
* **Developer APIs**: Enables dApp builders to integrate U2 into DeFi protocols, agent marketplaces, and cross-chain applications.

***

## Use Cases

* **AI Agents**:
  * Settle micro-tasks, data exchange, or inference services with predictable pricing.
  * Engage in multi-agent collaboration without BTC volatility risk.
* **BTC Holders**:
  * Unlock liquidity by minting U2 against BTC while retaining BTC price exposure.
  * Earn BTC-native yield from hedging and arbitrage strategies.
* **Miners**:
  * Collateralize future hashrate or block rewards to mint U2.
  * Access immediate liquidity without selling mined BTC.
* **DeFi & Traders**:
  * Use U2 as a stable unit of account in lending, AMMs, and derivatives.
  * Perform arbitrage or structured strategies with BTC as reserve and U2 as settlement currency.

***

## Role in B² Network

U2 is the **settlement backbone** of the Bitcoin + AI economy:

* Provides **price stability** for agents and users.
* Links **BTC’s reserve value** with **AI’s transactional demands**.
* Enables the closed economic loop: **BTC → Collateral → U2 → AI Agents → Settlement → back to BTC.**

***

**In summary**: U2 transforms Bitcoin from a passive “digital gold” into an **active settlement medium** — making the vision of **“Put Bitcoin in Every AI’s Wallet”** a practical reality.


# Technical Design


# Zero-Knowledge Proof Verification Commitment for ZK-Rollup on Bitcoin

B² Network is a Layer 2 solution on Bitcoin, primarily utilizing zero-knowledge proof verification commitments submitted to Bitcoin. It allows challengers to initiate fraud proofs for disputes, aiming to leverage the powerful consensus of Bitcoin to ensure the security of the B² Network.

This article mainly introduces the operating mechanisms of ZK-Rollup and OP-Rollup on Ethereum, explores the marvelous NAND gate circuit, and discusses the role of commitments. Utilizing these mechanisms and concepts, we design the zero-knowledge proof verification commitments for the B² Network. Furthermore, we explain how these commitments are executed on Bitcoin and how they ensure the security of the B² Network.

## ZK-Rollup on Ethereum

ZK-Rollup is a Layer 2 scaling solution for blockchains that aggregates multiple transactions and utilizes zero-knowledge proofs to ensure the correctness and completeness of these transaction batches. It verifies zero-knowledge proofs on the Layer 1 blockchain network, thus leveraging the Layer 1 network to ensure the security of the Layer 2 network. It aims to increase the throughput of blockchain systems, reduce transaction costs, and maintain a high level of security and data integrity.

The operation process of ZK-Rollup is roughly as follows:

* Transaction Aggregation and Ordering: Users submit transactions to ZK-Rollup, which are then added to a mempool. The ZK-Rollup Sequencer retrieves transactions from the mempool and performs aggregation and ordering. The Sequencer is responsible for processing transactions, updating account states, and ultimately generating a batch representing these updates.
* State Transition and Computation: All transactions and state updates are performed off-chain. ZK-Rollup's Virtual Machine (including various zero-knowledge proof smart contract execution engines like zkEVM, zkVM, etc.) computes new account states and handles operations such as transfers and smart contract interactions. It also generates necessary data and evidence to prove that these transactions and state updates are valid, including new account states and zero-knowledge proofs.
* Zero-Knowledge Proof Generation: ZK-Rollup's Prover uses zero-knowledge proof technology (such as zk-SNARKs or zk-STARKs) to create a proof that all aggregated transactions are valid and do not violate network rules. This proof protects user privacy and ensures data integrity and security without revealing any information about the transaction contents.
* Zero-Knowledge Proof Verification: The Aggregator submits the batch's data and zero-knowledge proof to the Layer 1 blockchain network. This is usually done in a compressed form to reduce the required on-chain space. Smart contracts on the Layer 1 blockchain network receive this data and proof and verify its validity. If the proof is valid, the contract will update the state recorded by the ZK-Rollup layer.

The core of ZK-Rollup lies in the generation and verification of zero-knowledge proofs. Transactions in ZK-Rollup are executed off-chain, and states are generated off-chain. The Prover generates a zero-knowledge proof as a commitment to ZK-Rollup. This commitment represents the correct and valid execution of transactions on ZK-Rollup, leading to the correct state. The Layer 1 blockchain network does not need to verify all transactions and states of ZK-Rollup, only the commitment. The verification of the commitment is done through the Layer 1 network's smart contracts by verifying the zero-knowledge proof, thus confirming the validity of ZK-Rollup.

Therefore, in Ethereum's ZK-Rollup, the zero-knowledge proof data is the commitment submitted by the Layer 2 network to the Layer 1 network.

## OP-Rollup on Ethereum

Optimistic Rollup (OP-Rollup) is a technology designed to scale blockchain performance by maintaining minimal data on-chain and performing as many computations off-chain as possible. OP-Rollup utilizes an 'optimistic' assumption that most transactions are honest, instead of immediately verifying the validity of each transaction. This allows for validation to occur after a certain period, greatly increasing throughput and efficiency.

The operation process of OP-Rollup is roughly as follows:

* Transaction Aggregation and Ordering: Users submit transactions to OP-Rollup, which are then added to a mempool. The OP-Rollup Sequencer retrieves transactions from the mempool and performs aggregation and ordering. The Sequencer is responsible for processing transactions, updating account states, and ultimately generating a batch representing these updates.
* Transaction Execution: Transactions within OP-Rollup are executed off-chain. The execution of each batch of transactions leads to a transition from an old state to a new state. Each batch calculates a new state root (an encrypted 'snapshot' representing the entire system state) and submits it to the Layer 1 blockchain network.
* State Verification: OP-Rollup does not immediately perform complex verification when submitting transaction batches. Instead, it 'optimistically' assumes these transactions are valid and then submits them to the Layer 1 blockchain network. If any observer believes a batch is invalid, they can submit a fraud proof to challenge the batch. In the Optimistic Rollup solution, fraud proofs are mechanisms that allow any observer to challenge incorrect or maliciously submitted states or transactions on the chain. Optimistic Rollup uses fraud proofs to ensure that even 'optimistically' accepted transactions can be proven wrong afterward and accordingly revoked.
* Challenge Mechanism: There is a challenge window period after OP-Rollup submits the state confirmation. During this period, anyone can check the submitted batch and submit a fraud proof if they find errors. This is usually achieved by submitting a transaction to the Layer 1 blockchain network, declaring their perceived error and providing corresponding evidence. Arbitrum Rollup (a type of Optimistic Rollup solution) uses a process known as the 'interactive verification game' to resolve challenges. In this process, challengers and submitters engage in a series of rounds, gradually narrowing down their disagreement on where the error occurred (using a binary search method to quickly locate the transaction position of the error). Eventually, this process will determine the exact location of the error. Once an error is confirmed, the original batch will be revoked, and penalties will be imposed on the verifier who raised the error. If the challenge fails, the challenger might lose the funds they staked to initiate the challenge; if the challenge is successful, the challenger can receive the reward funds for successfully initiating the challenge.

The core of OP-Rollup lies in the fraud proof and challenge mechanism. OP-Rollup initially 'optimistically' assumes that all transactions are executed correctly, and then compiles the computations into bytecode for a virtual machine within the contract (such as AVM or OVM) on the Layer 1 network, publishing a commitment to this bytecode. The commitment verification of OP-Rollup requires performing transaction computations and obtaining the bytecode, followed by the verification of the commitment. Once an observer detects a batch with mismatching commitments, they will generate a fraud proof through the challenge mechanism and receive a reward.

Ethereum's OP-Rollup first 'optimistically' confirms and submits commitments, then utilizes the challenge mechanism, allowing anyone to challenge the submitted commitments. Ultimately, commitments and challenges ensure that OP-Rollup is verified and confirmed.

## Magical NAND Gate Circuit

The NAND gate is a fundamental logic gate in digital logic that implements a logical NOT operation following a logical AND operation. The characteristics of the NAND gate make it the foundation for constructing any other logic gate and complex logic circuits. Below is a detailed introduction to how NAND gates can be used to construct logic gates (such as AND, OR, XOR gates) as well as addition and subtraction gates.

### NAND Gate Basics

The NAND gate has two inputs and produces an output of 0 only when both inputs are 1; in all other cases, the output is 1. This can be represented by the logical expression A NAND B.

### Constructing Basic Logic Gates

#### AND Gate（AND）

To construct an AND gate using NAND gates:

1. Step 1: Connect the two inputs to a NAND gate.
2. Step 2: Connect the output of this NAND gate to both inputs of another NAND gate.
3. Result: The output of the second NAND gate is the result of the AND gate.

#### OR Gate（OR）

To construct an OR gate using NAND gates:

1. Step 1: Pass each input through a NAND gate (with itself), producing the effect of two NOT gates.
2. Step 2: Connect these two NAND gates' outputs as inputs to another NAND gate.
3. Result: The output of this NAND gate is the result of the OR gate.

#### XOR Gate（XOR）

To construct an XOR gate (more complex) using NAND gates:

1. Step 1: Construct two NAND gates, each input connected to one.
2. Step 2: Connect the outputs of the first step's NAND gates to the input of a third NAND gate.
3. Step 3: Connect the original input A and the output of the first NAND gate to a fourth NAND gate, and the original input B and the output of the second NAND gate to a fifth NAND gate.
4. Step 4: Finally, connect the outputs of the fourth and fifth NAND gates to a sixth NAND gate.
5. Result: The output of the sixth NAND gate is the result of the XOR gate.

### Constructing Addition Gates

#### Half Adder

A half adder is a simple adder that can handle the addition of two bits, producing a sum and a carry.

1. Sum: Use an XOR gate to generate the sum.
2. Carry: Use an AND gate to generate the carry.
3. Construct these basic gates using NAND gates, then combine them to form a half adder.

#### Full Adder

A full adder considers the carry input from a lower bit.

1. Step 1: Construct two half adders; the first deals with A and B, the second with the sum of the first half adder and carry input C.
2. Sum: The sum output of the second half adder.
3. Carry: The carry outputs of the two half adders are connected through an OR gate.
4. Construct half adders and an OR gate using NAND gates, then combine them to form a full adder.

### Constructing Subtraction Gates

#### Half Subtractor

A half subtractor deals with the subtraction of two bits.

1. Difference: Use an XOR gate to generate the difference.
2. Borrow: Use a NAND gate and a NOT gate to generate the borrow.
3. Construct an XOR gate and other required logic using NAND gates, then combine them to form a half subtractor.

#### Full Subtractor

A full subtractor considers the borrow from a higher bit.

1. Step 1: Construct two half subtractors, the first dealing with A and B, the second with the difference of the first half subtractor and borrow input.
2. Difference: The difference output of the second half subtractor.
3. Borrow: The borrow outputs of the two half subtractors are connected through an OR gate.
4. Construct half subtractors and an OR gate using NAND gates, then combine them to form a full subtractor.

### Constructing Multiplication Gates

#### Binary Multiplication

Implement the multiplication of two binary numbers.

1. Step 1: Use AND gates for bit multiplication.
2. Step 2: Use a series of full adders for continuous addition.
3. Step 3: Implement shifting and accumulation.

### Constructing Registers

#### D Flip-Flop

Stores a single bit of binary information.

1. Step 1: Use NAND gates to create a latch.
2. Step 2: Expand the latch into a flip-flop.

#### Register

Stores multiple bits of binary information.

* Connect multiple D flip-flops in parallel, each storing one bit.

### Constructing Clocks

#### Oscillator

Provides periodic clock signals.

* Use NAND gates to create a feedback loop, producing continuous oscillation.

### Conclusion

The NAND gate is known as a 'universal logic gate' due to its ability to construct any other logic gate and complex circuits. Through the methods described above, the NAND gate can be utilized to build complex addition, subtraction, multiplication, as well as storage and clock circuits, which are the basis for arithmetic operations in computers and digital systems. In modern integrated circuit design, the NAND gate is widely used due to its simplicity and versatility.

In the practice of B² Network, any computational logic can be constructed using NAND gates.

## Commitment

Commitments have a wide range of applications in cryptography and blockchain, such as SHA256, Merkle Trees, and KZG in zero-knowledge proofs, all of which are forms of commitments. As introduced earlier, ZK-Rollup uses zero-knowledge proofs as the commitment for the Rollup, while OP-Rollup uses the bytecode within the virtual machine as the Rollup's commitment.

We can explain in detail how commitments are used through the example of a Merkle Tree:

* Commit: The Prover calculates the hash of all values, with the hashes serving as the leaves of a binary tree. The Prover then continually computes hashes upwards until the Merkle Tree is generated, and the tree root hash is published as the commitment.
* Reveal: The Prover reveals a value corresponding to a leaf node and its branch.
* Check: The Verifier calculates the hash using the revealed value and branch, and then compares it with the published commitment for verification.

For instance, in the following diagram:

* Commit: The Prover calculates the hash of transactions tx1, tx2...tx8, obtaining H(1), H(2)...H(8), and continually performs hash calculations pairwise to finally generate the binary tree structure shown in the diagram, which is the Merkle Tree. The Prover then publishes the root node value H(12345678) of the Merkle Tree as the commitment.
* Reveal: The Prover reveals a leaf node's corresponding value, such as tx3, along with its branch (H(4) -> H(12) -> H(5678)).
* Check: The Verifier calculates and verifies the commitment using the revealed tx3 and branch (H(4) -> H(12) -> H(5678)):
  1. Calculate the hash of tx3, H(3).
  2. Hash H(3) with H(4) from the branch to get H(34).
  3. Hash H(34) with H(12) from the branch to get H(1234).
  4. Hash H(1234) with H(5678) from the branch to get H(12345678).
  5. Compare H(12345678) with the published commitment for verification.

![Merkle tree proof](https://ipfs.io/ipfs/QmWZunnonmhrSoSTDpEFjGBrUKywDo3GpoYgnPrKcp4BSs)

## ZK Proof Verification Commitment of B² Network

**B² Network is a ZK-Rollup Layer 2 solution built on Bitcoin.**

### Limit of Bitcoin ZK-Rollup

Due to the Turing incompleteness of Bitcoin, it's not possible to perform zero-knowledge proof verification on Bitcoin. Therefore, the traditional approach of ZK-Rollup solutions, where zero-knowledge proofs are verified on a Layer 1 blockchain network, cannot be implemented on Bitcoin.

ZK-Rollup only writes the zero-knowledge proofs and the aggregated data of the Rollup into Bitcoin through Taproot. This ensures that the data of ZK-Rollup is anchored in Bitcoin and cannot be tampered with. However, it does not guarantee the validity and correctness of the transactions within the ZK-Rollup, nor can it utilize the powerful consensus capabilities of Bitcoin to ensure the security of the Layer 2 ZK-Rollup.

Therefore, it is necessary to confirm ZK-Rollup on Bitcoin.

### ZK Proof and Arithmetic Circuit

#### ZK Proof

In zero-knowledge proofs, arithmetic circuits are used to construct a proof that the prover knows certain secret information without revealing the information itself.

Zero-knowledge proofs use arithmetic circuits to generate a proof:

* Generating the Proof:
  * Once the arithmetic circuit is established, the prover uses their secret inputs to compute the circuit's output. During this process, the prover also generates additional information (such as commitments and random numbers unique to zero-knowledge proofs), which are used to construct the proof.
* Verifying the Proof:
  * The prover sends their proof to the verifier. The verifier does not know the prover's secret inputs but has a description of the circuit and the prover's proof. The verifier validates the proof's authenticity by performing the same computations as the circuit and comparing its results with the proof provided by the prover.

#### Arithmetic Circuit

Arithmetic circuits are typically represented as a directed acyclic graph (DAG), where each node represents an arithmetic operation and the edges represent the flow of data between operations. Input nodes represent the inputs to the circuit, typically some numbers or variables, while internal nodes represent arithmetic operations. The output of the circuit is the final result of the computation.

Basic gates in arithmetic circuits include:

* Addition Gate (Addition Gate): Performs addition operations.
* Multiplication Gate (Multiplication Gate): Performs multiplication operations.

As introduced earlier with NAND gates, arithmetic circuits can be converted into logic gate circuits based on NAND gates by transforming addition gates into NAND gates and multiplication gates into NAND gates, ultimately translating the entire arithmetic circuit into a circuit based on NAND gate logic.

### ZK Proof Verification Commitment

The verification procedure for zero-knowledge proofs itself is an arithmetic circuit, which can be converted into a logic gate circuit based on NAND gates. This effectively translates the zero-knowledge proof verification procedure into a logic gate circuit based on NAND gates.

NAND gates are implemented via Bitcoin script, assembling Bit Value Commitment as inputs and outputs into logic gates to enforce logical constraints.

This can be succinctly represented as *==\<hash\_c0> \<hash\_c1> \<hash\_b0> \<hash\_b1> \<hash\_a0> \<hash\_a1> OP\_GATECOMMITMENT==*, with the corresponding unlocking script being *==\<preimage\_a> \<preimage\_b> \<preimage\_c>==*.

In practice, NAND gates can be implemented through Bitcoin script, and from these NAND gates, addition and multiplication gates can be constructed. These addition and multiplication gates are then combined into an arithmetic circuit to ultimately build the zero-knowledge proof verification procedure. However, due to the vast number of gate circuits involved, the resulting Bitcoin script is also quite large and impractical to run on the Bitcoin network.

By assembling Bit Value Commitment as inputs and outputs into logic gates, each logic gate with different inputs and outputs acts as a leaf node, forming a circuit binary tree. The published Circuit Taproot is the root of this binary tree, reducing the size of the published data.

Circuit Taproot serves as the commitment for the B² Rollup submitted on the Layer 1 blockchain network, Bitcoin. Unlike traditional ZK-Rollups that can perform validation on the Layer 1 network, B² Rollup cannot directly execute validation on Bitcoin. However, an Optimistic Rollup-like approach can be adopted, providing a challenge mechanism for the commitment. The confirmation of the Circuit Taproot commitment is completed through this challenge mechanism.

## Challenges and Responses

Unlike BitVM, which requires pre-signing off-chain transactions between two parties, the B² Network adopts the publishing of UTXO transactions that lock a reward. The unlocking script is a Taproot script.

The specific unlocking Taproot script involves the Prover generating scripts for each branch of the Circuit Taproot Tree in advance, along with the given hash inputs. Challengers can execute the script using a preimage. If the output of the execution is inconsistent with the Prover's submission, they can unlock the entire Taproot using MAST (Merkelized Abstract Syntax Tree) to claim the locked reward.

Due to the small running cost and speed of the zero-knowledge verification procedure, all users on the Bitcoin network can act as observers for the Challenge mechanism, verifying the commitments submitted by B² Rollup. If an inconsistency in the commitment is discovered, they can immediately initiate a challenge.

The challenge mechanism is similar to Arbitrum Rollup's 'interactive verification game,' continuously searching for incorrectly executed logic gate computations. To find the erroneous gate among many, a binary search method is used to execute the gate circuit Bitcoin script. The challenger who finds the erroneous branch fastest can unlock the UTXO with the locked reward on the Bitcoin network and thus receive the reward.

Additionally, one branch of the Taproot locking script is a time-lock script. If no successful challenges occur, the Prover can unlock the UTXO and retrieve the reward after the challenge period ends, using the time-lock script.

## Summary

B² Network, through the Ordinals Protocol, aggregates the rollup's data and proof and writes them into Tapscript. It utilizes various decentralized storage protocols to save the detailed rollup data, effectively ensuring the data availability of the rollup.

B² Network records the zero-knowledge proof verification commitment on Bitcoin, allowing any observer to challenge the commitment. This mechanism enables the inheritance of Bitcoin's security, reaching consensus on the rollup's data on the Bitcoin network.


# DA Layer

Data Availability Layer is not only the storage of B² Network, but also the validation layer of B² Network.

DA Layer consists of three parts: [**Decentralized Storage**](https://github.com/b2network/docs/blob/main/decentralized_storage.md), [**B² Nodes**](/technical-design/da_layer/b2_nodes), and **Bitcoin Network**.


# Decentralized Storage

Nodes in Decentralized Storage receive rollup data sent by the Sequencer from Rollup Layer and store them. Storage Nodes run the ds-prover program of B² Network, periodically generating zero-knowledge proofs based on time and space for the stored rollup data. The ds-prover program sends the generated zk proof of storage to B² Nodes, and after verification, Storage Nodes receive certain storage rewards. The Storage Nodes in Decentralized Storage redundantly store copies of rollup data, ensuring the data availability of B² Network.


# B² Nodes

B² Nodes act as off-chain validators and are executors of multiple distinctive features in B² Network. B² Nodes consist of six main modules: ZK Proof Verifier of Rollup Module, ZK Proof Verifier of Storage Module, Sequencer Selector Module, Bitcoin Indexer Module, Bitcoin Committer Module, and Validator Set Module.

## ZK Proof Verifier of Rollup Module

B² Nodes obtain rollup transactions data from Decentralized Storage and rollup transaction merkle tree root hash and zk proof data from the Aggregator of the Rollup Layer. First, within the ZK Proof Verifier of Rollup Module, the merkle tree root hash is used to check if the rollup transactions stored in Decentralized Storage have been tampered with. Then, the zk proof data is used to verify whether the rollup transactions have been executed correctly and effectively.

## ZK Proof Verifier of Storage Module

In the ZK Proof Verifier of Storage Module, B² Nodes validate the zk proof of storage submitted by the Storage Nodes of Decentralized Storage. Once the verification is passed, B² Nodes distribute rewards to the Storage Nodes, incentivizing them to store copies of rollup data over the long term.

## Sequencer Selector Module

In the Sequencer Selector Module, B² Network implements a mechanism similar to Delegated Proof of Stake (DPoS), selecting a group of sequencers. These sequencers sequentially provide transaction ordering and packaging services for a specified period. Individuals or organizations wishing to compete as a sequencer must stake a certain amount of $BSQ and prepare the necessary hardware resources to run the sequencer service. Users can also delegate their $BSQ to candidates competing for a sequencer position. Ultimately, the top N candidates with the highest total staked and delegated $BSQ become the sequencer set for a period. Operating a sequencer service earns a certain percentage of transaction fees and additional $BSQ rewards.

## Bitcoin Indexer Module

The Bitcoin Indexer monitors blocks and transactions on the Bitcoin network. Upon obtaining the latest blocks and transactions, it generates zero-knowledge proofs for these blocks and transactions to ensure the accuracy of transaction information. The Bitcoin Indexer then sends the transactions and corresponding zk proofs to the Rollup Layer. When the zkEVM receives the Bitcoin transactions and zk proofs, it verifies them and generates the Bitcoin State. (See in Figure [B² Network Bitcoin Indexer](https://ipfs.io/ipfs/QmcfJr9KrqiN19iPFgeaabSgHV9oQgQdxCDTAcL3BgrLbc))

![B² Network Bitcoin Indexer](https://ipfs.io/ipfs/QmcfJr9KrqiN19iPFgeaabSgHV9oQgQdxCDTAcL3BgrLbc)

## Bitcoin Committer Module

The Bitcoin Committer sends two types of transactions to Bitcoin: one that writes rollup data into Bitcoin, and another that writes the zk proof verification commitment into Bitcoin.

* The Bitcoin Committer constructs a data structure to record B² rollup data and generates a Tapscript, known as a "B² Inscription." Then, the Bitcoin Committer sends a UTXO of one satoshi unit to a Taproot address containing the $B^{2}$ inscription. The rollup data is permanently written into Bitcoin. (See in Figure [Data availablity in B² Network](https://ipfs.io/ipfs/Qma2tcFRFA78cDNLDTZJzpa4fDWHR4TKGptc5Q6qpsS4yT))

![Data availablity in B² Network](https://ipfs.io/ipfs/Qma2tcFRFA78cDNLDTZJzpa4fDWHR4TKGptc5Q6qpsS4yT)

* The Bitcoin Committer breaks down large computational units from the ZK Proof Verifier of Rollup Module into smaller computational units. Each small computational unit is then turned into a bit value commitment and placed in a tapleaf script. The zk proof of rollup serves as the input for the first bit value commitment, with the output being the input for the next commitment, eventually forming a taproot. The Bitcoin Committer sends a UTXO of one satoshi unit to a Taproot address containing the commitment. The commitment based on zk proof verification is permanently written into Bitcoin. Additionally, the Bitcoin Committer sets a time-locked challenge, allowing challengers to contest the zk proof verification commitment. If there are no challengers or the challenge fails within the time lock, the rollup is finally confirmed on Bitcoin; if the challenge succeeds, the rollup is rolled back. (See in Figure [Commitment in B² Network](https://ipfs.io/ipfs/QmUSxP47LiQ1PaddAiCHw1SuKHwNVXe9KPi3Ta7JLXurEc))

![Commitment in B² Network](https://ipfs.io/ipfs/QmUSxP47LiQ1PaddAiCHw1SuKHwNVXe9KPi3Ta7JLXurEc)

## Validator Set Module

The Validator Set Module maintains members of the Schnorr signature on Bitcoin Layer1.


# B² Inscription

B² Inscription includes information such as:

1. Storage path of rollup data in decentralized storage.
2. Merkle tree root hash of rollup data.
3. Zk proof data of rollup data
4. Parent B² inscription UTXO hash.


# B² Commitment

TODO


# Bitcoin Network

Bitcoin serves as the ultimate settlement layer for B² Network. B² rollup data is stored on Bitcoin, allowing complete retrieval or restoration of B² rollup transactions based on the B² inscriptions on Bitcoin. The computational validity of zk proof verification of rollup is confirmed on Bitcoin, thereby confirming the B² rollup.


# For Users


# Connecting to B² Mainnet

Add B² network to your wallet by navigating to the **add network** option, and enter the respective network details as given below:

| Network    | RPC URL                                                                      | ChainID | Block Explorer URL                   | Currency |
| ---------- | ---------------------------------------------------------------------------- | ------- | ------------------------------------ | -------- |
| B² Mainnet | <p><https://rpc.bsquared.network><br><https://b2-mainnet.alt.technology></p> | 223     | <https://explorer.bsquared.network/> | BTC      |


# Set Gas Price

This document shows you how to set the priority price and base price for B² transactions in wallet. These prices determine how much you are willing to pay for your transaction to be included in the next block (Priority Gas Price) and how much you are willing to pay for the gas used by your transaction. Setting these prices correctly can help you save money and avoid delays.

To set the priority price and base price, follow these steps:

Metamask:

1. Open your metamask wallet and click on the B² Mainnet at the top right corner.
2. Click on the send button and enter the recipient address and the amount of BTC you want to send.
3. Before you confirm your transaction, click on the Estimated fee edit button (blue button) next to Edit gas fee page, and then click on the Advanced to the gas fee section.

![set-gas-price-01](https://quicknode.quicknode-ipfs.com/ipfs/QmfPdcszGgtkSC5DVW1Gu5cXHp2uuHFv5fKJjspPvNjh2t)

![set-gas-price-02](https://quicknode.quicknode-ipfs.com/ipfs/QmV97FWpSi7U7DLFaxLmU9hEFPLNAaiWKZk1fZr7B9NxUR)

4. You will see two sliders: one for the Max base fee (Gwei) price and one for the Priority Fee (Gwei). The priority price is the amount of BTC you are willing to pay per unit of gas for your transaction to be included in the next block. The base price is the amount of BTC you are willing to pay per unit of gas for the gas used by your transaction. The total gas fee is the sum of these two prices multiplied by the gas consumed. The base fee for BTC transactions is dynamic and depends on the demand for block space. The priority fee, which is paid to the sequencer who includes the transaction in a block, can also be as low as 0.0011 gwei. However, these fees may vary depending on the network congestion and the urgency of the transaction.

![set-gas-price-03](https://quicknode.quicknode-ipfs.com/ipfs/QmQe6spWbyRXAZwwqJrLAuzrJkoRK4YkpND8ytfjLK2mUf)

5. You can adjust the sliders according to your preferences. The higher the priority price, the faster your transaction will be confirmed, but the more expensive it will be. The lower the base price, the cheaper your transaction will be, but the more likely it will fail if the gas limit is too low.
6. Once you are satisfied with your settings, click on save and then confirm your transaction.


# Join B² Network Discovery


# Bridge to B² Mainnet

1. Enter the official website, and click on “Bridge”. Link: <https://www.bsquared.network/bridge/>

   **The withdraw function is not yet available.**

![](https://quicknode.quicknode-ipfs.com/ipfs/QmNMPhdisuvo3jzLEX9Z2aeA46zg6gt8pEjF1HsvmZTgCp)

2. Connect to the BTC mainnet address

![](https://quicknode.quicknode-ipfs.com/ipfs/QmW3iHXuSUdkYw5sJcqAauVzjz2PoCULmXav5yMQwqtDAB)

3. After successfully connecting the wallet, enter the cross-chain amount.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmULsRB26rT5n1NFDqZuSzc9DaDUZK8V7qGHgirFbfLwRb)

4. After clicking **Deposit Funds**, confirm by signing in the wallet.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmfGg3odn94wDAKrYWyGiyNfKLtj6QY89MYQHL4vWcr5Mz)

5. The transaction status can be viewed through the browser or bridge history after the bridge submission has been successfully made. Notice that only after the transaction on the BTC mainnet has exceeded 6 confirmations will the bridge transaction be conducted on the B² Mainnet. The waiting time is 1-2 hours.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmZZuicAXA68P8vsba9ZKGnSPqi6xRqSsojJcKst64bVGz)

6. Verify if transactions on both chains are successful on the **bridge history** page.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmcuzSTjw2oPtXWbG2SRU4gpBEtLnMBazMQawCBFPGbrxn)

7. If transactions on both chains are successful, click the address in the top right corner to check if the balance is correct.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmTe9abDg1urAwNTMaVEY9NA6igv5UcPrDsViQL64qHW1G)


# Transfer BlockHeadz NFT

### 1. Bridging from Haven Testnet to B² Mainnet for BlockHeadz NFT

For BlockHeadz NFT users on the Haven Testnet, we offer the quickest cross-chain solutions to the B² Mainnet tailored for different scenarios.

**Scenario 1**: For BlockHeadz NFT in an unlocked state, where the owner address is an EVM address, a Unisat wallet BTC address, or an OKX wallet BTC mainnet address. **Solution**: Users simply need to log in to the BlockHeadz official website and connect their wallet to view their NFT on the B² Mainnet.

**Scenario 2**: For BlockHeadz NFT in a locked state. **Solution:** Users just log in to the BlockHeadz official website and connect their wallet to view their NFT in its locked state.

**Scenario 3**: For BlockHeadz NFT in an unlocked state, where the owner address is an OKX wallet BTC testnet address. **Solution**: Navigate to a dedicated page at the bottom of the BlockHeadz official website, connect the OKX wallet at the top left corner of the page, and if there are NFTs available to claim, submit your BTC mainnet address to proceed.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmPKNxv5sqNp5yqepLVU1p8xnhZ4vPagDjT1jsw8r6iRrS)

### 2. Bridge from the Bitcoin Mainnet to the B² Mainnet

After confirming that the Bitcoin Mainnet is the currently selected network, connect your wallet.

![](https://quicknode.quicknode-ipfs.com/ipfs/Qmb6qWP1KzaoJJVMxuPGLcaFX1AsGZHfMq8Z8eZbqQ2yJp)

Once your wallet is connected, click the "Bridge to B²" button.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmZ5SbB9TMvmCFzboU8SoPApEa2kTRgciSxQkyCXaKtz2e)

Please be aware that in the process of bridging from the Bitcoin Mainnet to the B² Mainnet, we currently only support Native Segwit (P2WPKH) and Taproot (P2TR) address types. Nested Segwit (P2SH P2WPKH) and Legacy (P2PKH) address types are not supported at this time. It's important to note that we anticipate supporting all address types in the next version.

Moreover, if you use an unsupported address type for bridging, you will receive the following notification.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmaUScF6bEuCTbKscq2jeEhNKx9HPorPhBjySAEhcSVFMw)

The Bridge feature supports batch operations, allowing you to select up to 10 NFTs for cross-chain transactions simultaneously.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmQiSUGngJYbtC2KaBrYGR7JR8FNDgxE4fZPu9vQLQSkJK)

Please enter your B² Mainnet address, which must start with 0x. For BTC addresses, you can switch to the B² Mainnet and connect your BTC address to find the corresponding 0x address in the bottom right corner of the particle wallet.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmauPfGyzL7jnf8rHB9jz7uXo14poSyMgxWTdnU8DkeaLS)

After wallet signing, you can view the transaction status in your browser and anticipate approximately an hour's wait. Once the transaction is successful, switch to the B² Mainnet to view your NFT and access the transaction history.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmZ13QCCvLiSPN2Z7vZNbMAcYmUy1Uz3ytRh1Vw1Qy51BA)

![](https://quicknode.quicknode-ipfs.com/ipfs/QmQ8EwAUSNa9WZmAS43bQnVoCcTvftfNvhJ7idhWS2PsqZ)

### 3. Bridge from the B² Mainnet to the Bitcoin Mainnet

After ensuring that the B² Mainnet is the selected network, connect your wallet.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmedsYiJQnjyJ8hQaKyxfFm6gRLs2FEMFKDZK4S6hAsHLy)

After selecting the NFT(s) you wish to bridge, click the "Bridge" button. Then, link a Bitcoin Mainnet address and click the "confirm" button for wallet signing. Once you have confirmed the signing with your Bitcoin Mainnet address, you can monitor the transaction status in your browser.

![](https://quicknode.quicknode-ipfs.com/ipfs/QmYD5j3YkZ6Nsc8E7R348khheCrjnqwgeC8qwPeNwMsuuU)

![](https://quicknode.quicknode-ipfs.com/ipfs/QmVKGuCoKnYfvEhbcaL5J8FJHiV7tfoVuEspnaLU6kJafY)

![](https://quicknode.quicknode-ipfs.com/ipfs/QmazSptYgZ3meZ8MUgQKTrdnJrUT8GMyZ44UPcFPcr4Z8N)


# Add B2 token on BNB Chain

Using MetaMask as an example:

1. [Add BNB Chain to Wallet](https://chainlist.org/chain/56) – open the link and connect your MetaMask wallet.

   ![image\_1](https://github.com/user-attachments/assets/37d9ae51-7f5c-4c9f-8798-a216c58f2570)
2. Check the pop-up from your MetaMask wallet and click **"Approve."**

   ![image\_2](https://github.com/user-attachments/assets/0c5cbbca-f066-4181-8267-ac4fa79ac8b7)
3. You’ll notice that the BNB Chain has been added successfully, and your wallet is now connected to it.

   ![image\_3](https://github.com/user-attachments/assets/77bfe0f1-5f79-409e-8ca6-35df9d078b0d)
4. Start adding the B2 token by copying this contract address:**0x783c3f003f172c6Ac5AC700218a357d2D66Ee2a2**
5. Open your MetaMask wallet, make sure you're still connected to the BNB Chain, then click **"Tokens" > "More" > "Import tokens."**

   ![image\_4](https://github.com/user-attachments/assets/2a8aa3ce-fe8f-449a-bc85-e58e880ebe4a)
6. Select **"Custom Token"**, then paste the B2 contract address into the **Token Contract Address** field. The **Token Symbol** and **Token Decimal** will be filled in automatically. Click **"Next."**

![image\_5](https://github.com/user-attachments/assets/264c27ce-efad-4fc7-b7a2-4a8432fdcc86)

8. In the pop-up window titled **"Import Tokens"**, click **"Import."**

   ![image\_6](https://github.com/user-attachments/assets/4290a243-8b9e-47c7-9f5d-51893b76ece9)
9. Congratulations! You have successfully imported the B2 token on the BNB Chain.

   ![image\_7](https://github.com/user-attachments/assets/d81bf55c-b7ac-4dbf-86db-9565d6fd410e)


# For Developers


# Basic information

#### Connecting to B² Mainnet

Add B² network with the respective network details as given below:

| Network    | RPC URL                                                                                                                                                     | ChainID | Block Explorer URL                                                                          | Currency |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------- | -------- |
| B² Mainnet | <p><https://mainnet.b2-rpc.com><br><https://rpc.bsquared.network><br><https://b2-mainnet.alt.technology><br><https://b2-mainnet-public.s.chainbase.com></p> | 223     | <p><https://explorer.bsquared.network><br><https://mainnet-blockscout.bsquared.network></p> | BTC      |

#### List of Token Contracts

**Native Token**

* BTC

**ERC-20 Token**

* WBTC: 0x4200000000000000000000000000000000000006
* USDC: 0xE544e8a38aDD9B1ABF21922090445Ba93f74B9E5
* USDT: 0x681202351a488040Fa4FdCc24188AfB582c9DD62
* ETH: 0xD48d3A551757ac47655fCe25BDE1B0B6b1Cb2a5A
* MATIC: 0xc3ee2Df14B1Bc526c24ED802f1873d49664a0d5c
* FDUSD: 0xC2Fe4f673455Ef92299770a09CDB5E8756A525D5
* BSTONE: 0x7537C1F80c9E157ED7AFD93a494be3e1f04f1462
* ordi: 0xa0f4470B714677AEEcE0d20074c540b3Cf6a477E
* sats: 0x7eBFcE05E418C380a2b6EB0F65995cA04ef4bc00
* WETH: 0xD48d3A551757ac47655fCe25BDE1B0B6b1Cb2a5A

**ERC-721 Token**

* BlockHeadz: 0x066466d7EAa56b60AAF0436dbDA6f92DB7BD2468

**ERC-1155 Token**

* Buzz Mining Rigs: 0xD1b76c0f58c6d65E396F98cAea94Cd717c3a848e


# Write a contract

This section explains how to automatically write a smart contract using the OpenZeppelin Wizard. The resulting smart contract code can either be integrated with Remix by Clicking the **Open in Remix** button, or copied to a clipboard and pasted in the user’s intended IDE.

## Getting started

Navigate to the [OpenZeppelin Wizard](https://wizard.openzeppelin.com/) in your browser. First thing to notice is the **Solidity Wizard** and **Cairo Wizard** buttons.

One can choose any of the following tabs to begin creating an out-of-box smart contract code in either Solidity (for EVM chains) or Cairo (useful for Starknet). These are:

* **ERC20** for writing an ERC-20 token smart contract.
* **ERC721** for writing an NFT token smart contract.
* **ERC1155** for writing an ERC-1155 token smart contract.
* **Governor** for creating a DAO.
* **Custom** for writing a customized smart contract.

## Writing an NFT contract

For illustration purposes, we will be creating a NFT smart contract.

Suppose you wanted to create a *Mintable*, *Burnable* ERC721 token and specify an appropriate license for it.

1. Select the ERC721 tab.
2. Give your NFT a name and a symbol by filling the Name and Symbol fields.
3. Use the check-boxes on the left to select features of your token.
4. Put a tick on the Mintable check-box.
5. Put a tick on the Auto Increment Ids check-box, this ensures uniqueness of each minted NFT.
6. Put a tick on the Burnable check-box.
7. Either leave the default MIT license or type the license of your choice.

Notice that new lines of code are automatically written each time a feature is selected.


# Deploy a contract with Hardhat

This section is a guide on how to deploy a smart contract on the B² Network using [Hardhat](https://hardhat.org/).

Hardhat is a popular smart contract development frameworks. It is used in the B² rollup as a default for deploying and automatically verifying smart contracts.

## Initial setup

* Get some test BTC from Bitcoin testnet faucet, and cross chain the test BTC from Bitcoin testnet to B² Network Testnet by test bridge.
* Install Hardhat and dependencies

  ```
  npm install --save-dev ethers hardhat @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers dotenv
  ```
* Run ***npx hardhat init*** to init a new project, and you will be shown some options to facilitate project creation:

  ```
  $ npx hardhat init
  888    888                      888 888               888
  888    888                      888 888               888
  888    888                      888 888               888
  8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
  888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
  888    888 .d888888 888    888  888 888  888 .d888888 888
  888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
  888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

  Welcome to Hardhat v2.19.3

  ? What do you want to do? …
  ▸ Create a JavaScript project
    Create a TypeScript project
    Create a TypeScript project (with Viem)
    Create an empty hardhat.config.js
    Quit
  ```
* Open the hardhat.config.js file and paste the below code:

  ```
  require("dotenv").config();
  require("@nomicfoundation/hardhat-toolbox");

  /** @type import('hardhat/config').HardhatUserConfig */
  module.exports = {
      solidity: "0.8.9",
      paths: {
          artifacts: "./src",
      },
      networks: {
          b2Testnet: {
              url: `https://zkevm-rpc.bsquared.network`,
              accounts: [process.env.ACCOUNT_PRIVATE_KEY],
          },
      },
  };    
  ```

## Add contract code and scripts

* Create a new contract code file, in the contracts folder, named Storage.sol
* Copy the below code and paste it in the Storage contract code:

  ```
  //SPDX-License-Identifier: MIT
  pragma solidity ^0.8.9;

  contract Storage {
      uint256 _count = 0;

      function set(uint256 count) public {
          _count = count;
      }

      function get() public view returns (uint256){
          return _count;
      }
  }
  ```
* Create a new file in the scripts folder deploy-storage.js
* Add the code below to the deploy-counter.js file:

  ```
  const hre = require("hardhat");

  async function main() {
      const deployedContract = await hre.ethers.deployContract("Storage");
      await deployedContract.waitForDeployment();
      console.log(
          `Storage contract deployed to https://testnet.bsquared.network/address/${deployedContract.target}`
      );
  }

  main().catch((error) => {
      console.error(error);
      process.exitCode = 1;
  });
  ```
* Before compiling the contract, you need to install the toolbox. You may need to change directory to install outside the project. Use this command:

  ```
  npm install --save-dev @nomicfoundation/hardhat-toolbox
  ```
* Compile your contract code (i.e., go back to the project root in the CLI):

  ```
  npx hardhat compile
  ```
* Now run the scripts:

  ```
  npx hardhat run scripts/deploy-storage.js --network b2Testnet
  ```


# Verify contract code with Hardhat in B² Explorer

## Install plugin

1. `npm install --save-dev @nomicfoundation/hardhat-verify`
2. And add the following statement to your hardhat.config.js:

   ```js
   require("@nomicfoundation/hardhat-verify");
   ```

   Or, if you are using TypeScript, add this to your hardhat.config.ts:

   ```ts
   import "@nomicfoundation/hardhat-verify";
   ```

## Config hardhat.config.js or hardhat.config.ts

```js
module.exports = {
  solidity: "0.8.28",
  networks: {
    b2: {
      url: "https://rpc.bsquared.network",
      chainId: 223,
      accounts: "abc",
    },
  },
  etherscan: {
    apiKey: {
      b2: "no-api-key",
    },
    customChains: [
      {
        network: "b2",
        chainId: 223,
        urls: {
          apiURL: "https://12d6a1773a-backend-blockscout.bsquared.network/api/",
          browserURL: "https://explorer.bsquared.network",
        },
      },
    ],
  },
  sourcify: {
    enabled: false,
  },
}
```

## Verify

1. Assuming we have deployed the Locker contract [B² Network address details for 0xc1189535d0De120b5DeA3704BEa0e29af0715433 | Blockscout](https://explorer.bsquared.network/address/0xc1189535d0De120b5DeA3704BEa0e29af0715433?tab=contract)
2. We can use the following cli to verify

   ```bash
   npx hardhat verify --network b2 0xc1189535d0De120b5DeA3704BEa0e29af0715433 1893456000

   [dotenv@17.3.1] injecting env (2) from .env -- tip: 🔐 prevent committing .env to code: https://dotenvx.com/precommit
   [WARNING] Network and explorer-specific api keys are deprecated in favour of the new Etherscan v2 api. Support for v1 is expected to end by May 31st, 2025. To migrate, please specify a single Etherscan.io api key the apiKey config value.
   Successfully submitted source code for contract
   contracts/Lock.sol:Lock at 0xc1189535d0De120b5DeA3704BEa0e29af0715433
   for verification on the block explorer. Waiting for verification result...

   Successfully verified contract Lock on the block explorer.
   https://explorer.bsquared.network/address/0xc1189535d0De120b5DeA3704BEa0e29af0715433#code
   ```
3. For more features, please refer to

   ```bash
   t14p hardhat-etherjs-v5-js git:(main) ✗ npx hardhat verify --help
   Hardhat version 2.19.5

   Usage: hardhat [GLOBAL OPTIONS] verify [--constructor-args <INPUTFILE>] [--contract <STRING>] [--libraries <INPUTFILE>] [--list-networks] [--no-compile] [address] [...constructorArgsParams]

   OPTIONS:

     --constructor-args	File path to a javascript module that exports the list of arguments. 
     --contract        	Fully qualified name of the contract to verify. Skips automatic detection of the contract. Use if the deployed bytecode matches more than one contract in your project. 
     --libraries       	File path to a javascript module that exports the dictionary of library addresses for your contract. Use if there are undetectable library addresses in your contract. Library addresses are undetectable if they are only used in the constructor for your contract. 
     --list-networks   	Print the list of supported networks 
     --no-compile      	Don't compile before running this task 

   POSITIONAL ARGUMENTS:

     address              	Address of the smart contract to verify 
     constructorArgsParams	Contract constructor arguments. Ignored if the --constructor-args option is used. (default: [])

   verify: Verifies contract on Etherscan

   For global options help run: hardhat help

   ```

## Reference

1. [hardhat/packages/hardhat-verify at main · NomicFoundation/hardhat](https://github.com/nomicfoundation/hardhat/tree/main/packages/hardhat-verify)


# Integrate Particle Account Abstraction

[Particle Network](https://particle.network) is the Intent-Centric, Modular Access Layer for Web3 applications. While Particle Network offers a range of solutions (including Modular Smart Wallet-as-a-Service) across the Web3 ecosystem, their flagship Bitcoin product is BTC Connect.

BTC Connect is the first account abstraction protocol for the Bitcoin ecosystem, unifying the experience between smart accounts on Bitcoin Layer-2s and standard BTC accounts through existing wallet interfaces. Particle Network has deployed ERC-4337 AA infrastructure natively on B², which developers can tap into to leverage smart accounts. This is achieved by having users connect to your application (through BTC Connect) with their UniSat, OKX, or Bitget wallet (with more on the way, such as Xverse, Leather, etc.). Upon connecting, a smart account will be generated and assigned to their BTC account on B². This smart account can then be used and authenticated directly through their native Bitcoin wallet.

Currently, BTC Connect has been deployed on the B² testnet, alongside native support for B² within its primary SDK, `@particle-network/btc-connectkit`.

Building an AA-enabled application on B² using BTC Connect only takes a few lines of code. This document will provide a high-level overview of this integration process, although for a detailed tutorial, visit the [Particle Network documentation](https://developers.particle.network/reference/btc-connect-web).

## Introduction to BTC Connect: Configuration

BTC Connect is primarily available through its React-based JS library, `@particle-network/btc-connectkit`. To install it, run one of the two commands at the root of your project:

```shell=
yarn add @particle-network/connectkit @particle-network/chains


# OR


npm install @particle-network/connectkit @particle-network/chains
```

`@particle-network/btc-connectkit` needs to be initialized and configured through the `ConnectProvider` component (generally within your `index` file), wrapping the primary application component in which you intend to use BTC Connect.

This configuration process contains two halves, `options` and `connectors`. The first will be used to customize and authenticate the SDK through your `projectId`, `clientKey`, and `appId` from the [Particle dashboard](https://dashboard.particle.network), while the second will be used to define the wallets you'd like to be supported (currently, BTC Connect supports UniSat (`UnisatConnector`), Bitget (`BitgetConnector`), or OKX (`OKXConnector`)).

The following snippet is an example of what your `index` file *may* look like once you've configured `ConnectProvider`.

```typescript=
import React from 'react';
import ReactDOM from 'react-dom/client';
import {
  ConnectProvider,
  OKXConnector,
  BitgetConnector,
  UnisatConnector,
} from '@particle-network/btc-connectkit';


import { BSquaredTestnet } from '@particle-network/chains';


import App from './App';


ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <ConnectProvider
      options={{
        projectId: process.env.REACT_APP_PROJECT_ID, // --
        clientKey: process.env.REACT_APP_CLIENT_KEY, // Retrieved from https://dashboard.particle.network
        appId: process.env.REACT_APP_APP_ID, // --
        aaOptions: {
          accountContracts: {
            BTC: [
              {
                chainIds: [BSquaredTestnet.id],
                version: '1.0.0', // Will always be 1.0.0 for now
              },
            ],
          },
        },
        walletOptions: {
          visible: true, // Determines whether or not a dedicated wallet interface for the smart account is shown
        }
      }}
      connectors={[new UnisatConnector(), new OKXConnector(), new BitgetConnector()]}
    >
      <App />
    </ConnectProvider>
  </React.StrictMode>
);
```

With this complete, BTC Connect will be ready to use through the component you wrapped with `ConnectProvider` (`App` in the example above).You can nowbegin driving wallet connection and deploying smart accounts on B².

## Introduction to BTC Connect: General Usage

The BTC Connect SDK, `@particle-network/btc-connectkit`, can be used in three primary ways:

1. Facilitation of wallet connection through a built-in modal.
2. Execution of operations with the native Bitcoin account (inscriptions, P2P BTC transactions).
3. Execution of operations with the associated smart account (any contract call or transaction on B²).

Each type of operation has corresponding hooks exported by `@particle-network/btc-connectkit`, such as:

* `useConnectModal`, for wallet connection.
* `useAccounts`, to retrieve active Bitcoin addresses (after wallet connection).
* `useBTCProvider`, for controlling the native Bitcoin account.
* `useETHProvider`, for controlling the associated smart account on B².

Wallet connection is initiated through one primary function within BTC Connect, `openConnectModal()` from `useConnectModal`. Upon calling this function, the user will be shown a standardized connection interface containing the wallets previously defined within `connectors`.

After connecting with their wallet of choice, a smart account will be automatically generated and assigned to the user’s Bitcoin public key and address. For this, both `sendBitcoin` from `useBTCProvider` and `smartAccount` from `useETHProvider` will be available.

`smartAccount` from `useETHProvider` will act as the central object controlling the underlying smart account, handling everything from the conversion of transactions to UserOperations, the execution of UserOperations, etc.

In the example application shown below, we call `openConnectModal()` to onboard a user into the application. We then focus on two functions: `executeTxEvm`, which uses `smartAccount` to construct and execute a gasless transaction, and `executeTxBtc`, which uses `sendBitcoin` to transfer 1 satoshi back to the sender.

```typescript=
import React, { useState, useEffect } from 'react';
import { useETHProvider, useBTCProvider, useConnectModal } from '@particle-network/btc-connectkit';


import { notification } from 'antd'; // Optional, just a frontend component to indicate successful transactions
import './App.css';


const App = () => {
  const { smartAccount } = useETHProvider(); // For handling the smart account
  const { openConnectModal } = useConnectModal(); // For facilitating wallet connection
  const { accounts, sendBitcoin } = useBTCProvider(); // To send native Bitcoin and track active addresses


  const executeTxEvm = async () => {
    const tx = {
      to: "0x00000000000000000000000000000000000dEAD0", // Sample recipient, burn address
      value: '100000000000', // wei value, 0.0000001 BTC
      data: "0x" // Leave as 0x unless you're calling a contract
    };


    const feeQuotes = await smartAccount.getFeeQuotes(tx); // Converts tx to a list of potential UserOperations
    const { userOp, userOpHash } = feeQuotes.verifyingPaymasterGasless; // Chooses a gasless UserOperation (sponsored for free as this is on the bSquared testnet)
    const hash = await smartAccount.sendUserOperation({ userOp, userOpHash }); // Executes the UserOperation
    
    notification.success({
      message: 'Transaction Successful',
      description: (
        <div>
          Transaction Hash: <a href={`https://testnet.bsquared.network/tx/${hash}`} target="_blank" rel="noopener noreferrer">{hash}</a>
        </div>
      )
    });
  };




  const executeTxBtc = async () => {
    const hash = await sendBitcoin(accounts[0], 1); // Sends 1 satoshi back to the sender (the connected wallet)
    
    notification.success({
      message: 'Transaction Successful',
      description: (
        <div>
          Transaction Hash: <a href={`https://live.blockcypher.com/btc-testnet/tx/${hash}`} target="_blank" rel="noopener noreferrer">{hash}</a>
        </div>
      )
    });
  };


  return (
      // Your JSX
    );
};


export default App;
```

## Learn More

To learn more about the process covered above, Particle Network has a variety of content covering the implementation of BTC Connect, including:

* The GitHub repository for the code covered in this document: <https://github.com/TABASCOatw/particle-btc-connect-demo>
* The official `@particle-network/btc-connectkit` repository: <https://github.com/Particle-Network/particle-btc-connect>
* Tutorial video (covering the code on this document): <https://twitter.com/TABASCOweb3/status/1750072016076464467>
* Documentation: <https://developers.particle.network/reference/btc-connect-web>
* Blog post: <https://blog.particle.network/btc-connect-bitcoin-account-abstraction>


# Integrate B² Network Oracle Services

B2 Oracle Service is a decentralized, multi-signature price oracle running on [B2 Network](https://www.bsquared.network/) (a Bitcoin Layer 2). It publishes price data (BTC/USD, USDT/USD, and BTC-pegged assets) on-chain and exposes it through **two industry-standard interfaces**, so existing integrations work without code changes:

* **Chainlink-compatible** — the standard `AggregatorV3Interface` (drop-in for any protocol built against Chainlink feeds)
* **Supra-compatible** — the `ISupraSValueFeed` push-model interface (drop-in for any protocol built against Supra)

## How It Works

```
  ┌──────────────────────────────────────────────────────────────┐
  │                        DeFi Protocols                        │
  └───────────────┬─────────────────────────────┬────────────────┘
                  │ AggregatorV3Interface       │ ISupraSValueFeed
                  ▼                             ▼
  ┌───────────────────────────┐   ┌───────────────────────────┐
  │      AggregatorProxy      │◀──│    SupraSValueAdapter     │
  │  stable integration addr  │   │  read-only Supra facade   │
  └───────────────┬───────────┘   └───────────────────────────┘
                  ▼
  ┌───────────────────────────┐
  │      OracleAggregator     │  ← verifies ≥3-of-4 signer ECDSA
  │  bounds, replay & fresh-  │    signatures before storing a
  │  ness protection          │    new price round
  └───────────────▲───────────┘
                  │ transmit(report, signatures)
  ┌───────────────┴───────────┐
  │        Coordinator        │  ← polls prices, triggers updates,
  └──┬───────┬───────┬───────┬┘    collects signatures, pays gas
     ▼       ▼       ▼       ▼
  Signer1 Signer2 Signer3 Signer4   ← 4 independent verifiers,
     └───────┴───┬───┴───────┘        each holds its own key
                 ▼
   Binance / OKX / Coinbase / Kraken (public market data)
```

### Data pipeline

1. **Aggregation.** An off-chain coordinator continuously polls multiple centralized exchanges (Binance, OKX, Coinbase, Kraken) and computes the **median** price, tolerant to any single source failing or misreporting.
2. **Update triggers.** A new price is pushed on-chain when either the price **deviates beyond a configured threshold** from the last on-chain value, or a **heartbeat interval** expires — so the feed tracks volatile markets closely while proving liveness in quiet ones.
3. **Independent multi-party verification.** Before anything goes on-chain, the coordinator must collect signatures from independent signer services. Each signer **fetches exchange prices itself**, recomputes the median, and only signs if the proposed price is within its own tolerance. The coordinator never holds signer keys; signers never see each other's keys.
4. **On-chain verification.** The `OracleAggregator` contract accepts a new round only if it carries valid ECDSA signatures from **at least 3 of the 4 authorized signers** (threshold and signer set are on-chain state, rotatable by the owner). Forging a price requires compromising 3 independent parties simultaneously.

### On-chain safeguards

* **Price bounds** — each aggregator is deployed with immutable `minAnswer`/`maxAnswer`; out-of-range prices are rejected even with valid signatures.
* **Replay protection** — every signature binds to a `feedId = keccak256(chainId, aggregator, description, configEpoch)`. Signatures cannot be replayed across chains, contracts, or signer-set rotations (each rotation bumps `configEpoch`, instantly invalidating all outstanding signatures).
* **Freshness & monotonicity** — round IDs and observation timestamps must be strictly increasing; timestamps more than 300 s in the future are rejected.
* **Safe upgrades** — consumers integrate against a proxy whose address never changes. The underlying aggregator can be replaced through a two-step propose/confirm process (with phase-encoded round IDs, mirroring Chainlink's `EACAggregatorProxy`), and all admin roles use two-step ownership transfer.

## Contract Addresses (B2 Mainnet, chainId 223)

| Feed             | Interface                         | Address                                      |
| ---------------- | --------------------------------- | -------------------------------------------- |
| BTC / USD        | Chainlink `AggregatorV3Interface` | `0x3031EC46cb223dAF943FFDbCbDDE0374036E8a7f` |
| uBTC / USD       | Chainlink `AggregatorV3Interface` | `0xae06f38b576A921C768Afb172dc6fC6B88495D65` |
| WBTC / USD       | Chainlink `AggregatorV3Interface` | `0x68AFa281bd6C300E8e4DB84b12a4cAf16F737fFf` |
| uniBTC / USD     | Chainlink `AggregatorV3Interface` | `0x4F3E3cde41aaDBC58D015be913938c534D029bcc` |
| USDT / USD       | Chainlink `AggregatorV3Interface` | `0x3CcAfDd7C6609fe3C2C57bD883f98bfAEE4Ac074` |
| All of the above | Supra `ISupraSValueFeed`          | `0x76bc00D4C3BfBfC6ABb2cb018df0125a2Ad26767` |

uBTC, WBTC, and uniBTC are 1:1 BTC-pegged and priced identically to BTC. Chainlink-style integrations get a dedicated proxy address per asset (each backed by the same BTC/USD feed), so protocols can configure them like any independent feed. Supra-style integrations read all BTC-pegged assets through the **same pair indexes as BTC** — the returned price is the same value. USDT/USD is an independent feed with its own Supra pair index.

## Developer Guide

### Option A: Chainlink-style integration

The proxy addresses above are drop-in replacements for a Chainlink price feed:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData()
        external view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

contract Example {
    AggregatorV3Interface constant BTC_USD =
        AggregatorV3Interface(0x3031EC46cb223dAF943FFDbCbDDE0374036E8a7f);

    function btcPrice() external view returns (int256 price) {
        (, price,, uint256 updatedAt,) = BTC_USD.latestRoundData();
        require(block.timestamp - updatedAt < 3600, "stale price"); // always check freshness
    }
}
```

* `decimals()` is always **8** — e.g. $64,043.055 is returned as `6404305500000`
* `answer` is the USD price as a fixed-point integer
* `startedAt` = off-chain observation time, `updatedAt` = on-chain write time
* `roundId` is encoded as `(phaseId << 64) | aggregatorRoundId`, identical to Chainlink's proxy format

Quick check from the command line:

```bash
cast call 0x3031EC46cb223dAF943FFDbCbDDE0374036E8a7f \
  "latestRoundData()(uint80,int256,uint256,uint256,uint80)" \
  --rpc-url https://rpc.bsquared.network
```

### Option B: Supra-style integration

If your protocol already consumes Supra's push oracle, point it at the Supra-compatible address instead — pair indexes, return struct, and decimal conventions all follow Supra's catalog:

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface ISupraSValueFeed {
    struct priceFeed { uint256 round; uint256 decimals; uint256 time; uint256 price; }
    function getSvalue(uint256 _pairIndex) external view returns (priceFeed memory);
    function getSvalues(uint256[] memory _pairIndexes) external view returns (priceFeed[] memory);
}

contract Example {
    ISupraSValueFeed constant FEED =
        ISupraSValueFeed(0x76bc00D4C3BfBfC6ABb2cb018df0125a2Ad26767);

    function btcPrice() external view returns (uint256 price, uint256 decimals) {
        ISupraSValueFeed.priceFeed memory f = FEED.getSvalue(18); // 18 = BTC_USD
        require(block.timestamp * 1000 - f.time < 3600 * 1000, "stale price");
        return (f.price, f.decimals); // read decimals dynamically — it varies per pair
    }
}
```

Registered pair indexes (Supra's official numbering; uBTC / WBTC / uniBTC use the same BTC pairs — their prices equal BTC by definition):

| Pair index | Supra pair | Decimals |
| ---------- | ---------- | -------- |
| `0`        | BTC\_USDT  | 18       |
| `18`       | BTC\_USD   | 8        |
| `48`       | USDT\_USD  | 8        |

* `time` is a **millisecond** timestamp
* USDT-quoted pairs are served from the USD feed (USDT ≈ USD, deviation typically \~0.1%)

```bash
cast call 0x76bc00D4C3BfBfC6ABb2cb018df0125a2Ad26767 \
  "getSvalue(uint256)((uint256,uint256,uint256,uint256))" 18 \
  --rpc-url https://rpc.bsquared.network
# → (round, 8, 1784949600000, 6404305500000)   i.e. $64,043.055
```

Differences from Supra's official contracts (intentional):

1. **Unregistered pairs revert** with `"pair not registered"` instead of returning an all-zero struct — a zero price can silently poison liquidation logic.
2. `round` is the underlying proxy round ID (monotonically increasing `uint256`); Supra's is timestamp-shaped. Treat it as an opaque increasing value.
3. Updates are typically **fresher** than Supra's native push feed on B2 (which refreshes on a 10% deviation / 6-hour schedule).

### Integration checklist

* Always enforce a staleness check against `updatedAt` (Chainlink-style) or `time` (Supra-style); pick a window consistent with the feed's heartbeat.
* Integrate the **proxy / adapter addresses** listed above — never the underlying aggregator, whose address changes on upgrades.
* For Supra-style reads, take `decimals` from the returned struct rather than hardcoding it: it differs per pair (8 vs 18).


# Deploy a rollup node

Learn how to run a node for the B2.

## System Requirements

**hardware requirements**

* CPUs: 16 vCPUs
* RAM: 32 GB
* Storage: 1 TB NVMe Storage
* 100MBps bidirectional internet connection

You can run B2 on lower-spec hardware, but you may find that it is not highly performant or prone to crashing.

**software requirements**

OS：As long as Docker Engine can be installed, the operating system will suffice.

## Pre-install

### Install Docker

Please refer to the [Install Docker Engine](https://docs.docker.com/engine/install/)

### Install Docker-compose

Please refer to the [Install Docker Compose](https://docs.docker.com/compose/install/standalone/)

## Download Snapshot Data

```bash
docker run \
  --rm \
  --volume ./data:/data \
  ghcr.io/b2network/bsquared-snapshpt-download:20250707-160537 \
  mainnet-fullnode-snapshot /data
```

**The snapshot file will be updated every Friday. The download will be temporarily unavailable. Please wait a while and try again.**

## Setup B2 Node

Generate jwt secret:

```bash
openssl rand -hex 32 > ./data/jwt.txt
```

Create a `docker-compose.yaml` file and mount the data directory and json files which downloaded above.

**Changelog for the `docker-compose.yaml`:**

**Users who have already been set up can also upgrade,The upgrade will improve block synchronization.**

* L2 image change to `us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101315.2`
* OP image change to `us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.7.7`
* OP\_NODE\_P2P\_STATIC,GETH\_BOOTNODES (See below)

```bash
version: "3.9"
services:
  l2:
    #image: ghcr.io/b2network/op-geth:v1.0
    image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101315.2 
    container_name: l2
    environment:
      GETH_VERBOSITY: "3"
      GETH_DATADIR: "/db"
      GETH_ROLLUP_DISABLETXPOOLGOSSIP: "false"
      GETH_ROLLUP_SEQUENCERHTTP: "https://b2-mainnet.alt.technology/"
      GETH_HTTP: "true"
      GETH_HTTP_ADDR: "0.0.0.0"
      GETH_HTTP_API:  "web3,debug,eth,txpool,net,engine"
      GETH_HTTP_VHOSTS: "*" 
      GETH_WS:  "true"
      GETH_WS_ADDR: "0.0.0.0"
      GETH_WS_API: "web3,debug,eth,txpool,net,engine"
      GETH_AUTHRPC_ADDR:  "0.0.0.0"
      GETH_AUTHRPC_PORT: "8551"
      GETH_AUTHRPC_JWTSECRET: "/jwt.txt"
      GETH_BOOTNODES: "enode://55b79017f15cad10bb8ad433fb991e6a0d0ca5ccef3f9123618869ee405d61b564a44dee1b87c47e62dba51e63a9172e356714a7ecdf20594d041ddf9013136c@b2-mainnet-bootnodes-v2.altlayer.network:10201,enode://ad371eb83f665586985f4482adc8bb7fff793370843d73124e8b23c7aa69f01b6db93e5782ccbf7524d04aa5345e6bd1feeca4ec7bb1a515c3af67484604a5a8@b2-mainnet-bootnodes-v2.altlayer.network:10202,enode://274310e51ffbc42167dbf1adbcf0ef43f50db9f8f0c84d9f25ac6cf1659ca57b09c9398fbc881485865170c8090250b8b803cb2f1be11aa65b488b3c8337be2d@b2-mainnet-bootnodes-v2.altlayer.network:10203,enode://01c15b6db86024b708a3f3e2cdea2769264bc81dc8997752b44b904daff98f2ca15ca1e3096ed601debe7ad0f057c12d30bf93aeaeb227a59443059402c57dec@b2-mainnet-bootnode2.bsquared.network:30303,enode://c6dc84f7885be7520fcd18ef1db35bc810d1402b9f8bd76871745ac760eb51deeed161a6ef49d05bb77ee0aabe3ace02800dea409ebfce623ac56291458cb132@b2-mainnet-bootnodes.alt.technology:10200,enode://4faae95a039ccb4eb27d1692709fd8646dc323c4d039c3db7870f77af2a2cdddad1feb8290b32070e1da3894fb1a78d8d23a1d1169939331da44e3816ec8d6ad@b2-mainnet-bootnodes.alt.technology:10210"
      GETH_METRICS: "true"
    restart: always
    network_mode: host
    volumes:
    - ./data/db:/db
    - ./data/genesis.json:/genesis.json
    - ./data/jwt.txt:/jwt.txt

  op-node:
    #image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:99a53381019d3571359d989671ccf70f8d69dfd9
    image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.7.7 
    container_name: op-node
    environment:
      OP_NODE_SYNCMODE: "execution-layer"
      OP_NODE_L1_TRUST_RPC: "true"
      OP_NODE_SEQUENCER_L1_CONFS: "10"
      OP_NODE_VERIFIER_L1_CONFS:  "10"
      OP_NODE_L1_BEACON: "https://hub-cl-rpc.bsquared.network"
      OP_NODE_L2_ENGINE_RPC: "ws://127.0.0.1:8551"
      OP_NODE_L2_ENGINE_AUTH: "/jwt.txt"
      OP_NODE_ROLLUP_CONFIG:  "rollup.json"
      OP_NODE_RPC_ADDR: "0.0.0.0"
      OP_NODE_L1_ETH_RPC: "https://hub-rpc.bsquared.network"
      OP_NODE_L1_RPC_KIND: "standard"
      OP_NODE_METRICS_ENABLED:  "true"
      OP_NODE_P2P_LISTEN_IP: "0.0.0.0"
      OP_NODE_P2P_LISTEN_TCP_PORT: "9222"
      OP_NODE_P2P_LISTEN_UDP_PORT: "9222"
      OP_NODE_P2P_DISCOVERY_PATH: "/data/node/opnode_discovery_db"
      OP_NODE_P2P_PEERSTORE_PATH: "/data/node/opnode_peerstore_db"
      OP_NODE_P2P_STATIC: "/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20201/p2p/16Uiu2HAm1hkacTvu8HzwPs2Mv8cHo6RfMX9vbEi4T8FuXFRK7VEM,/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20202/p2p/16Uiu2HAm1oTTtY6QkUdVUY8qn86Aa6MPR8FxMR4VQzXKT6tCPEun,/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20203/p2p/16Uiu2HAmJhSCro27M9ZQ4yPkEQjYcRx1QJ9BmzfunNPPHbJsXnGV,/dns/b2-mainnet-bootnode2.bsquared.network/tcp/9222/p2p/16Uiu2HAmSP44jYc7aJVXJhKVoYUFqkotwpEU1zqxYCksvUWwcyFT,/dns/b2-mainnet-bootnodes.alt.technology/tcp/20200/p2p/16Uiu2HAmBVxo37r3gVjK6P5m1cao5Y6UrXUu7EYd6xF4mBSVMraF,/dns/b2-mainnet-bootnodes.alt.technology/tcp/20210/p2p/16Uiu2HAmUXcXMoesAN5AjpkpYsTTHs2GWXvEEs7iRjNaL3A7WCSH"
    depends_on:
    - l2
    restart: always
    network_mode: host
    volumes:
    - ./data/node:/data/node
    - ./data/jwt.txt:/jwt.txt
    - ./data/rollup.json:/rollup.json
```

Now, All preparations are complete, and the data directory structure is as follow:

```bash
tree -L 3
.
├── data
│   ├── db
│   │   ├── geth
│   │   └── keystore
│   ├── db.tar.gz
│   ├── genesis.json
│   ├── jwt.txt
│   └── rollup.json
└── docker-compose.yml
```

The next step is to start the service.

## Start The Node

```bash
docker-compose up -d
```

## Verify Result

Watch the L2 container logs

```bash
docker logs -f l2
```

```bash
l2  | INFO [06-17|09:45:07.841] Merge configured:
l2  | INFO [06-17|09:45:07.841]  - Hard-fork specification:    https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/paris.md
l2  | INFO [06-17|09:45:07.841]  - Network known to be merged: true
l2  | INFO [06-17|09:45:07.841]  - Total terminal difficulty:  0
l2  | INFO [06-17|09:45:07.841]  - Merge netsplit block:       #0
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.841] Post-Merge hard forks (timestamp based):
l2  | INFO [06-17|09:45:07.841]  - Shanghai:                    @0          (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)
l2  | INFO [06-17|09:45:07.841]  - Cancun:                      @0
l2  | INFO [06-17|09:45:07.841]  - Regolith:                    @0
l2  | INFO [06-17|09:45:07.841]  - Canyon:                      @0
l2  | INFO [06-17|09:45:07.841]  - Ecotone:                     @0
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.841] ---------------------------------------------------------------------------------------------------------------------------------------------------------
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.877] Loaded most recent local block           number=2,593,146 hash=12c9b9..19e5d4 td=0 age=3d2h17m
l2  | INFO [06-17|09:45:07.877] Loaded most recent local finalized block number=2,592,324 hash=5dd607..3a9f3c td=0 age=3d2h44m
l2  | INFO [06-17|09:45:07.879] Loaded last snap-sync pivot marker       number=2,190,015
```

Block synchronization takes some time, please wait patiently. After some while，can check the syncing process by below command:

```bash
curl -s -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://localhost:8545 | jq '.result'
```

The block will catch up to the latest block once the request returns `false`.

```bash
# curl -s -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://localhost:8545 | jq '.result'
false
```


# Deploy a rollup archive node

Learn how to run a Archive node for the B2.

## System Requirements

**hardware requirements**

* CPUs: 16 vCPUs
* RAM: 32 GB
* Storage: 1 TB NVMe Storage
* 100MBps bidirectional internet connection

You can run B2 on lower-spec hardware, but you may find that it is not highly performant or prone to crashing.

**software requirements**

OS：As long as Docker Engine can be installed, the operating system will suffice.

## Pre-install

### Install Docker

Please refer to the [Install Docker Engine](https://docs.docker.com/engine/install/)

### Install Docker-compose

Please refer to the [Install Docker Compose](https://docs.docker.com/compose/install/standalone/)

## Download Snapshot Archive Data

```bash
docker run \
  --rm \
  --volume ./data:/data \
  ghcr.io/b2network/bsquared-snapshpt-download:20250707-160537 \
  mainnet-archivenode-snapshot /data
```

**The snapshot file will be updated every Friday. The download will be temporarily unavailable. Please wait a while and try again.**

## Setup B2 Archive Node

Generate jwt secret:

```bash
openssl rand -hex 32 > ./data/jwt.txt
```

Create a `docker-compose.yaml` file and mount the data directory and json files which downloaded above.

**Changelog for the `docker-compose.yaml`:**

**Users who have already been set up can also upgrade,The upgrade will improve block synchronization.**

* L2 image change to `us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101315.2`
* OP image change to `us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.7.7`
* OP\_NODE\_P2P\_STATIC,GETH\_BOOTNODES (See below)

```bash
version: "3.9"
services:
  l2:
    #image: ghcr.io/b2network/op-geth:v1.101311.0
    image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101315.2 
    container_name: l2
    environment:
      GETH_VERBOSITY: "3"
      GETH_DATADIR: "/db"
      GETH_ROLLUP_DISABLETXPOOLGOSSIP: "false"
      GETH_ROLLUP_SEQUENCERHTTP: "https://b2-mainnet.alt.technology/"
      GETH_HTTP: "true"
      GETH_HTTP_ADDR: "0.0.0.0"
      GETH_HTTP_VHOSTS: "*"
      GETH_HTTP_API: "web3,debug,eth,txpool,net,engine"
      GETH_WS: "true"
      GETH_WS_ADDR: "0.0.0.0"
      GETH_WS_API: "web3,debug,eth,txpool,net,engine"
      GETH_AUTHRPC_ADDR: "0.0.0.0"
      GETH_AUTHRPC_PORT: "8551"
      GETH_BOOTNODES: "enode://55b79017f15cad10bb8ad433fb991e6a0d0ca5ccef3f9123618869ee405d61b564a44dee1b87c47e62dba51e63a9172e356714a7ecdf20594d041ddf9013136c@b2-mainnet-bootnodes-v2.altlayer.network:10201,enode://ad371eb83f665586985f4482adc8bb7fff793370843d73124e8b23c7aa69f01b6db93e5782ccbf7524d04aa5345e6bd1feeca4ec7bb1a515c3af67484604a5a8@b2-mainnet-bootnodes-v2.altlayer.network:10202,enode://274310e51ffbc42167dbf1adbcf0ef43f50db9f8f0c84d9f25ac6cf1659ca57b09c9398fbc881485865170c8090250b8b803cb2f1be11aa65b488b3c8337be2d@b2-mainnet-bootnodes-v2.altlayer.network:10203,enode://01c15b6db86024b708a3f3e2cdea2769264bc81dc8997752b44b904daff98f2ca15ca1e3096ed601debe7ad0f057c12d30bf93aeaeb227a59443059402c57dec@b2-mainnet-bootnode2.bsquared.network:30303,enode://c6dc84f7885be7520fcd18ef1db35bc810d1402b9f8bd76871745ac760eb51deeed161a6ef49d05bb77ee0aabe3ace02800dea409ebfce623ac56291458cb132@b2-mainnet-bootnodes.alt.technology:10200,enode://4faae95a039ccb4eb27d1692709fd8646dc323c4d039c3db7870f77af2a2cdddad1feb8290b32070e1da3894fb1a78d8d23a1d1169939331da44e3816ec8d6ad@b2-mainnet-bootnodes.alt.technology:10210"
      GETH_METRICS: "true"
      GETH_SYNCMODE: "full"
      GETH_GCMODE: "archive"
      GETH_RPC_ALLOW_UNPROTECTED_TXS: "true"
    restart: always
    network_mode: host
    volumes:
    - ./data/db:/db
    - ./data/genesis.json:/genesis.json
    - ./data/jwt.txt:/jwt.txt

  op-node:
    #image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:99a53381019d3571359d989671ccf70f8d69dfd9
    image: us-docker.pkg.dev/oplabs-tools-artifacts/images/op-node:v1.7.7 
    container_name: op-node
    environment:
      OP_NODE_SYNCMODE: "execution-layer"
      OP_NODE_L1_TRUST_RPC: "true"
      OP_NODE_SEQUENCER_L1_CONFS: "10"
      OP_NODE_VERIFIER_L1_CONFS: "10"
      OP_NODE_L1_BEACON: "https://hub-cl-rpc.bsquared.network"
      OP_NODE_L2_ENGINE_RPC: "ws://127.0.0.1:8551"
      OP_NODE_L2_ENGINE_AUTH: "/jwt.txt"
      OP_NODE_ROLLUP_CONFIG: "rollup.json"
      OP_NODE_RPC_ADDR: "0.0.0.0"
      OP_NODE_L1_ETH_RPC: "https://hub-rpc.bsquared.network"
      OP_NODE_L1_RPC_KIND: "standard"
      OP_NODE_METRICS_ENABLED: "true"
      OP_NODE_P2P_LISTEN_IP: "0.0.0.0"
      OP_NODE_P2P_LISTEN_TCP_PORT: "9222"
      OP_NODE_P2P_LISTEN_UDP_PORT: "9222"
      OP_NODE_P2P_DISCOVERY_PATH: "/data/node/opnode_discovery_db"
      OP_NODE_P2P_PEERSTORE_PATH: "/data/node/opnode_peerstore_db"
      OP_NODE_P2P_PRIV_PATH: "/data/node/opnode_p2p_priv.txt"
      OP_NODE_P2P_STATIC: "/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20201/p2p/16Uiu2HAm1hkacTvu8HzwPs2Mv8cHo6RfMX9vbEi4T8FuXFRK7VEM,/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20202/p2p/16Uiu2HAm1oTTtY6QkUdVUY8qn86Aa6MPR8FxMR4VQzXKT6tCPEun,/dns/b2-mainnet-bootnodes-v2.altlayer.network/tcp/20203/p2p/16Uiu2HAmJhSCro27M9ZQ4yPkEQjYcRx1QJ9BmzfunNPPHbJsXnGV,/dns/b2-mainnet-bootnode2.bsquared.network/tcp/9222/p2p/16Uiu2HAmSP44jYc7aJVXJhKVoYUFqkotwpEU1zqxYCksvUWwcyFT,/dns/b2-mainnet-bootnodes.alt.technology/tcp/20200/p2p/16Uiu2HAmBVxo37r3gVjK6P5m1cao5Y6UrXUu7EYd6xF4mBSVMraF,/dns/b2-mainnet-bootnodes.alt.technology/tcp/20210/p2p/16Uiu2HAmUXcXMoesAN5AjpkpYsTTHs2GWXvEEs7iRjNaL3A7WCSH"
    depends_on:
    - l2
    restart: always
    network_mode: host
    volumes:
    - ./data/node:/data/node
    - ./data/jwt.txt:/jwt.txt
    - ./data/rollup.json:/rollup.json
```

Now, All preparations are complete, and the data directory structure is as follow:

```bash
tree -L 3
.
|-- data
|   |-- archive-data.tar.gz
|   |-- db
|   |   |-- geth
|   |   `-- keystore
|   |-- genesis.json
|   |-- jwt.txt
|   `-- rollup.json
`-- docker-compose.yml
```

The next step is to start the service.

## Start The Node

```bash
docker-compose up -d
```

## Verify Result

Watch the L2 container logs

```bash
docker logs -f l2
```

```bash
l2  | INFO [06-17|09:45:07.841] Merge configured:
l2  | INFO [06-17|09:45:07.841]  - Hard-fork specification:    https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/paris.md
l2  | INFO [06-17|09:45:07.841]  - Network known to be merged: true
l2  | INFO [06-17|09:45:07.841]  - Total terminal difficulty:  0
l2  | INFO [06-17|09:45:07.841]  - Merge netsplit block:       #0
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.841] Post-Merge hard forks (timestamp based):
l2  | INFO [06-17|09:45:07.841]  - Shanghai:                    @0          (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)
l2  | INFO [06-17|09:45:07.841]  - Cancun:                      @0
l2  | INFO [06-17|09:45:07.841]  - Regolith:                    @0
l2  | INFO [06-17|09:45:07.841]  - Canyon:                      @0
l2  | INFO [06-17|09:45:07.841]  - Ecotone:                     @0
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.841] ---------------------------------------------------------------------------------------------------------------------------------------------------------
l2  | INFO [06-17|09:45:07.841]
l2  | INFO [06-17|09:45:07.877] Loaded most recent local block           number=2,593,146 hash=12c9b9..19e5d4 td=0 age=3d2h17m
l2  | INFO [06-17|09:45:07.877] Loaded most recent local finalized block number=2,592,324 hash=5dd607..3a9f3c td=0 age=3d2h44m
l2  | INFO [06-17|09:45:07.879] Loaded last snap-sync pivot marker       number=2,190,015
```

Block synchronization takes some time, please wait patiently. After some while，can check the syncing process by below command:

```bash
curl -s -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://localhost:8545 | jq '.result'
```

The block will catch up to the latest block once the request returns `false`.

```bash
# curl -s -X POST -H 'Content-Type: application/json' --data '{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}' http://localhost:8545 | jq '.result'
false
```


# Deploy a node from scratch(snap sync)

Deployment is similar to the previous two articles, with the following differences:

1. No need to download snapshot data.
2. Start the node with snap sync to quickly bring up a usable node.

## Steps

1. Download the following files:

   * [genesis.json](https://github.com/b2network/docs/blob/main/nodes/genesis.json)
   * [rollup.json](https://github.com/b2network/docs/blob/main/nodes/rollup.json)

   ```bash
   bsquare-snap data git:(main) ✗ ls *.json | xargs sha1sum
   21248ccd9515c620b8440b3c2f53fbca0e8a3d2a  genesis.json
   094b023b962645933894185ff4d9f568edd3865b  rollup.json
   ```
2. Create a docker-compose.yml file，referring to [Setup B2 Node](/for-developers/running_rollup_node#setup-b2-node)
3. Start the container `us-docker.pkg.dev/oplabs-tools-artifacts/images/op-geth:v1.101315.2` and run `geth init genesis.json` to initialize the node, remember to persist the data( default path `/root/.ethereum`)
4. Configure environment variables:
   1. op-geth: `GETH_SYNCMODE=snap`
   2. op-node: `OP_NODE_SYNCMODE=execution-layer`
5. `docker compose up -d` to start the node.
6. ![](/files/b28FNUo8cnkz6L4ymIFR)


# OP-Geth Catch-Up & Recovery Runbook

## 1. Background

When an op-geth node has been offline long enough that the L1 blobs covering the gap have expired (L1 blob retention is a fixed number of epochs, typically on the order of days), `op-node` may fail to catch it up normally:

* `op-node` sees a `finalized` block already present in the datadir and chooses to CL-sync instead of EL-sync. CL-sync needs the (now expired) blobs for the gap, so it deadlocks permanently.
* Separately, `engine_forkchoiceUpdated` **ignores** a zero `finalizedBlockHash` instead of clearing it, so the engine's `finalized` label stays pinned at whatever it was before the outage. If `op-node`'s `FindL2Heads` walk ever starts from that stale label, it can walk back past a full `seq_window` and drop below the L1 blob retention boundary, reproducing the same deadlock.

The fix bypasses `op-node` entirely and drives `op-geth`'s execution layer straight from a healthy public B2 peer via the **Engine API**, then repairs the `safe`/`finalized` labels so that once `op-node` is turned back on, its backward walk terminates near the new head instead of at the stale pre-outage `finalized` block.

Two scripts implement this:

| Script          | Purpose                                                                                                                                                             |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `drive_sync.py` | Feeds the current network tip to geth (`engine_newPayloadV3` + `engine_forkchoiceUpdatedV3`) so geth's BeaconSync walks backward from the tip and fills in the gap. |
| `set_labels.py` | Once geth is caught up, advances the `safe`/`finalized` labels to blocks near the new head so `op-node`'s backstop is no longer stale.                              |

## 2. Symptoms

* `op-node` logs show it stuck on CL sync / waiting on blob retrieval that will never succeed.
* `eth_getBlockByNumber("finalized")` on geth returns a very old block compared to `"latest"`.
* geth's head is not advancing even though the network `tip` (from a public peer) is far ahead.

## 3. Prerequisites

* [drive\_sync.py](https://github.com/b2network/docs/tree/main/nodes/drive_sync.py)
* [set\_labels.py](https://github.com/b2network/docs/tree/main/nodes/set_labels.py)
* Network access from wherever `drive_sync.py` and `set_labels.py` run to:
  * the public B2 RPC endpoint: `https://b2-mainnet.alt.technology` (this is the fixed value for `PUBLIC_RPC` in `drive_sync.py`)
  * the local geth node's Engine API and RPC ports (values depend on the deployment — host networking, Docker Compose service name, or Kubernetes pod/service, etc.)
* Read access to whatever Engine API JWT secret file geth was started with, from the same execution context that will run the scripts.
* **`op-node` must be stopped for the entire duration of this procedure.** `op-node`, `drive_sync.py`, and `set_labels.py` all issue `engine_forkchoiceUpdated` calls; running any of them concurrently races and can corrupt the sync state.
* Before running either script, set its constants to match the execution context it will actually run from — these are deployment-specific and will differ between environments/incidents:
  * `drive_sync.py`: `JWT_PATH`, `ENGINE`, `LOCAL_RPC` (`PUBLIC_RPC` is fixed, see above).
  * `set_labels.py`: `JWT_PATH`, `ENGINE`, `LOCAL_RPC`, `FINALIZED_LAG`.
  * If a script is copied into a different host/container than the one it was last configured for, verify connectivity (e.g. a simple RPC call) before trusting any output it produces — a wrong `ENGINE`/`LOCAL_RPC` value will just fail to connect rather than silently doing the wrong thing, but a wrong `JWT_PATH` pointing at the *right host's* JWT for the *wrong* geth instance would not necessarily fail loudly.
  * example:

    ```py
    JWT_PATH = "/jwt.txt"
    ENGINE = "http://127.0.0.1:8551"
    PUBLIC_RPC = "https://b2-mainnet.alt.technology"
    LOCAL_RPC = "http://127.0.0.1:8545"
    FINALIZED_LAG = 2000  # ~1.1h behind head, comfortably inside blob retention
    ```

## 4. Procedure

### Step 0 — Stop op-node

Stop whatever supervises `op-node` in the target deployment (e.g. its Docker Compose service, Kubernetes deployment, or systemd unit).

Confirm it is actually stopped (no process issuing `forkchoiceUpdated`) before continuing.

### Step 1 — Run drive\_sync.py

Deploy `drive_sync.py` to wherever it can reach both the public RPC and the local geth Engine API (copy method depends on the environment — `scp`, `kubectl cp`, etc.), configure its constants per Step 3 above, then run:

```sh
python3 drive_sync.py
```

This pulls the current tip block and its raw transactions from `PUBLIC_RPC`, submits the tip via `engine_newPayloadV3`, and points `engine_forkchoiceUpdatedV3` at it. This kicks off (or continues) geth's BeaconSync, which then backfills from its peers on its own.

A `SYNCING` status in the output is expected and fine. An `INVALID` status is fatal — the script exits non-zero; stop and investigate (mismatched JWT, wrong RPC endpoint, or a bad payload) before retrying.

Since the tip keeps advancing and geth may lose peers over time, re-run this script as needed until the local head has caught up to (or is acceptably close to) the network tip — compare the `local head=` / `behind=` values it prints, or query `eth_blockNumber` directly against both the local node and `PUBLIC_RPC`.

### Step 2 — Run set\_labels.py

Once geth's head is caught up, deploy `set_labels.py` to an execution context that can reach the local geth Engine API and RPC (configure its constants per Step 3 above — this may be a different execution context than `drive_sync.py`, e.g. a container on the geth's own network rather than the host), then run:

```sh
python3 set_labels.py
```

It will:

1. Read the current `latest` head.
2. Compute `finalized = head - FINALIZED_LAG`.
3. Call `engine_forkchoiceUpdatedV3` with `head = safe = latest`, `finalized` = the computed block.
4. Read back and print the `safe` and `finalized` labels to confirm they moved.

If the resulting status is not `VALID`, the script exits non-zero — stop and investigate before restarting `op-node`.

### Step 3 — Start op-node

Start `op-node` back up under its normal supervision (Docker Compose, Kubernetes, systemd, etc.).

## 5. Verification / Success Criteria

* `eth_getBlockByNumber("finalized")` and `("safe")` on geth now return recent blocks, not the stale pre-outage `finalized` block.
* `op-node` logs show it deriving/verifying new L2 blocks rather than stalling on blob retrieval.
* geth's `latest` head continues to advance in step with the network after `op-node` resumes control of forkchoice updates.

## 6. Rollback / Troubleshooting

* **`newPayloadV3` returns `INVALID`**: stop immediately (the script already exits `1`). Re-check that the block header and raw RLP came from the same block (the script pins both fetches to one block hash) and that the JWT secret matches the target geth instance.
* **geth has too few devp2p peers**: manually re-dial known bootnodes for the network (e.g. via `admin.addPeer(...)` on the geth console) and re-run `drive_sync.py` afterward.
* **A script can't connect to the configured `ENGINE`/`LOCAL_RPC`**: double check which host/container it's actually running from vs. the one its constants were set for (see Step 3 in Prerequisites) — the two scripts may need different values depending on where each is executed.
* **Accidentally ran `op-node` at the same time as `drive_sync.py` or `set_labels.py`**: stop everything, re-check the current `latest`/`safe`/`finalized` labels, and re-run from Step 0 — do not assume the state is consistent.

## 7. Safety Notes

* `op-node` **must never run at the same time** as `drive_sync.py` or `set_labels.py` — all of them issue competing `engine_forkchoiceUpdated` calls.
* All block data driving the recovery comes from the canonical B2 network over devp2p/RPC (a public peer and the local peer set) — the same trust assumption the rest of the node already relies on. No new trust boundary is introduced.
* `FINALIZED_LAG` must stay small enough to land after the L1 blob retention boundary and after any node offline gaps, but large enough to give a safety margin behind the head. Choose its value per incident — do not set it to `0`, given `engine_forkchoiceUpdated`'s known behavior of ignoring a zero `finalizedBlockHash` instead of clearing it.


# Tokenomics

## Total Supply

**210,000,000 B2**

## Token Allocation

| Category                              | Percentage of Total Supply | B2 Amount     | Description                                  | Initial Unlock        | Release Schedule                                           |
| ------------------------------------- | -------------------------- | ------------- | -------------------------------------------- | --------------------- | ---------------------------------------------------------- |
| Investors                             | 10%                        | 21,000,000 B2 | Allocated to investors.                      | None                  | Cliff: 12 months; Linear Monthly Release: 25 months        |
| Team + Advisors                       | 10%                        | 21,000,000 B2 | Allocated to team and advisors.              | None                  | Cliff: 12 months; Linear Monthly Release: 36 months        |
| Ecosystem Incentive - BUZZ I          | 5.5%                       | 11,550,000 B2 | Airdropped to participants in BUZZ I event.  | 6.25% at TGE          | Remaining over 4 months: 50%, 25%, 12.5%, 6.25%            |
| Ecosystem Incentive - BUZZ II         | 5%                         | 10,500,000 B2 | Airdropped to participants in BUZZ II event. | 100% at TGE           | -                                                          |
| Ecosystem Incentive - Testnet Odyssey | 0.5%                       | 1,050,000 B2  | Airdropped to Testnet Odyssey participants.  | 100% at TGE           | -                                                          |
| Staking (HIVE)                        | 20%                        | 42,000,000 B2 | Stake BTC, safeguard B2.                     | 2.94% of total supply | Validator node reward & BTC staking reward; LMR: 96 months |
| Bitcoin Extensive Networks Incentive  | 11%                        | 23,100,000 B2 | Rewards for Bitcoin extensive network event. | None                  | Cliff: 6 months; LMR: 34 months                            |
| Ecosystem Reserve                     | 24%                        | 50,400,000 B2 | Rewards for ecosystem development.           | None                  | Cliff: 6 months; LMR: 47 months                            |
| Public Distribution                   | 12%                        | 25,200,000 B2 | Allocated for listing.                       | -                     | Released according to actual needs                         |
| Initial Liquidity Provision           | 2%                         | 4,200,000 B2  | For CEX and DEX liquidity.                   | 100% at TGE           | -                                                          |

## B2 Token Utility

### Current Use Cases

1. **Transaction Fees (Gas) on B² Hub**\
   Used to pay gas fees on the B² Hub (Data Availability Layer).
2. **Staking for Network Security**\
   Users stake B2 to become Validators or delegate B2 to earn rewards.
3. **Incentives for Rollup Mainnet Bootstrapping (TVL Mining)**\
   Incentives for early liquidity and participation campaigns.
4. **Ecosystem Liquidity Incentives**\
   Rewards to support liquidity across the ecosystem.
5. **Fee Discounts on B² Rollup**\
   Discounts on gas fees for B² Rollup users.
6. **Governance Rights**\
   Vote on proposals such as fee adjustments and protocol upgrades.

### Future Use Cases

1. **Sequencer Staking**\
   Stake B2 to become Sequencers and earn transaction fee rewards.
2. **Rollup Layer Staking Across Ecosystem**\
   Use B2 for staking across other Rollups on B² Hub (DA Layer).


# Press-Kit

## White Logo

![white\_1](https://b2-static.bsquared.network/logo/white1.png)

![white\_2](https://b2-static.bsquared.network/logo/white2.png)

![white\_3](https://b2-static.bsquared.network/logo/white3.png)

## Transparent Logo

![transparent\_1](https://b2-static.bsquared.network/logo/transparent1.png)

![transparent\_2](https://b2-static.bsquared.network/logo/transparent2.png)

![transparent\_3](https://b2-static.bsquared.network/logo/transparent3.png)

## Transparent White Logo

![transparent\_white\_1](https://b2-static.bsquared.network/logo/transparent_white1.png)

![transparent\_white\_2](https://b2-static.bsquared.network/logo/transparent_white2.png)

![transparent\_white\_3](https://b2-static.bsquared.network/logo/transparent_white3.png)

## Black Logo

![Black\_1](https://b2-static.bsquared.network/logo/Black1.png)

![Black\_2](https://b2-static.bsquared.network/logo/Black2.png)

![Black\_3](https://b2-static.bsquared.network/logo/Black3.png)


