GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing bitcoinj.org — Getting started in Java Initial setupbitcoinj has logging and assertions built in. Assertions are always checked by default regardless of whether the bitcoinj uses Gradle as its build system and is distributed via git. There are source code/jar downloads you can use, but it’s more secure to get it directly from the source repository. To get the code and install it, grab Maven or Gradle, and add it to your path. Also make sure you have Git installed. Probably your Java IDE has some Maven/Gradle and Git integration too, but having them available via the command line is still very useful. Now get the latest version of the code. You can use the instructions on the Using Maven or Using Gradle page - just run the commands there and you’ll get the right version of the code (unless this website is itself compromised). This is intended to protect against compromised mirrors or source downloads - because git works using source tree hashes, if you get a source hash in the right manner, you are guaranteed to end up with the right code. You can read the full program here. Basic structureA bitcoinj application uses the following objects:
To simplify setting them up, there is also a Let’s go through the code and see how it works. SetupWe use a utility function to configure logging to have more compact, less verbose log formatting. Then we check the command line arguments. Then we select the network we’re going to use based on an optional command line parameter: There are multiple separate, independent Bitcoin networks:
Each network has its own genesis block, its own port number and its own address prefix bytes to prevent you accidentally trying to send coins across networks (which won’t work). These facts are encapsulated in a It’s strongly recommended that you develop your software on the testnet or using regtest mode. If you accidentally lose test coins, it’s no big deal as they are valueless, and you can get lots of them for free from a TestNet faucet. Make sure to send the coins back to the faucet when you’re done with them, so others can use them too. In regtest mode there’s no public infrastructure, but you can get a new block whenever you want without having to wait for one by running Keys and addressesBitcoin transactions typically send money to a public elliptic curve key. The sender creates a transaction containing the address of the recipient, where the address is an encoded form of a hash of their public key. The recipient then signs a transaction claiming the coins with their own private key. A key is represented with the An address is a textual encoding of a public key. Actually, it is a 160-bit hash of a public key, with a version byte and some checksum bytes, encoded into text using a Bitcoin-specific encoding called base58. Base58 is designed to avoid letters and numbers that could be confused with each other when written down, such as 1 and uppercase i. Because an address encodes the network for which the key is intended to be used, we need to pass in the network parameters here. The second parameter is just the user provided string. The constructor will throw if it’s unparseable or for the wrong network. Wallet app kitbitcoinj consists of various layers, each of which operates at a lower level than the last. A typical application that wants to send and receive money needs at least a To simplify this process, which often amounts to boilerplate, we provide a high level wrapper called The kit takes three arguments - the It also provides an overridable method that we can put our own code in, to customise the objects it creates for us. We override that here. Note that the appkit will actually create and set up the objects on a background thread, and thus Here, we simply check that the wallet has at least one key, and if not we add a fresh one. If we load a wallet from disk then of course this codepath is not taken. Next up, we check if we’re using regtest mode. If we are, then we tell the kit to connect only to localhost where a bitcoind in regtest mode is expected to be running. Finally, we call The The kit has accessors on it that give access to the underlying objects it configures. You can’t call these (they will assert) until the class is either started or in the process of starting up, because the objects would not be created. After the app has started up, you’ll notice there are two files in the directory where the app runs: a .wallet file, and a .spvchain file. They go together and must not be separated. Handling eventsWe want to know when we receive money so that we can forward it. This is an event and like most Java APIs in bitcoinj you learn about events by registering event listeners, which are just objects that implement an interface. There are a handful of event listener interfaces in the library:
Most apps don’t need to use all of these. Each interface provides a group of related events – you probably don’t care about all of them. Events in bitcoinj are run in a dedicated background thread that’s just used for running event listeners, called the user thread. That means it may run in parallel to other code in your application, and if you’re writing a GUI app, it means you aren’t allowed to directly modify the GUI because you aren’t in the GUI or “main” thread. However, your event listeners do not themselves need to be thread safe as events will queue up and execute in order. Nor do you have to worry about many other issues that commonly arise when using multi-threaded libraries (for instance, it’s safe to re-enter the library and it’s safe to do blocking operations). A note about writing GUI appsMost widget toolkits like Swing, JavaFX or Android have what is called thread affinity, meaning you can only use them from a single thread. To get back from a background thread to the main thread, you normally pass a closure to some utility function that schedules the closure to be run when the GUI thread is idle. To simplify the task of writing GUI apps with bitcoinj, you can specify an arbitrary Executor whenever you register an event listener. That executor will be asked to run the event listener. By default, this means passing the given Now methods on “listener” will be invoked in the UI thread automatically. Because this can get repetitive and annoying, you can also change the default executor, so all events always run on your UI thread: In some cases bitcoinj can generate a large number of events very fast, this is typical when syncing the blockchain with a wallet that has a lot of transactions in it as each one can generate a transaction confidence changed event (as they get buried deeper and deeper). It’s very likely that in future the way wallet events work will change to avoid this problem, but for now that’s how the API works. If the user thread falls behind then memory bloat can occur as event listener invocations queue up on the heap. To avoid this, you can register event handlers with Receiving moneyHere we can see what happens when our app receives money. We print out how much we received, formatted into text using a static utility method. Then we do something a bit more advanced. We call this method: Every transaction has a confidence object associated with it. The notion of confidence encapsulates the fact that Bitcoin is a global consensus system which constantly strives to reach agreement on a global ordering of transactions. Because this is a hard problem (when faced with malicious actors), it’s possible for a transaction to be double spent (in bitcoinj terminology we say it’s “dead”). That is, it’s possible for us to believe that we have received money, and later we discover the rest of the world disagrees with us. Confidence objects contain data we can use to make risk based decisions about how likely we are to have actually received money. They can also help us learn when confidence changes or reaches a certain threshold. Futures are an important concept in concurrent programming and bitcoinj makes heavy use of them, in particular, we use the Guava extension to the standard Java Here we request a depth future. This future completes when a transaction is buried by at least that many blocks in the chain. A depth of one means it appeared in the top block in the chain. So here, we’re saying “run this code when the transaction has at least one confirmation”. Normally you’d use a utility method called Then we just invoke a method we define ourselves called There’s an important thing to note here. It’s possible for a depth future to run, and then the depth of a transaction changes to be less than the future’s parameter. This is because at any time the Bitcoin network may undergo a “reorganisation”, in which the best known chain switches from one to another. If your transaction appears in the new chain at a different place, the depth may actually go down instead of up. When processing an inbound payment, you should ensure that if a transaction’s confidence goes down, you try to abort whatever service you were providing for that money. You can learn more about this topic by reading up on the SPV security model. Handling of re-orgs and double spends is a complex topic that is not covered in this tutorial. You can learn more by reading the other articles. Sending coinsThe final part of the ForwardingService is sending the coins we just received onwards. Firstly we query how much money we received (of course this is the same as Then we decide how much to send - it’s the same as what we received, minus a fee. We don’t have to attach a fee, but if we don’t, it might take a while to confirm. The default fee is quite low. To send coins, we use the wallets
Customizing the sending process and setting feesTransactions in Bitcoin can have fees attached. This is useful as an anti-denial-of-service mechanism, but it’s primarily intended to incentivise mining in later years of the system when inflation has dropped off. You can control the fee attached to a transaction by customizing a send request: Note that here, we actually set a fee per kilobyte of created transaction. This is how Bitcoin works - priority of a transaction is determined by fee divided by size, thus larger transactions require higher fees to be considered “the same” as smaller transactions. 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. |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |