mirror of
https://github.com/ChristopherA/Learning-Bitcoin-from-the-Command-Line.git
synced 2025-06-06 23:46:22 +00:00
Update 12_2_Accessing_Bitcoind_with_C.md
This commit is contained in:
parent
9172ca6897
commit
360f261076
@ -2,11 +2,11 @@
|
||||
|
||||
> **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
|
||||
|
||||
Though command-line `curl` is the easiest way to access the `bitcoind` directly, there are [many other options](https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)) for doing so and most of them support more fully featured programming languages. The best package for doing so in C is currently [libbitcoinrpc](https://github.com/gitmarek/libbitcoinrpc/blob/master/README.md). It uses a `curl` library for accessing the data and it uses the somewhat clunky `jansson` library for decoding the JSON.
|
||||
Though command-line `curl` is the easiest way to access the `bitcoind` directly, there are many other options for doing so and most of them support more fully featured programming languages. The best package for doing so in C is currently [libbitcoinrpc](https://github.com/gitmarek/libbitcoinrpc/blob/master/README.md). It uses a `curl` library for accessing the data and it uses the somewhat clunky `jansson` library for encoding and decoding the JSON.
|
||||
|
||||
## Set Up libbitcoinrpc
|
||||
|
||||
To use `libbitcoinrpc`, you need to install a basic C setup and the dependent packages, `libcurl`, `libjansson`, and `libuuid`. The following will do so on a Ubuntu system:
|
||||
To use `libbitcoinrpc`, you need to install a basic C setup and the dependent packages `libcurl`, `libjansson`, and `libuuid`. The following will do so on a Ubuntu system:
|
||||
```
|
||||
$ sudo apt-get install make gcc libcurl4-openssl-dev libjansson-dev uuid-dev
|
||||
```
|
||||
@ -51,7 +51,7 @@ To use `libbitcoinrpc`, make sure that your code files include the appropriate h
|
||||
```
|
||||
You'll also need to link in the appropriate libraries whenever you compile:
|
||||
```
|
||||
$ cc mybitcoinclient.c -lbitcoinrpc -ljansson -o rpcclient
|
||||
$ cc mybitcoinclient.c -lbitcoinrpc -ljansson -o mybitcoinclient
|
||||
```
|
||||
|
||||
### Build Your Connection
|
||||
@ -62,15 +62,15 @@ First, initialize the library:
|
||||
```
|
||||
bitcoinrpc_global_init();
|
||||
```
|
||||
Then connect to your `bitcoind`. The four arguments for `bitcoinrpc_cl_init_params` are username, password, IP address, and port. As usual, you should extract the user and password from `~/.bitcoin/bitcoin.conf`, while IP address 127.0.0.1 and port 18332 should be correct for the standard testnet setup described in this documents.
|
||||
Then connect to your `bitcoind` with `bitcoinrpc_cl_init_params`. The four arguments for `bitcoinrpc_cl_init_params` are username, password, IP address, and port. You should already know all of this information from your work with `curl`. As you'll recall, the IP address 127.0.0.1 and port 18332 should be correct for the standard testnet setup described in this documents, while you can extract the user and password from `~/.bitcoin/bitcoin.conf`.
|
||||
```
|
||||
bitcoinrpc_cl_t *rpc_client;
|
||||
rpc_client = bitcoinrpc_cl_init_params ("bitcoinrpc", "d8340efbcd34e312044c8431c59c792c", "127.0.0.1", 18332);
|
||||
rpc_client = bitcoinrpc_cl_init_params("bitcoinrpc", "d8340efbcd34e312044c8431c59c792c", "127.0.0.1", 18332);
|
||||
```
|
||||
|
||||
> **MAINNET VS TESTNET:** The port would be 8332 for a mainnet setup.
|
||||
|
||||
If `rpc_client` is successful, then you can go.
|
||||
If `rpc_client` is successfully initialized, you'll be able to send off RPC commands.
|
||||
|
||||
Later, when you're all done with your `bitcoind` connection, you should close it:
|
||||
```
|
||||
@ -81,44 +81,46 @@ Appendix I shows the complete code for a test of a `bitcoind` connection.
|
||||
|
||||
### Make an RPC Call
|
||||
|
||||
In order to use an RPC method in `bitcoinrpc`, you must initialize a variable of type `bitcoinrpc_method_t`. You do so with the appropriate value for the method you want to use, all of which are listed in the [bitcoinrpc Reference](https://github.com/gitmarek/libbitcoinrpc/blob/master/doc/reference.md).
|
||||
In order to use an RPC method using `libbitcoinrpc`, you must initialize a variable of type `bitcoinrpc_method_t`. You do so with the appropriate value for the method you want to use, all of which are listed in the [bitcoinrpc Reference](https://github.com/gitmarek/libbitcoinrpc/blob/master/doc/reference.md).
|
||||
```
|
||||
bitcoinrpc_method_t *getmininginfo = NULL;
|
||||
getmininginfo = bitcoinrpc_method_init(BITCOINRPC_METHOD_GETMININGINFO);
|
||||
```
|
||||
Usually you would set parameters here, but `getmininginfo` requires no parameters, so you can skip that for now.
|
||||
Usually you would set parameters next, but `getmininginfo` requires no parameters, so you can skip that for now.
|
||||
|
||||
Two more objects are required, a "response object" and an "error object". They're created via standard `bitcoinrpc` function calls:
|
||||
You must also create two other objects, a "response object" and an "error object". They can be initialized as follows:
|
||||
```
|
||||
bitcoinrpc_resp_t *btcresponse = NULL;
|
||||
btcresponse = bitcoinrpc_resp_init();
|
||||
|
||||
bitcoinrpc_err_t btcerror;
|
||||
```
|
||||
And now you can put it all together to make a `getmininginfo` RPC call:
|
||||
With your four standard variables in hand, you can make a `getmininginfo` RPC call using `bitcoinrpc_call`:
|
||||
```
|
||||
bitcoinrpc_call (rpc_client, getmininginfo, btcresponse, &btcerror);
|
||||
bitcoinrpc_call(rpc_client, getmininginfo, btcresponse, &btcerror);
|
||||
```
|
||||
### Output Your Response
|
||||
|
||||
Retrieve the output of your call as a JSON object with `bitcoinrpc_resp_get`.
|
||||
You'll want to know what the RPC call returned. To do so, retrieve the output of your call as a JSON object with `bitcoinrpc_resp_get` and save it into a standard `jansson` object, of type `json_t`:
|
||||
```
|
||||
json_t *jsonresponse = NULL;
|
||||
jsonresponse = bitcoinrpc_resp_get (btcresponse);
|
||||
jsonresponse = bitcoinrpc_resp_get(btcresponse);
|
||||
```
|
||||
If you want to output the complete JSON results of the RPC call, you can do so with a simple invocation of `json_dumps`, from the `jansson` library:
|
||||
If you want to output the complete JSON results of the RPC call, you can do so with a simple invocation of `json_dumps`, also from the `jansson` library:
|
||||
```
|
||||
printf ("%s\n", json_dumps (j, JSON_INDENT(2)));
|
||||
printf ("%s\n", json_dumps(j, JSON_INDENT(2)));
|
||||
```
|
||||
However since you're now writing complete programs, you're probably going to want to do more subtle work, such as pulling out individual JSON values for specific usage. The [jansson Reference](https://jansson.readthedocs.io/en/2.10/apiref.html) details how to do so.
|
||||
However, since you're now writing complete programs, you probablywant to do more subtle work, such as pulling out individual JSON values for specific usage. The [jansson Reference](https://jansson.readthedocs.io/en/2.10/apiref.html) details how to do so.
|
||||
|
||||
You can drill down to the `result` JSON object:
|
||||
Just as when you were using `curl`, you'll find that RPC returns a JSON object containing an `id`, an `error`, and most importantly a JSON object of the `result`.
|
||||
|
||||
The `json_object_get` function will let you retrieve a value (such as the `result`) from a JSON object by key:
|
||||
```
|
||||
json_t *jsonresult = NULL;
|
||||
jsonresult = json_object_get(jsonresponse,"result");
|
||||
printf ("%s\n", json_dumps (jsonresult, JSON_INDENT(2)));
|
||||
```
|
||||
Alternatively, you can drill down to an individual item like `blocks`:
|
||||
However, you probably want to drill down further, to get a specific variable. Once you've retrieved the appropriate value, you will need to convert it to a standard C object by using the appropriate `json_*_value` function. For example, accessing an integer uses `json_integer_value`:
|
||||
```
|
||||
json_t *jsonblocks = NULL;
|
||||
jsonblocks = json_object_get(jsonresult,"blocks");
|
||||
@ -128,9 +130,9 @@ blocks = json_integer_value(jsonblocks);
|
||||
printf("Block Count: %d\n",blocks);
|
||||
```
|
||||
|
||||
> **WARNING:** It's extremely easy to segfault your C code when working with jansson objects if you get confused with what type of object you're retrieving. Make careful use of `bitcoin-cli help` to know what you should expect, and if you experience a segmentation fault, first look at your JSON retrieval functions.
|
||||
> **WARNING:** It's extremely easy to segfault your C code when working with `jansson` objects if you get confused with what type of object you're retrieving. Make careful use of `bitcoin-cli help` to know what you should expect, and if you experience a segmentation fault, first look at your JSON retrieval functions.
|
||||
|
||||
Appendix II has an example of this complete code.
|
||||
Appendix II has an example of this complete code for accessing mining information.
|
||||
|
||||
### Make an RPC Call with Arguments
|
||||
|
||||
@ -138,20 +140,20 @@ But what if your RPC call _did_ have arguments?
|
||||
|
||||
#### Create a JSON Array
|
||||
|
||||
To send parameters to your RPC call using `libbitcoinrpc` you have to wrap them in a JSON array. An array is just a simple listing of values, so all you have to do is encode the parameters as elements of the array.
|
||||
To send parameters to your RPC call using `libbitcoinrpc` you have to wrap them in a JSON array. Since an array is just a simple listing of values, all you have to do is encode the parameters as ordered elements in the array.
|
||||
|
||||
Create the array using the `json_array` function from `jansson`:
|
||||
Create the JSON array using the `json_array` function from `jansson`:
|
||||
```
|
||||
json_t *params = NULL;
|
||||
params = json_array();
|
||||
```
|
||||
You can then fill it by converting C-typed objects into JSON-typed objects and appending them to the array:
|
||||
You'll then reverse the procedure that you followed to access JSON values: you'll convert C-typed objects to JSON-typed objects using the `json_*` functions. Afterward, you'll append them to the array:
|
||||
```
|
||||
json_array_append_new(params,json_string(tx_rawhex));
|
||||
```
|
||||
Note that there are two variants to the append command: `json_array_append_new`, which appends a newly created variable, and `json_array_append`, which appends an existing variable.
|
||||
|
||||
This methodology will serve for the majority of RPC commands with parameters, but there are some that are much more complex. In these cases you may need to create subsidiary JSON objects or JSON arrays, which you then append to the parameters array as usual. The next section contains an example of doing so using `createrawtransaction`, which contains an array of objects for the inputs, an object for the outputs and the `locktime` parameter.
|
||||
This simple methodology will serve for the majority of RPC commands with parameters, but some RPC commands require more complex inputs. In these cases you may need to create subsidiary JSON objects or JSON arrays, which you will then append to the parameters array as usual. The next section contains an example of doing so using `createrawtransaction`, which contains a JSON array of JSON objects for the inputs, a JSON object for the outputs, and the `locktime` parameter.
|
||||
|
||||
#### Assign the Parameters
|
||||
|
||||
@ -165,7 +167,7 @@ This section doesn't include a full example of this more complex methodology, bu
|
||||
|
||||
By linking to the `bitcoinrpc` and `jansson` libraries, you can easily access `bitcoind` via RPC calls from a C library. To do so, you create an RPC connection, then make individual RPC calls, some of them with parameters. `jansson` then allows you to decode the JSON responses.
|
||||
|
||||
_What is the power of C?_ C allows you to take the next step beyond shell-scripting, permitting the creation of more comprehensive and robust programs. A more comprehensive example will appear in the next chapter.
|
||||
_What is the power of C?_ C allows you to take the next step beyond shell-scripting, permitting the creation of more comprehensive and robust programs. A few examples appear in the next two sections.
|
||||
|
||||
## Appendix I: Testing a Bitcoind Connection
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user