├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-Apache-2.0 ├── LICENSE-MIT ├── README.md ├── examples └── get_new_address.rs ├── rust-toolchain ├── src ├── bitcoin_rpc_api.rs ├── bitcoincore.rs ├── lib.rs ├── stub_rpc_client.rs └── types │ ├── address.rs │ ├── block.rs │ ├── blockchain.rs │ ├── keys.rs │ ├── mod.rs │ ├── script.rs │ ├── serde │ ├── mod.rs │ └── network.rs │ └── transaction.rs └── tests ├── common ├── assert.rs ├── mod.rs ├── test_client.rs └── test_lifecycle.rs └── rpc_calls.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Rust template 3 | # Generated by Cargo 4 | # will have compiled files and executables 5 | /target/ 6 | 7 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 8 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 9 | Cargo.lock 10 | 11 | # These are backup files generated by rustfmt 12 | **/*.rs.bk 13 | ### JetBrains template 14 | 15 | .idea 16 | 17 | ### Emacs template 18 | # -*- mode: gitignore; -*- 19 | *~ 20 | \#*\# 21 | /.emacs.desktop 22 | /.emacs.desktop.lock 23 | *.elc 24 | auto-save-list 25 | tramp 26 | .\#* 27 | 28 | # Org-mode 29 | .org-id-locations 30 | *_archive 31 | 32 | # flymake-mode 33 | *_flymake.* 34 | 35 | # eshell files 36 | /eshell/history 37 | /eshell/lastdir 38 | 39 | # elpa packages 40 | /elpa/ 41 | 42 | # reftex files 43 | *.rel 44 | 45 | # AUCTeX auto folder 46 | /auto/ 47 | 48 | # cask packages 49 | .cask/ 50 | dist/ 51 | 52 | # Flycheck 53 | flycheck_*.el 54 | 55 | # server auth directory 56 | /server/ 57 | 58 | # projectiles files 59 | .projectile 60 | 61 | # directory configuration 62 | .dir-locals.el 63 | ### Linux template 64 | # temporary files which can be created if a process still has a handle open of a deleted file 65 | .fuse_hidden* 66 | 67 | # KDE directory preferences 68 | .directory 69 | 70 | # Linux trash folder which might appear on any partition or disk 71 | .Trash-* 72 | 73 | # .nfs files are created when an open file is removed but is still being accessed 74 | .nfs* 75 | ### macOS template 76 | # General 77 | .DS_Store 78 | .AppleDouble 79 | .LSOverride 80 | 81 | # Icon must end with two \r 82 | Icon 83 | 84 | # Thumbnails 85 | ._* 86 | 87 | # Files that might appear in the root of a volume 88 | .DocumentRevisions-V100 89 | .fseventsd 90 | .Spotlight-V100 91 | .TemporaryItems 92 | .Trashes 93 | .VolumeIcon.icns 94 | .com.apple.timemachine.donotpresent 95 | 96 | # Directories potentially created on remote AFP share 97 | .AppleDB 98 | .AppleDesktop 99 | Network Trash Folder 100 | Temporary Items 101 | .apdisk 102 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: 3 | directories: 4 | - "$HOME/.cargo" 5 | - "$HOME/.cache/sccache" 6 | rust: stable 7 | before_script: 8 | - rustup component add rustfmt-preview 9 | - docker pull coblox/bitcoin-core:0.16.1-r2 10 | - which sccache || cargo install sccache 11 | script: 12 | - cargo fmt -- --check 13 | - RUSTC_WRAPPER=~/.cargo/bin/sccache cargo build --all 14 | - RUSTC_WRAPPER=~/.cargo/bin/sccache cargo test --all 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bitcoin_rpc_client" 3 | version = "0.6.1" 4 | authors = [ "CoBloX developers " ] 5 | description = "Rust client library for talking to Bitcoin Core nodes using JsonRPC." 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/coblox/bitcoinrpc_rust_client" 8 | categories = ["api-bindings"] 9 | keywords = ["bitcoin", "rpc", "client"] 10 | 11 | [dependencies] 12 | base64 = "0.9" 13 | bitcoin = { version = "0.18", features = ["use-serde"] } 14 | bitcoin_hashes = "0.3.2" 15 | hex = "0.3" 16 | jsonrpc_client = "0.2" 17 | log = "0.4" 18 | serde = "1" 19 | serde_derive = "1" 20 | serde_json = "1" 21 | 22 | [dev-dependencies] 23 | env_logger = "0.6" 24 | testcontainers = "0.7" 25 | -------------------------------------------------------------------------------- /LICENSE-Apache-2.0: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2018 CoBloX 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bitcoin RPC Client 2 | 3 | [![Build Status](https://travis-ci.com/coblox/bitcoinrpc-rust-client.svg?branch=master)](https://travis-ci.com/coblox/bitcoinrpc-rust-client) 4 | [![Crates.io](https://img.shields.io/crates/v/bitcoin_rpc_client.svg)](https://crates.io/crates/bitcoin_rpc_client) 5 | 6 | ## Deprecated. This library is unmaintained in favor of https://github.com/rust-bitcoin/rust-bitcoincore-rpc 7 | 8 | This crate provides a Rust interface to the Bitcoin JSON-RPC API. 9 | 10 | It is currently work-in-progress as not all RPC calls are implemented. 11 | 12 | ## Features 13 | 14 | - Does not use macros 15 | - Automatic retry mechanism if bitcoin-core is not yet ready 16 | - Provides trait of all RPC methods for easy mocking (`BitcoinRpcApi`) 17 | 18 | ## Usage 19 | 20 | Check `examples/` but basically, given a URL and the username/password for the node, you can construct a client and call the desired RPC method. 21 | 22 | ## License 23 | 24 | Licensed under either of 25 | 26 | * Apache License, Version 2.0 27 | ([LICENSE-APACHE](LICENSE-Apache-2.0) or http://www.apache.org/licenses/LICENSE-2.0) 28 | * MIT license 29 | ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 30 | 31 | at your option. 32 | 33 | ## Contribution 34 | 35 | Unless you explicitly state otherwise, any contribution intentionally submitted 36 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 37 | dual licensed as above, without any additional terms or conditions. 38 | -------------------------------------------------------------------------------- /examples/get_new_address.rs: -------------------------------------------------------------------------------- 1 | #![allow(deprecated)] 2 | extern crate bitcoin_rpc_client; 3 | 4 | use bitcoin_rpc_client::BitcoinCoreClient; 5 | use bitcoin_rpc_client::BitcoinRpcApi; 6 | use std::env::var; 7 | 8 | fn main() { 9 | let url = var("BITCOIN_CORE_URL").unwrap(); 10 | let user = var("BITCOIN_CORE_USER").unwrap(); 11 | let password = var("BITCOIN_CORE_PASSWORD").unwrap(); 12 | 13 | let client = BitcoinCoreClient::new(&url, &user, &password); 14 | 15 | let address = client 16 | .get_new_address() 17 | .unwrap() // Handle network error here 18 | .unwrap(); // Handle RpcError 19 | 20 | println!("Generated address: {:?}", address); 21 | } 22 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | stable 2 | -------------------------------------------------------------------------------- /src/bitcoin_rpc_api.rs: -------------------------------------------------------------------------------- 1 | use bitcoin::Address; 2 | use bitcoin::Script; 3 | use jsonrpc_client::ClientError; 4 | use jsonrpc_client::RpcError; 5 | use rpc; 6 | use types::address::AddressInfoResult; 7 | use BlockHash; 8 | use TransactionId; 9 | 10 | #[deprecated( 11 | since = "0.6.1", 12 | note = "This library is deprecated in favor of bitcoincore-rpc." 13 | )] 14 | #[allow(unused_variables)] 15 | pub trait BitcoinRpcApi: Send + Sync { 16 | // Order as per: https://bitcoin.org/en/developer-reference#rpcs 17 | 18 | fn add_multisig_address( 19 | &self, 20 | number_of_required_signatures: u32, 21 | participants: Vec<&Address>, 22 | ) -> Result, ClientError> { 23 | unimplemented!() 24 | } 25 | 26 | // TODO: abandontransaction 27 | // TODO: addmultisigaddress 28 | // TODO: addnode 29 | // TODO: addwitnessaddress 30 | // TODO: backupwallet 31 | // TODO: bumpfee 32 | // TODO: clearbanned 33 | // TODO: createmultisig 34 | 35 | fn create_raw_transaction( 36 | &self, 37 | inputs: Vec<&rpc::NewTransactionInput>, 38 | output: &rpc::NewTransactionOutput, 39 | ) -> Result, ClientError> { 40 | unimplemented!() 41 | } 42 | 43 | fn decode_rawtransaction( 44 | &self, 45 | tx: rpc::SerializedRawTransaction, 46 | ) -> Result, ClientError> { 47 | unimplemented!() 48 | } 49 | 50 | fn decode_script( 51 | &self, 52 | script: Script, 53 | ) -> Result, ClientError> { 54 | unimplemented!() 55 | } 56 | 57 | // TODO: disconnectnode 58 | 59 | fn dump_privkey( 60 | &self, 61 | address: &Address, 62 | ) -> Result, ClientError> { 63 | unimplemented!() 64 | } 65 | 66 | // TODO: dumpwallet 67 | // TODO: encryptwallet 68 | // TODO: estimatefee 69 | // TODO: estimatepriority 70 | 71 | fn fund_raw_transaction( 72 | &self, 73 | tx: &rpc::SerializedRawTransaction, 74 | options: &rpc::FundingOptions, 75 | ) -> Result, ClientError> { 76 | unimplemented!() 77 | } 78 | 79 | fn generate( 80 | &self, 81 | number_of_blocks: u32, 82 | ) -> Result, RpcError>, ClientError> { 83 | unimplemented!() 84 | } 85 | 86 | // TODO: generatetoaddress 87 | // TODO: getaddednodeinfo 88 | 89 | fn get_address_info( 90 | &self, 91 | address: &Address, 92 | ) -> Result, ClientError> { 93 | unimplemented!() 94 | } 95 | 96 | // TODO: getaddressesbylabel 97 | 98 | fn get_balance(&self) -> Result, ClientError> { 99 | unimplemented!() 100 | } 101 | 102 | fn get_best_block_hash(&self) -> Result, ClientError> { 103 | unimplemented!() 104 | } 105 | 106 | fn get_block( 107 | &self, 108 | header_hash: &BlockHash, 109 | ) -> Result, RpcError>, ClientError> { 110 | unimplemented!() 111 | } 112 | 113 | // TODO(evg): add verbosity param to get_block instead of separate methods? 114 | fn get_block_verbose( 115 | &self, 116 | header_hash: &BlockHash, 117 | ) -> Result, RpcError>, ClientError> { 118 | unimplemented!() 119 | } 120 | 121 | fn get_blockchain_info(&self) -> Result, ClientError> { 122 | unimplemented!() 123 | } 124 | 125 | fn get_block_count(&self) -> Result, ClientError> { 126 | unimplemented!() 127 | } 128 | 129 | fn get_block_hash(&self, height: u32) -> Result, ClientError> { 130 | unimplemented!() 131 | } 132 | 133 | // TODO: getblockheader 134 | // TODO: getblocktemplate 135 | // TODO: getchaintips 136 | // TODO: getconnectioncount 137 | // TODO: getdifficulty 138 | // TODO: getgenerate 139 | // TODO: gethashespersec 140 | // TODO: getinfo 141 | // TODO: getmemoryinfo 142 | // TODO: getmempoolancestors 143 | // TODO: getmempooldescendants 144 | // TODO: getmempoolentry 145 | // TODO: getmempoolinfo 146 | // TODO: getmininginfo 147 | // TODO: getnettotals 148 | // TODO: getnetworkhashesps 149 | // TODO: getnetworkinfo 150 | 151 | fn get_new_address(&self) -> Result, ClientError> { 152 | unimplemented!() 153 | } 154 | 155 | // TODO: getpeerinfo 156 | // TODO: getrawchangeaddress 157 | // TODO: getrawmempool 158 | 159 | fn get_raw_transaction_serialized( 160 | &self, 161 | tx: &TransactionId, 162 | ) -> Result, ClientError> { 163 | unimplemented!() 164 | } 165 | 166 | fn get_raw_transaction_verbose( 167 | &self, 168 | tx: &TransactionId, 169 | ) -> Result, ClientError> { 170 | unimplemented!() 171 | } 172 | 173 | // TODO: getreceivedbylabel 174 | // TODO: getreceivedbyaddress 175 | // TODO: gettxout 176 | // TODO: gettxoutsetinfo 177 | // TODO: getunconfirmedbalance 178 | // TODO: getwalletinfo 179 | // TODO: getwork 180 | // TODO: importaddress 181 | // TODO: importmulti 182 | // TODO: importprivkey 183 | // TODO: importprunedfunds 184 | // TODO: importwallet 185 | // TODO: keypoolrefill 186 | // TODO: invalidateblock 187 | // TODO: keypoolrefill 188 | // TODO: listlabels 189 | // TODO: listaddressgroupings 190 | // TODO: listbanned 191 | // TODO: listlockunspent 192 | // TODO: listreceivedbylabel 193 | // TODO: listreceivedbyaddress 194 | // TODO: listsinceblock 195 | // TODO: listtransactions 196 | 197 | fn list_unspent( 198 | &self, 199 | min_confirmations: rpc::TxOutConfirmations, 200 | max_confirmations: Option, 201 | recipients: Option>, 202 | ) -> Result, RpcError>, ClientError> { 203 | unimplemented!() 204 | } 205 | 206 | // TODO: lockunspent 207 | // TODO: ping 208 | // TODO: preciousblock 209 | // TODO: prioritisetransaction 210 | // TODO: pruneblockchain 211 | // TODO: removeprunedfunds 212 | // TODO: sendmany 213 | 214 | fn send_raw_transaction( 215 | &self, 216 | tx_data: rpc::SerializedRawTransaction, 217 | ) -> Result, ClientError> { 218 | unimplemented!() 219 | } 220 | 221 | fn send_to_address( 222 | &self, 223 | address: &Address, 224 | amount: f64, 225 | ) -> Result, ClientError> { 226 | unimplemented!() 227 | } 228 | // TODO: setlabel 229 | // TODO: setban 230 | // TODO: setgenerate 231 | // TODO: setnetworkactive 232 | // TODO: settxfee 233 | // TODO: signmessage 234 | // TODO: signmessagewithprivkey 235 | 236 | fn sign_raw_transaction_with_key( 237 | &self, 238 | tx: &rpc::SerializedRawTransaction, 239 | private_keys: Option>, 240 | dependencies: Option>, 241 | signature_hash_type: Option, 242 | ) -> Result, ClientError> { 243 | unimplemented!() 244 | } 245 | 246 | // TODO: signrawtransactionwithwallet 247 | // TODO: stop 248 | // TODO: submitblock 249 | 250 | fn validate_address( 251 | &self, 252 | address: &Address, 253 | ) -> Result, ClientError> { 254 | unimplemented!() 255 | } 256 | 257 | // TODO: verifychain 258 | // TODO: verifymessage 259 | // TODO: verifytxoutproof 260 | // TODO: walletlock 261 | // TODO: walletpassphrase 262 | // TODO: walletpassphrasechange 263 | } 264 | -------------------------------------------------------------------------------- /src/bitcoincore.rs: -------------------------------------------------------------------------------- 1 | use base64; 2 | use bitcoin::Address; 3 | use bitcoin::Script; 4 | use jsonrpc_client::{ 5 | header::{HeaderMap, HeaderValue, AUTHORIZATION}, 6 | ClientError, HTTPClient, JsonRpcVersion, RpcClient, RpcError, RpcRequest, 7 | }; 8 | use rpc; 9 | use serde::{de::DeserializeOwned, ser::Serialize}; 10 | use std::fmt::Debug; 11 | use types::address::AddressInfoResult; 12 | use BitcoinRpcApi; 13 | use BlockHash; 14 | use TransactionId; 15 | 16 | struct RetryConfig { 17 | max_retries: u32, 18 | interval: u64, 19 | } 20 | 21 | #[deprecated( 22 | since = "0.6.1", 23 | note = "This library is deprecated in favor of bitcoincore-rpc." 24 | )] 25 | pub struct BitcoinCoreClient { 26 | client: RpcClient, 27 | retry_config: Option, 28 | } 29 | 30 | #[allow(dead_code)] 31 | impl BitcoinCoreClient { 32 | pub fn new(url: &str, username: &str, password: &str) -> Self { 33 | let mut headers = HeaderMap::new(); 34 | headers.insert( 35 | AUTHORIZATION, 36 | HeaderValue::from_str(&format!( 37 | "Basic {}", 38 | base64::encode(&format!("{}:{}", username, password)) 39 | )) 40 | .unwrap(), 41 | ); 42 | 43 | let client = HTTPClient::builder() 44 | .default_headers(headers) 45 | .build() 46 | .expect("unable to create HTTP client"); 47 | 48 | let rpc_client = RpcClient::new(client, url); 49 | 50 | BitcoinCoreClient { 51 | client: rpc_client, 52 | retry_config: Some(RetryConfig { 53 | max_retries: 10, 54 | interval: 500, 55 | }), 56 | } 57 | } 58 | 59 | fn get_raw_transaction( 60 | &self, 61 | tx: &TransactionId, 62 | verbose: bool, 63 | ) -> Result, ClientError> 64 | where 65 | R: DeserializeOwned, 66 | { 67 | self.send(&RpcRequest::new2( 68 | JsonRpcVersion::V1, 69 | "42", 70 | "getrawtransaction", 71 | tx, 72 | verbose, 73 | )) 74 | } 75 | } 76 | 77 | impl BitcoinRpcApi for BitcoinCoreClient { 78 | // Order as per: https://bitcoin.org/en/developer-reference#rpcs 79 | 80 | fn add_multisig_address( 81 | &self, 82 | number_of_required_signatures: u32, 83 | participants: Vec<&Address>, 84 | ) -> Result, ClientError> { 85 | self.send(&RpcRequest::new2( 86 | JsonRpcVersion::V1, 87 | "42", 88 | "addmultisigaddress", 89 | number_of_required_signatures, 90 | participants, 91 | )) 92 | } 93 | 94 | fn create_raw_transaction( 95 | &self, 96 | inputs: Vec<&rpc::NewTransactionInput>, 97 | output: &rpc::NewTransactionOutput, 98 | ) -> Result, ClientError> { 99 | self.send(&RpcRequest::new2( 100 | JsonRpcVersion::V1, 101 | "42", 102 | "createrawtransaction", 103 | inputs, 104 | output, 105 | )) 106 | } 107 | 108 | fn decode_rawtransaction( 109 | &self, 110 | tx: rpc::SerializedRawTransaction, 111 | ) -> Result, ClientError> { 112 | self.send(&RpcRequest::new1( 113 | JsonRpcVersion::V1, 114 | "42", 115 | "decoderawtransaction", 116 | tx, 117 | )) 118 | } 119 | 120 | fn decode_script( 121 | &self, 122 | script: Script, 123 | ) -> Result, ClientError> { 124 | self.send(&RpcRequest::new1( 125 | JsonRpcVersion::V1, 126 | "42", 127 | "decodescript", 128 | script, 129 | )) 130 | } 131 | 132 | fn dump_privkey( 133 | &self, 134 | address: &Address, 135 | ) -> Result, ClientError> { 136 | self.send(&RpcRequest::new1( 137 | JsonRpcVersion::V1, 138 | "42", 139 | "dumpprivkey", 140 | address, 141 | )) 142 | } 143 | 144 | fn fund_raw_transaction( 145 | &self, 146 | tx: &rpc::SerializedRawTransaction, 147 | options: &rpc::FundingOptions, 148 | ) -> Result, ClientError> { 149 | self.send(&RpcRequest::new2( 150 | JsonRpcVersion::V1, 151 | "42", 152 | "fundrawtransaction", 153 | tx, 154 | options, 155 | )) 156 | } 157 | 158 | fn generate( 159 | &self, 160 | number_of_blocks: u32, 161 | ) -> Result, RpcError>, ClientError> { 162 | self.send(&RpcRequest::new1( 163 | JsonRpcVersion::V1, 164 | "42", 165 | "generate", 166 | number_of_blocks, 167 | )) 168 | } 169 | 170 | fn get_address_info( 171 | &self, 172 | address: &Address, 173 | ) -> Result, ClientError> { 174 | self.send(&RpcRequest::new1( 175 | JsonRpcVersion::V1, 176 | "42", 177 | "getaddressinfo", 178 | address, 179 | )) 180 | } 181 | 182 | fn get_balance(&self) -> Result, ClientError> { 183 | self.send(&RpcRequest::new0(JsonRpcVersion::V1, "42", "getbalance")) 184 | } 185 | 186 | fn get_best_block_hash(&self) -> Result, ClientError> { 187 | self.send(&RpcRequest::new0( 188 | JsonRpcVersion::V1, 189 | "42", 190 | "getbestblockhash", 191 | )) 192 | } 193 | 194 | fn get_block( 195 | &self, 196 | header_hash: &BlockHash, 197 | ) -> Result, RpcError>, ClientError> { 198 | self.send(&RpcRequest::new1( 199 | JsonRpcVersion::V1, 200 | "42", 201 | "getblock", 202 | header_hash, 203 | )) 204 | } 205 | 206 | fn get_block_verbose( 207 | &self, 208 | header_hash: &BlockHash, 209 | ) -> Result, RpcError>, ClientError> { 210 | self.send(&RpcRequest::new2( 211 | JsonRpcVersion::V1, 212 | "42", 213 | "getblock", 214 | header_hash, 215 | 2, 216 | )) 217 | } 218 | 219 | fn get_blockchain_info(&self) -> Result, ClientError> { 220 | self.send(&RpcRequest::new0( 221 | JsonRpcVersion::V1, 222 | "42", 223 | "getblockchaininfo", 224 | )) 225 | } 226 | 227 | fn get_block_count(&self) -> Result, ClientError> { 228 | self.send(&RpcRequest::new0(JsonRpcVersion::V1, "42", "getblockcount")) 229 | } 230 | 231 | fn get_block_hash(&self, height: u32) -> Result, ClientError> { 232 | self.send(&RpcRequest::new1( 233 | JsonRpcVersion::V1, 234 | "42", 235 | "getblockhash", 236 | height, 237 | )) 238 | } 239 | 240 | fn get_new_address(&self) -> Result, ClientError> { 241 | self.send(&RpcRequest::new2( 242 | JsonRpcVersion::V1, 243 | "42", 244 | "getnewaddress", 245 | "", 246 | "bech32", 247 | )) 248 | } 249 | 250 | fn get_raw_transaction_serialized( 251 | &self, 252 | tx: &TransactionId, 253 | ) -> Result, ClientError> { 254 | self.get_raw_transaction(tx, false) 255 | } 256 | 257 | fn get_raw_transaction_verbose( 258 | &self, 259 | tx: &TransactionId, 260 | ) -> Result, ClientError> { 261 | self.get_raw_transaction(tx, true) 262 | } 263 | 264 | fn list_unspent( 265 | &self, 266 | min_confirmations: rpc::TxOutConfirmations, 267 | max_confirmations: Option, 268 | recipients: Option>, 269 | ) -> Result, RpcError>, ClientError> { 270 | use rpc::TxOutConfirmations::*; 271 | 272 | let min_confirmations = match min_confirmations { 273 | Unconfirmed => 0, 274 | AtLeast(number) => number, 275 | }; 276 | 277 | self.send(&RpcRequest::new3( 278 | JsonRpcVersion::V1, 279 | "42", 280 | "listunspent", 281 | min_confirmations, 282 | max_confirmations, 283 | recipients, 284 | )) 285 | } 286 | 287 | fn send_raw_transaction( 288 | &self, 289 | tx_data: rpc::SerializedRawTransaction, 290 | ) -> Result, ClientError> { 291 | self.send(&RpcRequest::new1( 292 | JsonRpcVersion::V1, 293 | "42", 294 | "sendrawtransaction", 295 | tx_data, 296 | )) 297 | } 298 | 299 | fn send_to_address( 300 | &self, 301 | address: &Address, 302 | amount: f64, 303 | ) -> Result, ClientError> { 304 | self.send(&RpcRequest::new2( 305 | JsonRpcVersion::V1, 306 | "42", 307 | "sendtoaddress", 308 | address, 309 | amount, 310 | )) 311 | } 312 | 313 | fn sign_raw_transaction_with_key( 314 | &self, 315 | tx: &rpc::SerializedRawTransaction, 316 | private_keys: Option>, 317 | dependencies: Option>, 318 | signature_hash_type: Option, 319 | ) -> Result, ClientError> { 320 | self.send(&RpcRequest::new4( 321 | JsonRpcVersion::V1, 322 | "42", 323 | "signrawtransactionwithkey", 324 | tx, 325 | private_keys, 326 | dependencies, 327 | signature_hash_type, 328 | )) 329 | } 330 | 331 | fn validate_address( 332 | &self, 333 | address: &Address, 334 | ) -> Result, ClientError> { 335 | self.send(&RpcRequest::new1( 336 | JsonRpcVersion::V1, 337 | "42", 338 | "validateaddress", 339 | address, 340 | )) 341 | } 342 | } 343 | 344 | impl BitcoinCoreClient { 345 | fn send( 346 | &self, 347 | request: &RpcRequest

