https://aaron67.cc/2020/10/10/bitcoin-sign-transaction/
位元幣以 UTXO 的形式“存盤”在全網賬本中,被放置在其上的加密難題(鎖定腳本)鎖定,只有(要)提供正確的解鎖腳本解決或滿足這個加密難題或條件,才(就)可以用于支付,
結合豐富的操作碼,鎖定腳本和解鎖腳本的形式擁有廣泛的可能性,當鎖定腳本為OP_ADD 7 OP_EQUAL時,5 2和4 3都是正確解鎖腳本,當蔡明使用位元幣收款時,她需要提供一個收款模板(鎖定腳本),以確保這些位元幣只有自己才能花費,很明顯,上述這類鎖定腳本與現實世界人的身份毫無關聯,雖然蔡明可以想方設法將鎖定腳本搞的足夠復雜,但這種方式并不通用,更沒有安全保障,無法徹底杜絕其他人也能提供正確的解鎖腳本,
非對稱加密中的公鑰可以作為身份標識,簽名可以作為身份認證和授權的手段,為了做到這一點,蔡明需要在鎖定腳本里關聯自己的公鑰,并限制只有提供了正確的數字簽名才能花費這個 UTXO,數學原理可以保證,只要蔡明的私鑰沒有丟失或泄露就沒有其他人能提供正確的簽名,
上述這類交易被統稱為 P2PKH 交易(P2PK 的演進版),他們的鎖定腳本和解鎖腳本格式固定,能方便各類錢包集成,位元幣網路中的絕大多數交易都是(郭達付款給蔡明)這樣的形式,本文將以 P2PKH 交易為例,詳細介紹交易簽名的細節,
序列化 ECDSA 簽名
之前的文章介紹了如何創建 ECDSA 簽名,在將 ( r , s ) (r, s) (r,s) 放入解鎖腳本前,需要先對其序列化,格式如下,
| 位元組長度 | 內容 |
|---|---|
| 1 | 格式頭 0x30 |
| 1 | 緊跟其后的所有資料的總長度 |
| 1 | 整數標志 0x02 |
| 1 | R 的長度 |
| 變長 | 整數 r 按大端模式序列化后的位元組流 R,當流的起始位元組不小于 0x80 時,還需要在流的開頭添加 0x00 |
| 1 | 整數標志 0x02 |
| 1 | S 的長度 |
| 變長 | 整數 s 按大端模式序列化后的位元組流 S,當流的起始位元組不小于 0x80 時,還需要在流的開頭添加 0x00 |
根據定義不難寫出代碼,請注意序列化時 BIP-62 對 S 的處理,
from binascii import hexlify
def serialize_signature(signature: tuple) -> bytes:
"""Serialize ECDSA signature (r, s) to bitcoin DER format."""
r, s = signature
# BIP-62 enforce low s value in signature
if s > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0:
s = curve.n - s
# r
r_bytes = r.to_bytes(32, byteorder='big').lstrip(b'\x00')
if r_bytes[0] & 0x80:
r_bytes = b'\x00' + r_bytes
serialized = bytes([2, len(r_bytes)]) + r_bytes
# s
s_bytes = s.to_bytes(32, byteorder='big').lstrip(b'\x00')
if s_bytes[0] & 0x80:
s_bytes = b'\x00' + s_bytes
serialized += bytes([2, len(s_bytes)]) + s_bytes
return bytes([0x30, len(serialized)]) + serialized
def deserialize_signature(serialized: bytes) -> tuple:
"""Deserialize ECDSA bitcoin DER formatted signature to (r, s)"""
try:
assert serialized[0] == 0x30
assert int(serialized[1]) == len(serialized) - 2
# r
assert serialized[2] == 0x02
r_len = int(serialized[3])
r = int.from_bytes(serialized[4: 4 + r_len], byteorder='big')
# s
assert serialized[4 + r_len] == 0x02
s_len = int(serialized[5 + r_len])
s = int.from_bytes(serialized[-s_len:], byteorder='big')
return r, s
except Exception:
raise ValueError(f'Invalid DER encoded {hexlify(serialized)}.')
我們寫一個簡單的例子來測驗,
if __name__ == '__main__':
sig = (114587593887127314608220924841831336233967095853165151956820984900193959037698, 24000727837347392504013031837120627225728348681623127776947626422811445180558)
serialized_sig = serialize_signature(sig)
print(hexlify(serialized_sig))
decoded_sig = deserialize_signature(serialized_sig)
print(decoded_sig == sig)
運行結果為
b'3045022100fd5647a062d42cdde975ad4796cefd6b5613e731c08e0fb6907f757a60f44b020220350fee392713423ebfcd8026ea29cc95917d823392f07cd6c80f46712650388e'
True
準備作業
在繼續之前,我們需要先實作一些基礎方法,限于篇幅,完整的代碼請參考 Gist,
- crypto.py,包含常用的哈希演算法和 Base58Check 編解碼方法等
- meta.py,包含
int_to_varint、address_to_public_key_hash、build_locking_script等常用方法,這些內容在之前的“學習筆記”系列文章中都有過介紹
順便封裝一下交易的輸入和輸出,
from collections import namedtuple
from binascii import unhexlify
SEQUENCE = 0xffffffff.to_bytes(4, byteorder='little')
class TxIn:
def __init__(self, satoshi: int, txid: str, index: int, locking_script: str, sequence=SEQUENCE):
self.satoshi = satoshi.to_bytes(8, byteorder='little')
self.txid = unhexlify(txid)[::-1]
self.index = index.to_bytes(4, byteorder='little')
self.locking_script = unhexlify(locking_script)
self.locking_script_len = int_to_varint(len(self.locking_script))
self.unlocking_script = b''
self.unlocking_script_len = b''
self.sequence = sequence
TxOut = namedtuple('TxOut', 'address satoshi')
交易摘要
驗證 ECDSA 簽名是否有效,需要三個引數:
- 訊息
- ECC 公鑰
- ECDSA 簽名
如果你還記得 P2PKH 的定義,你會發現,不論是解鎖腳本還是鎖定腳本,都沒有明確簽名對應的訊息是什么,
[簽名] [公鑰] OP_DUP OP_HASH160 [公鑰哈希] OP_EQUALVERIFY OP_CHECKSIG
請注意,解鎖腳本中的簽名,其實由兩部分構成,
| 位元組長度 | 內容 |
|---|---|
| 1 | 緊跟其后的所有資料的總長度 |
| 變長 | 序列化后的 ECDSA 簽名 |
| 1 | SIGHASH |
之前的文章提到過,交易中簽名的訊息,是交易本身,更準確的說,是通過 SIGHASH 標記區分的、交易中特定的資料子集,
交易本身在簽名和驗簽時是已知的,也就是說,雖然腳本中沒有直接存盤訊息的內容,但存盤了能間接推算出訊息內容的 SIGHASH,這個“推算出的訊息內容”,叫交易的摘要,也叫原像(PreImage),
我們需要實作一個方法,根據交易和 SIGHASH 來計算交易的摘要,
SIGHASH 有 6 不同的型別:
- SIGHASH_ALL
- SIGHASH_NONE
- SIGHASH_SINGLE
- SIGHASH_ALL | ANYONECANPAY
- SIGHASH_NONE | ANYONECANPAY
- SIGHASH_SINGLE | ANYONECANPAY
全網幾乎所有的交易都使用 SIGHASH_ALL,這是最簡單的一種型別,我們將以此為例,其他型別的 SIGHASH 本文暫不涉及,你可以通過文章 SIGHASH flags 和 BIP-143 探索,
請注意,SIGHASH_ALL 會對所有的交易輸入簽名,也就是說,對應交易摘要的個數,與交易輸入的個數相同,
VERSION = 0x01.to_bytes(4, 'little')
LOCK_TIME = 0x00.to_bytes(4, byteorder='little')
SH_ALL = 0x01
SH_FORKID = 0x40
SIGHASH_ALL = SH_ALL | SH_FORKID
def serialize_outputs(outputs) -> bytes:
output_bytes = b''
for output in outputs:
output_bytes += output.satoshi.to_bytes(8, byteorder='little') + build_locking_script(address_to_public_key_hash(output.address))
return output_bytes
def transaction_digest(tx_ins: list, tx_outs: list, lock_time=LOCK_TIME, sighash=SIGHASH_ALL) -> list:
# BIP-143 https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
# 1. nVersion of the transaction (4-byte little endian)
# 2. hashPrevouts (32-byte hash)
# 3. hashSequence (32-byte hash)
# 4. outpoint (32-byte hash + 4-byte little endian)
# 5. scriptCode of the input (serialized as scripts inside CTxOuts)
# 6. value of the output spent by this input (8-byte little endian)
# 7. nSequence of the input (4-byte little endian)
# 8. hashOutputs (32-byte hash)
# 9. nLocktime of the transaction (4-byte little endian)
# 10. sighash type of the signature (4-byte little endian)
if sighash == SIGHASH_ALL:
hash_prevouts = double_sha256(b''.join([tx_in.txid + tx_in.index for tx_in in tx_ins]))
hash_sequence = double_sha256(b''.join([tx_in.sequence for tx_in in tx_ins]))
hash_outputs = double_sha256(serialize_outputs(tx_outs))
digests = []
for tx_in in tx_ins:
digests.append(
VERSION +
hash_prevouts + hash_sequence +
tx_in.txid + tx_in.index + tx_in.locking_script_len + tx_in.locking_script + tx_in.satoshi + tx_in.sequence +
hash_outputs +
lock_time +
sighash.to_bytes(4, byteorder='little')
)
return digests
raise ValueError(f'Unsupported SIGHASH value {sighash}')
實驗
讓我們在之前的例子上繼續,私鑰
0xf97c89aaacf0cd2e47ddbacc97dae1f88bec49106ac37716c451dcdd008a4b62
鎖定了 3 個 UTXO,
priv_key = 0xf97c89aaacf0cd2e47ddbacc97dae1f88bec49106ac37716c451dcdd008a4b62
pub_key = scalar_multiply(priv_key, curve.g)
inputs = [
TxIn(satoshi=1000, txid='d2bc57099dd434a5adb51f7de38cc9b8565fb208090d9b5ea7a6b4778e1fdd48', index=1, locking_script='76a9146a176cd51593e00542b8e1958b7da2be97452d0588ac'),
TxIn(satoshi=1000, txid='d2bc57099dd434a5adb51f7de38cc9b8565fb208090d9b5ea7a6b4778e1fdd48', index=2, locking_script='76a9146a176cd51593e00542b8e1958b7da2be97452d0588ac'),
TxIn(satoshi=1000, txid='fcc1a53e8bb01dbc094e86cb86f195219022c26e0c03d6f18ea17c3a3ba3c1e4', index=0, locking_script='76a9146a176cd51593e00542b8e1958b7da2be97452d0588ac'),
]
驗證已簽名的交易
事先使用其他錢包 App,消耗inputs[0],向地址1JDZRGf5fPjGTpqLNwjHFFZnagcZbwDsxw支付 800 聰,對應的交易是
4674da699de44c9c5d182870207ba89e5ccf395e5101dab6b0900bbf2f3b16cb
基于此場景,讓我們開始第一個實驗:驗證已簽名交易中的 ECDSA 簽名,
公鑰已知,為了驗簽,還需要利用這個交易
- 計算出交易摘要,得到要簽名的訊息
- 反序列化簽名,得到 ( r , s ) (r, s) (r,s)
開始吧,
- 構造輸入和輸出
tx_inputs = inputs[0:1]
tx_outputs = [TxOut(address='1JDZRGf5fPjGTpqLNwjHFFZnagcZbwDsxw', satoshi=800)]
- 根據交易的輸入和輸出計算交易摘要(使用 SIGHASH_ALL)
tx_digest = transaction_digest(tx_inputs, tx_outputs)[0]
- 反序列化簽名,得到 ( r , s ) (r, s) (r,s)
通過區塊鏈瀏覽器,查詢序列化后的交易資料,

