Last active
December 16, 2021 09:26
-
-
Save pierrenoizat/f082d62d49e49f81978b97ad5900789a to your computer and use it in GitHub Desktop.
Generate Segwit P2SH-P2WPKH address, create tx spending from it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bitcoin' | |
include Bitcoin | |
include Bitcoin::Builder | |
include Bitcoin::Protocol | |
include Bitcoin::Util | |
include Bitcoin::Secp256k1 | |
# Compute P2SH-P2WPKH address: | |
compressed_public_key = "02530c548d402670b13ad8887ff99c294e67fc18097d236d57880c69261b42def7" | |
redeem_script = Script.from_string("0 #{hash160(compressed_public_key)}").to_payload | |
p2sh__p2wpkh_address = hash160_to_p2sh_address(hash160(redeem_script.bth)) | |
# Build Segwit transaction spending from P2SH-P2WPKH address: | |
utxo_txid="4ec4f658d86549544ac0b7b4f62ff4225f458c97243c7abf17e67584e27d0d08" | |
utxo_index = 0 | |
amount = 100000 | |
fee = 15000 | |
@destination_address = "1Bwyn5f5EvUPazh3H2rns6ENjTUYnK9ben" | |
spend_tx = build_tx do |t| | |
t.lock_time 0 | |
t.input do |i| | |
i.prev_out utxo_txid, utxo_index, redeem_script, amount | |
i.sequence "ffffffff".htb | |
end | |
t.output do |o| | |
o.value amount-fee | |
o.script {|s| s.recipient @destination_address } | |
end | |
end | |
tx = Tx.new(spend_tx.to_payload) # unsigned tx | |
tx.in[0].script_sig = Script.new(Script.pack_pushdata(redeem_script)).to_payload | |
sig_hash = tx.signature_hash_for_witness_input(0, redeem_script, amount) | |
private_key_hex = "25940ad..f7b2d9" | |
sig = Secp256k1.sign(sig_hash, private_key_hex.htb) | |
tx.in[0].script_witness.stack << sig + [Tx::SIGHASH_TYPE[:all]].pack("C") | |
tx.in[0].script_witness.stack << compressed_public_key.htb | |
tx.to_witness_payload.bth # signed tx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment