Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Fund a native Bech32-encoded segwit P2WPKH address from a standard Bitcoin address, then spend from the P2WPKH address.
require 'btcruby'
require 'bitcoin'
require 'bech32'
require 'segwit_addr'
require 'active_support'
require 'active_support/core_ext'
require 'ffi'
BTC::Network.default= BTC::Network.mainnet
@public_key = "02530c548d402670b13ad8887ff99c294e67fc18097d236d57880c69261b42def7" # public key MUST be compressed
# Calculation of Native P2WPKH Address:
p2pkh_address = BTC::Data.data_from_hex(@public_key))
script_pub_key =
script_pub_key<< BTC::Script::OP_0
script_pub_key<< p2pkh_address.hash
native_p2wpkh_address =
native_p2wpkh_address.hrp = 'bc' # hrp = human-readable part
native_p2wpkh_address.scriptpubkey = script_pub_key.to_hex
puts "\n Native P2WPKH Address: #{native_p2wpkh_address.addr} \n\n" # bc1qg9stkxrszkdqsuj92lm4c7akvk36zvhqw7p6ck
# Transaction funding Native P2WPKH Address:
BTC::Network.default= BTC::Network.mainnet
@wif = "L2ULKxeRKzYD...EdCgVQgG93kyQMdTEwcoX3hF"
prev_out = "0dbf14f92a2929032b8628031c755e8320fd08bb350f416eaa9c134e2acf98fe"
prev_out_index = 0
value = 2440000
fee = 15000
tx = 1)
tx.lock_time = 0
tx.add_input( previous_id: prev_out,
previous_index: prev_out_index,
sequence: 0))
tx.add_output( value-fee, script: script_pub_key))
hashtype = BTC::SIGHASH_ALL
sighash = tx.signature_hash(input_index: 0,
output_script: BTC::PublicKeyAddress.parse(@user_key.address.to_s).script,
hash_type: hashtype)
tx.inputs[0].signature_script =
tx.inputs[0].signature_script << (@user_key.ecdsa_signature(sighash) + BTC::WireFormat.encode_uint8(hashtype))
tx.inputs[0].signature_script << @user_key.public_key
puts "Hex transaction:"
puts tx.to_hex
# Transaction spending from a P2WPKH address:
include Bitcoin::Builder
# clé privée de l'adresse P2WPKH, au format hex:
# adresse Bitcoin standard ("legacy") de destination:
destination_address = "1FiwwBm4KApZX1mHqxtxKniuL419o5icCC"
prev_out_index = 0 # index de l'unspent output (utxo) dans tx ci-dessus
value = 2425000 # valeur de l'utxo en satoshis
key =
script_pubkey =
fee = 15000
spend_tx = build_tx do |t|
t.lock_time 0
t.input do |i|
i.prev_out prev_out, prev_out_index, script_pubkey, value
i.sequence "ffffffff".htb
i.signature_key key
t.output do |o|
o.value value-fee
o.script {|s| s.recipient destination_address }
signed_tx = spend_tx.to_payload.unpack('H*')[0] # signed raw tx (in hex)

This comment has been minimized.

Show comment Hide comment

pierrenoizat Dec 10, 2017

This gist is using the remarkable bech32 gem from Shigeyuki Azuchi :


pierrenoizat commented Dec 10, 2017

This gist is using the remarkable bech32 gem from Shigeyuki Azuchi :

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment