summaryrefslogtreecommitdiff
path: root/btc-wire/src/rpc.rs
blob: 8121e1e17c09a3ae795d71dd170f23d40af52657 (plain)
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use bitcoin::{hashes::hex::ToHex, Address, Amount, BlockHash, SignedAmount, Txid};
use serde_json::{json, Value};
use std::{
    fmt::Debug,
    io::{self, BufRead, BufReader, Write},
    net::{SocketAddr, TcpStream},
    time::Duration,
};

use crate::config::BitcoinConfig;

// This is a very simple RPC client designed only for a specific bitcoind version
// and to use on an secure localhost connection to a trusted node
//
// No http format of body length check as we trust the node output
// No asynchronous request as bitcoind put requests in a queue and process
// them synchronously and we do not want to fill this queue

#[derive(Debug, serde::Serialize)]
struct BtcRequest<'a, T: serde::Serialize> {
    method: &'a str,
    id: u64,
    params: &'a T,
}

#[derive(Debug, serde::Deserialize)]
struct BtcResponse<T> {
    result: Option<T>,
    error: Option<BtcErr>,
    id: u64,
}

#[derive(Debug, serde::Deserialize)]
struct BtcErr {
    code: ErrorCode,
    message: String,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("{0:?}")]
    Transport(#[from] std::io::Error),
    #[error("{code:?} - {msg}")]
    RPC { code: ErrorCode, msg: String },
    #[error("JSON: {0}")]
    Json(#[from] serde_json::Error),
}

pub type Result<T> = std::result::Result<T, Error>;

const EMPTY: [(); 0] = [];

pub struct BtcRpc {
    addr: SocketAddr,
    path: String,
    id: u64,
    cookie: String,
    conn: Option<BufReader<TcpStream>>,
}

impl BtcRpc {
    pub fn common(config: &BitcoinConfig) -> io::Result<Self> {
        Self::new(config, None)
    }

    pub fn wallet(config: &BitcoinConfig, wallet: &str) -> io::Result<Self> {
        Self::new(config, Some(wallet))
    }

    fn new(config: &BitcoinConfig, wallet: Option<&str>) -> io::Result<Self> {
        let path = if let Some(wallet) = wallet {
            format!("/wallet/{}", wallet)
        } else {
            String::from("/")
        };
        let cookie_path = config.dir.join(".cookie");
        let cookie = std::fs::read(cookie_path)?;
        Ok(Self {
            addr: config.addr,
            path,
            id: 0,
            cookie: format!("Basic {}", base64::encode(&cookie)),
            conn: None,
        })
    }

    fn call<T>(&mut self, method: &str, params: &impl serde::Serialize) -> Result<T>
    where
        T: serde::de::DeserializeOwned + Debug,
    {
        if self.conn.is_none() {
            // Some call might hang waiting for a new block to be mined
            let timeout = Duration::from_secs(666);

            // Open connection
            let sock = TcpStream::connect_timeout(&self.addr, timeout)?;
            sock.set_read_timeout(Some(timeout))?;
            sock.set_write_timeout(Some(timeout))?;
            self.conn.replace(BufReader::new(sock));
        };
        let sock = self.conn.as_mut().unwrap();

        let request = BtcRequest {
            method,
            id: self.id,
            params,
        };

        // Serialize the body first so we can set the Content-Length header.
        let body = serde_json::to_vec(&request)?;
        let mut buf = Vec::new();
        // Write HTTP request
        {
            let sock = sock.get_mut();
            // Send HTTP request
            writeln!(buf, "POST {} HTTP/1.1\r", self.path)?;
            // Write headers
            writeln!(buf, "Accept: application/json-rpc\r")?;
            writeln!(buf, "Authorization: {}\r", self.cookie)?;
            writeln!(buf, "Content-Type: application/json-rpc\r")?;
            writeln!(buf, "Content-Length: {}\r", body.len())?;
            // Write separator
            writeln!(buf, "\r")?;
            sock.write_all(&buf).unwrap();
            buf.clear();
            // Write body
            sock.write_all(&body).unwrap();
            sock.flush().unwrap();
        }
        // Skip response
        loop {
            let amount = sock.read_until(b'\n', &mut buf).unwrap();
            let sep = buf[..amount] == [b'\r', b'\n'];
            buf.clear();
            if sep {
                break;
            }
        }
        // Read body
        let amount = sock.read_until(b'\n', &mut buf).unwrap();
        let response: BtcResponse<T> = serde_json::from_slice(&buf[..amount])?;

        assert_eq!(self.id, response.id);
        self.id += 1;
        if let Some(ok) = response.result {
            Ok(ok)
        } else {
            let err = response.error.unwrap();
            Err(Error::RPC {
                code: err.code,
                msg: err.message,
            })
        }
    }

    pub fn net_info(&mut self) -> Result<Empty> {
        self.call("getnetworkinfo", &EMPTY)
    }

    pub fn load_wallet(&mut self, name: &str) -> Result<Wallet> {
        self.call("loadwallet", &[name])
    }

    pub fn create_wallet(&mut self, name: &str) -> Result<Wallet> {
        self.call("createwallet", &[name])
    }

    pub fn get_new_address(&mut self) -> Result<Address> {
        self.call("getnewaddress", &EMPTY)
    }

    pub fn generate(&mut self, nb: u16, address: &Address) -> Result<Vec<BlockHash>> {
        self.call("generatetoaddress", &(nb, address))
    }

    pub fn wait_for_new_block(&mut self, timeout: u64) -> Result<Empty> {
        self.call("waitfornewblock", &[timeout])
    }

    pub fn get_balance(&mut self) -> Result<Amount> {
        let btc: f64 = self.call("getbalance", &EMPTY)?;
        Ok(Amount::from_btc(btc).unwrap())
    }

    pub fn send(&mut self, address: &Address, amount: &Amount, subtract_fee: bool) -> Result<Txid> {
        let btc = amount.as_btc();
        self.call("sendtoaddress", &(address, btc, (), (), subtract_fee))
    }

    /// Send transaction to multiple recipients
    pub fn send_many<'a, 'b>(
        &mut self,
        recipients: impl IntoIterator<Item = (&'a Address, &'b Amount)>,
    ) -> Result<Txid> {
        let amounts = Value::Object(
            recipients
                .into_iter()
                .map(|(addr, amount)| (addr.to_string(), amount.as_btc().into()))
                .collect(),
        );
        self.call("sendmany", &("", amounts))
    }

    pub fn send_custom<'a, 'b, 'c>(
        &mut self,
        inputs: impl IntoIterator<Item = &'a Txid>,
        outputs: impl IntoIterator<Item = (&'b Address, &'c Amount)>,
        data: Option<&[u8]>,
    ) -> Result<Txid> {
        let hex: String = self.call(
            "createrawtransaction",
            &[
                Value::Array(
                    inputs
                        .into_iter()
                        .enumerate()
                        .map(|(i, id)| json!({"txid": id.to_string(), "vout": i}))
                        .collect(),
                ),
                Value::Array({
                    let mut vec: Vec<Value> = outputs
                        .into_iter()
                        .map(|(addr, amount)| json!({&addr.to_string(): amount.as_btc()}))
                        .collect();
                    if let Some(data) = data {
                        vec.push(json!({ "data".to_string(): data.to_hex() }));
                    }
                    vec
                }),
            ],
        )?;
        let funded: HexWrapper = self.call("fundrawtransaction", &[hex])?;
        let signed: HexWrapper = self.call("signrawtransactionwithwallet", &[&funded.hex])?;
        self.call("sendrawtransaction", &[&signed.hex])
    }

    pub fn list_since_block(
        &mut self,
        hash: Option<&BlockHash>,
        confirmation: u8,
        include_remove: bool,
    ) -> Result<ListSinceBlock> {
        self.call("listsinceblock", &(hash, confirmation, (), include_remove))
    }

    pub fn get_tx(&mut self, id: &Txid) -> Result<TransactionFull> {
        self.call("gettransaction", &(id, (), true))
    }

    pub fn get_raw(&mut self, id: &Txid) -> Result<RawTransaction> {
        self.call("getrawtransaction", &(id, true))
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Wallet {
    pub name: String,
    pub warning: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
pub struct VoutScriptPubKey {
    pub asm: String,
    // nulldata do not have an address
    pub address: Option<Address>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Vout {
    #[serde(with = "bitcoin::util::amount::serde::as_btc")]
    pub value: Amount,
    pub n: u32,
    pub script_pub_key: VoutScriptPubKey,
}

#[derive(Debug, serde::Deserialize)]
pub struct Vin {
    pub sequence: u32,
    /// Not provided for coinbase txs.
    pub txid: Option<Txid>,
    /// Not provided for coinbase txs.
    pub vout: Option<u32>,
}

/// Enum to represent the category of a transaction.
#[derive(Copy, PartialEq, Eq, Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Category {
    Send,
    Receive,
    Generate,
    Immature,
    Orphan,
}

#[derive(Debug, serde::Deserialize)]
pub struct TransactionDetail {
    pub address: Option<Address>,
    pub category: Category,
    #[serde(with = "bitcoin::util::amount::serde::as_btc")]
    pub amount: SignedAmount,
    pub vout: u32,
    #[serde(default, with = "bitcoin::util::amount::serde::as_btc::opt")]
    pub fee: Option<SignedAmount>,
    /// Ony for send transaction
    pub abandoned: Option<bool>,
}

#[derive(Debug, serde::Deserialize)]
pub struct ListTransaction {
    pub confirmations: i32,
    pub txid: Txid,
    pub category: Category,
}

#[derive(Debug, serde::Deserialize)]
pub struct ListSinceBlock {
    pub transactions: Vec<ListTransaction>,
    #[serde(default)]
    pub removed: Vec<ListTransaction>,
    pub lastblock: BlockHash,
}

#[derive(Debug, serde::Deserialize)]
pub struct RawTransaction {
    pub vin: Vec<Vin>,
    pub vout: Vec<Vout>,
}

#[derive(Debug, serde::Deserialize)]
pub struct TransactionFull {
    pub confirmations: i32,
    pub time: u64,
    #[serde(with = "bitcoin::util::amount::serde::as_btc")]
    pub amount: SignedAmount,
    #[serde(default, with = "bitcoin::util::amount::serde::as_btc::opt")]
    pub fee: Option<SignedAmount>,
    pub details: Vec<TransactionDetail>,
    pub decoded: RawTransaction,
}

#[derive(Debug, serde::Deserialize)]
pub struct HexWrapper {
    pub hex: String,
}

#[derive(Debug, serde::Deserialize)]
pub struct Empty {}

/// Bitcoin RPC error codes <https://github.com/bitcoin/bitcoin/blob/master/src/rpc/protocol.h>
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde_repr::Deserialize_repr)]
#[repr(i32)]
pub enum ErrorCode {
    RpcInvalidRequest = -32600,
    RpcMethodNotFound = -32601,
    RpcInvalidParams = -32602,
    RpcInternalError = -32603,
    RpcParseError = -32700,

    /// std::exception thrown in command handling
    RpcMiscError = -1,
    /// Unexpected type was passed as parameter
    RpcTypeError = -3,
    /// Invalid address or key
    RpcInvalidAddressOrKey = -5,
    /// Ran out of memory during operation
    RpcOutOfMemory = -7,
    /// Invalid, missing or duplicate parameter
    RpcInvalidParameter = -8,
    /// Database error
    RpcDatabaseError = -20,
    /// Error parsing or validating structure in raw format
    RpcDeserializationError = -22,
    /// General error during transaction or block submission
    RpcVerifyError = -25,
    /// Transaction or block was rejected by network rules
    RpcVerifyRejected = -26,
    /// Transaction already in chain
    RpcVerifyAlreadyInChain = -27,
    /// Client still warming up
    RpcInWarmup = -28,
    /// RPC method is deprecated
    RpcMethodDeprecated = -32,
    /// Bitcoin is not connected
    RpcClientNotConnected = -9,
    /// Still downloading initial blocks
    RpcClientInInitialDownload = -10,
    /// Node is already added
    RpcClientNodeAlreadyAdded = -23,
    /// Node has not been added before
    RpcClientNodeNotAdded = -24,
    /// Node to disconnect not found in connected nodes
    RpcClientNodeNotConnected = -29,
    /// Invalid IP/Subnet
    RpcClientInvalidIpOrSubnet = -30,
    /// No valid connection manager instance found
    RpcClientP2pDisabled = -31,
    /// Max number of outbound or block-relay connections already open
    RpcClientNodeCapacityReached = -34,
    /// No mempool instance found
    RpcClientMempoolDisabled = -33,
    /// Unspecified problem with wallet (key not found etc.)
    RpcWalletError = -4,
    /// Not enough funds in wallet or account
    RpcWalletInsufficientFunds = -6,
    /// Invalid label name
    RpcWalletInvalidLabelName = -11,
    /// Keypool ran out, call keypoolrefill first
    RpcWalletKeypoolRanOut = -12,
    /// Enter the wallet passphrase with walletpassphrase first
    RpcWalletUnlockNeeded = -13,
    /// The wallet passphrase entered was incorrect
    RpcWalletPassphraseIncorrect = -14,
    /// Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
    RpcWalletWrongEncState = -15,
    /// Failed to encrypt the wallet
    RpcWalletEncryptionFailed = -16,
    /// Wallet is already unlocked
    RpcWalletAlreadyUnlocked = -17,
    /// Invalid wallet specified
    RpcWalletNotFound = -18,
    /// No wallet specified (error when there are multiple wallets loaded)
    RpcWalletNotSpecified = -19,
    /// This same wallet is already loaded
    RpcWalletAlreadyLoaded = -35,
    /// Server is in safe mode, and command is not allowed in safe mode
    RpcForbiddenBySafeMode = -2,
}