, 348 | ) -> Result, ClientError> { 349 | if let Some(ref config) = self.retry_config { 350 | for i in 0..config.max_retries { 351 | let result = self.client.send::(request); 352 | 353 | match result { 354 | Ok(Err(ref rpc_error)) if rpc_error.code == -28 => { 355 | info!("Bitcoind is still starting up. Request will be retried in {} milliseconds. ({}/{}) ", config.interval, i, config.max_retries); 356 | 357 | ::std::thread::sleep(::std::time::Duration::from_millis(config.interval)); 358 | continue; 359 | } 360 | _ => return result, 361 | } 362 | } 363 | } 364 | self.client.send(request) 365 | } 366 | } 367 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(test, deny(warnings))] 2 | #![allow(deprecated)] 3 | 4 | extern crate base64; 5 | extern crate bitcoin; 6 | extern crate bitcoin_hashes; 7 | extern crate hex as std_hex; 8 | extern crate jsonrpc_client; 9 | #[macro_use] 10 | extern crate log; 11 | extern crate serde; 12 | #[macro_use] 13 | extern crate serde_derive; 14 | extern crate serde_json; 15 | 16 | mod bitcoin_rpc_api; 17 | mod bitcoincore; 18 | mod stub_rpc_client; 19 | mod types; 20 | 21 | // Re-export types from rust-bitcoin crates so explicit dependency is not needed 22 | pub type TransactionId = bitcoin_hashes::sha256d::Hash; 23 | pub type BlockHash = bitcoin_hashes::sha256d::Hash; 24 | 25 | pub use bitcoin::network::constants::Network; 26 | pub use bitcoin::util::key::PrivateKey; 27 | pub use bitcoin::Address; 28 | pub use bitcoin::Script; 29 | 30 | pub use bitcoin_rpc_api::BitcoinRpcApi; 31 | pub use bitcoincore::BitcoinCoreClient; 32 | pub use stub_rpc_client::BitcoinStubClient; 33 | 34 | pub use jsonrpc_client::{ClientError, RpcError}; 35 | 36 | pub mod rpc { 37 | pub use types::address::*; 38 | pub use types::block::*; 39 | pub use types::blockchain::*; 40 | pub use types::keys::*; 41 | pub use types::script::*; 42 | pub use types::transaction::*; 43 | pub use types::{Account, SigHashType, TxOutConfirmations}; 44 | } 45 | -------------------------------------------------------------------------------- /src/stub_rpc_client.rs: -------------------------------------------------------------------------------- 1 | use bitcoin_rpc_api::BitcoinRpcApi; 2 | 3 | pub struct BitcoinStubClient {} 4 | 5 | impl BitcoinStubClient { 6 | pub fn new() -> Self { 7 | Self {} 8 | } 9 | } 10 | 11 | impl BitcoinRpcApi for BitcoinStubClient {} 12 | -------------------------------------------------------------------------------- /src/types/address.rs: -------------------------------------------------------------------------------- 1 | use bitcoin::Address; 2 | use bitcoin::Script; 3 | use types::script::ScriptType; 4 | 5 | #[derive(Deserialize, Serialize, Debug, PartialEq)] 6 | pub struct MultiSigAddress { 7 | pub address: Address, 8 | #[serde(rename = "redeemScript")] 9 | pub redeem_script: Script, 10 | } 11 | 12 | #[derive(Deserialize, Serialize, Debug, PartialEq)] 13 | pub struct Label { 14 | pub name: String, 15 | pub purpose: String, 16 | } 17 | 18 | /// Most of the Option are due to different address formats 19 | /// Different fields are returned for P2PKH and P2SH addresses. 20 | #[derive(Deserialize, Serialize, Debug, PartialEq)] 21 | pub struct AddressValidationResult { 22 | #[serde(rename = "isvalid")] 23 | is_valid: bool, 24 | address: Option

, 25 | #[serde(rename = "scriptPubKey")] 26 | script_pub_key: Option, 27 | #[serde(rename = "ismine")] 28 | is_mine: Option, 29 | #[serde(rename = "iswatchonly")] 30 | is_watch_only: Option, 31 | #[serde(rename = "isscript")] 32 | is_script: Option, 33 | #[serde(rename = "script")] 34 | script_type: Option, 35 | #[serde(rename = "hex")] 36 | redeem_script: Option