Guide To Connect To BCH (Bitcoin Cash) Node Wallet Using RPC

I’ll walk you through the initial setup and help you with the Nodejs code that is needed for creating the public address, getting wallet balance, and few more primary wallet interactions.

What is RPC in Crypto:

Remote Procedure Call is a technique used to perform actions in a distributed client-server based application. Invoking and executing procedure/subroutine with the same system or on systems connected to a shared network. Allows controlling the QT wallets of a core wallet (i.e we can write a piece of code to control a network, directing the network to perform a specific action of rescanning, create, and encrypt a wallet, etc..). This is essentially a request-response messaging passing system  (JSON RPC will enable us to establish an interactive connection between the server and the node wallet).

Using Node js code we can connect to the full node BTC wallet using the RPC commands. 

Installation node module 
npm install node-bitcoin-rpc

Code to connect to RPC  

let bitcoinCash_rpc = require(‘node-bitcoin-rpc’);
bitcoinCash_rpc.init(host, port, user, pass);

Create a file with .js extension and add the deceleration and initiation code. 

let bitcoinCash_rpc = require(‘node-bitcoin-rpc’);
let host = ‘host’;
let port = 18332;
let user = “username”;
let pass = ‘Password’;
function initBitCoinRpc() {
 bitcoinCash_rpc.init(host, port, user, pass);
 bitcoinCash_rpc.setTimeout(30000);
}

Generate public address
To generate a new public address (called as a public key) for a wallet we have to use the below method.
bitcoinCash_rpc.call(‘getnewaddress’, [], (err, res1) => {});

Below is the sample implementation using promises to control the asynchronous property of node js.

async function generateNewAddress() {
 return new Promise((resolve, reject) => {
   initBitCoinRpc();
   bitcoinCash_rpc.call(‘getnewaddress’, [], (err, res) => {
     if (err !== null) {
       console.log(err)
     } else {
       console.log(res)
     }
   });
 });
}

To maintain accounts in your wallet, you have to mention the account name in the params arrow-like [“accountName”]. This will generate a new account with an output address if there is no account with the name. If there exists an account with a matching name, then it returns a public address for that account.

For all other methods, you can pass a wallet account address ( public address) as a param as above.

The accounts functionality is deprecated in the latest node version. If you are willing to use then run the bitcoind with -deprecatedrpc=accounts option bitcoind -deprecatedrpc=accounts

To get the balance of the node wallet, we have to use the below method.
bitcoinCash_rpc.call(‘getbalance’, [‘*’, 1], (err, res1) => {})
Here ‘*’ indicates all the accounts and 1 indicates the minimum number of confirmations.

Below is the sample implementation in nodejs to get balance.

async function getBalance() {
 return new Promise((resolve, reject) => {
   initBitCoinRpc();
   bitcoinCash_rpc.call(‘getbalance’, [‘*’, 1], (err, res) => {
     if (err !== null) {
       console.log(err);
     } else {
       console.log(res)
     }
   });
 });
};

To get the list of transactions, we have to use the below method.
bitcoinCash_rpc.call(‘Listtransactions’, [‘*’, 100], (err, res1) => {});

Here * indicates all the accounts , 100 is the limit

Below is the sample implementation in nodejs to get transactions. 
async function getTransactions() {
 return new Promise((resolve, reject) => {
   initBitCoinRpc();
   bitcoinCash_rpc.call(‘listtransactions’, [‘*’, 100], (err, res) => {
     if (err !== null) {
       console.log(err)
} else {
       console.log(res)
     };
   });
 });
};

To get a specific transaction, we have to use the below method.
bitcoinCash_rpc.call(‘gettransaction’, [], (err, res1) => {});

You have to pass transaction Id in params.

To send currency to a specific address, we have to use the below method.
bitcoinCash_rpc.call(‘sendtoaddress’, [address, amount], (err, res1) =>{});

‘Address’ is the receiver’s address and ‘amount’ is the quantity

async function sendMoneyToAddress() {
   return new Promise((resolve, reject) => {
     initBitCoinRpc();
     }
     bitcoinCash_rpc.call(‘getbalance’, [], (err, res) => {
       if (err !== null) {
         reject(err);
       } else if (res.result > amount) {   
     bitcoinCash_rpc.call(‘sendtoaddress’, [address, amount], (err, res1) => 
       {
           if (err !== null) {
             reject(err);
          } else if (res1.error && res1.error.message) {
             resolve({
               message: res1.error.message,
               error: ‘OK’
             });
           } else if (res1.result) {
             resolve({
   txid: res1.result,
               success: ‘OK’
             });
           }
         });
       } else {
         resolve({
           message: ‘No amount in wallet’,
           error: ‘OK’
         });
       }
     });
   });
}

To receive currency to a specific address, we have to use the below method.
bitcoinCash_rpc.call(‘gettransaction’, [“txid”], (err, res1) => {});

async function getTransaction() {
 return new Promise((resolve, reject) => {
   initBitCoinRpc();
   bitcoinCash_rpc.call(‘gettransaction’, [“txid”], (err, res1) => {
     if (err !== null) {
       console.log(err);
     } else {
       console.log(res1.result);
     }
   });
 });
}

All of the above calls are basic RPC calls used in node wallet. To learn more about the RPC methods please check bitcoin official documentation

If you were unable to connect using the RPC make sure whether the ports were configured correctly or not (like outbound and inbound) open all ports for the outbound and RPC port for inbound.
 

Even then it’s not connecting recheck the rpcallowip in the config file. In the initial stage try to use rpcallowip=0.0.0.0/0 . Once everything is working, then you can add security.

Leave A Comment

Your email address will not be published. Required fields are marked *