1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! The canister interface for the [Bitcoin canister](https://github.com/dfinity/bitcoin-canister).

use std::ops::Deref;

use candid::{CandidType, Principal};
use ic_agent::{Agent, AgentError};
use serde::Deserialize;

use crate::{
    call::{AsyncCall, SyncCall},
    Canister,
};

/// The canister interface for the IC [Bitcoin canister](https://github.com/dfinity/bitcoin-canister).
#[derive(Debug)]
pub struct BitcoinCanister<'agent> {
    canister: Canister<'agent>,
    network: BitcoinNetwork,
}

impl<'agent> Deref for BitcoinCanister<'agent> {
    type Target = Canister<'agent>;
    fn deref(&self) -> &Self::Target {
        &self.canister
    }
}
const MAINNET_ID: Principal =
    Principal::from_slice(&[0x00, 0x00, 0x00, 0x00, 0x01, 0xa0, 0x00, 0x04, 0x01, 0x01]);
const TESTNET_ID: Principal =
    Principal::from_slice(&[0x00, 0x00, 0x00, 0x00, 0x01, 0xa0, 0x00, 0x01, 0x01, 0x01]);

impl<'agent> BitcoinCanister<'agent> {
    /// Create a `BitcoinCanister` interface from an existing canister object.
    pub fn from_canister(canister: Canister<'agent>, network: BitcoinNetwork) -> Self {
        Self { canister, network }
    }
    /// Create a `BitcoinCanister` interface pointing to the specified canister ID.
    pub fn create(agent: &'agent Agent, canister_id: Principal, network: BitcoinNetwork) -> Self {
        Self::from_canister(
            Canister::builder()
                .with_agent(agent)
                .with_canister_id(canister_id)
                .build()
                .expect("all required fields should be set"),
            network,
        )
    }
    /// Create a `BitcoinCanister` interface for the Bitcoin mainnet canister on the IC mainnet.
    pub fn mainnet(agent: &'agent Agent) -> Self {
        Self::for_network(agent, BitcoinNetwork::Mainnet).expect("valid network")
    }
    /// Create a `BitcoinCanister` interface for the Bitcoin testnet canister on the IC mainnet.
    pub fn testnet(agent: &'agent Agent) -> Self {
        Self::for_network(agent, BitcoinNetwork::Testnet).expect("valid network")
    }
    /// Create a `BitcoinCanister` interface for the specified Bitcoin network on the IC mainnet. Errors if `Regtest` is specified.
    pub fn for_network(agent: &'agent Agent, network: BitcoinNetwork) -> Result<Self, AgentError> {
        let canister_id = match network {
            BitcoinNetwork::Mainnet => MAINNET_ID,
            BitcoinNetwork::Testnet => TESTNET_ID,
            BitcoinNetwork::Regtest => {
                return Err(AgentError::MessageError(
                    "No applicable canister ID for regtest".to_string(),
                ))
            }
        };
        Ok(Self::create(agent, canister_id, network))
    }

    /// Gets the BTC balance (in satoshis) of a particular Bitcoin address, filtering by number of confirmations.
    /// Most applications should require 6 confirmations.
    pub fn get_balance(
        &self,
        address: &str,
        min_confirmations: Option<u32>,
    ) -> impl 'agent + AsyncCall<Value = (u64,)> {
        #[derive(CandidType)]
        struct In<'a> {
            address: &'a str,
            network: BitcoinNetwork,
            min_confirmations: Option<u32>,
        }
        self.update("bitcoin_get_balance")
            .with_arg(GetBalance {
                address,
                network: self.network,
                min_confirmations,
            })
            .build()
    }

    /// Gets the BTC balance (in satoshis) of a particular Bitcoin address, filtering by number of confirmations.
    /// Most applications should require 6 confirmations.
    pub fn get_balance_query(
        &self,
        address: &str,
        min_confirmations: Option<u32>,
    ) -> impl 'agent + SyncCall<Value = (u64,)> {
        self.query("bitcoin_get_balance_query")
            .with_arg(GetBalance {
                address,
                network: self.network,
                min_confirmations,
            })
            .build()
    }

    /// Fetch the list of [UTXOs](https://en.wikipedia.org/wiki/Unspent_transaction_output) for a Bitcoin address,
    /// filtering by number of confirmations. Most applications should require 6 confirmations.
    ///
    /// This method is paginated. If not all the results can be returned, then `next_page` will be set to `Some`,
    /// and its value can be passed to this method to get the next page.
    pub fn get_utxos(
        &self,
        address: &str,
        filter: Option<UtxosFilter>,
    ) -> impl 'agent + AsyncCall<Value = (GetUtxosResponse,)> {
        self.update("bitcoin_get_utxos")
            .with_arg(GetUtxos {
                address,
                network: self.network,
                filter,
            })
            .build()
    }

    /// Fetch the list of [UTXOs](https://en.wikipedia.org/wiki/Unspent_transaction_output) for a Bitcoin address,
    /// filtering by number of confirmations. Most applications should require 6 confirmations.
    ///
    /// This method is paginated. If not all the results can be returned, then `next_page` will be set to `Some`,
    /// and its value can be passed to this method to get the next page.
    pub fn get_utxos_query(
        &self,
        address: &str,
        filter: Option<UtxosFilter>,
    ) -> impl 'agent + SyncCall<Value = (GetUtxosResponse,)> {
        self.query("bitcoin_get_utxos_query")
            .with_arg(GetUtxos {
                address,
                network: self.network,
                filter,
            })
            .build()
    }

    /// Gets the transaction fee percentiles for the last 10,000 transactions. In the returned vector, `v[i]` is the `i`th percentile fee,
    /// measured in millisatoshis/vbyte, and `v[0]` is the smallest fee.
    pub fn get_current_fee_percentiles(&self) -> impl 'agent + AsyncCall<Value = (Vec<u64>,)> {
        #[derive(CandidType)]
        struct In {
            network: BitcoinNetwork,
        }
        self.update("bitcoin_get_current_fee_percentiles")
            .with_arg(In {
                network: self.network,
            })
            .build()
    }
    /// Gets the block headers for the specified range of blocks. If `end_height` is `None`, the returned `tip_height` provides the tip at the moment
    /// the chain was queried.
    pub fn get_block_headers(
        &self,
        start_height: u32,
        end_height: Option<u32>,
    ) -> impl 'agent + AsyncCall<Value = (GetBlockHeadersResponse,)> {
        #[derive(CandidType)]
        struct In {
            start_height: u32,
            end_height: Option<u32>,
        }
        self.update("bitcoin_get_block_headers")
            .with_arg(In {
                start_height,
                end_height,
            })
            .build()
    }
    /// Submits a new Bitcoin transaction. No guarantees are made about the outcome.
    pub fn send_transaction(&self, transaction: Vec<u8>) -> impl 'agent + AsyncCall<Value = ()> {
        #[derive(CandidType, Deserialize)]
        struct In {
            network: BitcoinNetwork,
            #[serde(with = "serde_bytes")]
            transaction: Vec<u8>,
        }
        self.update("bitcoin_send_transaction")
            .with_arg(In {
                network: self.network,
                transaction,
            })
            .build()
    }
}

