Skip to content

Instantly share code, notes, and snippets.

@mikezter
Created February 12, 2016 02:14
Show Gist options
  • Save mikezter/975093469a948adf5ccb to your computer and use it in GitHub Desktop.
Save mikezter/975093469a948adf5ccb to your computer and use it in GitHub Desktop.
script using bx libbitcoin-explorer to create a transaction ready to send to the bitcoin network
#!/usr/bin/env ruby
require 'json'
require 'active_support/core_ext/hash/conversions'
# BX libbitcoin-explorer
SRC_ADDR=""
DEST_ADDR=""
CHANGE_ADDR=""
OUTPUTS = [
[ DEST_ADDR, 10328414 ],
[ CHANGE_ADDR, 328414 ],
]
def arraytypes(out)
%w(transfers inputs outputs).each do |type|
out.sub! "<#{type}>", "<#{type} type=\"array\">"
end
end
def bx(cmd, *args, xml: false)
cmd = cmd.to_s.tr '_', '-'
cmdline = "bx #{cmd} "
cmdline += "-f xml " if xml
cmdline += args.join(' ')
out = `#{cmdline}`.strip
return out unless xml
arraytypes out
Hash.from_xml(out)
end
def fetch_input_transaction_id(addr)
history = bx :fetch_history, addr, xml: true
history.dig 'transfers', 0, 'received', 'hash'
end
def fetch_input(tx_id, addr)
tx = bx :fetch_tx, tx_id, xml: true
outputs = tx.dig 'transaction', 'outputs'
i = 0
outputs.each { |o| o['index'] = i; i += 1 }
outputs.find { |o| o['address'] == addr }
end
def create_tx(addr, outputs)
tx_id = fetch_input_transaction_id(addr)
input = fetch_input(tx_id, addr)
tx = tx_encode(input_def(tx_id, input), outputs)
puts "Fee:", fee(input['value'], outputs)
endorsement = sign_input(ec_private_key, input['script'], tx)
set_script(endorsement, public_key(wif_private_key), tx)
end
def set_script(endorsement, pubkey, tx)
bx :input_set, %("[ #{endorsement} ] [ #{pubkey} ]"), tx
end
def sign_input(key, script, tx)
bx :input_sign, key, "'#{script}'", tx
end
def ec_private_key
bx :wif_to_ec, wif_private_key
end
def wif_private_key
ENV['PRIVKEY']
end
def public_key(key)
bx :wif_to_public, key
end
def input_def(tx_id, input)
"#{tx_id}:#{input['index']}"
end
def tx_encode(input, outputs)
outputs = outputs.map { |o| ' -o ' + o.join(':') }.join
bx :tx_encode, '-i', input, outputs
end
def fee(input, outputs)
input.to_i - outputs.map { |o| o[1] }.reduce(:+)
end
puts create_tx(SRC_ADDR, OUTPUTS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment