Photo by Bermix Studio on Unsplash

How to query Bitcoin’s blockchain, with .Net

JB

--

I recently started a project where I wanted to start traversing and recording transactions from the bitcoin blockchain. I have since been successfull in my endevour but found documentation on the subject, slightly lacking, so I thought I would show how I accomplished it below.

Step 1.

Setting up a bitcoin node.

To be able to query the chain directly you will need to setup a bitcoin node.
Download bitcoin core and install.

After you have installed Bitcoin core, we will need to configure the node to allow RPC’s requests. The RPC server allows us to send HTTP requests over to the node, which will then grab the requested data and send it back.

To configure the node server, open up the config with a text editor. It can be found in the following locations by default:

Windows : 'C:\Users\username\AppData\Roaming\Bitcoin\bitcoin.conf'
Linux: '/home/username/.bitcoin/bitcoin.conf'
Mac OSX: '/Users/username/Library/Application Support/Bitcoin/bitcoin.conf'

Change the config to:

Caution, I have not included the prune command in this config, which means running the node will download large amounts of the blockchain. Please see if this is right for you.

Navigate to the parent file of bitcoin.conf and open the daemon folder. Copy the daemon folder address and add it as an environment variable. If you’ve successfully completed that step, you should now be able to run the command:

Now you should see the node starting to sync with the bitcoin blockchain, it is important that the node is running when you want to make requests. Now that’s done, lets dive into some C#.

Step 2.

Lets go over the basic layout of how the program will function:

Here’s how I’ve structured the options class:

Now we’re going to break down the main component of the code, the client.

This has 2 main sections, a couple functions that help call the RPC:

deserializeResponse() //Turns the JSON RPC response into a C# Class
getBaseParams() //Inserts all the required config values into a request
createReq() //Creates the request, and specifies what 'endpoint' to send to.
serializeReq() //Turns the request data into binary and packages it into the request.

And the another function `getBlockStats()` is calling the RPC method of the same name.

Here is the whole client:

The start function has a little example of going through the blockchain at height 100001–100011, and reporting how many transactions are recorded in each block.

The method names I keep in a constant file. And all the responses are wrapped in the Response class.

And here’s an example of what my response classes look like. You just need to match the RPC documentation for that method.

Thats it!

I hope this article helped you on your coding journey. Please slap the clap button and give me a follow 😊.

--

--

JB

Passionate developer who loves helping people via automation.