Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial sbtc docs update #1647

Merged
merged 22 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
235 changes: 123 additions & 112 deletions SUMMARY.md

Large diffs are not rendered by default.

51 changes: 32 additions & 19 deletions concepts/sbtc/README.md
kenrogers marked this conversation as resolved.
Show resolved Hide resolved
kenrogers marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,35 +1,48 @@
# sBTC
## Introduction to sBTC

To understand sBTC, we first need to understand the current limitations of Bitcoin (BTC).
sBTC is a SIP-010 token on the Stacks blockchain that represents Bitcoin (BTC) in a 1:1 ratio. It enables Bitcoin holders to participate in DeFi applications and other smart contract functionalities while maintaining a peg to the underlying Bitcoin.

Bitcoin is to date the most secure and decentralized blockchain. While Bitcoin is the largest cryptocurrency by market cap, comparatively few applications exist within the Bitcoin ecosystem. Developers interested in building applications for the Bitcoin community often find it difficult or impossible to implement their logic directly on the Bitcoin chain. Although Bitcoin has a simple scripting system built in, it lacks the expressiveness of many other smart contract languages.
### Purpose

sBTC is for:
The primary purpose of sBTC is to bridge Bitcoin to DeFi via the Stacks blockchain, providing Bitcoin holders with access to the rich functionality of smart contracts without sacrificing the security and value of their BTC holdings.

* Bitcoin holders who want to participate in smart contracts.
* Developers who want to build applications on Bitcoin.
### Key Benefits

