Resource Data

Accessing Blockchain Data from Bitcoin Smart Contracts: Part 3

This article first appeared on Medium.

The block header contains the timestamp when the block is created. But often we want to access the block height, which is not included in a block header. We are devising a new technique to recover block height with confidence, which is included in Coinbase transactions.

Block Height From Coinbase Transaction

A Coinbase transaction is the first transaction in a block.

Coinbase transaction in a block

BIP34 indicates that the block height should be the first item in the Coinbase transaction unlock script as shown below.

screenshot of a table with binary code
A Coinbase transaction

Function blockHeight () returns the height of a block with a given header, as shown below. Using our previous technique, we can access a transaction in a given block using the Merkle proof in rows 13 and 16. We can further verify that it is a Coinbase transaction that meets three constraints from row 5. at 8 :

  • He has exactly one txin.
  • The previous hash of this txin is 0x0000… 0000.
  • The previous index of this txin is 0xFFFFFFFF.

Once we have the Coinbase transaction, we extract the block height from it in row 21.

block height code screenshot
Blockchain contract

An alternative to check Coinbase

There is another way to verify a transaction is Coinbase, using its Merkle path. Since Coinbase is the first trade in a block, all of the nodes in its Merkle path should be on the right, as shown in the chart below.

an organizational chart
A Coinbase transaction and its Merkle path

We can just check if all the siblings on Merkle Road are on the right. The code is shown below:

a screenshot of the coinbase code
MerklePath contract


Once we have the height of a block, we can use it in all kinds of smart contracts.

Coinbase may contain other information besides the block height, such as MinerID. It can also be used in a smart contract.

We list some examples below:

  • A contract that can only be unlocked after a certain block height, similar to CheckLockTimeVerify.
  • A contract that only pays a miner if at least one of the blocks in the height of 720000 to 72010 is mined by him, which accepts low-cost private transactions from partners.

We look forward to all kinds of creative contracts that you can build on these techniques.

Read the latest ebook, BSV Blockchain as an Enterprise Cybersecurity Framework.

New to Bitcoin? Discover CoinGeek Bitcoin for beginners section, the ultimate resource guide to learning more about Bitcoin — as originally envisioned by Satoshi Nakamoto — and blockchain.