-
-
Save acidburn0zzz/a4fffebd39e8bab0fb39c9f1d788882c 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 'btcruby' | |
require 'bitcoin' | |
require 'bech32' | |
require './segwit_addr' | |
require 'active_support' | |
require 'active_support/core_ext' | |
require 'ffi' | |
# Computation of P2SH-P2WPKH address | |
user_key = BTC::Key.new(public_key:BTC.from_hex("024fffe85607b555cf7697e4be0d3d34dc1868baa57c235d926e447e926c08d287")) | |
p2pkh_address = BTC::PublicKeyAddress.new(public_key: user_key.compressed_public_key) | |
redeem_script = BTC::Script.new << BTC::Script::OP_0 << p2pkh_address.hash | |
p2sh_p2wpkh_address = BTC::ScriptHashAddress.new(redeem_script:redeem_script).to_s # exemple: 3Aatw8QQbi8aNThHT1oLH49aHxysBWNrSm | |
# Transaction spending from P2SH-P2WPKH address | |
include Bitcoin::Builder | |
include Bitcoin::Protocol | |
include Bitcoin::Secp256k1 | |
prev_out="2c727aaaa8af6cdd06fae3f1e1d107a33ffc04c588d1a71fc1b5d5ac5523dfdc" | |
prev_out_index = 0 | |
value = 1118994 | |
fee = 15000 | |
@destination_address = "1Bwyn5f5EvUPazh3H2rns6ENjTUYnK9ben" | |
@redeem_script = redeem_script.data | |
spend_tx = build_tx do |t| | |
t.lock_time 0 | |
t.input do |i| | |
i.prev_out prev_out, prev_out_index, @redeem_script, value | |
i.sequence "ffffffff".htb | |
end | |
t.output do |o| | |
o.value value-fee | |
o.script {|s| s.recipient @destination_address } | |
end | |
end | |
tx = Tx.new(spend_tx.to_payload) # yet unsigned tx | |
tx.in[0].script_sig = Bitcoin::Script.new(Bitcoin::Script.pack_pushdata(@redeem_script)).to_payload | |
sig_hash = tx.signature_hash_for_witness_input(0, @redeem_script, value) | |
private_key_hex = "4b5d5ef7b85148cff9...13be6a88a267a9a84b890872d6975c" | |
sig = Bitcoin::Secp256k1.sign(sig_hash, private_key_hex.htb) + [Tx::SIGHASH_TYPE[:all]].pack("C") | |
tx.in[0].script_witness.stack << sig | |
tx.in[0].script_witness.stack << Bitcoin::Key.new(private_key_hex, nil, true).pub.htb | |
tx.to_witness_payload.bth # signed tx in hex | |
# sample tx: 01000000000101dcdf2355acd5b5c11fa7d188c504fc3fa307d1e1f1e3fa06dd6cafa8aa7a722c0000000017160014b8e1a9c4599afc3faf3d39fc89e36c2b8769d855ffffffff017ad81000000000001976a91478171d72c99f8a780df2f67b2c0edf1cb5e15d7588ac02483045022100c1203556cf1a1c9cd1abf779db6a360b8b0263bdc8c8156ac3bf368736cfa33402202a2e5d91a49d0853db00536be11f36e5ffc93f4d920991a214131be3917c4b8c0121024fffe85607b555cf7697e4be0d3d34dc1868baa57c235d926e447e926c08d28700000000 | |
# sample tx id : 25305f1c4e59c1858e1c5b8fd7290cc26f9e8311b07991c07af65d194044635b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment