Access blockchain data from Bitcoin Smart contracts: Part 3

This post was first published on Medium.

Block header contains timestamp when the block is created. But often we want to access block height, which is not included in a block header. We devise a novel technique to fetch block height trustlessly, which is included in Coinbase transactions.

Block height From Coinbase transaction

A Coinbase transaction is the first transaction in a block.

BIP34 dictates block height must be the first item in the Coinbase transaction’s unlocking script as shown below.

The 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 Merkle proof at Line 13 and 16. We can further verify it is a Coinbase transaction satisfying three constraints from Line 5 to 8:

  • It has exactly one txin.
  • This txin’s prevout hash is 0x0000…0000.
  • This txin’s prevout index is 0xFFFFFFFF.

Once we have the Coinbase transaction, we extract block height from it at Line 21.

An alternative to verify Coinbase

There is another way to verify a transaction is Coinbase, using its Merkle path. Since Coinbase is the first transaction in a block, all nodes on its Merkle path must lie on the right as the graph shows below.

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


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

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

We list a few examples below:

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

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

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

Source: Read Full Article