#[derive(Debug, CandidType)]
struct GetBalance<'a> {
    address: &'a str,
    network: BitcoinNetwork,
    min_confirmations: Option<u32>,
}

#[derive(Debug, CandidType)]
struct GetUtxos<'a> {
    address: &'a str,
    network: BitcoinNetwork,
    filter: Option<UtxosFilter>,
}

/// The Bitcoin network that a Bitcoin transaction is placed on.
#[derive(Clone, Copy, Debug, CandidType, Deserialize, PartialEq, Eq)]
pub enum BitcoinNetwork {
    /// The BTC network.
    #[serde(rename = "mainnet")]
    Mainnet,
    /// The TESTBTC network.
    #[serde(rename = "testnet")]
    Testnet,
    /// The REGTEST network.
    ///
    /// This is only available when developing with local replica.
    #[serde(rename = "regtest")]
    Regtest,
}

/// Defines how to filter results from [`BitcoinCanister::get_utxos_query`].
#[derive(Debug, Clone, CandidType, Deserialize)]
pub enum UtxosFilter {
    /// Filter by the minimum number of UTXO confirmations. Most applications should set this to 6.
    #[serde(rename = "min_confirmations")]
    MinConfirmations(u32),
    /// When paginating results, use this page. Provided by [`GetUtxosResponse.next_page`](GetUtxosResponse).
    #[serde(rename = "page")]
    Page(#[serde(with = "serde_bytes")] Vec<u8>),
}

/// Unique output descriptor of a Bitcoin transaction.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct UtxoOutpoint {
    /// The ID of the transaction. Not necessarily unique on its own.
    #[serde(with = "serde_bytes")]
    pub txid: Vec<u8>,
    /// The index of the outpoint within the transaction.
    pub vout: u32,
}

/// A Bitcoin [`UTXO`](https://en.wikipedia.org/wiki/Unspent_transaction_output), produced by a transaction.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct Utxo {
    /// The transaction outpoint that produced this UTXO.
    pub outpoint: UtxoOutpoint,
    /// The BTC quantity, in satoshis.
    pub value: u64,
    /// The block index this transaction was placed at.
    pub height: u32,
}

/// Response type for the [`BitcoinCanister::get_utxos_query`] function.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct GetUtxosResponse {
    /// A list of UTXOs available for the specified address.
    pub utxos: Vec<Utxo>,
    /// The hash of the tip.
    #[serde(with = "serde_bytes")]
    pub tip_block_hash: Vec<u8>,
    /// The block index of the tip of the chain known to the IC.
    pub tip_height: u32,
    /// If `Some`, then `utxos` does not contain the entire results of the query.
    /// Call `bitcoin_get_utxos_query` again using `UtxosFilter::Page` for the next page of results.
    pub next_page: Option<Vec<u8>>,
}

/// Response type for the ``.
#[derive(Debug, Clone, CandidType, Deserialize)]
pub struct GetBlockHeadersResponse {
    /// The tip of the chain, current to when the headers were fetched.
    pub tip_height: u32,
    /// The headers of the requested block range.
    pub block_headers: Vec<Vec<u8>>,
}