Now let’s take a look at the demo.js file from the examples in the source tree. The demo program does a few basic things like creating a key and printing its address, and then brings up the network and prints some info about the peers it got connected to.
Running the demo
jjs -cp bitcoinj-0.14.7-bundled.jar demo.js
You’ll get a warning from SLF4J about not having any logging backend. That’s OK. We can look at how to set up logging later. For now let’s just examine the code.
Next up, we create a key, and show how to print its address.
This piece of code shows how to get connected to the P2P network. A
PeerGroup manages multiple peer connections. We have to configure it with a DNS discovery instance and then make it start. It will find and set up connections in the background. The last line waits for it to find at least three connected peers and then prints out their IP addresses and ports. The
connectedPeers property gives a list of
A note on asynchronicity
Here, we are taking the simple route: we’re just blocking the main thread when we need to wait for something to happen. Below, we’ll see how to do things asynchronously. The
get method blocks until the future’s result is ready.
Iterating over collections and arrays
The “subVer” field of a Peer is the bitcoin equivalent of an HTTP user agent string. The “bestHeight” field is the self-reported (unauthenticated) chain height that the peer claims to be on.
You can of course, also use the more modern JS style foreach that uses a closure, which is naturally less efficient:
Here we can see that we’re blocking again and measuring the ping time to the remote peer. Note that this is not an ICMP (internet level) ping, but rather a Bitcoin protocol specific ping message.
Let’s do that again, but this time in an async way:
Here we start a ping for each peer and add the returned future to the array. Then we add a closure that will run when the future completes. Note the final (required) parameter: it says which thread to run the closure in. Here we are specifying the ‘user thread’, which is a dedicated thread created by bitcoinj that hangs around waiting to run event handlers. By making things run in the user thread, you can be sure your own event handlers won’t end up running in parallel to each other (although they can still run in parallel to the main thread!). Once the future listener runs, we can get the result as normal safe in the knowledge that it won’t block.
The last forEach loop simply keeps the program running until all the pings have responses.
Where to go from here?
There are many other features in bitcoinj that this tutorial does not cover. You can read the other articles to learn more about full verification, wallet encryption and so on, and of course the JavaDocs detail the full API.
Have fun and if you have any questions, find us on IRC or the mailing list.