RateLimited°C
09-20-2024
BSV
$49.43
Vol 20.2m
1.51%
BTC
$63482
Vol 44202.51m
1.85%
BCH
$340.6
Vol 300.77m
-1.58%
LTC
$66.18
Vol 367.04m
1.47%
DOGE
$0.1
Vol 743.2m
2.51%

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

Coinbase transaction is the first transaction in a block.

screenshot of block header
Coinbase Transaction in a Block

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

screenshot of a table with binary code
A Coinbase Transaction

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.

screenshot of blockheight code
Blockchain Contract

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.

a flowchart
A Coinbase Transaction and its Merkle Path

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

a screenshot of coinbase code
MerklePath Contract

Summary

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.

Recommended for you

Blockchain enables autonomous AI agents to learn
Utilizing blockchain tech, a group of Belgian scientists enabled autonomous AI agents to learn and communicate securely, contributing to the...
September 17, 2024
WhatsOnChain gets own UTXO endpoints for BSV blockchain services
With ElectrumX set to retire in October, WhatsOnChain is gearing up to implement a new UTXO set of API endpoints,...
September 16, 2024
Advertisement