mirror of
https://github.com/ChristopherA/Learning-Bitcoin-from-the-Command-Line.git
synced 2025-06-07 16:06:26 +00:00
First edit & standardization
This commit is contained in:
parent
25a9316f25
commit
939f87957b
@ -1,20 +1,24 @@
|
||||
# 18.3: Accessing Bitcoind with NodeJS
|
||||
# 17.3: Accessing Bitcoind with NodeJS
|
||||
|
||||
## Set Up Node.js
|
||||
> **NOTE:** This is a draft in progress, so that I can get some feedback from early reviewers. It is not yet ready for learning.
|
||||
|
||||
BCRPC is built on node.js. Thus, you'll first need to install the `node.js` and `npm` (node package manager) packages for your system.
|
||||
This section explains how to interact with `bitcoind` using the NodeJS programming language and the [BCRPC package](https://github.com/dgarage/bcrpc).
|
||||
|
||||
## Setting Up Node.js
|
||||
|
||||
BCRPC is built on node.js. Thus, you'll first need to install the `node.js` and `npm` (the node package manager) packages for your system.
|
||||
|
||||
If you're using a Ubuntu machine, you can run the following commands to get a new version of `node.js` (as opposed to the horribly out-of-date version in the Ubuntu package system).
|
||||
|
||||
```
|
||||
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
|
||||
sudo apt-get install -y nodejs
|
||||
sudo npm install mocha -g
|
||||
$ curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
|
||||
$ sudo apt-get install -y nodejs
|
||||
$ sudo npm install mocha -g
|
||||
```
|
||||
|
||||
### Test BCRPC
|
||||
### Setting Up BCRPC
|
||||
|
||||
Clone the BCRPC package from GitHub and install its dependencies.
|
||||
You can now clone the BCRPC package from GitHub and install its dependencies.
|
||||
|
||||
```
|
||||
$ git clone https://github.com/dgarage/bcrpc.git
|
||||
@ -22,17 +26,17 @@ $ cd bcrpc
|
||||
$ npm install
|
||||
```
|
||||
|
||||
To test the BCRPC package, you must first set environmental variables for your rpcuser and rpcpassword. As noted in [§12.1: Accessing Bitcoind with Curl](12_1_Accessing_Bitcoind_with_Curl.md), these come from `~/.bitcoin/bitcoin.conf`. You must also set the RPC port to 18332 which should be correct for the standard testnet setup described in these documents.
|
||||
To test the BCRPC package, you must first set environmental variables for your rpcuser and rpcpassword. As usual, these come from `~/.bitcoin/bitcoin.conf`. You must also set the RPC port to 18332 which should be correct for the standard testnet setup described in these documents.
|
||||
|
||||
```
|
||||
$ export BITCOIND_USER=bitcoinrpc
|
||||
$ export BITCOIND_USER=StandUp
|
||||
$ export BITCOIND_PASS=d8340efbcd34e312044c8431c59c792c
|
||||
$ export BITCOIND_PORT=18332
|
||||
```
|
||||
|
||||
> **WARNING:** Obviously, you'd never put set your password in an environmental variable in a production environment.
|
||||
> :warning: **WARNING:** Obviously, you'd never put set your password in an environmental variable in a production environment.
|
||||
|
||||
> **MAINNET VS TESTNET:** The port would be 8332 for a mainnet setup.
|
||||
> :link: **MAINNET VS TESTNET:** The port would be 8332 for a mainnet setup.
|
||||
|
||||
You can now verify everything is working correctly:
|
||||
|
||||
@ -51,14 +55,14 @@ $ npm test
|
||||
2 passing (36ms)
|
||||
```
|
||||
|
||||
Congratulations, you now have a Bitcoin-ready RPC wrapper for Node.js working with your Bitcoin setup.
|
||||
Congratulations, you now have a Bitcoin-ready RPC wrapper for Node.js that is working with your Bitcoin setup.
|
||||
|
||||
### Set Up BCRPC
|
||||
### Creating a BCRPC Project
|
||||
|
||||
Leave the BCRPC directory and create a new Node.js project with BCRPC installed via npm.
|
||||
You can now create a new Node.js project and install BCRPC via npm.
|
||||
|
||||
```
|
||||
$ cd ..
|
||||
$ cd ~
|
||||
$ mkdir myproject
|
||||
$ cd myproject
|
||||
$ npm init
|
||||
@ -66,41 +70,54 @@ $ npm init
|
||||
$ npm install bcrpc
|
||||
```
|
||||
|
||||
In this ```myproject``` directory, create a file called ```server.js``` in which the JavaScript code can be executed. Enter the following at the top of the file to connect to your Bitcoin node:
|
||||
## Building Your Connection
|
||||
|
||||
In this ```myproject``` directory, create a `.js` file where you JavaScript code will be executed.
|
||||
|
||||
You can create an RPC connection by creatin an `RpcAgent`:
|
||||
```
|
||||
const RpcAgent = require('bcrpc');
|
||||
agent = new RpcAgent({port: 18332, user: 'bitcoinrpc', pass: 'd8340efbcd34e312044c8431c59c792c'});
|
||||
agent = new RpcAgent({port: 18332, user: 'StandUp', pass: 'd8340efbcd34e312044c8431c59c792c'});
|
||||
```
|
||||
Obviously, your `user` and `pass` should again match what's in your `~/.bitcoin/bitcoin.conf`, and you use `port 18332` if you're on testnet.
|
||||
|
||||
Now we can start writing programs in JavaScript that access Bitcoind. You can use the same RPC commands you would usually use via ```bitcoin-cli```, except they need to be in camelCase. For example, ```getblockhash``` would be ```getBlockHash``` instead.
|
||||
### Making an RPC Call
|
||||
|
||||
### Print the Newest Block
|
||||
Using BCRPC, you can use the same RPC commands you would usually use via ```bitcoin-cli``` with your `RpcAgent`, except they need to be in camelCase. For example, ```getblockhash``` would be ```getBlockHash``` instead.
|
||||
|
||||
To print the newest block number along with its hash, we can first call ```getBlockCount```, print it, then pass the block number to ```getBlockHash``` and then print the latest hash. Add this code to ```server.js```:
|
||||
To print the newest block number along, you just call `getBlockCount` thourgh your `RpcAgent`:
|
||||
|
||||
```
|
||||
agent.getBlockCount(function (err, blockCount) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(blockCount.result);
|
||||
});
|
||||
```
|
||||
|
||||
### Making an RPC Call with Arguments
|
||||
|
||||
The BCRPC functions can accept inputs. For example, ```getBlockHash``` takes ```blockCount.result``` as an input.
|
||||
|
||||
```
|
||||
agent.getBlockHash(blockCount.result, function (err, hash) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(hash.result);
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
You can run it with ```$ node server.js```. You should get an output similar to this:
|
||||
The result of the BCRPC functions is a JSON object containing information about any errors and the id of the request. When accessing our result, we add ```.result``` to the end of it to specify that we are interested in the actual result, not information about errors.
|
||||
|
||||
### Running Your Code
|
||||
|
||||
You can find the `getinfo` code in [the src directory](src/17_3_getinfo.js).
|
||||
```
|
||||
1773373
|
||||
0000000000000083d29c524d4cfc257adfab8fa9b6f0d207d1d0f1b63e1de11e
|
||||
$ node getinfo.js
|
||||
1831094
|
||||
00000000000002bf8b522a830180ad3a93b8eed33121f54b3842d8838580a53c
|
||||
```
|
||||
|
||||
The BCRPC functions can accept inputs. For example, ```getBlockHash``` takes ```blockCount.result``` as an input. The result of the BCRPC functions is a JSON object containing information about any errors and the id of the request. When accessing our result, we add ```.result``` to the end of it to specify that we are interested in the actual result, not information about errors. This is what output of the above example would look like if we replaced ```console.log(blockCount.result);``` and ```console.log(hash.result);``` with ```console.log(blockCount);``` and ```console.log(hash);```, respectively:
|
||||
|
||||
This is what output of the above example would look like if we replaced ```console.log(blockCount.result);``` and ```console.log(hash.result);``` with ```console.log(blockCount);``` and ```console.log(hash);```, respectively:
|
||||
```
|
||||
{ result: 1774686, error: null, id: null }
|
||||
{
|
||||
@ -110,9 +127,33 @@ The BCRPC functions can accept inputs. For example, ```getBlockHash``` takes ```
|
||||
}
|
||||
```
|
||||
|
||||
## Look Up Your Wallet
|
||||
## Looking Up Funds
|
||||
|
||||
You can also lookup your wallet and view your balance, transaction count et cetera:
|
||||
A useful function when accepting Bitcoin is checking the received Bitcoin for a specific address in your wallet. For example, if you were running an online store accepting Bitcoin, for each payment from a customer, you would generate a new address, show that address to the customer, then check the balance of the address after some time, to make sure the correct amount has been received:
|
||||
|
||||
```
|
||||
agent.getReceivedByAddress('mpGpCMX6SuUimDZKiVViuhd7EGyVxkNnha', function (err, addressInfo) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(addressInfo.result);
|
||||
});
|
||||
```
|
||||
|
||||
> :information_source: **NOTE:** Obviously, you'll need to enter an address recognized by your machine.
|
||||
|
||||
By default this functions checks the transactions that have been confirmed once, however you can increase this to a higher number such as 6:
|
||||
|
||||
```
|
||||
agent.getReceivedByAddress('mpGpCMX6SuUimDZKiVViuhd7EGyVxkNnha', 6, function (err, addressInfo) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(addressInfo.result);
|
||||
});
|
||||
```
|
||||
|
||||
### Looking Up Wallet Information
|
||||
|
||||
You can also lookup additional information about your wallet and view your balance, transaction count et cetera:
|
||||
|
||||
```
|
||||
agent.getWalletInfo(function (err, walletInfo) {
|
||||
@ -122,34 +163,33 @@ agent.getWalletInfo(function (err, walletInfo) {
|
||||
});
|
||||
```
|
||||
|
||||
When you run it, you should get an output similar to this:
|
||||
|
||||
The source is available as [walletinfo.js](src/17_3_walletinfo.js).
|
||||
```
|
||||
$ node walletinfo.js
|
||||
$ node walletinfo.js
|
||||
0.008498
|
||||
{
|
||||
walletname: '',
|
||||
walletversion: 169900,
|
||||
balance: 0.0011,
|
||||
balance: 0.010438,
|
||||
unconfirmed_balance: 0,
|
||||
immature_balance: 0,
|
||||
txcount: 2,
|
||||
keypoololdest: 1591844503,
|
||||
txcount: 4,
|
||||
keypoololdest: 1596567843,
|
||||
keypoolsize: 999,
|
||||
hdseedid: 'da5a1b058deb9e51ecffef1b0ddc069a5dfb2c5f',
|
||||
keypoolsize_hd_internal: 1000,
|
||||
paytxfee: 0,
|
||||
hdseedid: '6b9ccb7d96c45a3ca407a3f3b0e9b42501f05c49',
|
||||
private_keys_enabled: true
|
||||
private_keys_enabled: true,
|
||||
avoid_reuse: false,
|
||||
scanning: false
|
||||
}
|
||||
```
|
||||
Instead of printing all the details associated with your wallet, you can print specific information, such as your balance. Since a JSON object is being accessed, this can be done by changing the line ```console.log(walletInfo.result);``` to ```console.log(walletInfo.result.balance);```:
|
||||
|
||||
Instead of printing all the details associated with your wallet, you can print specific information such as your balance. Since a JSON object is being accessed, this can be done by changing the line ```console.log(walletInfo.result);``` to ```console.log(walletInfo.result.balance);```:
|
||||
## Creating an Address
|
||||
|
||||
```
|
||||
0.0011
|
||||
```
|
||||
|
||||
### Create an Address
|
||||
|
||||
We can pass additional arguments to RPC commands as well. Here is an example for generating a new legacy address, with the ```-addresstype``` flag.
|
||||
You can also pass additional arguments to RPC command. For example, the following generates a new legacy address, with the ```-addresstype``` flag.
|
||||
|
||||
```
|
||||
agent.getNewAddress('-addresstype', 'legacy', function (err, newAddress) {
|
||||
@ -158,37 +198,37 @@ agent.getNewAddress('-addresstype', 'legacy', function (err, newAddress) {
|
||||
console.log(newAddress.result);
|
||||
});
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
mtGPcBvRPZFEHo2YX8un9qqPBydhG82uuZ
|
||||
```
|
||||
|
||||
This example shows how we can use the same flags as ```bitcoin-cli``` in BCRPC. The example above would look like this from the command line:
|
||||
|
||||
This is the same as running the following from the command line:
|
||||
```
|
||||
$ bitcoin-cli getnewaddress -addresstype legacy
|
||||
mtGPcBvRPZFEHo2YX8un9qqPBydhG82uuZ
|
||||
```
|
||||
|
||||
In BCRPC ```getnewaddress``` is in camelCase (```getNewAddress```) and the that flags are normally separated by spaces are instead put in strings and separated by commas.
|
||||
In BCRPC, you can generally use the same flags as in ```bitcoin-cli``` in BCRPC. Though you use camelCase (```getNewAddress```) for the methods, the flags, which are normally separated by spaces on the command line, are instead placed in strings and separated by commas.
|
||||
|
||||
### List transactions
|
||||
## Sending a Transaction
|
||||
|
||||
We can list our previous transactions and view information about transactions such as amount and number of confirmations:
|
||||
You can send coins to an address most easily using the ```sendToAddress``` function:
|
||||
|
||||
```
|
||||
agent.listTransactions(function (err, transactions) {
|
||||
agent.sendToAddress(newAddress.result, 0.00001, function(err, txid) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(transactions.result);
|
||||
console.log(txid.result);
|
||||
});
|
||||
```
|
||||
|
||||
We can also examine a transaction based on its txid:
|
||||
This should print the txid of the transaction:
|
||||
|
||||
```
|
||||
agent.getTransaction('1661ce322c128e053b8ea8fcc22d17df680d2052983980e2281d692b9b4ab7df', function (err, transaction) {
|
||||
1679bee019c61608340b79810377be2798efd4d2ec3ace0f00a1967af70666b9
|
||||
```
|
||||
|
||||
### Looking Up a Transaction
|
||||
|
||||
You may now wish to view a transaction, such as the one you just sent.
|
||||
```
|
||||
agent.getTransaction(txid.result, function (err, transaction) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(transaction.result);
|
||||
@ -222,54 +262,14 @@ You should get an output similar to this:
|
||||
}
|
||||
```
|
||||
|
||||
### Get Amount Received by an Address
|
||||
|
||||
A useful function when accepting Bitcoin is checking the received Bitcoin of a specific address in your wallet. For example, if you were running an online store accepting Bitcoin, for each payment from a customer, you would generate a new address (as we did with ```getNewAddress``` function), show that address to the customer, then check the balance of the address after some time, to make sure the correct amount has been received:
|
||||
|
||||
```
|
||||
agent.getReceivedByAddress('mpGpCMX6SuUimDZKiVViuhd7EGyVxkNnha', function (err, addressInfo) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(addressInfo.result);
|
||||
});
|
||||
```
|
||||
|
||||
By default this functions checks the transactions that have been confirmed once, however we can increase this to a higher number such as 6:
|
||||
|
||||
```
|
||||
agent.getReceivedByAddress('mpGpCMX6SuUimDZKiVViuhd7EGyVxkNnha', 6, function (err, addressInfo) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(addressInfo.result);
|
||||
});
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```
|
||||
0.0011
|
||||
```
|
||||
|
||||
## Sending coins
|
||||
|
||||
We can send coins to an address using the ```sendToAddress``` function:
|
||||
|
||||
```
|
||||
agent.sendToAddress('n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi', 0.00001, function(err, txid) {
|
||||
if (err)
|
||||
throw Error(JSON.stringify(err));
|
||||
console.log(txid.result);
|
||||
});
|
||||
```
|
||||
|
||||
This should print the txid of the transaction:
|
||||
|
||||
```
|
||||
6172d60d154cd4bbb5b6adeaffa191866f3904dd3f525c7a079154aea906b723
|
||||
```
|
||||
|
||||
We can also use the ```getTransaction``` function to view how many confirmations it has, what fee we paid, et cetera.
|
||||
The full code is available as [sendtx.js](src/17_3_sendtx.js).
|
||||
|
||||
## Summary: Accessing Bitcoind with Node
|
||||
|
||||
With BCRPC we can do all the commands available through ```bitcoin-cli```, in JavaScript. The [BCRPC README](https://github.com/dgarage/bcrpc) has some examples which use promises (the examples in this document use callbacks). The [JavaScript behind it](https://github.com/dgarage/bcrpc/blob/master/index.js) is short and readable. Based on these examples you should be able to incorporate Bitcoin in a Node.js project and do things like sending and receiving coins.
|
||||
With BCRPC you can access all the RPC commands available through ```bitcoin-cli```, in JavaScript. The [BCRPC README](https://github.com/dgarage/bcrpc) has some examples which use promises (the examples in this document use callbacks). The [JavaScript behind it](https://github.com/dgarage/bcrpc/blob/master/index.js) is short and readable.
|
||||
|
||||
Based on these examples you should be able to incorporate Bitcoin in a Node.js project and do things like sending and receiving coins.
|
||||
|
||||
## What's Next?
|
||||
|
||||
Learn more about "Talking to Bitcoin in Other Languages" in [17.4: Accessing Bitcoin with Python](17_4_Accessing_Bitcoind_with_Python.md).
|
||||
|
Loading…
x
Reference in New Issue
Block a user