區塊頭包含區塊創建時的時間戳,但通常我們想要訪問區塊高度,它不包含在塊頭中,我們設計了一種新技術來無需信任地獲取包含在 coinbase 交易中的區塊高度,
Coinbase 交易的區塊高度
coinbase 交易是區塊中的第一筆交易,

BIP34 規定區塊高度必須是 coinbase 交易解鎖腳本中的第一項,如下所示,

函式 blockHeight() 回傳具有給定區塊頭的塊的高度,如下所示,使用我們之前的技術,我們可以在第 14 行和第 17 行使用 Merkle 證明訪問給定塊中的交易,我們可以進一步驗證它是滿足第 3 行到第 5 行三個約束條件的 coinbase 交易:
// is raw transaction a coinbase tx
static function isCoinbase(bytes tx) : bool {
return tx[4:5] == b'01' // only 1 input
&& tx[5:37] == b'0000000000000000000000000000000000000000000000000000000000000000' // null txid: all zeros
&& tx[37:41] == b'FFFFFFFF'; // null vout: all Fs
}
// get height of the block identified by the header
static function blockHeight(BlockHeader bh, bytes coinbaseTx, MerkleProof merkleproof) : int {
// ensure coinbase it's in the block
require(txInBlock(hash256(coinbaseTx), bh, merkleproof));
// ensure it's coinbase
require(MerklePath.isCoinbase(merkleproof));
// alternative
// require(isCoinbase(merkleproof));
return readBlockHeight(coinbaseTx);
}
// parse block height from coinbase tx: BIP34
static function readBlockHeight(bytes coinbaseTx) : int {
// block height is at the beginning of the unlocking script and encoded in varint
return Utils.fromLEUnsigned(Utils.readVarint(coinbaseTx[BLOCK_HEIGHT_POS:]));
}
驗證 Coinbase 的其它方法
還有另一種驗證交易的方法是 coinbase,使用它的 Merkle 路徑,由于 coinbase 是區塊中的第一筆交易,因此其 Merkle 路徑上的所有節點都必須位于右側,如下圖所示,

// a tx if coinbase if all nodes on its Merkle path are on the right branch
static function isCoinbase(MerkleProof merkleproof) : bool {
bool res = true;
loop (DEPTH) : i {
Node node = merkleproof[i];
if (node.left != INVALID_NODE) {
// node on the right
res = res && node.left == RIGHT_NODE;
}
}
return res;
}
總結
一旦我們有了一個區塊的高度,我們就可以在各種智能合約中使用它,
我們在下面列出了幾個例子:
-
一種只能在一定區塊高度后才能解鎖的合約,類似于 CheckLockTimeVerify,
-
如果礦工至少開采了從高度 720000 到 720010 的區塊中的一個,則只向礦工支付報酬,礦工接受合作伙伴的私人低費用交易,
我們期待您可以在這些技術的基礎上建立各種創造性的合約,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/392189.html
標籤:區塊鏈
下一篇:鏈游開發公司 區塊鏈游戲開發平臺