圖中標注的部分,是序列化后的 ECDSA 簽名,通過之前實作的方法反序列化,
serialized_sig = unhexlify('304402207e2c6eb8c4b20e251a71c580373a2836e209c50726e5f8b0f4f59f8af00eee1a022019ae1690e2eb4455add6ca5b86695d65d3261d914bc1d7abb40b188c7f46c9a5')
sig = deserialize_signature(serialized_sig)
- 驗簽
print(verify_signature(pub_key, tx_digest, sig))
運行結果為
True
驗簽成功,

創建交易并簽名
第二個小實驗,我們用自己實作的代碼,創建交易并對其簽名,如果交易廣播后位元幣網路能正常接受,那么說明我們的代碼是正確的,
這個交易會將inputs[1]和inputs[2]作為輸入,向地址18CgRLx9hFZqDZv75J5kED7ANnDriwvpi1支付 1700 聰,
開始吧,
- 構造輸入和輸出,并計算交易摘要
tx_inputs = inputs[1:]
tx_outputs = [TxOut(address='18CgRLx9hFZqDZv75J5kED7ANnDriwvpi1', satoshi=1700)]
tx_digests = transaction_digest(tx_inputs, tx_outputs)
- 對每個交易摘要簽名,并且構造對應的解鎖腳本
serialized_pub_key = serialize_public_key(pub_key)
for i in range(len(tx_digests)):
tx_digest = tx_digests[i]
sig = sign_message(priv_key, tx_digest)
serialized_sig = serialize_signature(sig)
# Build unlocking script = LEN + der + sighash + LEN + public_key
tx_inputs[i].unlocking_script = bytes([len(serialized_sig) + 1]) + serialized_sig + bytes([SIGHASH_ALL, len(serialized_pub_key)]) + serialized_pub_key
print(hexlify(tx_inputs[i].unlocking_script))
tx_inputs[i].unlocking_script_len = int_to_varint(len(tx_inputs[i].unlocking_script))
print(hexlify(tx_inputs[i].unlocking_script_len))
- 根據輸入(已簽名)和輸出構造完整的交易
序列化后的交易格式在“學習筆記”系列文章中有過詳細介紹,這里也列出來方便你對應代碼,
| 位元組長度 | 內容 |
|---|---|
| 4 | 交易結構的版本 |
| 1~9 VarInt | 交易包含幾個輸入,非零正整數 |
| 變長 | 輸入陣列 |
| 1~9 VarInt | 交易包含幾個輸出,非零正整數 |
| 變長 | 輸出陣列 |
| 4 | nLockTime |
def serialize_transaction(tx_ins: list, tx_outs: list, lock_time=LOCK_TIME) -> bytes:
# version
raw_transaction = VERSION
# inputs
raw_transaction += int_to_varint(len(tx_ins))
for tx_in in tx_ins:
raw_transaction += tx_in.txid + tx_in.index + tx_in.unlocking_script_len + tx_in.unlocking_script + tx_in.sequence
# outputs
raw_transaction += int_to_varint(len(tx_outs)) + serialize_outputs(tx_outs)
# lock_time
raw_transaction += lock_time
return raw_transaction
將序列化后的交易資料列印出來,廣播時會用到,同時計算交易的哈希,
raw = serialize_transaction(tx_inputs, tx_outputs)
print(hexlify(raw))
txid = double_sha256(raw)
print(txid)
- 驗證
代碼的運行結果為
b'463043022053b1f5a28a011c60614401eeef88e49c676a098ce36d95ded1b42667f40efa37021f4de6703f8c74b0ce5dad617c00d1fb99580beb7972bf681e7215911c3648de412102e46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789'
b'69'
b'483045022100b9f293781ae1e269591df779dbadb41b9971d325d7b8f83d883fb55f2cb3ff7602202fe1e822628d85b0f52966602d0e153be411980d54884fa48a41d6fc32b4e9f5412102e46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789'
b'6b'
b'010000000248dd1f8e77b4a6a75e9b0d0908b25f56b8c98ce37d1fb5ada534d49d0957bcd20200000069463043022053b1f5a28a011c60614401eeef88e49c676a098ce36d95ded1b42667f40efa37021f4de6703f8c74b0ce5dad617c00d1fb99580beb7972bf681e7215911c3648de412102e46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789ffffffffe4c1a33b3a7ca18ef1d6030c6ec222902195f186cb864e09bc1db08b3ea5c1fc000000006b483045022100b9f293781ae1e269591df779dbadb41b9971d325d7b8f83d883fb55f2cb3ff7602202fe1e822628d85b0f52966602d0e153be411980d54884fa48a41d6fc32b4e9f5412102e46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789ffffffff01a4060000000000001976a9144efe5cabaa9b56976d0c2a6171eb6af7f1ece36388ac00000000'
b'c04bbd007ad3987f9b2ea8534175b5e436e43d64471bf32139b5851adf9f477e'
其中,第一行和第三行是兩個交易輸入的解鎖腳本,倒數第二行是序列化后的交易,最后一行是這個交易的哈希,
我在 WhatsOnChain 上,正常廣播了這個交易,請注意下圖示注的部分,瀏覽器決議后的解鎖腳本,跟我們的計算結果是相同的,

至此,實驗成功,

完整代碼
Gist sign_transaction.py
參考
- BIP-62
- Programming Bitcoin by Jimmy Song,Chapter 4. Serialization
- Money Button Documentation,Signatures
- BIP-143
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/170080.html
標籤:其他
下一篇:Fortran程式設計 n!