sBTC empowers developers to build applications on Bitcoin by bridging Bitcoin and [Stacks](https://www.stacks.co/). We achieve this by introducing a fungible token (sBTC) on the Stacks blockchain. The token has the following properties:
1. **Bitcoin Compatibility**: Allows Bitcoin holders to participate in the Stacks ecosystem without selling their BTC.
2. **Quick Conversions**: Facilitates rapid movement between BTC and sBTC (within 3 Bitcoin blocks for deposit, 6 for withdrawal).
3. **Decentralized Management**: Initially utilizes a set of 15 community-chosen signers for maintaining the peg wallet.
4. **Community Governance**: Involves the community in key decisions, such as selecting the initial signing set.

* **1:1 redeemability**. sBTC can always be exchanged 1:1 for BTC on the Bitcoin chain, as long as the Stacks blockchain is operational.
* **Open membership**. Anyone can participate in the sBTC protocol. No centralized entity maintains custody over any BTC in the protocol.
## Key Concepts

Other tokens which try to achieve the same end as sBTC are
Understanding sBTC requires familiarity with several key concepts:

* [xBTC](https://www.stacks.co/blog/tokensoft-wrapped-fundamental-bitcoin-defi-building-blocks-xbtc)
### sBTC

While these tokens all achieve the same value as BTC, they maintain BTC reserves through trusted entities. sBTC is the only truly decentralized Bitcoin backed asset on Stacks.
sBTC is a [SIP-010](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) token on the Stacks Blockchain that can be converted back to BTC on the Bitcoin Blockchain. The key property of sBTC is its 1:1 peg to Bitcoin, meaning 1 sBTC is always equivalent to 1 BTC.

## How does sBTC work?
### sBTC UTXO

Bitcoin holders can do two things to interact with sBTC, deposit and withdraw. Both of these operations are controlled through special Bitcoin transactions.
The sBTC UTXO is the single unspent transaction output (UTXO) on the Bitcoin blockchain that holds the entire BTC balance pegged into sBTC. This UTXO is managed and maintained by the set of sBTC Signers.

To deposit BTC into sBTC, a Bitcoin holder would create a deposit transaction on the Bitcoin chain. This deposit transaction informs the protocol how much BTC the holder has deposited, and to which Stacks address the holder wishes to receive the sBTC. The sBTC system responds to the deposit transaction by minting sBTC to the given Stacks address.
### sBTC Signer

To withdraw BTC, a Bitcoin holder creates a withdrawal transaction on the Bitcoin chain. This withdrawal transaction informs the protocol how much sBTC the holder wishes to withdraw, from which stacks address the sBTC should be withdrawn and which Bitcoin address should receive the withdrawn BTC. In response to this transaction, the sBTC system burns the requested amount of sBTC from the given Stacks address and fulfills the withdrawal by issuing a BTC payment to the given BTC address with the same amount.
In sBTC, the sBTC Signer is a signer entity separate from the Stacks Nakamoto signer. sBTC signer responsibilities include:

The following diagram illustrates the deposit and withdrawal flows.
- Signing sBTC operations
- Communicating with the sBTC contracts on the Stacks chain
- Managing the sBTC UTXO

<figure><img src="../../.gitbook/assets/Diagram Feb 2 2024.png" alt=""><figcaption></figcaption></figure>
### sBTC Signer Set

Next let's take a deeper look at the design of sBTC.
The sBTC Signer Set is the group of all sBTC signers. This set has full democratic access to the sBTC UTXO and is responsible for maintaining the security of the peg wallet. The signers also have the ability to rotate their private keys for enhanced security.

### Emily API

kenrogers marked this conversation as resolved.
Show resolved Hide resolved
Emily is an API that helps facilitate and supervise the sBTC Bridge in addition to serving as a programmatic liaison between sBTC users and signers.

### SIP-010 Token

sBTC adheres to the [SIP-010](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) standard for fungible tokens on the Stacks blockchain. This ensures compatibility with wallets and applications that support the SIP-010 standard.

Understanding these concepts is crucial for grasping the overall architecture and functionality of sBTC. In the following sections, we'll explore how these concepts come together to create sBTC.
8 changes: 8 additions & 0 deletions concepts/sbtc/auxiliary-features/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Auxiliary Features

This section covers additional features that enhance the functionality and security of the sBTC system:

1. [Transaction Fee Sponsorship](fee-sponsorship.md): Allowing sBTC transactions to be sponsored
2. [Signer Wallet Rotation](signer-wallet-rotation.md): Enabling secure key rotation for sBTC Signers

These auxiliary features contribute to the overall robustness and user-friendliness of the sBTC ecosystem.
31 changes: 31 additions & 0 deletions concepts/sbtc/auxiliary-features/fee-sponsorship.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Transaction Fee Sponsorship

Transaction Fee Sponsorship is a feature in sBTC that allows users to pay for Stacks transaction fees using sBTC instead of STX.

## Overview

- sBTC transactions on Stacks can be sponsored in return for some sBTC.
- This feature improves user experience by allowing sBTC holders to use their tokens for gas fees.

## Implementation

The fee sponsorship system is implemented using the approach suggested in [stacks-network/stacks-core#4235](https://github.com/stacks-network/stacks-core/issues/4235).

Key points:

1. sBTC users can get support from existing STX holders for transaction fees.
2. The sponsor pays the STX fee and receives sBTC in return.

## User Experience

From a user's perspective:

1. When initiating an sBTC transaction, they can opt for fee sponsorship.
2. The user agrees to pay a small amount of sBTC for the sponsorship.
3. The transaction is then processed with the fees paid in STX by the sponsor.

## Benefits

1. **Improved UX**: Users don't need to hold STX to use sBTC.
2. **Lower Barrier to Entry**: New users can start using sBTC without first acquiring STX.
3. **Flexibility**: Provides an additional option for handling transaction fees.
41 changes: 41 additions & 0 deletions concepts/sbtc/auxiliary-features/signer-wallet-rotation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Signer Wallet Rotation

Signer Wallet Rotation is a crucial security feature in the sBTC system that allows sBTC Signers to rotate their private keys securely.

## Overview

- sBTC Signers have the ability to rotate their private keys.
kenrogers marked this conversation as resolved.
Show resolved Hide resolved
- This feature enhances the long-term security of the sBTC system.
- Key rotation is coordinated among signers and requires on-chain voting by the signers.

## Process

1. Signers coordinate offline to initiate the key rotation process.
2. Signers vote on-chain for the new signer set (new set of keys).
3. Once the new signer set is determined, signers conduct a wallet handoff.
4. The signers re-execute the Distributed Key Generation (DKG) process.

## Implementation

The Signer Wallet Rotation process is facilitated by:

1. **Signer Key Rotation CLI**: Allows individual signers to initiate a private key rotation.
2. **Key Rotation Clarity Contracts**: Handle the on-chain aspects of the rotation process.

## Security Considerations

- The rotation process must ensure that the sBTC UTxO remains secure throughout the transition.
- Proper coordination among signers is crucial to prevent any disruption in sBTC operations.
- The new keys must be thoroughly verified before being put into use.

## Benefits

1. **Enhanced Security**: Regular key rotations reduce the risk of key compromise.
2. **Flexibility**: Allows for the replacement of compromised or lost keys.
3. **Continuity**: Enables long-term operation of the sBTC system with evolving security measures.

## Best Practices

- Signers should rotate their keys on a regular schedule (e.g., every 6 months).
- Emergency rotation procedures should be in place for suspected key compromises.
- The rotation process should be audited and tested regularly to ensure smooth execution when needed.
119 changes: 119 additions & 0 deletions concepts/sbtc/clarity-contracts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# sBTC Clarity Contracts Documentation

This document provides an overview and detailed explanation of the [sBTC Clarity contracts](https://github.com/stacks-network/sbtc/tree/main/contracts). These contracts are designed to facilitate the creation, management, and transfer of sBTC tokens on the Stacks blockchain.

## Contracts Overview

1. [sbtc-bootstrap-signers](#sbtc-bootstrap-signers)
2. [sbtc-deposit](#sbtc-deposit)
3. [sbtc-registry](#sbtc-registry)
4. [sbtc-token](#sbtc-token)
5. [sbtc-withdrawal](#sbtc-withdrawal)

## sbtc-bootstrap-signers

This contract manages the signer set for the sBTC protocol.

### Key Functions

- `rotate-keys-wrapper`: Rotates the keys of the signers when the signer set is updated.
- `pubkeys-to-spend-script`: Generates the p2sh redeem script for a multisig.
- `pubkeys-to-principal`: Generates a principal given a set of pubkeys and an m-of-n threshold.

### Constants

- `key-size`: The required length of public keys (33 bytes).
- `ERR_KEY_SIZE`: Error code for invalid key size.
- `ERR_INVALID_CALLER`: Error code for unauthorized function caller.
- `ERR_SIGNATURE_THRESHOLD`: Error code for invalid signature threshold.

## sbtc-deposit

This contract handles the deposit of BTC to mint sBTC.

### Key Functions

- `complete-deposit-wrapper`: Completes a deposit request, minting sBTC to the recipient.
- `complete-deposits-wrapper`: Handles multiple deposit requests in a single transaction.

### Constants

- `txid-length`: The required length of a transaction ID (32 bytes).
- `dust-limit`: The minimum amount of satoshis that can be deposited (546 sats).
- `ERR_TXID_LEN`: Error code for invalid transaction ID length.
- `ERR_DEPOSIT_REPLAY`: Error code for attempting to complete an already processed deposit.
- `ERR_LOWER_THAN_DUST`: Error code for deposits below the dust limit.
- `ERR_INVALID_CALLER`: Error code for unauthorized function caller.

## sbtc-registry

This contract serves as the central registry for the sBTC protocol, managing withdrawal requests, deposits, and signer data.

### Key Functions

- `create-withdrawal-request`: Creates a new withdrawal request.
- `complete-withdrawal-accept`: Marks a withdrawal request as accepted.
- `complete-withdrawal-reject`: Marks a withdrawal request as rejected.
- `complete-deposit`: Records a completed deposit.
- `rotate-keys`: Updates the signer set, multi-sig principal, and aggregate public key.

### Data Structures

- `withdrawal-requests`: Map storing withdrawal request details.
- `withdrawal-status`: Map storing the status of withdrawal requests.
- `completed-deposits`: Map storing completed deposit information.
- `aggregate-pubkeys`: Map storing aggregate public keys to prevent replay attacks.
- `multi-sig-address`: Map storing multi-sig addresses to prevent replay attacks.
- `protocol-contracts`: Map storing active protocol contracts.

## sbtc-token

This contract implements the sBTC token, following the [SIP-010](https://github.com/stacksgov/sips/blob/main/sips/sip-010/sip-010-fungible-token-standard.md) fungible token standard.

### Key Functions

- `protocol-transfer`: Transfers sBTC between accounts (only callable by protocol contracts).
- `protocol-lock`: Locks sBTC by burning tokens and minting locked tokens.
- `protocol-unlock`: Unlocks sBTC by burning locked tokens and minting regular tokens.
- `protocol-mint`: Mints new sBTC tokens.
- `protocol-burn`: Burns sBTC tokens.
- `transfer`: Transfers sBTC tokens (implements SIP-010).

### Token Properties

- `token-name`: The name of the token ("sBTC").
- `token-symbol`: The symbol of the token ("sBTC").
- `token-uri`: Optional URI for token metadata.
- `token-decimals`: The number of decimal places for the token (8).

## sbtc-withdrawal

This contract handles the withdrawal of sBTC to receive BTC.

### Key Functions

- `initiate-withdrawal-request`: Initiates a new withdrawal request.
- `accept-withdrawal-request`: Accepts and processes a withdrawal request.
- `reject-withdrawal-request`: Rejects a withdrawal request.
- `complete-withdrawals`: Processes multiple withdrawal requests in a single transaction.

### Constants

- `MAX_ADDRESS_VERSION`: Maximum value of a valid address version (6).
- `MAX_ADDRESS_VERSION_BUFF_20`: Maximum address version for 20-byte hash addresses (4).
- `MAX_ADDRESS_VERSION_BUFF_32`: Maximum address version for 32-byte hash addresses (6).
- `DUST_LIMIT`: Minimum amount of sBTC that can be withdrawn (546 sats).

### Error Codes

- `ERR_INVALID_ADDR_VERSION`: Invalid address version.
- `ERR_INVALID_ADDR_HASHBYTES`: Invalid address hash bytes.
- `ERR_DUST_LIMIT`: Withdrawal amount below dust limit.
- `ERR_INVALID_REQUEST`: Invalid withdrawal request ID.
- `ERR_INVALID_CALLER`: Unauthorized function caller.
- `ERR_ALREADY_PROCESSED`: Withdrawal request already processed.
- `ERR_FEE_TOO_HIGH`: Paid fee higher than requested.

## Conclusion

Collectively, these contracts work together to create a decentralized system for managing sBTC, a synthetic representation of Bitcoin on the Stacks blockchain. The contracts handle key operations such as minting sBTC through deposits, burning sBTC through withdrawals, managing the signer set, and maintaining the overall state of the protocol.
83 changes: 83 additions & 0 deletions concepts/sbtc/clarity-contracts/sbtc-deposit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# sBTC Deposit Contract Documentation

## Overview

The [sBTC Deposit contract](https://github.com/stacks-network/sbtc/blob/main/contracts/contracts/sbtc-deposit.clar) (`sbtc-deposit.clar`) manages the deposit process for the sBTC system. It handles the validation and minting of sBTC tokens when users deposit Bitcoin, and interacts with the sBTC Registry contract to update the protocol state.

## Constants

- `txid-length`: The required length of a transaction ID (32 bytes).
- `dust-limit`: The minimum amount for a valid deposit (546 satoshis).

## Error Constants

- `ERR_TXID_LEN` (u300): Indicates that the provided transaction ID is not the correct length.
- `ERR_DEPOSIT_REPLAY` (u301): Signifies an attempt to replay a deposit that has already been completed.
- `ERR_LOWER_THAN_DUST` (u302): Indicates that the deposit amount is below the dust limit.
- `ERR_DEPOSIT_INDEX_PREFIX`: Used as a prefix for deposit-related errors in batch processing.
- `ERR_DEPOSIT` (u303): General deposit error.
- `ERR_INVALID_CALLER` (u304): Indicates that the caller is not authorized to perform the operation.

## Public Functions

### complete-deposit-wrapper

Processes a single deposit request.

- Parameters:
- `txid`: `(buff 32)` - The Bitcoin transaction ID
- `vout-index`: `uint` - The output index of the deposit transaction
- `amount`: `uint` - The amount of sBTC to mint (in satoshis)
- `recipient`: `principal` - The Stacks address to receive the minted sBTC
- Returns: `(response bool uint)`

Function flow:

1. Verifies that the caller is the current signer principal.
2. Checks that the deposit amount is above the dust limit.
3. Validates the transaction ID length.
4. Ensures the deposit hasn't been processed before (prevents replay).
5. Mints sBTC tokens to the recipient.
6. Updates the deposit state in the sBTC Registry contract.

### complete-deposits-wrapper

Processes multiple deposit requests in a single transaction.

- Parameters:
- `deposits`: `(list 650 {txid: (buff 32), vout-index: uint, amount: uint, recipient: principal})` - List of deposit data
- Returns: `(response uint uint)`

Function flow:

1. Verifies that the caller is the current signer principal.
2. Iterates through the list of deposits, processing each one using the `complete-individual-deposits-helper` function.

## Private Functions

### complete-individual-deposits-helper

Helper function to process individual deposits within the batch operation.

- Parameters:
- `deposit`: `{txid: (buff 32), vout-index: uint, amount: uint, recipient: principal}` - Single deposit data
- `helper-response`: `(response uint uint)` - Accumulator for tracking processed deposits
- Returns: `(response uint uint)`

Function flow:

1. Calls `complete-deposit-wrapper` for the individual deposit.
2. If successful, increments the processed deposit count.
3. If an error occurs, it's propagated with additional index information.

## Interactions with Other Contracts

- `.sbtc-registry`: Calls `get-current-signer-data`, `get-completed-deposit`, and `complete-deposit` to manage deposit state.
- `.sbtc-token`: Calls `protocol-mint` to create new sBTC tokens.

## Security Considerations

1. Access Control: Only the current signer principal can call the deposit completion functions.
2. Replay Prevention: The contract checks for previously processed deposits to prevent replay attacks.
3. Dust Limit: Enforces a minimum deposit amount to prevent spam and ensure economic viability.
4. Transaction ID Validation: Ensures the provided transaction ID is the correct length.
Loading
Loading