# Overview

## Overview

{% content-ref url="/pages/r6Xuu4uZ2MnKrTBRbdaL" %}
[Nomic Network](/nomic-network)
{% endcontent-ref %}

{% content-ref url="/pages/P9muvmcTcQqpv9jGVgn2" %}
[Bitcoin Decentralized Custody](/bitcoin)
{% endcontent-ref %}

{% content-ref url="/pages/dqt2joOtZ8M6gwKAQRgW" %}
[Governance](/governance)
{% endcontent-ref %}

{% content-ref url="/pages/Qmyd427K4jFhCrfExtXL" %}
[Contributors](/contributors)
{% endcontent-ref %}

{% content-ref url="/pages/JY8HjxxWIECfLI5e0v50" %}
[Foundation](/foundation)
{% endcontent-ref %}

{% content-ref url="/pages/bJC8dcRM9jjrWOtH9Wof" %}
[Brand](/brand)
{% endcontent-ref %}

## Technical Docs

<table data-view="cards" data-full-width="false"><thead><tr><th></th><th></th><th data-hidden></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Nomic Network Docs</strong></td><td>Technical docs for running a node of the Nomic Network blockchain.</td><td></td><td><a href="/files/FRfU76OYXwqzUt3OCvKL">/files/FRfU76OYXwqzUt3OCvKL</a></td><td><a href="https://docs.nomic.io/v/network/">https://docs.nomic.io/v/network/</a></td></tr><tr><td><strong>nBTC Docs</strong></td><td>Technical docs for integrating with nBTC, a 1:1 BTC backed token.</td><td></td><td><a href="/files/IGmtIDKg4CfAi7W8S58t">/files/IGmtIDKg4CfAi7W8S58t</a></td><td><a href="/spaces/urmuNAuy7TRjTID6NIYV">/spaces/urmuNAuy7TRjTID6NIYV</a></td></tr><tr><td><strong>Security Features</strong></td><td>Technical docs describing the security features of Nomic and nBTC.</td><td></td><td><a href="/files/SZsPdlatR6Pci9WpSY5C">/files/SZsPdlatR6Pci9WpSY5C</a></td><td><a href="/spaces/dBkQnBKauQorIEZlXR2j">/spaces/dBkQnBKauQorIEZlXR2j</a></td></tr></tbody></table>


# Nomic Network

The Nomic Network is a decentralized network of nodes (blockchain) powering Nomic's decentralized custody engine for Bitcoin.

## Infrastructure

Nomic is built on Orga. This page gives a high-level overview of the components.

### Orga

