Skip to content

Blocks

Most applications never touch a whole block, since nodes and APIs hand us Transactions one at a time. When we do need one, e.g. to check a Merkle root or to read the coinbase Transaction, the Block class parses the raw bytes. The examples on this page use the Bitcoin genesis block, which makes the results rather easy to check.

Block block = new Block(Utils.HEX.decode(rawBlockHex));
String blockHash = block.getHash().toString();
String merkleRoot = block.getMerkleRoot().toString();
List<Transaction> transactions = block.getTransactions();

In the preceding example:

  • the constructor takes the serialised block as bytes, and parses the header and every Transaction in it,
  • getHash() and getMerkleRoot() return a Sha256Hash, whose toString() gives us the hex in display byte order, the same as a block explorer shows,
  • getTransactions() returns the parsed Transactions, in block order.

The other header fields have getters of their own.

long version = block.getVersion();
String previousBlock = block.getPrevBlockHash().toString();
long time = block.getTime(); // seconds since the Unix epoch
long bits = block.getDifficultyTarget(); // the target, in compact form
long nonce = block.getNonce();

getTimeAsDate() gives us the time as a java.util.Date, and getTxIds() lists the Transaction ids.

The first Transaction in every block is the coinbase, which pays the block reward to the miner.

Transaction coinbase = block.getTransactions().get(0);
boolean isCoinbase = coinbase.isCoinBase();
BigInteger reward = coinbase.getOutputs().get(0).getAmount();

The genesis coinbase pays 50 coins, i.e. 5,000,000,000 satoshis. Since it is the only Transaction in the block, its id is also the block’s Merkle root.

Block block = new Block(Utils.HEX.decode(GENESIS_HEX));
byte[] bytes = block.bitcoinSerialize();

Parsing and serialising round-trip exactly, so the bytes we get out are the bytes we put in.

Do note that Block keeps every Transaction in memory. For the large blocks one finds on BSV today, that can be a great deal of memory, so it is worth reading only the blocks you need.