Difference between revisions of "Chain-key Bitcoin"

From Internet Computer Wiki
Jump to: navigation, search
m
(Editing and adding information from the ckBTC design document (https://docs.google.com/document/d/18n33mTyvZaaisN8KU4FeliITbrL8zrUCKxv6tVfXPH0/edit?pli=1#heading=h.kknwh0c6ltfe) as requested and discussed with @Thomas Locher)
Line 1: Line 1:
 
== Overview ==
 
== Overview ==
  
Chain-key Bitcoin (ckBTC) is a token on the Internet Computer that is backed 1:1 by bitcoin (BTC) such that 1 ckBTC can always be redeemed for 1 BTC and vice versa.
+
Chain-key Bitcoin (ckBTC) is a token on the Internet Computer that is backed 1:1 by Bitcoin (BTC) such that 1 ckBTC can always be redeemed for 1 BTC and vice versa.
  
Unlike other tokens pegged to bitcoin, the ckBTC token does not rely on a third-party bridge for the conversion between BTC and ckBTC, making it a substantially more secure alternative to “wrapped” tokens.
+
Unlike other tokens pegged to Bitcoin, the ckBTC token does not rely on a third-party bridge for the conversion between BTC and ckBTC, making it a substantially more secure alternative to “wrapped” tokens.
  
While chain-key bitcoin and regular bitcoin have the same value, the advantage of chain-key bitcoin is fast and cheap transfers: A transfer is finalized within a few seconds (a speed-up of roughly three orders of magnitude compared to transfers on the Bitcoin blockchain) and only costs 0.0000001 ckBTC (approximately two orders of magnitude lower than the Bitcoin miner fees).  
+
While chain-key Bitcoin and regular Bitcoin have the same value, the advantage of chain-key Bitcoin is fast and cheap transfers: A transfer is finalized within a few seconds (a speed-up of roughly three orders of magnitude compared to transfers on the Bitcoin blockchain) and only costs 0.0000001 ckBTC (approximately two orders of magnitude lower than the Bitcoin miner fees).  
  
 
== Architecture ==
 
== Architecture ==
Line 11: Line 11:
 
The ckBTC functionality is built upon the [[Bitcoin integration]] of the Internet Computer, which makes it possible for canisters to receive, hold, and send bitcoin.
 
The ckBTC functionality is built upon the [[Bitcoin integration]] of the Internet Computer, which makes it possible for canisters to receive, hold, and send bitcoin.
  
There are two canisters, the ckBTC minter and ckBTC ledger, that together provide the ckBTC functionality. The ckBTC minter mints new ckBTC tokens whenever it receives bitcoin. Likewise, it burns ckBTC tokens whenever an owner of ckBTC tokens requests a withdrawal of bitcoin.
+
There are two canisters, the ckBTC minter and ckBTC ledger, that together provide the ckBTC functionality. The ckBTC minter mints new ckBTC tokens whenever it receives Bitcoin. Likewise, it burns ckBTC tokens whenever an owner of ckBTC tokens requests a withdrawal of Bitcoin. The ckBTC minter needs to receive BTC, based on a large number of confirmations due to the lack of finality in Bitcoin, before it mints the same amount in ckBTC and it burns ckBTC before it transfers BTC back to the users.
The ckBTC ledger is [https://github.com/dfinity/ICRC-1/blob/main/standards/ICRC-1/README.md ICRC-1 compliant], updating the balance accounts when ckBTC tokens are transferred and executing the mint and burn operations coming from the ckBTC minter.
+
 
 +
A best-effort approach is used for the transfer of BTC to the users, i.e., the user cannot get the burned ckBTC back. Rather, the ckBTC minter repeatedly attempts to transfer BTC out. Note that “user” refers to the caller of the functions exposed by the ckBTC minter and ckBTC ledger in the following. A human user or another canister may be behind the function invocations.
 +
 
 +
The ckBTC ledger is [https://github.com/dfinity/ICRC-1/blob/main/standards/ICRC-1/README.md ICRC-1 compliant], updating the balance accounts when ckBTC tokens are transferred and executing the mint and burn operations coming from the ckBTC minter.  
 +
 
 
An overview of the basic architecture is depicted in the following figure.
 
An overview of the basic architecture is depicted in the following figure.
 
[[File:CkBTC Specification - Overview (Version 2).png|alt=|center|thumb|600x600px|High-level overview of chain-key Bitcoin.]]
 
[[File:CkBTC Specification - Overview (Version 2).png|alt=|center|thumb|600x600px|High-level overview of chain-key Bitcoin.]]
 
The figure shows the main flow at a high level of abstraction: Users interact with the ckBTC minter and the ckBTC ledger to convert ckBTC/BTC and transfer ckBTC, respectively. The ckBTC minter interacts with the Bitcoin canister to retrieve information about the Bitcoin network state and send Bitcoin transactions.
 
The figure shows the main flow at a high level of abstraction: Users interact with the ckBTC minter and the ckBTC ledger to convert ckBTC/BTC and transfer ckBTC, respectively. The ckBTC minter interacts with the Bitcoin canister to retrieve information about the Bitcoin network state and send Bitcoin transactions.
  
The ckBTC minter further interacts with the [[Know-Your-Transaction (KYT) Canister|KYT canister]] for "know-your-transaction" (KYT) checks. These checks are meant to ensure that the ckBTC minter only uses "clean" bitcoins to back the issued ckBTC tokens and to prevent transferring bitcoins to Bitcoin addresses that are considered to be associated with illicit activity. As such, these KYT checks provide an additional layer of security to ckBTC users.
+
The ckBTC minter further interacts with the [[Know-Your-Transaction (KYT) Canister|KYT canister]] for "know-your-transaction" (KYT) checks. These checks are meant to ensure that the ckBTC minter only uses "clean" Bitcoins to back the issued ckBTC tokens and to prevent transferring Bitcoins to Bitcoin addresses that are considered to be associated with illicit activity. As such, these KYT checks provide an additional layer of security to ckBTC users.
  
 
== Technical Details ==
 
== Technical Details ==
 +
 +
=== Bitcoin Addresses ===
 +
Within this page, Bitcoin addresses are implicitly understood to be of type P2WPKH (“pay to witness public key hash”) as defined in [https://en.bitcoin.it/wiki/BIP_0141 BIP-141]. All addresses are rendered in the Bech32 format as defined in [https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki BIP-173]. The main advantage of P2WPKH over the legacy P2PKH address type is that its use results in lower transaction fees.
 +
 +
For this reason, it is the default address type in most wallets for standard transactions.
  
 
=== ckBTC Ledger ===
 
=== ckBTC Ledger ===
 +
The ckBTC ledger is a [https://dashboard.internetcomputer.org/canister/mxzaz-hqaaa-aaaar-qaada-cai canister], controlled by the NNS (specifically, the [https://dashboard.internetcomputer.org/canister/r7inp-6aaaa-aaaaa-aaabq-cai NNS root canister]), running on the [https://dashboard.internetcomputer.org/subnet/pzp6e-ekpqk-3c5x7-2h6so-njoeq-mt45d-h3h6c-q3mxf-vpeq5-fk5o7-yae pzp6e] subnet. Since it is ICRC-1 compliant, it offers [https://github.com/dfinity/ICRC-1/blob/aa82e52aaa74cc7c5f6a141e30b708bf42ede1e3/standards/ICRC-1/README.md#methods all functions] defined in the ICRC-1 standard. In particular, it provides the functionality to transfer ckBTC between accounts.
 +
 +
The ckBTC ledger is responsible for keeping account balances and for transferring ckBTC between accounts. It provides the following functionality:
 +
 +
* It enables the ckBTC minter to mint and burn ckBTC.
 +
* It enables the transfer of ckBTC among users.
  
The ckBTC ledger is a [https://dashboard.internetcomputer.org/canister/mxzaz-hqaaa-aaaar-qaada-cai canister], controlled by the NNS (specifically, the [https://dashboard.internetcomputer.org/canister/r7inp-6aaaa-aaaaa-aaabq-cai NNS root canister]), running on the [https://dashboard.internetcomputer.org/subnet/pzp6e-ekpqk-3c5x7-2h6so-njoeq-mt45d-h3h6c-q3mxf-vpeq5-fk5o7-yae pzp6e] subnet. Since it is ICRC-1 compliant, it offers [https://github.com/dfinity/ICRC-1/blob/aa82e52aaa74cc7c5f6a141e30b708bf42ede1e3/standards/ICRC-1/README.md#methods all functions] defined in the ICRC-1 standard. In particular, it provides the functionality to transfer ckBTC between accounts. As mentioned above, the transfer fee is 0.0000001 ckBTC.
+
As mentioned above, the transfer fee is 0.0000001 ckBTC, the equivalent of 10 Satoshi. Since the fee in ckBTC is burned, every transaction leads to a growing surplus in BTC controlled by the ckBTC minter. The surplus will eventually be used to cover the cycle cost of the ckBTC minter.  
  
The minting account is the ckBTC minter’s default account, that is, the account derived from the ckBTC minter’s principal ID and the all-zero subaccount.
+
The minting account is the ckBTC minter’s default account; that is, the account derived from the ckBTC minter’s principal ID and the all-zero subaccount.
  
The initial supply of the ckBTC ledger is 0. ckBTC tokens are minted only when the ckBTC minter receives bitcoin, ensuring that the ckBTC supply managed by the ckBTC ledger is upper bounded by the amount of bitcoin held by the ckBTC minter.
+
The initial supply of the ckBTC ledger is 0. ckBTC tokens are minted only when the ckBTC minter receives Bitcoin, ensuring that the ckBTC supply managed by the ckBTC ledger is upper bounded by the amount of Bitcoin held by the ckBTC minter.
  
 
=== ckBTC Minter ===
 
=== ckBTC Minter ===
  
The ckBTC minter is a [https://dashboard.internetcomputer.org/canister/mqygn-kiaaa-aaaar-qaadq-cai canister] that is controlled by the NNS and running on the [https://dashboard.internetcomputer.org/subnet/pzp6e-ekpqk-3c5x7-2h6so-njoeq-mt45d-h3h6c-q3mxf-vpeq5-fk5o7-yae pzp6e] subnet as well. It has a few important configuration parameters including:
+
The ckBTC minter is a [https://dashboard.internetcomputer.org/canister/mqygn-kiaaa-aaaar-qaadq-cai canister] that is controlled by the NNS and running on the [https://dashboard.internetcomputer.org/subnet/pzp6e-ekpqk-3c5x7-2h6so-njoeq-mt45d-h3h6c-q3mxf-vpeq5-fk5o7-yae pzp6e] subnet as well.
 +
 
 +
The ckBTC minter is the canister responsible for managing deposited BTC and minting/burning ckBTC based on the amount of deposited BTC. It provides the following functionality:
 +
 
 +
* For a certain principal ID and an optional subaccount, it returns a specific Bitcoin address under the ckBTC minter’s control.
 +
* Users can inform the ckBTC minter about Bitcoins that were sent to an address controlled by the ckBTC minter. If the balance has increased, the ckBTC minter mints the same amount in ckBTC for the user associated with the Bitcoin address.
 +
* Users can ask the ckBTC minter to track the balance of a Bitcoin address until new funds are received, which then automatically triggers the minting of the equivalent amount of ckBTC.
 +
* Users can request to get bitcoins back. The ckBTC minter burns the same amount of ckBTC and transfers the Bitcoins to the address provided by the user.
 +
 
 +
The ckBTC minter canister has a few important configuration parameters including:
  
 
* <code>retrieve_btc_min_amount</code>: This is the minimum ckBTC amount that can be burned and, correspondingly, the minimum BTC amount that can be withdrawn. The parameter is set to 0.001 BTC, or 100,000 satoshi.
 
* <code>retrieve_btc_min_amount</code>: This is the minimum ckBTC amount that can be burned and, correspondingly, the minimum BTC amount that can be withdrawn. The parameter is set to 0.001 BTC, or 100,000 satoshi.
Line 38: Line 62:
 
* <code>kyt_fee</code>: The fee that must be paid for KYT checks. It is currently set to 2000 satoshi.
 
* <code>kyt_fee</code>: The fee that must be paid for KYT checks. It is currently set to 2000 satoshi.
 
The other parameters are self-explanatory and can be found in the [https://github.com/dfinity/ic/blob/master/rs/bitcoin/ckbtc/minter/ckbtc_minter.did ckBTC minter Candid file].
 
The other parameters are self-explanatory and can be found in the [https://github.com/dfinity/ic/blob/master/rs/bitcoin/ckbtc/minter/ckbtc_minter.did ckBTC minter Candid file].
 +
 +
=== State Management ===
 +
 +
==== Managed Addresses ====
 +
A Bitcoin address that is controlled by the ckBTC minter and has a positive balance is called a managed address. If the balance of a managed address reduces to zero, the address is no longer managed and can be removed from the state.
 +
 +
Note that it is possible to increase the balance again, in which case the address becomes managed again.
 +
 +
==== Unspent Transaction Outputs ====
 +
Once a new Unspent Transaction Output (UTXO) under the control of the ckBTC minter is discovered (using the <code>update_balance</code> function), it is stored internally in a set called <code>available_utxos</code> (defined [https://github.com/dfinity/ic/blob/2348b094d3d27616ee3f049d3048baa1da8d625a/rs/bitcoin/ckbtc/minter/src/state.rs#L305C14-L305C14 here] in the source code).
 +
 +
All discovered UTXOs remain in this set until a Bitcoin transaction is created to spend one or more of them when retrieving Bitcoins. When a transaction is created spending some UTXOs, these UTXOs are removed from the set <code>available_utxos</code> and inserted in the <code>used_utxos</code> field of the <code>SubmittedBtcTransaction</code> struct (defined [https://github.com/dfinity/ic/blob/70d19f16c17f8f42987a46d473ba27705927cdb7/rs/bitcoin/ckbtc/minter/src/state.rs#L87 here] in the source code), which is the internal representation of a Bitcoin transaction.
 +
 +
A UTXO is removed from the ckBTC state when the <code>SubmittedBtcTransaction</code> struct that contains the UTXO is removed from the state.
 +
 +
==== Transactions ====
 +
To provide information about current transactions, outgoing transactions must be cached. A transaction is cached until its inputs are no longer considered unspent based on a large number of confirmations.
 +
 +
Every transaction that the ckBTC minter creates has an output that sends the ckBTC minter fee plus the transaction change back to its main BTC address (P2WPKH address derived from its public key with an empty derivation path) using the Bitcoin integration’s <code>get_utxos</code> function.
 +
 +
A transaction can be removed from the cache if the transaction output that belongs to the ckBTC minter appears in the returned list when calling <code>get_utxos</code> with sufficient confirmations for the ckBTC minter’s main BTC address.
 +
 +
The ckBTC minter may resubmit transactions, making use of Bitcoin’s request by fee (RBF) mechanism as defined in [https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki BIP-125]. In the case of ckBTC, a resubmission adds a transaction to the cache that spends exactly the same UTXOs as the transaction it replaces. The only difference is that the BTC amount sent to the user is reduced in order to increase the fee.
 +
 +
BIP-125 states that at most 100 transactions may be evicted from the mempool, i.e., the fee cannot be increased more than 100 times. Moreover, the fee must be increased at least by the minimum relay fee (see minrelaytxfee [https://en.bitcoin.it/wiki/Miner_fees#Relaying here]) of 1 Satoshi/vbyte.
 +
 +
For example, if we assume a minimum increase of 200 Satoshi (the minimum fee for a basic segwit transaction with one input and one output is 192 Satoshi and the number per output is always lower than 200 if there are at least as many outputs as inputs), the minimum transfer amount should be at least 20,000 Satoshi which equals 0.0002 BTC. When adding a base fee at a large fee rate of 100 Satoshi/vbyte and assuming a virtual transaction size of 200 vbyte per output, we get a minimum transfer amount of 0.0004 BTC. Adding a security margin, we define the minimum retrieval amount to be <code>MIN_RETRIEVAL_AMOUNT = 0.001 BTC</code>.
 +
 +
''To ensure that every transaction can potentially be updated, the RBF flag must be set on every transaction.''
 +
 +
==== Know Your Transaction & Fees ====
 +
Before UTXOs are accepted, they undergo a know-your-transaction (KYT) check where information about the UTXO is sent to a “KYT canister”, which interacts with KYT service providers, such as Chainalysis, to check if the UTXO is “clean” using HTTPS outcalls.
 +
 +
In a similar fashion, there is a KYT check of the destination address when attempting to transfer Bitcoins out of the ckBTC minter.
 +
 +
Both of these KYT checks incur fees, charged in ckBTC:
 +
 +
* The KYT fee is subtracted from the amount to be minted and the amount transferred out.
 +
* The KYT fee is 2000 satoshi per KYT check.
 +
 +
The KYT canister supports multiple KYT access key providers, called maintainers, each having a principal ID and (secret) access key to the external KYT service. Since the maintainers pay for their subscriptions, they must be remunerated. To this end, the ckBTC minter maintains a mapping of maintainers to the owed amount, which is the number of KYT checks that were performed with the respective maintainer’s credentials times the KYT fee of 2000 Satoshi.
 +
 +
Each successful response from the KYT canister contains the principal ID of the maintainer so that the ckBTC minter can update the owed amount correctly. Once every 24 hours, the ckBTC minter pays out the owed amounts in ckBTC to all maintainers.
 +
 +
== Converting BTC to ckBTC ==
 +
 +
In this section, the process to convert BTC to ckBTC is explained, making use of the ckBTC minter and ckBTC ledger endpoints.
 +
 +
The first step is for the user to determine the Bitcoin address where the user is supposed to transfer Bitcoin for the minting process by calling the <code>get_btc_address</code> endpoint. Next, the user transfers the desired BTC amount to this Bitcoin address. Subsequently, the user calls the <code>track_balance</code> endpoint to inform the ckBTC minter that it is about to receive Bitcoins at the given address.
 +
 +
Internally, the tracking works as follows. Since the expected time between Bitcoin blocks is 10 minutes, the ckBTC minter first checks if new unspent transaction outputs (UTXOs) are available for that address with at least the required number of confirmations after <code>10*min_confirmations</code> minutes. If there is at least one new UTXO, tracking stops and the ckBTC minter instructs the ckBTC ledger to mint the same amount of ckBTC tokens into the account derived from the principal ID and the subaccount.
 +
 +
If no new UTXOs are discovered with sufficiently many confirmations, the ckBTC ledger checks if there are new UTXOs with at least one confirmation. If this is not the case, tracking stops as well. Otherwise, the expected time until the first new UTXO reaches the desired number of confirmations is computed, which is 10 minutes times the difference between the desired number of confirmations and the current number of confirmations. The same process then repeats until ckBTC tokens are minted or tracking stops.
 +
 +
It is evident from this description that it’s possible that tracking may stop before ckBTC tokens are minted, for example, if it takes an unusually long time until the transaction appears in a block. In this case, the endpoint can be invoked again. Alternatively, the user can wait until the transaction has the required number of confirmations and call the <code>update_balance</code> endpoint.
 +
 +
The following figure depicts the conversion flow using the <code>track_balance</code> endpoint.
 +
[[File:CkBTC Specification - Submission (simplified) - Version 2.png|alt=|center|thumb|600x600px|Process of converting BTC to ckBTC.]]
 +
 +
 +
In this figure, the ckBTC minter discovers the new UTXO after the waiting period by calling <code>get_utxos</code> on the Bitcoin canister. As mentioned above, it is possible that it may take several interactions with the Bitcoin canister until the transaction has received sufficiently many confirmations before the ckBTC minter issues the mint transaction to the ckBTC ledger. After a successful KYT check, the ckBTC ledger is instructed to mint ckBTC tokens for the user. The minted amount corresponds to the value of the UTXO minus the KYT fee.
 +
 +
=== Technical Details ===
 +
As mentioned above, a call to the <code>update_balance</code> endpoint triggers a call to the Bitcoin canister to get UTXOs for the Bitcoin address associated with the given <code>principal-subaccount</code> pair. Let '''''R''''' denote the set of returned UTXOs. The following pseudo-code illustrates how the UTXOs are processed:<syntaxhighlight lang="rust">
 +
for utxo in new_utxos(R):        // R = set of received UTXOs in the get_utxos call
 +
    if utxo.value >= KYT_FEE:
 +
        if utxo in checked_utxos:

 +
            (uuid, state) = checked_utxos.get(utxo)
 +
        else:
 +
            (uuid, state, kyt_provider) = kyt_canister.check(utxo).await?
 +
            if state == clean:
 +
                D = D \ {utxo}
 +
                P = P ∪ {utxo}
 +
                checked_utxos.set(utxo, (uuid, clean))
 +
                owed_kyt_fee[kyt_provider] += KYT_FEE
 +
        if state == clean:
 +
            ckbtc_ledger.mint(utxo.value-KYT_FEE, recipient_account, uuid).await?

 +
            checked_utxos.remove(utxo)

 +
        else:
 +
            add_to_quarantine_list(utxo)
 +
    else:
 +
        add_to_ignore_list(utxo)
 +
return response with UTXO statuses
 +
</syntaxhighlight>A UTXO is considered if its value is at least the KYT fee, which is a configuration parameter of the ckBTC minter. UTXOs whose value lie below the KYT fee are added to an ignore list. The additional state <code>checked_utxos</code> is maintained to remember that a UTXO was checked if the state is clean. Once the corresponding amount of ckBTC has been minted, this state can be removed again. If the UTXO is tainted, it is moved to a quarantine list instead. UTXOs in the ignore list and quarantine list remain there.
 +
 +
The function <code>new_utxos</code> filters out all UTXOs on the ignore list, the quarantine list, and the sets '''''P''''' and '''''S'''''. On the other hand, the <code>checked_utxos</code> data structure is not considered.
 +
 +
=== Automated Tracking ===
 +
The <code>update_balance</code> function only triggers a minting operation if the corresponding Bitcoin transaction has sufficient confirmations, which implies that it is the user’s responsibility to check the number of confirmations before making the <code>update_balance</code> call.
 +
 +
In order to improve the user experience, the additional endpoint <code>track_balance</code>, with the same parameters as <code>update_balance</code>, is provided. When invoked instead of <code>update_balance</code>, the ckBTC minter starts tracking the Bitcoin address derived from the provided principal ID and subaccount using the <code>get_btc_address</code> endpoint. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.
 +
 +
The balance of the Bitcoin address is not tracked indefinitely. Tracking is stopped if either at least one new unspent transaction output (UTXO) is discovered or there is no new UTXO within a certain time interval as defined in the following:
 +
 +
* Since the expected time between Bitcoin blocks is 10 minutes, the ckBTC minter first checks if new UTXOs are available for that address with at least the required number of confirmations after <code>10*MIN_CONFIRMATIONS</code> minutes.
 +
* If there is at least one new UTXO, tracking stops and the same flow as for <code>update_balance</code> is triggered. If the KYT check is successful, the ckBTC minter instructs the ckBTC ledger to mint the same amount of ckBTC tokens minus the KYT fee into the account derived from the principal ID and the subaccount.
 +
* If no new UTXOs are discovered with sufficiently many confirmations, the ckBTC ledger checks if there are new UTXOs with at least one confirmation. If this is not the case, tracking stops as well. Otherwise, the expected time until the first new UTXO reaches the desired number of confirmations is computed, which is 10 minutes times the difference between the desired number of confirmations and the current number of confirmations. The next check is scheduled after this many minutes and the process repeats until a new UTXO is discovered or tracking stops.
 +
 +
 +
It is evident from this description that it is possible that tracking may stop before ckBTC tokens are minted, for example, if it takes an unusually long time until the transaction appears in a block. In this case, the endpoint can be invoked again. Alternatively, the user can wait until the transaction has the required number of confirmations and call the <code>update_balance</code> endpoint.
 +
 +
== Converting ckBTC to BTC ==
 +
 +
The process to convert ckBTC to BTC consists of the following steps:
 +
 +
# Transfer request: The user moves the ckBTC that he/she wants to convert to BTC to a special ckBTC withdrawal account under the control of the ckBTC minter and requests a transfer. The destination Bitcoin address undergoes a KYT check. If the check is successful, the request is accepted and put into a queue.
 +
# Submission: On a heartbeat, the ckBTC minter attempts to submit transactions for validated transfer requests.
 +
# Finalization: On a heartbeat, the ckBTC minter checks which transactions went through and finalizes these transactions.
 +
# Resubmission: The ckBTC minter can resubmit a transaction that has been pending at least for a specific amount of time with a higher fee.
 +
 +
The individual parts are discussed in greater detail in the following sections.
 +
 +
The first step to convert ckBTC to BTC is to transfer the amount to be retrieved to the owner-specific withdrawal account under the ckBTC minter’s control. This step is required because only the ckBTC minter can burn tokens and it can only burn those tokens in one of its accounts. The withdrawal account can be obtained by calling the <code>get_withdrawal_account</code> endpoint.
 +
 +
After the user has transferred the desired ckBTC amount to the withdrawal account, the user can call the <code>retrieve_btc</code> endpoint to inform the ckBTC minter about the withdrawal intent. In addition to specifying the withdrawal amount, the Bitcoin address where the withdrawn funds are to be sent must be specified as well.
 +
 +
The ckBTC minter first performs a KYT check against the targeted Bitcoin address. If the check is successful, the ckBTC minter instructs the ckBTC ledger to burn the ckBTC in the withdrawal account. Lastly, the ckBTC minter deducts the KYT fee from the amount to be retrieved and puts the corresponding retrieval request into a queue and checks the status of the queue on a heartbeat.
 +
 +
If the oldest request has been in the queue for at least 10 minutes or at least 20 retrieval requests have been accumulated at the time of the heartbeat, the ckBTC minter creates a single Bitcoin transaction to serve up to 100 retrieval requests as follows:
 +
 +
# It selects available UTXOs with a total sum of at least the sum in the retrieval requests.
 +
# It constructs a Bitcoin transaction with the selected UTXOs as inputs and an output for each retrieval request plus an additional output for the ckBTC minter’s fee.
 +
# It uses the Bitcoin canister’s fee API to determine an appropriate fee for the transaction, using the median fee rate.
 +
# It distributes the fee evenly among all outputs other than the output for the ckBTC minter’s fee.
 +
# For each input of the transaction, the ckBTC minter invokes the threshold ECDSA functionality (calling the <code>sign_with_ecdsa</code> function) to obtain the required signatures and puts them into the transaction.
 +
# Lastly, it sends the Bitcoin transaction by invoking the <code>send_transaction</code> function of the Bitcoin integration API.
 +
 +
The BTC retrieval process is depicted in the following figure.
 +
[[File:CkBTC Specification - Withdrawal (simplified)- Version 2.png|alt=|center|thumb|600x600px|Process of converting ckBTC to BTC.]]
 +
 +
 +
Note that the amounts in the transfer to the withdrawal account and the retrieval request need not be the same. The <code>retrieve_btc_status</code> endpoint can be used to query the current status of a retrieval request.
 +
 +
=== Technical Details ===
 +
 +
==== Transfer Request ====
 +
The ckBTC minter can only burn ckBTC under its control. Therefore, the first step is to transfer ckBTC to the ckBTC withdrawal account controlled by the ckBTC minter and associated with the owner of the ckBTC that are to be burned. Specifically, the withdrawal account is a ckBTC ledger account where the principal ID is the ckBTC minter and the subaccount is derived deterministically from the owner’s principal ID.
 +
 +
After this transfer, the user sends a <code>retrieve_btc</code> request, specifying the amount that they would like to retrieve, the Bitcoin address where the funds are to be transferred, and, optionally, a fee level (which have yet to be defined).
 +
 +
Upon receiving such a request, the ckBTC minter first performs a KYT check against the Bitcoin address where funds are supposed to be sent. If the check is successful, the ckBTC minter issues a burn request to the ckBTC ledger, burning the amount in the received request in the user’s ckBTC withdrawal account. If the burn operation is successful, the ckBTC minter creates a transfer request, removing the <code>KYT_FEE</code> from the transfer amount, and appends it to its pending-requests queue.
 +
 +
Alternatively, if the destination address does not pass the KYT check, a burn request is sent to the ckBTC ledger, burning the <code>KYT_FEE</code> amount.
 +
 +
The steps of a successful request are illustrated in the following figure.
 +
 +
Recall that the ckBTC ledger uses the ckBTC minter default account as the minting account. Withdrawal accounts should never resolve to the default minting account because the ckBTC ledger considers the minting account for minting only.
 +
 +
The following pseudo-code illustrates how the <code>retrieve_btc</code> endpoint works, given the parameters <code>amount</code> and <code>btc_address</code>.<syntaxhighlight lang="rust">
 +
assert(amount >= max(MIN_RETRIEVAL_AMOUNT, KYT_FEE))
 +
    assert(ckbtc_ledger.balance_of(withdrawal_account).await? >= amount)
 +
  (uuid, state, kyt_provider) = kyt_canister.check(btc_address).await?

 +
 +
if state == clean:
 +
    index = ckbtc_ledger.burn(amount, withdrawal_account).await?
 +
    owed_kyt_fee[kyt_provider] += KYT_FEE
 +
    create_request(amount-KYT_FEE, index, btc_address, uuid)
 +
else:
 +
    index = ckbtc_ledger.burn(KYT_FEE, withdrawal_account).await?

 +
    owed_kyt_fee[kyt_provider] += KYT_FEE
 +
    return Error("Failed KYT check", index)
 +
</syntaxhighlight>Note that a failure to perform the KYT check results in a rejected request. Further note that if the KYT check succeeds but the burn transaction fails (regardless of the state of the KYT response), no KYT fee is charged and the request is rejected. A subsequent request with the same parameters will result in another call to the KYT canister again, which is acceptable because multiple identical calls to the KYT service provider do not result in increased fees.
 +
 +
For each retrieval request, the ckBTC minter stores the following data:
 +
 +
* <code>block_index</code>: The block index of the burn operation used to burn the ckBTC. Since the block index is unique, it is used as the request ID.
 +
* <code>amount</code>: The total amount of tokens to retrieve. This amount must be at least the minimum retrieval amount as defined above.
 +
* <code>address</code>: The address where the Bitcoins will be sent.
 +
* <code>received_at</code>: The timestamp when the request was received.
 +
* <code>fee_level</code>: If no fee level is provided, a medium fee level is used.
 +
 +
==== Submission ====
 +
The ckBTC minter uses the heartbeat mechanism to initiate Bitcoin transfers. On a heartbeat, the following steps are carried out:
 +
 +
# Check if there is at least one request that is 10 minutes old or there are at least 20 requests in the pending-requests queue. If not, stop.
 +
# Update the balance of the ckBTC minter’s main BTC address (the P2WPKH address derived from its public key with an empty derivation path) using the Bitcoin integration’s <code>get_utxos</code> function.
 +
# Determine the total amount of Bitcoins available, which is the sum of all Bitcoins in processed UTXOs, plus Bitcoins under the ckBTC minter’s main BTC address.
 +
# Call the transfer function with the next batch of requests with the same fee level that can be served given the total amount of available Bitcoins. A transaction is created, setting the transaction ID for each request in the batch, and sent to the Bitcoin network.
 +
# Every request in this batch is then moved to the unconfirmed-transfers queue.
 +
 +
As evident from the steps outlined above, the transfer function can handle multiple requests at the same time. Handling multiple requests in a single transaction has several advantages over sending individual transactions:
 +
 +
# Requests can possibly be served more quickly, especially if the ckBTC minter must wait for change to return to its main BTC address.
 +
# As the fee for the non-input bytes is shared, the fee per request is slightly lower.
 +
# Serving multiple requests at the same time makes denial-of-service attacks where an attacker attempts to keep the pool of usable UTXOs empty with many small requests harder.
 +
 +
Given this set of requests, the next step is to select UTXOs for the transaction.
 +
 +
Since UTXOs are always spent entirely, the difference between the sum of Bitcoins in the spent UTXOs and the requested amount must be transferred to a new UTXO as well. The ckBTC minter uses its main BTC address to accumulate “change”.
 +
 +
All UTXOs of its main BTC address are immediately transferred to the corresponding set '''''P''''' of processed UTXOs. The reason is that there is no minting for the balances in these UTXOs.
 +
 +
The transfer function performs the following steps:
 +
 +
# First, the transfer function determines the “target”, the total number t (≤ T) of Bitcoins that must be transferred out to handle all requests in the given batch.
 +
# Then, the function selects UTXOs for the transaction from one or more sets '''''P''''' of its managed addresses. The selected UTXOs are moved from the sets '''''P''''' to the corresponding sets '''''S'''''.
 +
# Next, the Bitcoin transaction is built and computes the fee based on current Bitcoin fees (using the <code>get_current_fee_percentiles</code> Bitcoin integration endpoint) and the size of the transaction. The fee rate in Satoshi/vbyte is determined by the fee level. Note that the fee is deducted by splitting it evenly among the handled retrieval requests, deducting the same fraction of the total fee from each output that is not returning change and the ckBTC minter fee to the ckBTC minter. The ckBTC minter fee is <code>246*in + 7*out + 52 Satoshi</code>, where in and out denote the number of transaction inputs and outputs, respectively (as specified here).
 +
# Every input is signed using the threshold ECDSA interface.
 +
# Finally, the transaction is submitted using the <code>send_transaction</code> Bitcoin integration endpoint.
 +
 +
The following UTXO selection algorithm, in pseudo-code, is used:<syntaxhighlight lang="rust">
 +
// t = target (satoshis), P = Union of all sets of processed UTXOs
 +
// Pre-condition: sum(P) >= t
 +
select_utxos(t, P):
 +
    return greedy(t, P)
 +
 +
greedy(t, A):               // t = target, A = Available UTXOs
 +
    if t ≤ 0 or |A| = 0: return {}
 +
    m := max(A)            // The UTXO with the largest value
 +
    if m.value < t:
 +
        return {m} ∪ greedy(t-m.value, A \ {m})
 +
    else:
 +
        return min({p ∊ A | p.value ≥ t})
 +
 +
</syntaxhighlight>The algorithm has the following properties:
 +
 +
* It uses the smallest number of UTXOs possible for the given target.
 +
* If a single UTXO suffices, it uses the UTXO that results in the smallest change.
 +
 +
Once the transaction is sent, the requests are moved to the unconfirmed-transfers queue.
 +
 +
==== Finalization ====
 +
The ckBTC minter uses the heartbeat mechanism to determine the status of sent transactions as well. Specifically, the ckBTC minter periodically wakes up and checks the state of the requests in the unconfirmed-transfers queue.The  ckBTC minter checks the UTXOs of its main account to determine which transactions have sufficiently many confirmations.
 +
 +
Such requests can then be stored in a confirmed-transfers queue for some time in order to enable a more long-term look-up of the transaction status.
 +
 +
==== Resubmission ====
 +
It is possible that it takes a long time for a transaction to be included in a block. If fees increase significantly for some time, a transaction may even be stuck for a long time or dropped entirely. While the ckBTC minter enforces a reasonable fee through its fee levels, it may still be necessary to issue a transaction again because burned ckBTC are never returned and UTXOs are never freed and are thus stuck when the transaction spending these UTXOs is stuck.
 +
 +
The ckBTC minter resubmits a transaction that has not been confirmed within a certain number of hours. Given that the ckBTC minter always waits for many confirmations, the waiting time will likely be multiple hours up to one day, though this parameter has not been defined yet.
 +
 +
The new transaction will use the UTXOs reserved for the requests. The transaction will be identical except that the outputs for each user will be reduced due to the increased fee. The new fee is the sum of the old transaction fee plus the size of the transaction (in vbytes) times the minimum relay fee of 1 Satoshi/vbyte plus the ckBTC minter fee again because it must acquire new signatures and send the new transaction to the Bitcoin canister.
 +
 +
== Fees ==
 +
 +
The ckBTC canisters run on an application subnet and must be self-sustainable. Rather than charging cycles for the endpoints, the ckBTC minter accumulates a surplus of BTC over time. In the future, the ckBTC minter will mint ckBTC to get the total ckBTC supply and the BTC amount under the ckBTC minter's control to match. The ckBTC minter can then trade these extra ckBTC tokens for cycles to charge both the ckBTC minter and ckBTC ledger.
 +
 +
There is a growing surplus of BTC because there is a ckBTC transfer fee of 0.0000001 ckBTC, which is burned, and a ckBTC minter fee when retrieving BTC. The latter is determined as follows:
 +
 +
* Under the conservative assumption that 1 BTC = 10,000 XDR, 1 billion cycles corresponds to 10 Satoshi (because 1 trillion cycles corresponds to 1 XDR).
 +
* The [https://internetcomputer.org/docs/current/developer-docs/deploy/computation-and-storage-costs/ cost] to obtain a single EDCSA signature is approximately 21.54 billion cycles on a 28-node subnet, whereas sending a Bitcoin transaction costs 5 billion cycles plus 20 million cycles per byte.
 +
 +
Given these numbers, the cost to sign and send a transaction with <code>in</code> inputs and <code>out</code> outputs is
 +
 +
21.54b*in + 5b + tx_size*20m cycles
 +
< 21.54b*in + 5b + (149*in + 35*out + 10)*20m cycles
 +
< 24.52b*in +0.7b*out + 5.2b cycles
 +
< 246*in + 7*out + 52 satoshi.
 +
 +
The formula <code>246*in + 7*out + 52</code> is used to determine the ckBTC minter’s fee in satoshi. Since every transaction has at least one input and one output, the fee is at least 305 Satoshi.
 +
 +
This conservative pricing strategy is used to subsidize the other endpoints, which are free of charge. Moreover, while the <code>retrieve_btc</code> endpoint is relatively expensive, the fee is typically still lower than the Bitcoin miner fee.
 +
 +
As mentioned above, there is also a KYT fee (currently 2000 Satoshi) when converting BTC to ckBTC and vice versa.
 +
 +
== ckBTC Minter API ==
  
 
The ckBTC minter provides the following endpoints:
 
The ckBTC minter provides the following endpoints:
Line 52: Line 332:
 
* <code>get_events</code>: Returns a set of events at the ckBTC minter.
 
* <code>get_events</code>: Returns a set of events at the ckBTC minter.
  
The endpoints are discussed in more detail in the following.
+
The endpoints are discussed in more detail in the following sections.
  
==== get_btc_address(owner: opt principal, subaccount: opt blob) ====
+
==== <code>get_btc_address(owner: opt principal, subaccount: opt blob)</code> ====
  
 
The provided principal ID and subaccount are concatenated to form the derivation path for the [https://internetcomputer.org/docs/current/references/ic-interface-spec#ic-ecdsa_public_key ecdsa_public_key] function, which returns the derived public key. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.
 
The provided principal ID and subaccount are concatenated to form the derivation path for the [https://internetcomputer.org/docs/current/references/ic-interface-spec#ic-ecdsa_public_key ecdsa_public_key] function, which returns the derived public key. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.
Line 62: Line 342:
 
Note that the key derivation is not [https://en.bitcoin.it/wiki/BIP_0032 BIP-32] compliant where 31 bits are used for each derivation level. Instead, a single derivation is performed based on the full principal ID and subaccount. Since the derivation is deterministic, a canister can derive the Bitcoin address for a given principal ID and subaccount itself.
 
Note that the key derivation is not [https://en.bitcoin.it/wiki/BIP_0032 BIP-32] compliant where 31 bits are used for each derivation level. Instead, a single derivation is performed based on the full principal ID and subaccount. Since the derivation is deterministic, a canister can derive the Bitcoin address for a given principal ID and subaccount itself.
  
==== track_balance(owner: opt principal, subaccount: opt blob) ====
+
==== <code>track_balance(owner: opt principal, subaccount: opt blob)</code> ====
 
'''NOTE: This endpoint is work-in-progress and not available yet.'''
 
'''NOTE: This endpoint is work-in-progress and not available yet.'''
  
Line 71: Line 351:
 
If at least one new UTXO is discovered, the same amount of ckBTC tokens minus the KYT fee are minted and made available to the owner.
 
If at least one new UTXO is discovered, the same amount of ckBTC tokens minus the KYT fee are minted and made available to the owner.
  
==== update_balance(owner: opt principal, subaccount: opt blob) ====
+
==== <code>update_balance(owner: opt principal, subaccount: opt blob)</code> ====
  
 
Instead of having the ckBTC minter track the balance of a Bitcoin address, the <code>update_balance</code> function can be invoked to instruct the ckBTC minter to check if there are new UTXOs for a particular Bitcoin address.
 
Instead of having the ckBTC minter track the balance of a Bitcoin address, the <code>update_balance</code> function can be invoked to instruct the ckBTC minter to check if there are new UTXOs for a particular Bitcoin address.
Line 79: Line 359:
 
The ckBTC minter effectively invokes this endpoint itself on a timer when the <code>track_balance</code> function is used.
 
The ckBTC minter effectively invokes this endpoint itself on a timer when the <code>track_balance</code> function is used.
  
==== estimate_withdrawal_fee(amount: opt nat64) ====
+
==== <code>estimate_withdrawal_fee(amount: opt nat64)</code> ====
 
The endpoint returns an estimate for the fee that must be paid when retrieving the given BTC amount. Internally, a transaction is built (without valid signatures) to determine the fee, which consists of the Bitcoin miner fee, the ckBTC minter fee, and the KYT fee. If no amount is provided, it is assumed that three inputs are required to build the transaction.
 
The endpoint returns an estimate for the fee that must be paid when retrieving the given BTC amount. Internally, a transaction is built (without valid signatures) to determine the fee, which consists of the Bitcoin miner fee, the ckBTC minter fee, and the KYT fee. If no amount is provided, it is assumed that three inputs are required to build the transaction.
  
Line 86: Line 366:
 
The fee can change when a) a new Bitcoin block is mined in the meantime, which causes the Bitcoin canister to update the Bitcoin miner fees or b) another retrieval request is handled first, spending some of the outputs that were used when estimating the fee.
 
The fee can change when a) a new Bitcoin block is mined in the meantime, which causes the Bitcoin canister to update the Bitcoin miner fees or b) another retrieval request is handled first, spending some of the outputs that were used when estimating the fee.
  
==== get_deposit_fee ====
+
==== <code>get_deposit_fee</code> ====
 
The endpoint returns the fee that the ckBTC minter charges for minting ckBTC when receiving new UTXOs. Currently, this fee is simply the KYT fee.
 
The endpoint returns the fee that the ckBTC minter charges for minting ckBTC when receiving new UTXOs. Currently, this fee is simply the KYT fee.
  
==== get_withdrawal_account ====
+
==== <code>get_withdrawal_account</code> ====
  
 
The function returns the caller’s withdrawal account, which is the account derived from the ckBTC minter’s principal ID and the subaccount derived from the caller’s principal ID.
 
The function returns the caller’s withdrawal account, which is the account derived from the ckBTC minter’s principal ID and the subaccount derived from the caller’s principal ID.
Line 95: Line 375:
 
A user can only retrieve BTC by first transferring ckBTC to this particular account.
 
A user can only retrieve BTC by first transferring ckBTC to this particular account.
  
==== retrieve_btc(address: text, amount: nat64) ====
+
==== <code>retrieve_btc(address: text, amount: nat64)</code> ====
  
 
The function instructs the ckBTC minter to burn the specified amount. Once the request is picked up from the queue, a Bitcoin transaction is created containing an output that transfers the requested amount (minus fees as discussed below) to the specified Bitcoin address.
 
The function instructs the ckBTC minter to burn the specified amount. Once the request is picked up from the queue, a Bitcoin transaction is created containing an output that transfers the requested amount (minus fees as discussed below) to the specified Bitcoin address.
Line 101: Line 381:
 
Since Bitcoin retrieval is handled asynchronously, the function returns the block index of the transaction burning the ckBTC tokens.
 
Since Bitcoin retrieval is handled asynchronously, the function returns the block index of the transaction burning the ckBTC tokens.
  
==== retrieve_btc_status(block_index: nat64) ====
+
==== <code>retrieve_btc_status(block_index: nat64)</code> ====
  
 
The status of a BTC retrieval request can be checked using this function. The different possible statuses are:
 
The status of a BTC retrieval request can be checked using this function. The different possible statuses are:
Line 113: Line 393:
 
* <code>Confirmed</code>: The Bitcoin transaction serving the BTC retrieval request is confirmed inside the ckBTC minter, which happens when the transaction has at least the minimum required number of confirmations specified in the min_confirmations parameter above.
 
* <code>Confirmed</code>: The Bitcoin transaction serving the BTC retrieval request is confirmed inside the ckBTC minter, which happens when the transaction has at least the minimum required number of confirmations specified in the min_confirmations parameter above.
  
==== get_minter_info ====
+
==== <code>get_minter_info</code> ====
 
The function returns the following parameters internal to the ckBTC minter:
 
The function returns the following parameters internal to the ckBTC minter:
  
Line 120: Line 400:
 
* <code>retrieve_btc_min_amount</code>
 
* <code>retrieve_btc_min_amount</code>
  
==== get_events(start: nat64, length: nat64) ====
+
==== <code>get_events(start: nat64, length: nat64)</code> ====
  
 
The ckBTC minter tracks the events that change its internal state. Given a start index and a length parameter, the ckBTC minter returns all events sequentially from the event at the given start index up to the event at index start+length-1.
 
The ckBTC minter tracks the events that change its internal state. Given a start index and a length parameter, the ckBTC minter returns all events sequentially from the event at the given start index up to the event at index start+length-1.
  
 
Note that this endpoint is used for debugging purposes and there is no guarantee that the endpoint will continue to exist in this form.
 
Note that this endpoint is used for debugging purposes and there is no guarantee that the endpoint will continue to exist in this form.
 
=== Converting BTC to ckBTC ===
 
 
In this section, the process to convert BTC to ckBTC is explained, making use of the ckBTC minter and ckBTC ledger endpoints.
 
 
The first step is for the user to determine the Bitcoin address where the user is supposed to transfer bitcoin for the minting process by calling the <code>get_btc_address</code> endpoint. Next, the user transfers the desired BTC amount to this Bitcoin address. Subsequently, the user calls the <code>track_balance</code> endpoint to inform the ckBTC minter that it is about to receive bitcoins at the given address.
 
 
Internally, the tracking works as follows. Since the expected time between Bitcoin blocks is 10 minutes, the ckBTC minter first checks if new unspent transaction outputs (UTXOs) are available for that address with at least the required number of confirmations after <code>10*min_confirmations</code> minutes. If there is at least one new UTXO, tracking stops and the ckBTC minter instructs the ckBTC ledger to mint the same amount of ckBTC tokens into the account derived from the principal ID and the subaccount.
 
 
If no new UTXOs are discovered with sufficiently many confirmations, the ckBTC ledger checks if there are new UTXOs with at least one confirmation. If this is not the case, tracking stops as well. Otherwise, the expected time until the first new UTXO reaches the desired number of confirmations is computed, which is 10 minutes times the difference between the desired number of confirmations and the current number of confirmations. The same process then repeats until ckBTC tokens are minted or tracking stops.
 
 
It is evident from this description that it’s possible that tracking may stop before ckBTC tokens are minted, for example, if it takes an unusually long time until the transaction appears in a block. In this case, the endpoint can be invoked again. Alternatively, the user can wait until the transaction has the required number of confirmations and call the <code>update_balance</code> endpoint.
 
 
The following figure depicts the conversion flow using the <code>track_balance</code> endpoint.
 
[[File:CkBTC Specification - Submission (simplified) - Version 2.png|alt=|center|thumb|600x600px|Process of converting BTC to ckBTC.]]
 
 
 
In this figure, the ckBTC minter discovers the new UTXO after the waiting period by calling <code>get_utxos</code> on the Bitcoin canister. As mentioned above, it is possible that it may take several interactions with the Bitcoin canister until the transaction has received sufficiently many confirmations before the ckBTC minter issues the mint transaction to the ckBTC ledger. After a successful KYT check, the ckBTC ledger is instructed to mint ckBTC tokens for the user. The minted amount corresponds to the value of the UTXO minus the KYT fee.
 
 
=== Converting ckBTC to BTC ===
 
 
The first step to convert ckBTC to BTC is to transfer the amount to be retrieved to the owner-specific withdrawal account under the ckBTC minter’s control. This step is required because only the ckBTC minter can burn tokens and it can only burn those tokens in one of its accounts. The withdrawal account can be obtained by calling the <code>get_withdrawal_account</code> endpoint.
 
 
After the user has transferred the desired ckBTC amount to the withdrawal account, the user can call the <code>retrieve_btc</code> endpoint to inform the ckBTC minter about the withdrawal intent. In addition to specifying the withdrawal amount, the Bitcoin address where the withdrawn funds are to be sent must be specified as well.
 
 
The ckBTC minter first performs a KYT check against the targeted Bitcoin address. If the check is successful, the ckBTC minter instructs the ckBTC ledger to burn the ckBTC in the withdrawal account. Lastly, the ckBTC minter deducts the KYT fee from the amount to be retrieved and puts the corresponding retrieval request into a queue and checks the status of the queue on a heartbeat.
 
 
If the oldest request has been in the queue for at least 10 minutes or at least 20 retrieval requests have been accumulated at the time of the heartbeat, the ckBTC minter creates a single Bitcoin transaction to serve up to 100 retrieval requests as follows:
 
 
# It selects available UTXOs with a total sum of at least the sum in the retrieval requests.
 
# It constructs a Bitcoin transaction with the selected UTXOs as inputs and an output for each retrieval request plus an additional output for the ckBTC minter’s fee.
 
# It uses the Bitcoin canister’s fee API to determine an appropriate fee for the transaction, using the median fee rate.
 
# It distributes the fee evenly among all outputs other than the output for the ckBTC minter’s fee.
 
# For each input of the transaction, the ckBTC minter invokes the threshold ECDSA functionality (calling the <code>sign_with_ecdsa</code> function) to obtain the required signatures and puts them into the transaction.
 
# Lastly, it sends the Bitcoin transaction by invoking the <code>send_transaction</code> function of the Bitcoin integration API.
 
 
The BTC retrieval process is depicted in the following figure.
 
[[File:CkBTC Specification - Withdrawal (simplified)- Version 2.png|alt=|center|thumb|600x600px|Process of converting ckBTC to BTC.]]
 
 
 
Note that the amounts in the transfer to the withdrawal account and the retrieval request need not be the same. The <code>retrieve_btc_status</code> endpoint can be used to query the current status of a retrieval request.
 
 
=== Fees ===
 
 
The ckBTC canisters run on an application subnet and must be self-sustainable. Rather than charging cycles for the endpoints, the ckBTC minter accumulates a surplus of BTC over time. In the future, the ckBTC minter will mint ckBTC to get the total ckBTC supply and the BTC amount under the ckBTC minter's control to match. The ckBTC minter can then trade these extra ckBTC tokens for cycles to charge both the ckBTC minter and ckBTC ledger.
 
 
There is a (growing) surplus of BTC because there is a ckBTC transfer fee of 0.0000001 ckBTC, which is burned, and a ckBTC minter fee when retrieving BTC. The latter is determined as follows. Under the conservative assumption that 1 BTC = 10,000 XDR, 1 billion cycles corresponds to 10 satoshi (because 1 trillion cycles corresponds to 1 XDR). The [https://internetcomputer.org/docs/current/developer-docs/deploy/computation-and-storage-costs/ cost] to obtain a single EDCSA signature is approximately 21.54 billion cycles on a 28-node subnet, whereas sending a Bitcoin transaction costs 5 billion cycles plus 20 million cycles per byte.
 
 
Given these numbers, the cost to sign and send a transaction with <code>in</code> inputs and <code>out</code> outputs is
 
 
21.54b*in + 5b + tx_size*20m cycles
 
< 21.54b*in + 5b + (149*in + 35*out + 10)*20m cycles
 
< 24.52b*in +0.7b*out + 5.2b cycles
 
< 246*in + 7*out + 52 satoshi.
 
 
The formula <code>246*in + 7*out + 52</code> is used to determine the ckBTC minter’s fee in satoshi. Since every transaction has at least one input and one output, the fee is at least 305 satoshi.
 
 
This conservative pricing strategy is used to subsidize the other endpoints, which are free of charge. Moreover, while the <code>retrieve_btc</code> endpoint is relatively expensive, the fee is typically still lower than the Bitcoin miner fee.
 
 
As mentioned above, there is also a KYT fee (currently 2000 satoshi) when converting BTC to ckBTC and vice versa.
 
  
 
== See also ==
 
== See also ==

Revision as of 17:19, 17 July 2023

Overview

Chain-key Bitcoin (ckBTC) is a token on the Internet Computer that is backed 1:1 by Bitcoin (BTC) such that 1 ckBTC can always be redeemed for 1 BTC and vice versa.

Unlike other tokens pegged to Bitcoin, the ckBTC token does not rely on a third-party bridge for the conversion between BTC and ckBTC, making it a substantially more secure alternative to “wrapped” tokens.

While chain-key Bitcoin and regular Bitcoin have the same value, the advantage of chain-key Bitcoin is fast and cheap transfers: A transfer is finalized within a few seconds (a speed-up of roughly three orders of magnitude compared to transfers on the Bitcoin blockchain) and only costs 0.0000001 ckBTC (approximately two orders of magnitude lower than the Bitcoin miner fees).

Architecture

The ckBTC functionality is built upon the Bitcoin integration of the Internet Computer, which makes it possible for canisters to receive, hold, and send bitcoin.

There are two canisters, the ckBTC minter and ckBTC ledger, that together provide the ckBTC functionality. The ckBTC minter mints new ckBTC tokens whenever it receives Bitcoin. Likewise, it burns ckBTC tokens whenever an owner of ckBTC tokens requests a withdrawal of Bitcoin. The ckBTC minter needs to receive BTC, based on a large number of confirmations due to the lack of finality in Bitcoin, before it mints the same amount in ckBTC and it burns ckBTC before it transfers BTC back to the users.

A best-effort approach is used for the transfer of BTC to the users, i.e., the user cannot get the burned ckBTC back. Rather, the ckBTC minter repeatedly attempts to transfer BTC out. Note that “user” refers to the caller of the functions exposed by the ckBTC minter and ckBTC ledger in the following. A human user or another canister may be behind the function invocations.

The ckBTC ledger is ICRC-1 compliant, updating the balance accounts when ckBTC tokens are transferred and executing the mint and burn operations coming from the ckBTC minter.

An overview of the basic architecture is depicted in the following figure.

High-level overview of chain-key Bitcoin.

The figure shows the main flow at a high level of abstraction: Users interact with the ckBTC minter and the ckBTC ledger to convert ckBTC/BTC and transfer ckBTC, respectively. The ckBTC minter interacts with the Bitcoin canister to retrieve information about the Bitcoin network state and send Bitcoin transactions.

The ckBTC minter further interacts with the KYT canister for "know-your-transaction" (KYT) checks. These checks are meant to ensure that the ckBTC minter only uses "clean" Bitcoins to back the issued ckBTC tokens and to prevent transferring Bitcoins to Bitcoin addresses that are considered to be associated with illicit activity. As such, these KYT checks provide an additional layer of security to ckBTC users.

Technical Details

Bitcoin Addresses

Within this page, Bitcoin addresses are implicitly understood to be of type P2WPKH (“pay to witness public key hash”) as defined in BIP-141. All addresses are rendered in the Bech32 format as defined in BIP-173. The main advantage of P2WPKH over the legacy P2PKH address type is that its use results in lower transaction fees.

For this reason, it is the default address type in most wallets for standard transactions.

ckBTC Ledger

The ckBTC ledger is a canister, controlled by the NNS (specifically, the NNS root canister), running on the pzp6e subnet. Since it is ICRC-1 compliant, it offers all functions defined in the ICRC-1 standard. In particular, it provides the functionality to transfer ckBTC between accounts.

The ckBTC ledger is responsible for keeping account balances and for transferring ckBTC between accounts. It provides the following functionality:

  • It enables the ckBTC minter to mint and burn ckBTC.
  • It enables the transfer of ckBTC among users.

As mentioned above, the transfer fee is 0.0000001 ckBTC, the equivalent of 10 Satoshi. Since the fee in ckBTC is burned, every transaction leads to a growing surplus in BTC controlled by the ckBTC minter. The surplus will eventually be used to cover the cycle cost of the ckBTC minter.

The minting account is the ckBTC minter’s default account; that is, the account derived from the ckBTC minter’s principal ID and the all-zero subaccount.

The initial supply of the ckBTC ledger is 0. ckBTC tokens are minted only when the ckBTC minter receives Bitcoin, ensuring that the ckBTC supply managed by the ckBTC ledger is upper bounded by the amount of Bitcoin held by the ckBTC minter.

ckBTC Minter

The ckBTC minter is a canister that is controlled by the NNS and running on the pzp6e subnet as well.

The ckBTC minter is the canister responsible for managing deposited BTC and minting/burning ckBTC based on the amount of deposited BTC. It provides the following functionality:

  • For a certain principal ID and an optional subaccount, it returns a specific Bitcoin address under the ckBTC minter’s control.
  • Users can inform the ckBTC minter about Bitcoins that were sent to an address controlled by the ckBTC minter. If the balance has increased, the ckBTC minter mints the same amount in ckBTC for the user associated with the Bitcoin address.
  • Users can ask the ckBTC minter to track the balance of a Bitcoin address until new funds are received, which then automatically triggers the minting of the equivalent amount of ckBTC.
  • Users can request to get bitcoins back. The ckBTC minter burns the same amount of ckBTC and transfers the Bitcoins to the address provided by the user.

The ckBTC minter canister has a few important configuration parameters including:

  • retrieve_btc_min_amount: This is the minimum ckBTC amount that can be burned and, correspondingly, the minimum BTC amount that can be withdrawn. The parameter is set to 0.001 BTC, or 100,000 satoshi.
  • max_time_in_queue_nanos: Any BTC retrieval request should be kept in a queue for at most this time. Caching requests rather than handling them right away has the advantage that multiple requests can be served in a single transaction, saving Bitcoin miner fees. The parameter is set to 10 minutes, which corresponds to the expected time between Bitcoin blocks.
  • min_confirmations: The number of confirmations required for the ckBTC minter to accept a Bitcoin transaction. In particular, the ckBTC minter does not mint ckBTC before a transaction transferring BTC to a Bitcoin address managed by the ckBTC minter reaches this number of transactions. The parameter was initially set to 72 but has been reduced to 12 in the meantime.
  • kyt_fee: The fee that must be paid for KYT checks. It is currently set to 2000 satoshi.

The other parameters are self-explanatory and can be found in the ckBTC minter Candid file.

State Management

Managed Addresses

A Bitcoin address that is controlled by the ckBTC minter and has a positive balance is called a managed address. If the balance of a managed address reduces to zero, the address is no longer managed and can be removed from the state.

Note that it is possible to increase the balance again, in which case the address becomes managed again.

Unspent Transaction Outputs

Once a new Unspent Transaction Output (UTXO) under the control of the ckBTC minter is discovered (using the update_balance function), it is stored internally in a set called available_utxos (defined here in the source code).

All discovered UTXOs remain in this set until a Bitcoin transaction is created to spend one or more of them when retrieving Bitcoins. When a transaction is created spending some UTXOs, these UTXOs are removed from the set available_utxos and inserted in the used_utxos field of the SubmittedBtcTransaction struct (defined here in the source code), which is the internal representation of a Bitcoin transaction.

A UTXO is removed from the ckBTC state when the SubmittedBtcTransaction struct that contains the UTXO is removed from the state.

Transactions

To provide information about current transactions, outgoing transactions must be cached. A transaction is cached until its inputs are no longer considered unspent based on a large number of confirmations.

Every transaction that the ckBTC minter creates has an output that sends the ckBTC minter fee plus the transaction change back to its main BTC address (P2WPKH address derived from its public key with an empty derivation path) using the Bitcoin integration’s get_utxos function.

A transaction can be removed from the cache if the transaction output that belongs to the ckBTC minter appears in the returned list when calling get_utxos with sufficient confirmations for the ckBTC minter’s main BTC address.

The ckBTC minter may resubmit transactions, making use of Bitcoin’s request by fee (RBF) mechanism as defined in BIP-125. In the case of ckBTC, a resubmission adds a transaction to the cache that spends exactly the same UTXOs as the transaction it replaces. The only difference is that the BTC amount sent to the user is reduced in order to increase the fee.

BIP-125 states that at most 100 transactions may be evicted from the mempool, i.e., the fee cannot be increased more than 100 times. Moreover, the fee must be increased at least by the minimum relay fee (see minrelaytxfee here) of 1 Satoshi/vbyte.

For example, if we assume a minimum increase of 200 Satoshi (the minimum fee for a basic segwit transaction with one input and one output is 192 Satoshi and the number per output is always lower than 200 if there are at least as many outputs as inputs), the minimum transfer amount should be at least 20,000 Satoshi which equals 0.0002 BTC. When adding a base fee at a large fee rate of 100 Satoshi/vbyte and assuming a virtual transaction size of 200 vbyte per output, we get a minimum transfer amount of 0.0004 BTC. Adding a security margin, we define the minimum retrieval amount to be MIN_RETRIEVAL_AMOUNT = 0.001 BTC.

To ensure that every transaction can potentially be updated, the RBF flag must be set on every transaction.

Know Your Transaction & Fees

Before UTXOs are accepted, they undergo a know-your-transaction (KYT) check where information about the UTXO is sent to a “KYT canister”, which interacts with KYT service providers, such as Chainalysis, to check if the UTXO is “clean” using HTTPS outcalls.

In a similar fashion, there is a KYT check of the destination address when attempting to transfer Bitcoins out of the ckBTC minter.

Both of these KYT checks incur fees, charged in ckBTC:

  • The KYT fee is subtracted from the amount to be minted and the amount transferred out.
  • The KYT fee is 2000 satoshi per KYT check.

The KYT canister supports multiple KYT access key providers, called maintainers, each having a principal ID and (secret) access key to the external KYT service. Since the maintainers pay for their subscriptions, they must be remunerated. To this end, the ckBTC minter maintains a mapping of maintainers to the owed amount, which is the number of KYT checks that were performed with the respective maintainer’s credentials times the KYT fee of 2000 Satoshi.

Each successful response from the KYT canister contains the principal ID of the maintainer so that the ckBTC minter can update the owed amount correctly. Once every 24 hours, the ckBTC minter pays out the owed amounts in ckBTC to all maintainers.

Converting BTC to ckBTC

In this section, the process to convert BTC to ckBTC is explained, making use of the ckBTC minter and ckBTC ledger endpoints.

The first step is for the user to determine the Bitcoin address where the user is supposed to transfer Bitcoin for the minting process by calling the get_btc_address endpoint. Next, the user transfers the desired BTC amount to this Bitcoin address. Subsequently, the user calls the track_balance endpoint to inform the ckBTC minter that it is about to receive Bitcoins at the given address.

Internally, the tracking works as follows. Since the expected time between Bitcoin blocks is 10 minutes, the ckBTC minter first checks if new unspent transaction outputs (UTXOs) are available for that address with at least the required number of confirmations after 10*min_confirmations minutes. If there is at least one new UTXO, tracking stops and the ckBTC minter instructs the ckBTC ledger to mint the same amount of ckBTC tokens into the account derived from the principal ID and the subaccount.

If no new UTXOs are discovered with sufficiently many confirmations, the ckBTC ledger checks if there are new UTXOs with at least one confirmation. If this is not the case, tracking stops as well. Otherwise, the expected time until the first new UTXO reaches the desired number of confirmations is computed, which is 10 minutes times the difference between the desired number of confirmations and the current number of confirmations. The same process then repeats until ckBTC tokens are minted or tracking stops.

It is evident from this description that it’s possible that tracking may stop before ckBTC tokens are minted, for example, if it takes an unusually long time until the transaction appears in a block. In this case, the endpoint can be invoked again. Alternatively, the user can wait until the transaction has the required number of confirmations and call the update_balance endpoint.

The following figure depicts the conversion flow using the track_balance endpoint.

Process of converting BTC to ckBTC.


In this figure, the ckBTC minter discovers the new UTXO after the waiting period by calling get_utxos on the Bitcoin canister. As mentioned above, it is possible that it may take several interactions with the Bitcoin canister until the transaction has received sufficiently many confirmations before the ckBTC minter issues the mint transaction to the ckBTC ledger. After a successful KYT check, the ckBTC ledger is instructed to mint ckBTC tokens for the user. The minted amount corresponds to the value of the UTXO minus the KYT fee.

Technical Details

As mentioned above, a call to the update_balance endpoint triggers a call to the Bitcoin canister to get UTXOs for the Bitcoin address associated with the given principal-subaccount pair. Let R denote the set of returned UTXOs. The following pseudo-code illustrates how the UTXOs are processed:

for utxo in new_utxos(R):        // R = set of received UTXOs in the get_utxos call
    if utxo.value >= KYT_FEE:
        if utxo in checked_utxos:

            (uuid, state) = checked_utxos.get(utxo)
        else:
            (uuid, state, kyt_provider) = kyt_canister.check(utxo).await?
            if state == clean:
                D = D \ {utxo}
                P = P  {utxo}
                checked_utxos.set(utxo, (uuid, clean))
                owed_kyt_fee[kyt_provider] += KYT_FEE
        if state == clean:
            ckbtc_ledger.mint(utxo.value-KYT_FEE, recipient_account, uuid).await?
            checked_utxos.remove(utxo)
        else:
            add_to_quarantine_list(utxo)
    else:
        add_to_ignore_list(utxo)
return response with UTXO statuses

A UTXO is considered if its value is at least the KYT fee, which is a configuration parameter of the ckBTC minter. UTXOs whose value lie below the KYT fee are added to an ignore list. The additional state checked_utxos is maintained to remember that a UTXO was checked if the state is clean. Once the corresponding amount of ckBTC has been minted, this state can be removed again. If the UTXO is tainted, it is moved to a quarantine list instead. UTXOs in the ignore list and quarantine list remain there.

The function new_utxos filters out all UTXOs on the ignore list, the quarantine list, and the sets P and S. On the other hand, the checked_utxos data structure is not considered.

Automated Tracking

The update_balance function only triggers a minting operation if the corresponding Bitcoin transaction has sufficient confirmations, which implies that it is the user’s responsibility to check the number of confirmations before making the update_balance call.

In order to improve the user experience, the additional endpoint track_balance, with the same parameters as update_balance, is provided. When invoked instead of update_balance, the ckBTC minter starts tracking the Bitcoin address derived from the provided principal ID and subaccount using the get_btc_address endpoint. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.

The balance of the Bitcoin address is not tracked indefinitely. Tracking is stopped if either at least one new unspent transaction output (UTXO) is discovered or there is no new UTXO within a certain time interval as defined in the following:

  • Since the expected time between Bitcoin blocks is 10 minutes, the ckBTC minter first checks if new UTXOs are available for that address with at least the required number of confirmations after 10*MIN_CONFIRMATIONS minutes.
  • If there is at least one new UTXO, tracking stops and the same flow as for update_balance is triggered. If the KYT check is successful, the ckBTC minter instructs the ckBTC ledger to mint the same amount of ckBTC tokens minus the KYT fee into the account derived from the principal ID and the subaccount.
  • If no new UTXOs are discovered with sufficiently many confirmations, the ckBTC ledger checks if there are new UTXOs with at least one confirmation. If this is not the case, tracking stops as well. Otherwise, the expected time until the first new UTXO reaches the desired number of confirmations is computed, which is 10 minutes times the difference between the desired number of confirmations and the current number of confirmations. The next check is scheduled after this many minutes and the process repeats until a new UTXO is discovered or tracking stops.


It is evident from this description that it is possible that tracking may stop before ckBTC tokens are minted, for example, if it takes an unusually long time until the transaction appears in a block. In this case, the endpoint can be invoked again. Alternatively, the user can wait until the transaction has the required number of confirmations and call the update_balance endpoint.

Converting ckBTC to BTC

The process to convert ckBTC to BTC consists of the following steps:

  1. Transfer request: The user moves the ckBTC that he/she wants to convert to BTC to a special ckBTC withdrawal account under the control of the ckBTC minter and requests a transfer. The destination Bitcoin address undergoes a KYT check. If the check is successful, the request is accepted and put into a queue.
  2. Submission: On a heartbeat, the ckBTC minter attempts to submit transactions for validated transfer requests.
  3. Finalization: On a heartbeat, the ckBTC minter checks which transactions went through and finalizes these transactions.
  4. Resubmission: The ckBTC minter can resubmit a transaction that has been pending at least for a specific amount of time with a higher fee.

The individual parts are discussed in greater detail in the following sections.

The first step to convert ckBTC to BTC is to transfer the amount to be retrieved to the owner-specific withdrawal account under the ckBTC minter’s control. This step is required because only the ckBTC minter can burn tokens and it can only burn those tokens in one of its accounts. The withdrawal account can be obtained by calling the get_withdrawal_account endpoint.

After the user has transferred the desired ckBTC amount to the withdrawal account, the user can call the retrieve_btc endpoint to inform the ckBTC minter about the withdrawal intent. In addition to specifying the withdrawal amount, the Bitcoin address where the withdrawn funds are to be sent must be specified as well.

The ckBTC minter first performs a KYT check against the targeted Bitcoin address. If the check is successful, the ckBTC minter instructs the ckBTC ledger to burn the ckBTC in the withdrawal account. Lastly, the ckBTC minter deducts the KYT fee from the amount to be retrieved and puts the corresponding retrieval request into a queue and checks the status of the queue on a heartbeat.

If the oldest request has been in the queue for at least 10 minutes or at least 20 retrieval requests have been accumulated at the time of the heartbeat, the ckBTC minter creates a single Bitcoin transaction to serve up to 100 retrieval requests as follows:

  1. It selects available UTXOs with a total sum of at least the sum in the retrieval requests.
  2. It constructs a Bitcoin transaction with the selected UTXOs as inputs and an output for each retrieval request plus an additional output for the ckBTC minter’s fee.
  3. It uses the Bitcoin canister’s fee API to determine an appropriate fee for the transaction, using the median fee rate.
  4. It distributes the fee evenly among all outputs other than the output for the ckBTC minter’s fee.
  5. For each input of the transaction, the ckBTC minter invokes the threshold ECDSA functionality (calling the sign_with_ecdsa function) to obtain the required signatures and puts them into the transaction.
  6. Lastly, it sends the Bitcoin transaction by invoking the send_transaction function of the Bitcoin integration API.

The BTC retrieval process is depicted in the following figure.

Process of converting ckBTC to BTC.


Note that the amounts in the transfer to the withdrawal account and the retrieval request need not be the same. The retrieve_btc_status endpoint can be used to query the current status of a retrieval request.

Technical Details

Transfer Request

The ckBTC minter can only burn ckBTC under its control. Therefore, the first step is to transfer ckBTC to the ckBTC withdrawal account controlled by the ckBTC minter and associated with the owner of the ckBTC that are to be burned. Specifically, the withdrawal account is a ckBTC ledger account where the principal ID is the ckBTC minter and the subaccount is derived deterministically from the owner’s principal ID.

After this transfer, the user sends a retrieve_btc request, specifying the amount that they would like to retrieve, the Bitcoin address where the funds are to be transferred, and, optionally, a fee level (which have yet to be defined).

Upon receiving such a request, the ckBTC minter first performs a KYT check against the Bitcoin address where funds are supposed to be sent. If the check is successful, the ckBTC minter issues a burn request to the ckBTC ledger, burning the amount in the received request in the user’s ckBTC withdrawal account. If the burn operation is successful, the ckBTC minter creates a transfer request, removing the KYT_FEE from the transfer amount, and appends it to its pending-requests queue.

Alternatively, if the destination address does not pass the KYT check, a burn request is sent to the ckBTC ledger, burning the KYT_FEE amount.

The steps of a successful request are illustrated in the following figure.

Recall that the ckBTC ledger uses the ckBTC minter default account as the minting account. Withdrawal accounts should never resolve to the default minting account because the ckBTC ledger considers the minting account for minting only.

The following pseudo-code illustrates how the retrieve_btc endpoint works, given the parameters amount and btc_address.

assert(amount >= max(MIN_RETRIEVAL_AMOUNT, KYT_FEE))
    assert(ckbtc_ledger.balance_of(withdrawal_account).await? >= amount)
  (uuid, state, kyt_provider) = kyt_canister.check(btc_address).await?

if state == clean:
    index = ckbtc_ledger.burn(amount, withdrawal_account).await?
    owed_kyt_fee[kyt_provider] += KYT_FEE
    create_request(amount-KYT_FEE, index, btc_address, uuid)
 else:
    index = ckbtc_ledger.burn(KYT_FEE, withdrawal_account).await?
    owed_kyt_fee[kyt_provider] += KYT_FEE
    return Error("Failed KYT check", index)

Note that a failure to perform the KYT check results in a rejected request. Further note that if the KYT check succeeds but the burn transaction fails (regardless of the state of the KYT response), no KYT fee is charged and the request is rejected. A subsequent request with the same parameters will result in another call to the KYT canister again, which is acceptable because multiple identical calls to the KYT service provider do not result in increased fees.

For each retrieval request, the ckBTC minter stores the following data:

  • block_index: The block index of the burn operation used to burn the ckBTC. Since the block index is unique, it is used as the request ID.
  • amount: The total amount of tokens to retrieve. This amount must be at least the minimum retrieval amount as defined above.
  • address: The address where the Bitcoins will be sent.
  • received_at: The timestamp when the request was received.
  • fee_level: If no fee level is provided, a medium fee level is used.

Submission

The ckBTC minter uses the heartbeat mechanism to initiate Bitcoin transfers. On a heartbeat, the following steps are carried out:

  1. Check if there is at least one request that is 10 minutes old or there are at least 20 requests in the pending-requests queue. If not, stop.
  2. Update the balance of the ckBTC minter’s main BTC address (the P2WPKH address derived from its public key with an empty derivation path) using the Bitcoin integration’s get_utxos function.
  3. Determine the total amount of Bitcoins available, which is the sum of all Bitcoins in processed UTXOs, plus Bitcoins under the ckBTC minter’s main BTC address.
  4. Call the transfer function with the next batch of requests with the same fee level that can be served given the total amount of available Bitcoins. A transaction is created, setting the transaction ID for each request in the batch, and sent to the Bitcoin network.
  5. Every request in this batch is then moved to the unconfirmed-transfers queue.

As evident from the steps outlined above, the transfer function can handle multiple requests at the same time. Handling multiple requests in a single transaction has several advantages over sending individual transactions:

  1. Requests can possibly be served more quickly, especially if the ckBTC minter must wait for change to return to its main BTC address.
  2. As the fee for the non-input bytes is shared, the fee per request is slightly lower.
  3. Serving multiple requests at the same time makes denial-of-service attacks where an attacker attempts to keep the pool of usable UTXOs empty with many small requests harder.

Given this set of requests, the next step is to select UTXOs for the transaction.

Since UTXOs are always spent entirely, the difference between the sum of Bitcoins in the spent UTXOs and the requested amount must be transferred to a new UTXO as well. The ckBTC minter uses its main BTC address to accumulate “change”.

All UTXOs of its main BTC address are immediately transferred to the corresponding set P of processed UTXOs. The reason is that there is no minting for the balances in these UTXOs.

The transfer function performs the following steps:

  1. First, the transfer function determines the “target”, the total number t (≤ T) of Bitcoins that must be transferred out to handle all requests in the given batch.
  2. Then, the function selects UTXOs for the transaction from one or more sets P of its managed addresses. The selected UTXOs are moved from the sets P to the corresponding sets S.
  3. Next, the Bitcoin transaction is built and computes the fee based on current Bitcoin fees (using the get_current_fee_percentiles Bitcoin integration endpoint) and the size of the transaction. The fee rate in Satoshi/vbyte is determined by the fee level. Note that the fee is deducted by splitting it evenly among the handled retrieval requests, deducting the same fraction of the total fee from each output that is not returning change and the ckBTC minter fee to the ckBTC minter. The ckBTC minter fee is 246*in + 7*out + 52 Satoshi, where in and out denote the number of transaction inputs and outputs, respectively (as specified here).
  4. Every input is signed using the threshold ECDSA interface.
  5. Finally, the transaction is submitted using the send_transaction Bitcoin integration endpoint.

The following UTXO selection algorithm, in pseudo-code, is used:

// t = target (satoshis), P = Union of all sets of processed UTXOs
// Pre-condition: sum(P) >= t
select_utxos(t, P):
    return greedy(t, P)

greedy(t, A):	               // t = target, A = Available UTXOs
    if t  0 or |A| = 0: return {}
    m := max(A)             // The UTXO with the largest value
    if m.value < t:
        return {m}  greedy(t-m.value, A \ {m})
    else:
        return min({p  A | p.value  t})

The algorithm has the following properties:

  • It uses the smallest number of UTXOs possible for the given target.
  • If a single UTXO suffices, it uses the UTXO that results in the smallest change.

Once the transaction is sent, the requests are moved to the unconfirmed-transfers queue.

Finalization

The ckBTC minter uses the heartbeat mechanism to determine the status of sent transactions as well. Specifically, the ckBTC minter periodically wakes up and checks the state of the requests in the unconfirmed-transfers queue.The  ckBTC minter checks the UTXOs of its main account to determine which transactions have sufficiently many confirmations.

Such requests can then be stored in a confirmed-transfers queue for some time in order to enable a more long-term look-up of the transaction status.

Resubmission

It is possible that it takes a long time for a transaction to be included in a block. If fees increase significantly for some time, a transaction may even be stuck for a long time or dropped entirely. While the ckBTC minter enforces a reasonable fee through its fee levels, it may still be necessary to issue a transaction again because burned ckBTC are never returned and UTXOs are never freed and are thus stuck when the transaction spending these UTXOs is stuck.

The ckBTC minter resubmits a transaction that has not been confirmed within a certain number of hours. Given that the ckBTC minter always waits for many confirmations, the waiting time will likely be multiple hours up to one day, though this parameter has not been defined yet.

The new transaction will use the UTXOs reserved for the requests. The transaction will be identical except that the outputs for each user will be reduced due to the increased fee. The new fee is the sum of the old transaction fee plus the size of the transaction (in vbytes) times the minimum relay fee of 1 Satoshi/vbyte plus the ckBTC minter fee again because it must acquire new signatures and send the new transaction to the Bitcoin canister.

Fees

The ckBTC canisters run on an application subnet and must be self-sustainable. Rather than charging cycles for the endpoints, the ckBTC minter accumulates a surplus of BTC over time. In the future, the ckBTC minter will mint ckBTC to get the total ckBTC supply and the BTC amount under the ckBTC minter's control to match. The ckBTC minter can then trade these extra ckBTC tokens for cycles to charge both the ckBTC minter and ckBTC ledger.

There is a growing surplus of BTC because there is a ckBTC transfer fee of 0.0000001 ckBTC, which is burned, and a ckBTC minter fee when retrieving BTC. The latter is determined as follows:

  • Under the conservative assumption that 1 BTC = 10,000 XDR, 1 billion cycles corresponds to 10 Satoshi (because 1 trillion cycles corresponds to 1 XDR).
  • The cost to obtain a single EDCSA signature is approximately 21.54 billion cycles on a 28-node subnet, whereas sending a Bitcoin transaction costs 5 billion cycles plus 20 million cycles per byte.

Given these numbers, the cost to sign and send a transaction with in inputs and out outputs is

21.54b*in + 5b + tx_size*20m cycles
< 21.54b*in + 5b + (149*in + 35*out + 10)*20m cycles
< 24.52b*in +0.7b*out + 5.2b cycles
< 246*in + 7*out + 52 satoshi.

The formula 246*in + 7*out + 52 is used to determine the ckBTC minter’s fee in satoshi. Since every transaction has at least one input and one output, the fee is at least 305 Satoshi.

This conservative pricing strategy is used to subsidize the other endpoints, which are free of charge. Moreover, while the retrieve_btc endpoint is relatively expensive, the fee is typically still lower than the Bitcoin miner fee.

As mentioned above, there is also a KYT fee (currently 2000 Satoshi) when converting BTC to ckBTC and vice versa.

ckBTC Minter API

The ckBTC minter provides the following endpoints:

  • get_btc_address: Returns a specific Bitcoin address that the caller can use to obtain ckBTC by sending BTC to this address.
  • track_balance: Instructs the ckBTC minter to track a certain Bitcoin address until funds are added, which will trigger the minting of ckBTC. NOTE: This endpoint is work-in-progress and not available yet.
  • update_balance: Instructs the ckBTC minter to check the balance of a Bitcoin address and mint ckBTC into the account of the owner.
  • estimate_withdrawal_fee: Returns a current estimate for the fee to be paid when retrieving a certain BTC amount.
  • get_deposit_fee: Returns the fee charged when minting ckBTC.
  • get_withdrawal_account: Returns a specific ckBTC account where the owner must transfer ckBTC before being able to retrieve BTC.
  • retrieve_btc: Instructs the ckBTC minter to burn a certain ckBTC amount and send the corresponding BTC amount, minus fees, to a provided Bitcoin address.
  • retrieve_btc_status: Returns the status of a previous retrieve_btc call.
  • get_minter_info: Returns information about the ckBTC minter itself.
  • get_events: Returns a set of events at the ckBTC minter.

The endpoints are discussed in more detail in the following sections.

get_btc_address(owner: opt principal, subaccount: opt blob)

The provided principal ID and subaccount are concatenated to form the derivation path for the ecdsa_public_key function, which returns the derived public key. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.

This public key is encoded as a pay-to-witness-public-key-hash (P2WPKH) Bitcoin address and returned as a text.

Note that the key derivation is not BIP-32 compliant where 31 bits are used for each derivation level. Instead, a single derivation is performed based on the full principal ID and subaccount. Since the derivation is deterministic, a canister can derive the Bitcoin address for a given principal ID and subaccount itself.

track_balance(owner: opt principal, subaccount: opt blob)

NOTE: This endpoint is work-in-progress and not available yet.

The ckBTC minter starts tracking the Bitcoin address derived from the provided principal ID and subaccount using the get_btc_address endpoint. If no principal ID is provided, then the sender’s principal ID is used. If no subaccount is provided, then the default subaccount (all zeros) is used.

The balance of the Bitcoin address is not tracked indefinitely. Tracking is stopped if either at least one new unspent transaction output (UTXO) is discovered or there is no new UTXO within a certain time interval (details about balance tracking are provided below).

If at least one new UTXO is discovered, the same amount of ckBTC tokens minus the KYT fee are minted and made available to the owner.

update_balance(owner: opt principal, subaccount: opt blob)

Instead of having the ckBTC minter track the balance of a Bitcoin address, the update_balance function can be invoked to instruct the ckBTC minter to check if there are new UTXOs for a particular Bitcoin address.

If there is at least one new UTXO, the corresponding ckBTC amount is minted, otherwise an error is returned.

The ckBTC minter effectively invokes this endpoint itself on a timer when the track_balance function is used.

estimate_withdrawal_fee(amount: opt nat64)

The endpoint returns an estimate for the fee that must be paid when retrieving the given BTC amount. Internally, a transaction is built (without valid signatures) to determine the fee, which consists of the Bitcoin miner fee, the ckBTC minter fee, and the KYT fee. If no amount is provided, it is assumed that three inputs are required to build the transaction.

If there is no change to the internal state of the ckBTC minter and the Bitcoin canister before issuing the request to retrieve bitcoins, the fee will be exactly the returned estimate.

The fee can change when a) a new Bitcoin block is mined in the meantime, which causes the Bitcoin canister to update the Bitcoin miner fees or b) another retrieval request is handled first, spending some of the outputs that were used when estimating the fee.

get_deposit_fee

The endpoint returns the fee that the ckBTC minter charges for minting ckBTC when receiving new UTXOs. Currently, this fee is simply the KYT fee.

get_withdrawal_account

The function returns the caller’s withdrawal account, which is the account derived from the ckBTC minter’s principal ID and the subaccount derived from the caller’s principal ID.

A user can only retrieve BTC by first transferring ckBTC to this particular account.

retrieve_btc(address: text, amount: nat64)

The function instructs the ckBTC minter to burn the specified amount. Once the request is picked up from the queue, a Bitcoin transaction is created containing an output that transfers the requested amount (minus fees as discussed below) to the specified Bitcoin address.

Since Bitcoin retrieval is handled asynchronously, the function returns the block index of the transaction burning the ckBTC tokens.

retrieve_btc_status(block_index: nat64)

The status of a BTC retrieval request can be checked using this function. The different possible statuses are:

  • Unknown: There is no information available on the ckBTC minter because there is no retrieval request associated with the given block index or the retrieval request is old and the corresponding information has already been removed.
  • Pending: The BTC retrieval request is queued.
  • Signing: The BTC retrieval request is acquiring all signatures to serve the BTC retrieval request.
  • Sending: The Bitcoin transaction serving the BTC retrieval request is being sent.
  • Submitted: The Bitcoin transaction has been transmitted. The transaction ID is returned.
  • AmountTooLow: The BTC retrieval request could not be served because the Bitcoin miner fees are prohibitively high.
  • Confirmed: The Bitcoin transaction serving the BTC retrieval request is confirmed inside the ckBTC minter, which happens when the transaction has at least the minimum required number of confirmations specified in the min_confirmations parameter above.

get_minter_info

The function returns the following parameters internal to the ckBTC minter:

  • kyt_fee
  • min_confirmations
  • retrieve_btc_min_amount

get_events(start: nat64, length: nat64)

The ckBTC minter tracks the events that change its internal state. Given a start index and a length parameter, the ckBTC minter returns all events sequentially from the event at the given start index up to the event at index start+length-1.

Note that this endpoint is used for debugging purposes and there is no guarantee that the endpoint will continue to exist in this form.

See also