Access Blockchain Data from Bitcoin Smart Contracts: Part 3
Access Block Height and Coinbase Transaction
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.