哪些網(wǎng)站可以做教師資格證題目seo網(wǎng)絡優(yōu)化軟件
我們已經(jīng)執(zhí)行了 Bitcoin SV 和 Bitcoin Core 之間的首次原子交換。 這一成就代表了比特幣 SV 的重大進步,以去信任的方式促進了與其他區(qū)塊鏈的無縫互操作性。
圖片源自Gemini
在上一篇文章中,我們解釋了原子交換的高級理論。 我們深入研究了使用哈希時間鎖定合約(HTLC)在 BSV 和 BTC 之間進行原子交換的實際示例。 讓我們將此過程分解為四個基本步驟,每個步驟都包含您可以自己運行的代碼片段。
第 1 步:Alice 在 BTC 上發(fā)起交易
該過程從 Alice 開始,她選擇一個隨機整數(shù) x
并使用 SHA-256 算法創(chuàng)建一個哈希值 (xHash)。 接下來,Alice 部署了一個 Pay-to-Witness-Script-Hash (P2WSH) 交易,其中包括她想要與 Bob 交易的 BTC 數(shù)量。
我們使用 bitcoinutils 庫構(gòu)建 Alice 的交易:
def main():# always remember to setup the networksetup('testnet')# TODO: remember to adjust the values marked by "TODO" to your use case.alicePriv = PrivateKey('TODO')alicePub = alicePriv.get_public_key()bobPub = PublicKey('TODO')txid = 'TODO' # Previous transaction IDvout = 2 # Previous transaction ouput indexamount = 0.00001850 # Amount in outputfee = 0.00000125 # Fee in new transactionx = 'f00cfd8df5f92d5e94d1ecbd9b427afd14e03f8a3292ca4128cd59ef7b9643bc'xHash = '1908c59a71781b7a44182ec39dd84a8a9e13dc31691fead8631730f5f5ab7b65'nBlocksLocked = '06' # 6 blocks ~ 1 hr# HTLC script:htlc_redeem_script = Script(['OP_IF','OP_SHA256',xHash,'OP_EQUALVERIFY',bobPub.to_hex(),'OP_CHECKSIG','OP_ELSE',nBlocksLocked,'OP_CHECKSEQUENCEVERIFY','OP_DROP',alicePriv.get_public_key().to_hex(),'OP_CHECKSIG','OP_ENDIF'])toAddress = P2wshAddress.from_script(htlc_redeem_script)# Create transaction input from tx id of utxo.txIn = TxInput(txid, vout)redeem_script1 = Script(['OP_DUP', 'OP_HASH160', alicePub.to_hash160(), 'OP_EQUALVERIFY', 'OP_CHECKSIG'])# Create transaction output, which contains the P2WSH for the HTLC script.txOut = TxOutput(to_satoshis(amount - fee), toAddress.to_script_pub_key())# Create transaction.tx = Transaction([txIn], [txOut], has_segwit=True)# Sign transaction.sig1 = alicePriv.sign_segwit_input(tx, 0, redeem_script1, to_satoshis(amount))tx.witnesses.append(Script([sig1, alicePub.to_hex()]))# Print raw signed transaction ready to be broadcast.print("\nRaw signed transaction:\n" + tx.serialize())print("\nTxId:", tx.get_txid())
執(zhí)行后,代碼將打印原始的序列化交易,我們可以使用 Blockstream 的區(qū)塊瀏覽器將其廣播到 BTC 網(wǎng)絡。
該 P2WSH 交易腳本由條件子句組成,這些條件子句包括需要 Bob 的公鑰和秘密 x,或者 Alice 的簽名和花費交易的時間延遲。
Bob 在 BTC 上進行應答
作為回應,Bob 在 BSV 區(qū)塊鏈上部署了等效的 sCrypt 智能合約,其中包含他準備與 Alice 交換的 BSV 金額。
class HashTimeLockContract extends SmartContract {@prop() readonly alicePubKey: PubKey@prop() readonly bobPubKey: PubKey@prop() readonly hashX: Sha256@prop() readonly timeout: bigint // Can be a timestamp or block height.// hash lock@method()public unlock(x: ByteString, aliceSig: Sig) {// Check if H(x) == this.hashXassert(sha256(x) == this.hashX, 'Invalid secret.')// Verify Alices signature.assert(this.checkSig(aliceSig, this.alicePubKey))}// time lock@method()public cancel(bobSig: Sig) {assert(this.ctx.locktime >= this.timeout, 'locktime has not yet expired')// Verify Bobs signature.assert(this.checkSig(bobSig, this.bobPubKey))}
}
Bob 獲得了 x
的哈希值,但不是 x
本身,以及 Alice 的公鑰。 然后,他使用以下部署代碼部署智能合約:
const alicePubKey = bsv.PublicKey.fromHex('TODO')const bobPrivKey = bsv.PrivateKey.fromWIF('TODO')
const bobPubKey = bobPrivKey.publicKeyconst amount = 100000 // TODO: amount of BSV to be locked in the contractconst xHash = toByteString('1908c59a71781b7a44182ec39dd84a8a9e13dc31691fead8631730f5f5ab7b65'
)
const lockTimeMin = 1688715000 // Timestamp, after which Bob can withdraw his funds.await CrossChainSwap.compile()// Connect Bob signer.
const provider = new DefaultProvider(bsv.Networks.testnet)
const signer = new TestWallet(bobPrivKey, provider)const crossChainSwap = new CrossChainSwap(PubKey(alicePubKey.toHex()),PubKey(bobPubKey.toHex()),xHash,BigInt(lockTimeMin)
)
await crossChainSwap.connect(signer)// Contract deployment.
const deployTx = await crossChainSwap.deploy(amount)
console.log('CrossChainSwap contract deployed: ', deployTx.id)
第三步:Alice 解鎖 Bob 的合約
成功部署 sCrypt 合約后,Alice 現(xiàn)在可以通過泄露秘密 x
來調(diào)用 Bob 合約的公共方法 unlock()
。 結(jié)果,Alice 擁有了 Bob 的 BSV。
const deployedContractTXID = 'TODO'
const x = toByteString('f00cfd8df5f92d5e94d1ecbd9b427afd14e03f8a3292ca4128cd59ef7b9643bc')// Alice unlocks contract and takes the funds.
const provider = new DefaultProvider(bsv.Networks.testnet)
const signer = new TestWallet(alicePrivKey, provider)const tx = await signer.provider.getTransaction(deployedContractTXID)
const crossChainSwap = CrossChainSwap.fromTx(tx, 0)
await crossChainSwap.connect(signer)const { tx: callTx, atInputIndex } =await crossChainSwap.methods.unlock(x,(sigResps) => findSig(sigResps, alicePubKey),{pubKeyOrAddrToSign: alicePubKey,} as MethodCallOptions<CrossChainSwap>)
console.log('CrossChainSwap "unlock" method called: ', callTx.id)
第四步:Bob 取回 Alice 的 BTC
一旦 Alice 透露了 x
,Bob 就可以用它來解鎖 BTC 區(qū)塊鏈上的 P2WSH UTXO。 這個過程允許鮑勃索取愛麗絲的比特幣,從而完成原子交換。
def main():# always remember to setup the networksetup('testnet')# TODO: Set values:bobPriv = PrivateKey('TODO')bobPub = bobPriv.get_public_key()alicePub = PublicKey('TODO')txid = 'TODO' # Previous transaction IDvout = 0 # Previous transaction ouput indexamount = 0.00001725 # Amount in outputfee = 0.00000125 # Fee in new transactionx = 'f00cfd8df5f92d5e94d1ecbd9b427afd14e03f8a3292ca4128cd59ef7b9643bc'xHash = '1908c59a71781b7a44182ec39dd84a8a9e13dc31691fead8631730f5f5ab7b65'nBlocksLocked = '06' # 6 blocks ~ 1 hrtoAddress = P2wpkhAddress.from_address('TODO')# HTLC Script:htlc_redeem_script = Script(['OP_IF','OP_SHA256',xHash,'OP_EQUALVERIFY',bobPub.to_hex(),'OP_CHECKSIG','OP_ELSE',nBlocksLocked,'OP_CHECKSEQUENCEVERIFY','OP_DROP',alicePub.to_hex(),'OP_CHECKSIG','OP_ENDIF'])fromAddress = P2wshAddress.from_script(htlc_redeem_script)# Create transaction input from tx id of UTXOtxin = TxInput(txid, vout)txOut1 = TxOutput(to_satoshis(amount - fee), toAddress.to_script_pub_key())tx = Transaction([txin], [txOut1], has_segwit=True)# NOTE: In P2WSH, the argument for OP_IF and OP_NOTIF MUST be exactly an empty vector or 0x01, or the script evaluation fails immediately.# Normal unlock:sig1 = bobPriv.sign_segwit_input(tx, 0, htlc_redeem_script, to_satoshis(amount))tx.witnesses.append(Script([sig1,x,'01', # OP_TRUEhtlc_redeem_script.to_hex()]))# print raw signed transaction ready to be broadcastedprint("\nRaw signed transaction:\n" + tx.serialize())print("\nTxId:", tx.get_txid())
我們可以廣播打印的原始交易并完成交換。
爭議解決
在發(fā)生爭議的情況下,Alice 和 Bob 都可以在一段時間后提取資金。
此功能提供了一種故障安全機制,可確保在交換不成功或有爭議的情況下不會永久鎖定資金。 時間限制為雙方解鎖各自的合同提供了足夠的窗口。
在愛麗絲的例子中,我們可以修改見證人的構(gòu)造:
# ...# Create transaction input from tx id of UTXO.
txin = TxInput(txid, vout, sequence=bytes.fromhex('FFFFFFFE'))# ...locktime = bytes.fromhex('64A7F990') # 1688730000
tx = Transaction([txin], [txOut1], has_segwit=True, locktime=locktime)# Withdrawal:
sig1 = alicePriv.sign_segwit_input(tx, 0, htlc_redeem_script, to_satoshis(amount))
tx.witnesses.append(Script([sig1,'', # OP_FALSEhtlc_redeem_script.to_hex()]))#...
傳遞 OP_FALSE
作為第一個輸入將在 OP_ELSE
之后執(zhí)行腳本,這會檢查時間鎖定是否已過期。
同樣,在 Bob 的情況下,我們修改代碼以調(diào)用 cancel
方法:
// Bob withdraws after timeout passed.
const { tx: callTx, atInputIndex } =await crossChainSwap.methods.cancel((sigResps) => findSig(sigResps, bobPubKey),{lockTime: 1688730000,pubKeyOrAddrToSign: bobPubKey,} as MethodCallOptions<CrossChainSwap>)
console.log('CrossChainSwap "cancel" method called: ', callTx.id)
首次成功跨鏈BTC-BSV互換
我們在 BSV 和 BTC 主網(wǎng)之間進行了首次成功的原子交換。
-
BTC 上的初始 P2WSH 交易:af7a8c31e489c18d6fe46141cf2cbc777aeb23672679eb199bde4813d6fe41d4
-
BSV 上等效的 sCrypt 智能合約交易:8598d203e8bdd45b7025e334cdebdef06be88381dec245d95108e658e8373f9c
-
Alice 調(diào)用
unlock
方法:68c2c5a91645112df6b62a5ee6ea9e0e22f29499b88c9ccffc23f8f86ec63d09 -
鮑勃解鎖了 BTC:9c697bf8f0d2c11285cfab3a2b8a856a1c18ae048d481c7bb3f93f9ccd2dbaad
這也是一個未完成的交換示例。 愛麗絲和鮑勃都收回了他們的資金。
- BTC: 395dde14e489208302c1d6ac3b4fc0db890c000fd79f3e836fc74043a54480ff
- BSV: 12e701237a1f6da2b69f1d4dab2b1208d3f6003f7b45ef178c5c7d9e00c54273
本文中顯示的所有代碼都可以在我們的 GitHub 上找到。