Desktop version

Home arrow Education arrow Bitcoin for the befuddled

Hello Money!

Okay, let's write our first Bitcoin app. Simply type the following complete program into a file named hellomoney.js:

Before we start running the app, let's analyze what the code does line by line.

: Initializing the Connection with Bitcoin Core

The first line indicates that we're using the node-bitcoin library O. Next, we establish a connection to the Bitcoin Core server that we set up 0. Because we'll be running the app on the same machine that Bitcoin Core is installed on, our host is set to 'localhost'. By default, the bitcoin server will run on port 8332.

Important: On the next two lines ©0, input the user ID and password that you entered into the bitcoin.conf file. Replace the placeholders shown here with your own. Then, we create a variable to keep track of the previous balance in our program ©, which we start at zero.

: The Main Loop

Now we'll write a loop that checks the balance in our wallet and reports to us when it has changed. The basic steps follow:

1. Ask Bitcoin Core for the current balance in its wallet.

2. If the balance is higher than the previous balance, print a message, and update the previous balance to the current balance.

3. Set a timer that completes the entire procedure again every five seconds.

The following mainLoop function carries out the preceding steps:

First, the function asks Bitcoin Core for the balance O. As we do this, we create a callback function, which reads function(eii,balance) {}. A callback function is called at some future date. In this instance, it will be called when we receive the resulting balance from Bitcoin Core.

If you've never worked with Node.js before, you may need some time to learn how to

read this type of programming idiom. The philosophy in Node.js is that whenever your program has to wait on an external process (in this case the Bitcoin Core program), it makes you create callback functions, as opposed to stopping the program dead as you wait for a result to arrive. This is called asynchronous programming and enables your program to do other tasks while waiting for data to come in.

When the balance becomes available, we first check whether an error has occurred and display it if one has 0. Next, we check whether the new balance is higher than the previous balance ©. If so, we print a message 0 and update the previous balance 0. Finally, we create a timer that runs every 5000 milliseconds with the setlnterval function to repeatedly call mainLoop ©.

The Bitcoin Core JSON-RPC API

The mainLoop function operates by talking with Bitcoin Core. This talking protocol is formatted as JSON-RPC, or JavaScript Object Notation - Remote Procedure Call. Simply put, JSON-RPC describes a structure with which two computers (or two programs on a single computer) can write messages to each other in a way that's easy for computer programmers to integrate into their code.

In our small app, we use only a single command to communicate with Bitcoin Core—the client.getBalance function. But many more commands are available that let you manipulate Bitcoin addresses, modify the wallet, analyze transactions, and complete most other tasks you'd want to do in a Bitcoin program. To learn which functions are available in the JSON-RPC interface, browse to the official API function list at https://en.bitcoin.it/wiki/ Original_Bitcoin_client/API_calls_list.

Running the Hello Money! App

To try out our shiny new Hello Money! program, run the following command in a console from the directory containing hellomoney.js:

Next, simply send 0.001 bitcoins to the wallet managed by Bitcoin Core from another wallet. To do this, you'll need to use one of the public addresses, which you can find by clicking Receive in Bitcoin Core. The way we've written the app, it will count money that has arrived in your wallet only if it has received a confirmation on the blockchain. (In the next section, we'll write a Hello Money! program that detects money immediately on arrival, without requiring confirmations.)

Because confirmations typically take about 10 minutes, you'll need to wait a bit before you see the following:

Congratulations! You've written a program that can watch a Bitcoin wallet and detect when money has been sent to it. If you then send additional money, the app will create messages to report on these new deposits as well.

Limitations of Writing Bitcoin Programs That Use JSON-RPC

By using JSON-RPC, we were able to write a program in JavaScript in no time that could report money sent to a Bitcoin wallet. However, if you're an experienced programmer (or have an advanced understanding of the Bitcoin protocol), you'll identify many problems with our example app.

One problem is that the app uses polling to detect when money has arrived. Polling constantly checks the status of Bitcoin Core by interrogating the software every five seconds. This process is similar to asking: "Do you have money yet? Do you have money now? What about now?" As you might imagine, repeatedly asking the same question like this not efficient.

If you're writing a production-quality application, it's therefore best to write it using pushing. Pushing involves specifying that our app is waiting for money and that it would like to be notified when money has arrived. But because of the way our connection with Bitcoin Core is set up, enabling pushing is rather difficult. After all, Bitcoin Core is primarily meant to be a wallet app in which no pushing to external programs is needed. Automating Bitcoin Core with JSON-PRC is a bit of a hack, and for this reason, we may run into limitations, such as needing to use inefficient polling.

In more recent versions of Bitcoin Core and bitcoind, a feature called wallet Notify

allows for pushing, but the way it works is rather complicated—enough so that we recommend you avoid using it. Instead, we would suggest you use BitcoinJ instead of Bitcoin Core for pushing, as we will discuss in Appendix B.

Another problem with our app is that we're just checking a crude balance amount to determine when money was sent to our wallet. However, the Bitcoin blockchain can sometimes trigger situations that cause the balance of a wallet to jump in ways that are unexpected and could make our app produce incorrect results.

For instance, suppose our wallet receives some money with one confirmation, but the blockchain suddenly forks, unconfirming the transaction that was tied to that money and causing the wallet to suddenly lose much of the confirmed money. Then, within the same five-second window, someone sends us more money. In this case, the balance in the wallet could actually decrease, even though we received some new money, and the Hello Money! message will never be triggered.

This is a very rare scenario, but if you're writing an app that manipulates large quantities of money, such incorrect behavior is intolerable. The solution to this problem is to use client.listTransactions (instead of client.getBalance). Then review these transactions to determine whether any new transactions involved sending money to the wallet in the last five seconds, which is what our app is looking for. However, this is too complicated to add to our simple Hello Money! program.

An additional problem is that Bitcoin Core (and bitcoind) requires large amounts of blockchain data and computational resources to run, even though our little app doesn't need most of this power. Is there any way of reducing these resource requirements? As you'll see in Appendix B, we can do this by writing a program that runs directly on the Bitcoin network.

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >

Related topics