Nomic is built on [Orga](https://github.com/turbofish-org/orga), a custom stack for writing Proof-of-Stake blockchains in Rust, authored and maintained by [Turbofish](https://turbofish.org). The scope of Orga is similar to the [Cosmos SDK](https://docs.cosmos.network/), but written in Rust with a focus on safety, performance, and expressiveness through composability. Under the hood, Orga depends on [CometBFT](https://cometbft.com) (f.k.a. Tendermint) as its consensus engine.

### Merk

[Merk](https://github.com/turbofish-org/merk) is a high-performance Merkle key/value store - more specifically, it's a Merkle AVL tree built on top of RocksDB. Merk prioritizes throughput and reliability, and supports fast and efficient proofs required for Nomic's IBC interaction with other networks, and for end-user light clients.

## NOM Token

NOM is the staking token used to secure the Nomic network. Stakers can receive both NOM and nBTC staking rewards.

The NOM distribution is inspired by the OSMO token. The network will start with a supply of 21,000,000 NOM, and the maximum supply after 9 years of inflation is 210,000,000 NOM (as an homage to Bitcoin’s 21,000,000 BTC).

#### Initial Distribution

**Total:** 21,000,000 NOM

* **Airdrop I** - 3,500,000 NOM

  Targeting ATOM holders and stakers - see Airdrop 1.
* **Reserve for Airdrops II & III** - 7,000,000 NOM

  These tokens were reserved at genesis. See Airdrop 2, which was executed on August 24, 2023.
* **Strategic Reserve** - 10,500,000 NOM

  Based on standards from $OSMO and other Cosmos projects, the strategic reserve is used to create strategic partnerships for Nomic. It is held in a multisig by the Nomic DAO Foundation and is strictly for the purpose of achieving the long-term goals of Nomic. It will not be used to market sell and strategic partners will be subject to vesting periods.

  At the discretion of the foundation, the reserve may also be used to delegate to validators who are providing high value services to Nomic, such as operating infrastructure like block explorers and relayers, or contributing open source tooling/resources to the ecosystem. In order to maintain decentralization of the network, the strategic reserve will not “overstake” such to have a controlling share of the network.

#### Inflation Schedule

**Total Distributed After Genesis:** 189,000,000 NOM

NOM will be distributed over 9 years, reducing the inflation rate by 1/3 each year.

Inflation begins 24 hours after the launch of the Stakenet - Feb 1, 2022 at 20:40 UTC. This gives the community time to make delegations so that the initial validators do not receive an unfair advantage for claiming the staking rewards.

* **Staking Rewards** - 47,250,000 NOM

  Rewards will be distributed to NOM validators and delegators in a similar fashion to other Cosmos chains.
* **Protocol Incentives** - 85,050,000 NOM

  This share of the NOM supply will be used for future incentives to be decided by governance or proposed in later upgrades. For instance, potential incentives could be paid to nBTC holders or liquidity providers for NOM or nBTC pools on Osmosis.

  Excess protocol incentive NOM accumulates into a pool to be distributed later by protocol enhancements.
* **Developer Vesting** - 47,250,000 NOM

  The developer share will be vested over time to the core contributors and founders of Nomic, Turbofish. Note that since the network is decentralized, in the event the Turbofish team is no longer the primary contributor to development, the developer share can be redirected to vest to other teams or individuals.
* **Community Pool** - 9,450,000 NOM

  A share of NOM will be collected into a pool which can be spent by network governance discretionarily. The network does not yet include a mechanism to spend these funds, so they will accumulate until a later upgrade which adds coordination mechanisms for fund allocation.

### Airdrop 1

The Stakenet launch occurred on January 31, 2022 and included an airdrop to ATOM holders and stakers.

**Eligibility:**

* ATOM holders/stakers with balance of at least 1.5 ATOM
* Snapshot: Cosmos block 9,150,000 (Jan 21st, 2022 at 11:22:43 UTC)

**Distribution:**

* Total amount: 3,500,000 NOM
* Formula:
  * `(min(liquidBalance, 1000) + (4 * min(stakedBalance, 1000))) / 20.299325`
  * (A 1000 ATOM cap on both liquid balance and staked balance, with a 4x multiplier on staked balance)

### Airdrop 2

Airdrop 2 executed on August 24th with the activation of the Stakenet v6 upgrade.

**Eligibility:**

* ATOM, OSMO, JUNO, EVMOS, or KUJI stakers
* Snapshot: September 27th 2022

**Distribution:**

* Total amount: 3,500,000 NOM
* Formula:
  * Linear for staked ATOM, OSMO, JUNO, EVMOS, or KUJI for validators outside the top 20 on each network
  * (A max of 10,000 tokens per network are counted)


# Bitcoin Decentralized Custody

## What is nBTC?

When BTC is moved into Nomic's decentralized custody, it can be turned into an asset called nBTC. The creation of nBTC only happens when deposits of BTC are detected by the Nomic protocol, so nBTC is always backed exactly 1:1 by BTC held in the decentralized custody reserves. Holders of nBTC can withdraw BTC from the decentralized custody at any point.

nBTC is not a synthetic asset, and is not like other BTC-like assets which only offer price exposure. Since nBTC is truly backed by BTC, it gives the holder ownership of the equivalent amount of BTC.

## How it Works

Nomic's decentralized custody is operated through the decentralized protocol rules of the Nomic blockchain - there are no central authorities or trusted parties to rely on for the secure operation of the decentralized custody.

A **reserve** of Bitcoin is maintained in a decentralized way through use of a special multisig script. The collective whole of the network validators cooperates to hold or disburse funds as **signatories** of the reserve, since their signatures are required to control the funds on the Bitcoin blockchain.

To disburse funds from the reserve, more than 90% of the signatory set must sign the Bitcoin transaction (weighted by voting power). This is enforced on the Bitcoin blockchain through the **reserve script**, which looks something like this:

```
<pubkey1> OP_CHECKSIG
OP_IF
  <voting_power1>
OP_ELSE
  0
OP_ENDIF

OP_SWAP
<pubkey2> OP_CHECKSIG
OP_IF
  <voting_power2>
  OP_ADD
OP_ENDIF

OP_SWAP
<pubkey...> OP_CHECKSIG
OP_IF
  <voting_power...>
  OP_ADD
OP_ENDIF

OP_SWAP
<pubkeyN> OP_CHECKSIG
OP_IF
  <voting_powerN>
  OP_ADD
OP_ENDIF

<90%_of_total_voting_power>
OP_GREATERTHAN
```

Periodically, the network creates **checkpoint transactions**, which spend all incoming deposits, as well as an output form the previous checkpoint transaction. Checkpoints have the following structure:

**Inputs:**

* The reserve output of the previous checkpoint transaction.
* All unspent deposit outputs, if any.

**Outputs:**

* The **reserve output**, equal to the amount of Bitcoin which are held in reserve. Paid to the updated reserve script based on the most recent signatory set.
* All pending withdrawals, if any.

The Nomic blockchain maintains a light client of the Bitcoin blockchain, verifying the proof-of-work of each header and attempting to stay up-to-date on the heaviest chain. By verifying transactions against the Bitcoin blockchain, the protocol can detect incoming deposits by checking for outputs which pay to a recent signatory set reserve script (along with a commitment to the destination on the Nomic chain, which can be the address of a Nomic account or an account on a remote IBC chain).

Whenever a new Bitcoin block is mined, or a deposit transaction is confirmed on the Bitcoin network, the data will need to be carried to the Nomic chain. Conversely, when a transaction is signed by the signatory set in the checkpointing process, it will need to be broadcast to the Bitcoin network. This job is done by **relayer** nodes, which can be any node with knowledge of both networks running software to broadcast the relayed data.

Note that no trust is placed in the relayer nodes and the system operates correctly as long as at least a single relayer node is active and up-to-date on the canonical Bitcoin chain.

**Relayed from Bitcoin to Nomic:**

* *Bitcoin block mined* - header is relayed
* *Deposit transaction is confirmed* - transaction and Merkle proof are relayed

**Relayed from Nomic to Bitcoin:**

* *Checkpoint signed by signatory set* - assembled transaction is relayed

## Key Security Features

Security is the main priority in the Nomic design. To make the decentralized custody as safe as possible, various security features have been included to cover different threat models and risks.

### **Emergency Disbursal**

In the case of an extended liveness failure, all deposited funds would be frozen in place on the Bitcoin blockchain with no recourse other than manually resolving the situation with the signatories.

To protect against this case, as part of the checkpointing process signatories also sign a set of **"emergency disbursal"** transactions which spend the entire reserve and pay out to each individual nBTC-holder on the Bitcoin blockchain. Signatories publish these signatures to the network at the time of the checkpoint so that relayers may assemble them. These transactions are timelocked 2 weeks past the checkpoint, so the emergency disbursal only happens if a checkpoint has not been created for an extended period of time.

Note that to be included in the emergency disbursal, an nBTC holder must first set their “recovery script” on the Nomic chain, representing something such as their personal wallet address.

#### **90% Signatory Set Threshold**

When signing checkpoint transactions, the network is able to use a high signature threshold - 90% of the signatory set voting power must sign to create valid Bitcoin transactions. Even with this high threshold, the network is secure against liveness faults due to the Emergency Disbursal mechanism. The high threshold means that only 10% of the voting power needs to be honest to ensure there are no unexpected spends of the reserve.

### **Circuit Breakers**

Circuit breaker mechanisms are often used in engineering to provide safety by shutting down the system when extreme conditions are detected. In the case of Nomic, the circuit breaker detects when a large amount of funds are leaving the decentralized custody in a 24-hour period, or if there is a large shift in signatory voting power. When the mechanism is tripped, signatories will automatically stop signing checkpoint transactions, giving the network time to verify the transaction and respond accordingly before any funds leave the reserve.

### **Fully-Verifying**

Many decentralized bridge designs make security compromises in the interest of being easier to implement. For instance, the common model is to trust the validators to report on the state of the remote chain. This gives network validators the power to mint bridge assets at will, which means a lot of trust is placed in them to operate the bridge honestly.

Nomic, on the other hand, provides a stronger security guarantee by maintaining an in-protocol light client of the Bitcoin blockchain, verifying the headers and proof-of-work, and verifying inclusion of transactions via Merkle proofs. This means that nBTC can only be minted if an equivalent amount of BTC is moved into the decentralized custody on the Bitcoin chain.

## Fees

Bitcoin miner fees are paid when depositing into the decentralized custody since the deposit output must be spent to collect the funds into the reserve. A small miner fee is also taken from withdrawals based on the size of the output, usually totaling in the hundreds of satoshis. The Nomic protocol constantly adjusts the amount of fees paid to miners, to pay at current Bitcoin fee market rates.

In addition to Bitcoin miner fees, the Nomic protocol collects bridge fees when BTC is deposited, and when nBTC is transferred to a remote IBC chain. No bridge fees are collected when withdrawing or for IBC transfers to the Nomic chain to ensure that holding 1 nBTC is tied to the ability to receive 1 BTC on the Bitcoin blockchain (minus Bitcoin miner fees).

Bridge fees collected by the protocol are first paid into the **network fee fund**, which maintains a small balance in order to pay for the miner fees for checkpoint transactions (for the bytes of the transaction not covered by depositors and withdrawal initiators). All nBTC collected in fees beyond what is required for checkpoints is paid into the **reward pool**, which is distributed to stakers on the Nomic chain over time (at a rate of 1/2377 of the current pool balance every 2 minutes).

## Capacity Limits

During the early stages of the bridge, capacity limits are in place to slow the growth of the reserve. When the bridge reaches its capacity limit, clients will not allow generating deposit addresses so that users can not deposit more BTC.

In the pre-audited state of the bridge, Nomic has a capacity limit of **21 BTC**. Like the bridge fee rates, this parameter will be controlled by Nomic DAO governance in a future upgrade.


# Governance

Nomic is governed by holders of the NOM token.

Whilst the project undergoes a security audit, the bridge currently implements a capacity limit of **21 BTC**, and fixed deposit and IBC transfer fees. BTC deposits are disabled by the protocol when the bridge reaches this capacity limit.

After the successful completion of the audits, the network’s next upgrade will put control of the capacity limit and fee parameters under control of NOM holders using simple coin voting via the Nomic app. The right to vote may also be delegated to validators.

A beta governance system is currently in place. A future upgrade will be released which will introduce a novel futarchy-based governance mechanism for lifting the NOM transfer restriction and selecting other chain parameters.


# Contributors

Nomic is an open-source project spearheaded by contributors. Anyone is able to contribute to Nomic via GitHub.

## Core Contributors

### Turbofish

Nomic’s founders and core contributors are Turbofish. Turbofish are building the next generation of open-source blockchain technologies, focusing on security, decentralization, and efficiency.

Turbofish was founded in 2018 by ex-Cosmos/Tendermint employees [Matt Bell](https://twitter.com/mappum) and [Judd Keppel](https://twitter.com/juddkeppel).

You can learn more about Turbofish at [turbofish.org](https://turbofish.org/)

## Other Contributors

A full list of contributors can be found on GitHub here:

[Contributors to nomic-io/nomic](https://github.com/nomic-io/nomic/graphs/contributors)


# Foundation

Nomic is a decentralised network run by nodes, validators, contributors and the community. The Nomic DAO is represented in ‘the real world’ by the Nomic DAO Foundation. Having a legal entity helps protect the members of the DAO and allows the DAO to contract with other entities in ‘the real world’.

## Nomic DAO Foundation

The Nomic DAO Foundation is a non-profit dedicated to the growth and integration of the Nomic ecosystem. The Foundation supports the goals and objectives of the Nomic DAO (decentralized autonomous organization), is the initial steward of the Nomic blockchain, and will support and grow the Nomic DAO until it becomes self-sufficient.

The Nomic DAO Foundation is an exempted limited guarantee foundation company, which is a type of non-profit, incorporated in the Cayman Islands. The Nomic DAO Foundation has no share capital, therefore no shareholders or owners, it is memberless. It is governed by a board of directors.

The Foundation’s incorporation and governing documents specifically contemplate DAO-governance and outline the process for DAO to make recommendations to the Foundation’s Board of Directors. The Board is then bound to “observe, implement, carry out, action and execute with best efforts any and all DAO Recommendations,” subject to directors’ fiduciary duties and legal requirements.

### Nomic DAO Ltd.

Nomic DAO Ltd. is a business company incorporated in the British Virgin Islands. It is a wholly-owned subsidiary of the Nomic DAO Foundation and the Foundation is the sole member and sole director.

Nomic DAO Ltd. is the entity responsible for issuing the NOM tokens as described [here](/nomic-network#nom-token).


# Brand

{% embed url="<https://www.figma.com/design/OExRhRrsJndbnBcs56ipQC/Nomic-Brand-Kit?node-id=0-1&t=83wNanhVyPh28u8B-1>" fullWidth="false" %}


# Running a Node

This guide will walk you through starting or upgrading a full node on the Nomic Network.

Running a node increases the health of the network by decentralizing ledger validation and data, even for non-validator nodes. Community members are encouraged to run a node, especially when regularly interacting with the network via transactions and queries.

### Need help?

If you need any help getting your node running, join the [Discord](https://discord.gg/jH7U2NRJKn) and ask for the Validator role.


# Setup

These instructions will help you set up a new Nomic Stakenet node from scratch. If you are already running an older Nomic node, follow the [upgrade instructions](/network/running-a-node/upgrading) instead.

### Requirements

* \>= 4GB RAM
* \>= 100GB of storage
* Linux or macOS

### 1. Build Nomic

Start by building Nomic.

1. Install rustup if you haven't already:

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```

2. Install required dependencies:

**Ubuntu/Debian:**

```bash
sudo apt install build-essential libssl-dev pkg-config clang
```

**Fedora:**

```bash
sudo dnf install clang openssl-devel && sudo dnf group install "C Development Tools and Libraries"
```

3. Clone the repo and switch to the correct directory and branch:

```bash
git clone https://github.com/nomic-io/nomic.git
cd nomic
git checkout v9.0.0
```

4. Build and install. This adds a `nomic` command to your PATH:

```bash
cargo install --locked --path .
nomic --version
```

### 2. Run your node

Start your Nomic node:

```bash
nomic start
```

This will run the Nomic state machine and a CometBFT process. For new nodes, the state-sync process will run automatically to get the node up to speed with the current chain.


# Upgrading

Nomic has its own unique upgrade system. Once you switch to the latest release, your node will signal its readiness, and the network will automatically switch to the new version once enough voting power has signalled.

To prepare your Nomic Stakenet node for a network upgrade, simply compile the new version then restart:

```bash
# from `nomic` directory
git pull
git checkout v9.0.0
cargo install --path . --locked --bin nomic

# relaunch node with:
nomic start

# run your signer with:
nomic signer
```

{% hint style="warning" %}
**Remember to keep your Bitcoin key safe, and to keep your signer running** The key is located at `~/.nomic-stakenet-3/signer/xpriv` - it's important to back it up. If you are moving your validator node from another machine, remember to copy this key in addition to the other usual keys (`priv_validator_key.json`, `node_key.json`, etc). For nodes in the top 20, not running a signer for 20 checkpoints will result in jailing.
{% endhint %}


# Testnet

Nomic Testnet v10.1 has been released.

{% hint style="info" %}
**NOTE:** this testnet spawns a new network (*nomic-testnet-9*), with a fresh state. To join the validator set, you'll need to declare your validator as detailed here: [Validating](/network/validating)
{% endhint %}

```console
# from `nomic` directory
git pull
git checkout v10.1.0
cargo install --path . --locked --bin nomic

# launch node:
nomic start --network testnet
```

Thanks for keeping your nodes running. Stay tuned, there will be more upgrades in the near future.


# Validating

Becoming a validator comes with extra responsibility compared to running a non-validating full node. Your node becomes an authority for producing blocks and a signatory for the Bitcoin held in the bridge.

### 1. Acquiring nBTC and staking for voting power

First, find your address by running `nomic balance` (for now this must be run on the same machine as your active full node). You'll need to fund this Nomic account with nBTC.

You can declare your node as a validator and delegate to yourself with this command:

```bash
nomic declare \
  <validator_consensus_key> \
  <amount> \
  <commission_rate> \
  <max_commission_rate> \
  <max_commission_rate_change_per_day> \
  <min_self_delegation> \
  <moniker> \
  <website> \
  <identity> \
  <details>
```

If you do not have NOM, you can deposit BTC and set `amount` to 0 for 100 satoshis of nBTC.

{% hint style="warning" %}
**IMPORTANT NOTE:** Carefully double-check all the fields since you will not be able to modify the `commission_max` or `commission_max_change` after declaring. If you make a mistake, you will have to declare a new validator instead.
{% endhint %}

* The `validator_consensus_key` field is the base64 pubkey `value` field found under `"validator_info"` in the output of <http://localhost:26657/status>.
* The `identity` field is the 64-bit hex key suffix found on your Keybase profile, used to get your profile picture in wallets and block explorers.

For example:

```bash
nomic declare \
  ohFOw5u9LGq1ZRMTYZD1Y/WrFtg7xfyBaEB4lSgfeC8= \
  100000 \
  0.042 \
  0.1 \
  0.01 \
  100000 \
  "Foo's Validator" \
  "https://foovalidator.com" \
  37AA68F6AA20B7A8 \
  "Please delegate to me!"
```

### 2. Run your Bitcoin signer

Validating on Nomic means you partake in the Bitcoin signing process of the funds in the Bitcoin decentralized custody. It is very important that you run a [signer](/network/signer).


# Signer

Validating on Nomic means you partake in the Bitcoin signing process of the funds in the Bitcoin decentralized custody. It is very important that you run a signer.

You can run the signer with:

```
nomic signer
```

This will automatically generate a Bitcoin extended private key and store it at `~/.nomic-stakenet-3/signer/xpriv`. It will also prompt you to submit your public key to the network so you can be added to the multisig.&#x20;

{% hint style="danger" %}
**KEEP THIS KEY SAFE** - similar to your validator private key, it is important to be mindful of this key so that it is never lost or stolen.
{% endhint %}

Leave this process running, it will automatically sign Bitcoin transactions that the network wants to create.

In the future, we hope for the community to come up with alternative types of signers which provide for extra security, by e.g. airgapping keys, using HSMs, or prompting the user for an encryption key.

### Circuit Breaker

The signer process will automatically halt signing if, over the past 24 hours, the signatory set has changed too much, or if too much Bitcoin is being withdrawn from the bridge.

These parameters are tunable:

```
nomic signer

        --max-sigset-change-rate <MAX_SIGSET_CHANGE_RATE>
            Limits the maximum allowed signatory set change within 24 hours

            The Total Variation Distance between a day-old signatory set and the newly-proposed
            signatory set may not exceed this value

            [default: 0.04]

        --max-withdrawal-rate <MAX_WITHDRAWAL_RATE>
            Limits the fraction of the total reserve that may be withdrawn within the trailing
            24-hour period

            [default: 0.04]
```

Tweaking these parameters is a decision that requires careful thought. A future release will integrate these circuit breaker checks into the protocol itself.


# IBC Relayer

Running an IBC relayer for Nomic works mostly the same as with other Cosmos chains, but with a few caveats:

1. Currently, Nomic is only compatible with [Hermes](https://hermes.informal.systems) and does not support the ibc-go relayer.
2. Hermes must be configured with a custom proof spec. Please see the example configuration below.

## 1. Configure Hermes

Here's an example Hermes configuration relaying between a local Nomic and Osmosis node:

<pre class="language-toml"><code class="lang-toml"><strong># ~/.hermes/config.toml
</strong>
[[chains]]
id = 'nomic-stakenet-3'
rpc_addr = 'http://127.0.0.1:26657'
event_source = { mode = 'pull' }
grpc_addr = 'http://127.0.0.1:9001'
rpc_timeout = '10s'
account_prefix = 'nomic'
key_name = 'testkey'
store_prefix = 'ibc'
max_gas = 40000000
gas_price = { price = 0.001, denom = 'stake' }
clock_drift = '20s'
proof_specs = '''
[
  {
    "inner_spec": {
      "child_order": [
        0,
        1,
        2
      ],
      "child_size": 32,
      "empty_child": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
      "min_prefix_length": 1,
      "max_prefix_length": 1,
      "hash": 6
    },
    "leaf_spec": {
      "hash": 6,
      "prehash_key": 0,
      "prehash_value": 0,
      "length": 4,
      "prefix": "AA"
    },
    "max_depth": 0,
    "min_depth": 0
  },
  {
    "inner_spec": {
      "child_order": [
        0
      ],
      "child_size": 32,
      "empty_child": "",
      "min_prefix_length": 0,
      "max_prefix_length": 0,
      "hash": 6
    },
    "leaf_spec": {
      "hash": 6,
      "prehash_key": 0,
      "prehash_value": 0,
      "length": 0,
      "prefix": ""
    },
    "max_depth": 0,
    "min_depth": 0
  }
]
'''

[[chains]]
id = 'osmosis-1'
rpc_addr = 'http://127.0.0.1:26757'
grpc_addr = 'http://127.0.0.1:9090'
websocket_addr = 'ws://127.0.0.1:26757/websocket'
rpc_timeout = '10s'
account_prefix = 'osmo'
key_name = 'osmosis'
address_type = { derivation = 'cosmos' }
store_prefix = 'ibc'
default_gas = 5000000
max_gas = 15000000
gas_price = { price = 0.0026, denom = 'uosmo' }
gas_multiplier = 1.1
max_msg_num = 20
max_tx_size = 209715
clock_drift = '20s'
max_block_time = '10s'
trusting_period = '10days'
trust_threshold = { numerator = '1', denominator = '3' }
[chains.packet_filter]
policy = 'allow'
list = [
  ['transfer', 'channel-5555'], # nomic-stakenet-3
]
</code></pre>

The `proof_specs` and `event_source` fields for Nomic are the main differences to note for those otherwise familiar with IBC relaying with Hermes.

Please refer to the [Hermes docs](https://hermes.informal.systems) for more information.

## 2. Run gRPC server

Nomic features a gRPC server to support IBC relaying, which implements only the minimum set of gRPC methods required by Hermes. The server does not run by default, and must be run in a separate process with:

```bash
# default port 9001
nomic grpc
```

or:

```bash
nomic grpc <PORT>
```

## 3. Fund relayer with nBTC

Fees for IBC transactions are paid with nBTC (1 sat per tx). After you've configured your relayer, you'll need to fund its Nomic account (`hermes keys list --chain nomic-stakenet-3` to see the address) with nBTC.

## 4. (Optional) Relay operator keys

To ensure that nBTC is recoverable by the remote chain's validator set in the event of an Emergency Disbursal, run:

```bash
nomic relay-op-keys <COUNTERPARTY-RPC> <CLIENT_ID>
```

This command may be re-run anytime to refresh the operator keys of the remote chain's validator set. If an Emergency Disbursal occurs on Nomic, a portion of the Bitcoin reserves equal to the nBTC held in channels backed by the specified client will become spendable by 2/3+ of the voting power of that network's top 30 validators.

## Other notes

Below are a couple other notes to keep in mind, given Nomic's custom IBC implementation.

### Channel ports

For channels supporting token transfers, the Nomic channel port **must** be `transfer`. ICS 20 is the only application-layer standard currently supported by Nomic:

```bash
hermes create channel --a-chain osmosis-1  --b-chain nomic-stakenet-3 --a-port transfer --b-port transfer --new-client-connection
```

### Manual clearing

Typically, the main Hermes process (`hermes start`) will properly relay packets between Nomic and its counterparty. However, if it seems like an event has been missed by Hermes, packets can be manually cleared (bidirectionally) with:

```bash
hermes clear packets --chain nomic-stakenet-3 --port transfer --channel channel-1
```


# Bitcoin Relayer

Relayer nodes carry data between the Bitcoin blockchain and the Nomic blockchain. You can help support the health of the network by running a Bitcoin node alongside your Nomic node and running the relayer process.

### 1. Sync a Bitcoin node

Download Bitcoin Core: <https://bitcoin.org/en/download>

Run it with:

```bash
# mainnet
bitcoind -server -rpcuser=satoshi -rpcpassword=nakamoto

# testnet
bitcoind -server -testnet -rpcuser=satoshi -rpcpassword=nakamoto
```

{% hint style="info" %}
**NOTE:** To save on disk space, you may want to configure your Bitcoin node to prune block storage. For instance, add `-prune=5000` to only keep a maximum of 5000 MB of blocks. You may also want to use the `-daemon` option to keep the node running in the background.
{% endhint %}

### 2. Run the relayer process

```bash
# mainnet
nomic relayer --rpc-port=8332 --rpc-user=satoshi --rpc-pass=nakamoto

# testnet
nomic relayer --rpc-port=18332 --rpc-user=satoshi --rpc-pass=nakamoto
```

Leave this running - the relayer will constantly scan the Bitcoin and Nomic chains and broadcast relevant data.

The relayer will also create a server which listens on port 9000 for clients to announce their deposit addresses. To help make the network more reliable, if you run a relayer please open this port and add your node's address in a Github issue so clients can make use of your node. If you're going to make this service public, putting the server behind an HTTP reverse proxy is recommended for extra safety.


# Key Management

When running a node, care must be put into handling the various keys to ensure they are not lost or leaked.

If your node is in the validator set or signatory set, you have an important responsibility to keep signing so that the network can remain live. Also, if these keys are stolen the security of the bridge is at risk.

## List of Keys

* **Consensus key (validators)**
  * `~/.nomic-stakenet-3/tendermint/config/prev_validator_key.json`
  * Used to sign blocks on the Nomic blockchain.
* **Signatory key (signatories)**
  * `~/.nomic-stakenet-3/signer/xpriv`
  * Used to sign Bitcoin transactions for the bridge.
* **Wallet key (all nodes)**
  * `~/.orga-wallet/privkey`
  * Used to sign transactions created through the Nomic CLI (declaring a validator, transferring tokens, etc.)

*On testnet, the path will instead start with `~/.nomic-testnet-4d`*

## Backing Up

It is important to make backups of these keys, since losing them can be hard to recover from.

When backing up, ensure your keys are copied somewhere other than where you run your nodes - preferably on an offline machine, encrypted with a passphrase, or stored on other medium not vulnerable to malware such as paper.

## Migrating Validator Nodes

Sometimes it is necessary to move your keys to a different machine to start operating your node there. When you do this, make sure to transfer all the keys as listed above into their respective paths.

Additionally, make sure to transfer `~/.nomic-stakenet-3/tendermint/data/priv_validator_state.json`. This file ensures your node will not accidentally cause a double-sign, which is a slashable offense that will jail your validator.


# Listing in Codebase

If running a reliable node or relayer, you can help the network by listing them in the network config files so that others can automatically connect.

* Add public RPC URL(s) with port (preferably an HTTPS URL, which may require using a reverse proxy) to `state_sync_rpc`
* Add your Tendermint peer id (found in the `/status` RPC endpoint) and IP with port to `--p2p.seeds` in `tendermint_flags`
* If running a Bitcoin relayer, add the URL (preferably an HTTPS URL, which may require using a reverse proxy) to `btc_relayer`

## Stakenet

For Stakenet please make a GitHub issue or PR to the below file:

{% @github-files/github-code-block url="<https://github.com/nomic-io/nomic/blob/develop/networks/stakenet.toml>" %}

## Testnet

For Stakenet please make a GitHub issue or PR to the below file:

{% @github-files/github-code-block url="<https://github.com/nomic-io/nomic/blob/develop/networks/testnet.toml>" %}


# Integrating nBTC via IBC

IBC is a blockchain interoperability protocol used by 110+ chains. This page gives a high-level overview of how to integrate nBTC into any IBC-compatible chain.

## Prerequisites

As a prerequisite, follow the instructions to configure an [IBC relayer](/network/ibc-relayer) to work with Nomic. IBC transactions require the relayer account to be funded with a small amount of nBTC, as IBC-related transactions are charged a fee of 1 Satoshi each.

## Creating a channel

Once `hermes` is [configured for Nomic](/network/ibc-relayer), the next step is to create an IBC channel with Nomic.

```bash
hermes create channel --a-chain <your-chain-id> --b-chain nomic-stakenet-3 --a-port
transfer --b-port transfer --new-client-connection
```

Nomic currently requires both ends of the channel to use the "transfer" port.

## Relaying operator keys

To ensure that nBTC is recoverable by the remote chain's validator set in the event of an Emergency Disbursal, run:

```bash
nomic relay-op-keys <COUNTERPARTY-RPC> <CLIENT_ID>
```

This command may be re-run anytime to refresh the operator keys of the remote chain's validator set. If an Emergency Disbursal occurs on Nomic, a portion of the Bitcoin reserves equal to the nBTC held in channels backed by the specified client will become spendable by 2/3+ of the voting power of that network's top 30 validators.

## Interchain Deposits

Interchain Deposits allow the generation of Bitcoin addresses which commit to an ICS-20 token transfer packet, automatically forwarding any received funds to an address on the counterparty chain.

Interchain Deposits require communication with a [Bitcoin relayer](/network/bitcoin-relayer). The set of relayers used by your front-end should be selected with care.

After a channel has been opened between your chain and Nomic, see [`nomic-bitcoin-js`](https://www.npmjs.com/package/nomic-bitcoin) for information on generating and displaying deposit addresses.

### Withdrawals to Bitcoin

nBTC may be withdrawn as Bitcoin directly from the counterparty chain. ICS-20 transfer packets support a `memo` field. Providing a memo of the form "withdraw:\<dest>" for an incoming nBTC transfer packet to Nomic will trigger a withdrawal of the Bitcoin to `<dest>` at the next checkpoint. `<dest>` may be either:

1. A Bech32 Bitcoin address.
2. A hex-encoded Bitcoin script.


# Integrating nBTC on EVM

Nomic supports bridging Bitcoin to EVM-based chains.

## Contract Addresses

Nomic's decentralized custody bridging contract can be found at the following contract addresses:

<table><thead><tr><th width="185">Network</th><th>Bridge Contract Address</th></tr></thead><tbody><tr><td>Ethereum Mainnet</td><td><a href="https://etherscan.io/address/0xef0adb7bb6a97b037412946e4cb25d17836f6faa">0xef0adb7bb6a97b037412946e4cb25d17836f6faa</a></td></tr><tr><td>Ethereum Sepolia</td><td><a href="https://sepolia.etherscan.io/address/0x794bdA49337C667ED03265618821b944Ed11bcED">0x794bdA49337C667ED03265618821b944Ed11bcED</a></td></tr><tr><td>Ethereum Holešky</td><td><a href="https://holesky.etherscan.io/address/0x936366c13b43Ab6eC8f70A69038E9187fED0Cd1e">0x936366c13b43Ab6eC8f70A69038E9187fED0Cd1e</a></td></tr><tr><td>Berachain bArtio</td><td><a href="https://bartio.beratrail.io/address/0xea55b1E6df415b96C194146abCcE85e6f811CAb7">0xea55b1E6df415b96C194146abCcE85e6f811CAb7</a></td></tr></tbody></table>

nBTC on EVM-based chains is issued as an ERC-20 token at the following contract addresses:

<table><thead><tr><th width="185">Network</th><th>Token Contract Address</th></tr></thead><tbody><tr><td>Ethereum Mainnet</td><td><a href="https://etherscan.io/address/0x26a5eba128b5523bb7380f6a42c6c236cd9bdc12">0x26a5eba128b5523bb7380f6a42c6c236cd9bdc12</a></td></tr><tr><td>Ethereum Sepolia</td><td><a href="https://sepolia.etherscan.io/token/0xA229EaE06B1F8137461A9D309478da3C8d910E53">0xA229EaE06B1F8137461A9D309478da3C8d910E53</a></td></tr><tr><td>Ethereum Holešky</td><td><a href="https://holesky.etherscan.io/address/0x54360db096a2cb43b411f89a584da69a7bac0663">0x54360db096a2cb43b411f89a584da69a7bac0663</a></td></tr><tr><td>Berachain bArtio</td><td><a href="https://bartio.beratrail.io/address/0x45a1947cb7315ce9c569b011a6dee4f67813bb75">0x45a1947cb7315ce9c569b011a6dee4f67813bb75</a></td></tr></tbody></table>

Additional network contract addresses will be listed on here in the future, as well as documentation for creating your own customizable deployments in any EVM environment.

## Interchain Deposits

Interchain Deposits allow the generation of Bitcoin addresses which commit to a destination on an EVM-based chain, automatically forwarding any received funds as nBTC to a contract on that chain.

The EVM destination may be either:

* an Ethereum address to receive the nBTC;
* a contract call to be executed with the received nBTC.

Interchain Deposits require communication with [Bitcoin relayers](/network/bitcoin-relayer). The set of relayers used by your front-end should be selected with care.

See [`nomic-bitcoin-js`](https://www.npmjs.com/package/nomic-bitcoin) for more information on generating and displaying Bitcoin deposit addresses.

### Withdrawing to Bitcoin

Bitcoin may be withdrawn to a Bitcoin address directly via contract calls on EVM-based chains.

First, `approve` must be called on the token contract (see above table):

```typescript
web3.eth.abi.encodeFunctionCall({
    name: 'approve',
    type: 'function',
    inputs: [
    {
        type: 'address',
        name: 'spender'
    },
    {
        type: 'uint256',
        name: 'amount'
    }
    ]
}, [tokenContractAddress, usatAmount]);
```

Next, initiate the withdrawal to a Bitcoin address with a call to the bridge contract:

<pre class="language-typescript"><code class="lang-typescript"><strong>import { buildDestination } from 'nomic-bitcoin'
</strong><strong>
</strong><strong>let destination = buildDestination({
</strong><strong>    bitcoinAddress: 'tb1...'
</strong><strong>})
</strong><strong>
</strong><strong>web3.eth.abi.encodeFunctionCall({
</strong>    name: 'sendToNomic',
    type: 'function',
    inputs: [
    {
        type: 'address',
        name: '_tokenContract'
    },
    {
        type: 'string',
        name: '_destination'
    },
    {
        type: 'uint256',
        name: '_amount'
    }
    ]
}, [tokenContractAddress, destination, usatAmount]);
</code></pre>


# Emergency Disbursal

## Introduction

In the event of an extended liveness failure, for example, downtime caused by a bug or an attack, funds in typical custody systems and bridges remain inaccessible for an indefinite amount of time. The funds are stuck until the issue is resolved and signatories manually intervene, leaving depositors with no recourse.

Nomic protects against this by including an Emergency Disbursal mechanism, making user funds accessible even during a liveness failure.

## Mechanism

The Emergency Disbursal is conceptually simple: the network produces and signs timelocked Bitcoin transactions each time a new checkpoint transaction is made. If the next checkpoint confirms on the Bitcoin network, the UTXOs spent by the previous checkpoint transactions are now spent by the checkpoint. This invalidates the old Emergency Disbursal which is now atomically replaced by the new one.

### Transaction Structure

Nomic periodically moves funds in “[checkpoint transaction](broken://spaces/wouPLII4HXZ3uzgba1H6/pages/7MddoYvV6rxwIZWq4dGe#how-it-works)s”, which result in a “reserve output” that contains a pool of funds held in decentralized custody. The Emergency Disbursal makes up a tree of transactions: a set of “final transactions”, each including a large set of outputs to the recipients of the Emergency Disbursal and a single input, and a single “intermediate transaction” with outputs corresponding to the inputs of final transactions and a single input spending from the reserve output.

Outputs are split across multiple final transactions because of size constraints - Bitcoin’s default policies limit transactions to 100,000 virtual bytes. Assuming there are 100,000 accounts on the network, and each of these accounts receive a pay-to-pubkey-hash UTXO (34 bytes each), this would require over 3.4M vbytes of transaction data (a small amount of additional space is required for the base transaction fields and the inputs). This structure could then be made up of about 36 transactions, 1 intermediate transaction which directly spends the reserve output and has 35 outputs, and 35 transactions which spend outputs from the intermediate transaction and pay out to many P2PKH outputs (one for each account).

All final transactions and the intermediate transaction include a timelock at a timestamp in the future based on some parameter - e.g., two weeks. Since Bitcoin signatures commit to the inputs they spend, signed emergency disbursals will automatically be invalidated as soon as a newer checkpoint happens since it will spend the same reserve UTXO and become confirmed before the emergency disbursal unlocks.

For atomicity in moving the funds to a new checkpoint, the network first coordinates signing of the next checkpoint’s Emergency Disbursal transactions before advancing to the signatures for the checkpoint transaction. This ensures that if a liveness failure happens during the signing process, it is guaranteed that the most recently confirmed checkpoint has valid and signed Emergency Disbursal transactions spending from it.

### Fees

In order to pay for the high cost of Bitcoin network fees for the Emergency Disbursal transactions to be included in blocks, the proper fee amounts based on the network’s last known fee levels and the transaction and witness sizes are deducted from final transaction outputs. This cost is shared across all outputs, and results in any accounts which have too small of a balance to pay their share of the fee being pruned and becoming wholly paid into the shared fee.

In the event the Emergency Disbursal transactions pay too low of a fee and are not being confirmed in blocks, the transactions can be fee-bumped collectively by any recipients of final transactions if they simply spend their (unconfirmed) outputs with a high fee rate. Bitcoin mempools use the child-pays-for-parent fee rules meaning any recipient can help contribute additional fees to the network’s Emergency Disbursal transactions.

### Outputs

To convert onchain accounts into recipients of the Emergency Disbursal, we have to derive a Bitcoin script for each to include in a transaction output. Depending on the type of account, there are different ways to build Bitcoin scripts which can be spent by the intended user.

#### nBTC on Nomic

Native accounts on the Nomic chain each have an optional “recovery script” which can be set by the user at any point, to define the output script for their emergency disbursal payouts. The user simply has to pick a destination address and input it in their Nomic protocol client (e.g. [app.nomic.io](https://app.nomic.io/bitcoin)). Each new Emergency Disbursal will include an output with their latest recovery script and balance.

In the future, the protocol could potentially derive an output for all accounts, even those that do not set a recovery script. This is possible because Nomic account address hashes and keys are compatible with Bitcoin script (`ripemd160`, `sha256`, and `secp256k1`).

#### nBTC on Remote IBC Chains

If funds have been moved over a channel to a remote IBC chain based on Tendermint or CometBFT consensus, the Nomic network needs a different way to reason about paying out via the Emergency Disbursal. Instead of paying to individual users, since their balances may change and are not known on the Nomic chain, a multisig wallet is constructed instead, made from the keys of the top 40 validators.

To power IBC, the Nomic network already accepts relayed proofs of the current validator set of the remote chain. The validator set gets retained in the state, and additional proofs about the remote chain’s state are accepted in order to relay and verify the validator’s `secp256k1` operator keys. This process can happen automatically by third-party relayer nodes which carry data between both networks.

In the future, it could be possible to create an IBC standard to allow remote protocols, contracts, and users to set their own recovery scripts and have their balances tracked by the Nomic protocol to include individuals as recipients outside of the chain-wide multisig. However, care must be taken since this could mean there would be a short time where a user can hold a balance which is not currently reflected in the most recently created Emergency Disbursal transactions.

#### nBTC on Ethereum/EVM

On Ethereum, nBTC is deployed as an ERC-20 token representing BTC. For its Emergency Disbursal scheme, accounts can opt to set a recovery script, similar to native Nomic accounts. Once opted-in, transfers to and from the user will result in a call to the Nomic decentralized custody contract's `setEmergencyDisbursalBalance` function, queueing up a message to be relayed to the Nomic protocol which updates the user’s output in the next Emergency Disbursal.

Note that unlike native Nomic accounts, this system does not reflect users’ balance changes into their Emergency Disbursal output until the next checkpoint update. However, this is only a temporary condition (at most, a period of hours but often a period of minutes) - nBTC transfers can be considered to have “soft finality” when the ERC-20 token transfer confirms on Ethereum, and “hard finality” once signed into a Nomic checkpoint.

#### Decentralized Custody Contracts on EVM

On EVM-based networks, usage of the Nomic network happens via bridge contracts deployed by different projects that opt to use Nomic’s decentralized BTC custody. These consumers of the bridge contract can arbitrarily assign the BTC they hold into Emergency Disbursal outputs at any time via the `setEmergencyDisbursalBalance(bytes script, u64 amount)` contract call.

This means that consumers of Nomic’s decentralized custody can choose their own paradigm for updating the Emergency Disbursal payouts for their users - a necessary flexibility since contracts could represent relationships more complex than simple user accounts (for instance, the BTC may be collateral in a loan, or be in a DAO-owned treasury).


