Skip to content

Instantly share code, notes, and snippets.

@werner
Forked from pierrenoizat/p2sh_p2wpkh.rb
Last active January 7, 2019 20:56
Show Gist options
  • Save werner/170358b3dc45a7507529a156a515d435 to your computer and use it in GitHub Desktop.
Save werner/170358b3dc45a7507529a156a515d435 to your computer and use it in GitHub Desktop.
Generate Segwit P2SH-P2WPKH address, create tx spending from it. with xpub
require 'btcruby'
require 'bitcoin'
require 'bech32'
require './segwit_addr'
require 'active_support'
require 'active_support/core_ext'
require 'ffi'
# Computation of P2SH-P2WPKH address
p2pkh_address = BTC::PublicKeyAddress.new(public_key: "tpubb5EfG8gQ6RzUC2WmC1cCYW...", network: BTC::Network.testnet)
redeem_script = BTC::Script.new << BTC::Script::OP_0 << p2pkh_address.hash
p2sh_p2wpkh_address = BTC::ScriptHashAddress.new(redeem_script:redeem_script, network: BTC::Network.testnet).to_s
# 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