Skip to content

Instantly share code, notes, and snippets.

@icostan
Created November 14, 2018 08:09
Show Gist options
  • Save icostan/9754487fe8045e2fa6515b1bdccb30b3 to your computer and use it in GitHub Desktop.
Save icostan/9754487fe8045e2fa6515b1bdccb30b3 to your computer and use it in GitHub Desktop.
Transaction = Struct.new :version, :inputs, :outputs, :locktime do
def serialize
inputs_hex = inputs.map(&:serialize).join
outputs_hex = outputs.map(&:serialize).join
int_to_hex(version) + byte_to_hex(inputs.size) + inputs_hex +
byte_to_hex(outputs.size) + outputs_hex + int_to_hex(locktime)
end
def hash
hash_to_hex sha256(sha256(serialize))
end
def signature_hash(lock_script = nil, sighash_type = 0x1)
inputs.first.unlock_script = lock_script if lock_script
hash = sha256(sha256(serialize + int_to_hex(sighash_type)))
[hash].pack('H*')
end
def sign(private_key, public_key, lock_script, sighash_type = 0x01)
bytes_string = signature_hash lock_script, sighash_type
r, s = ecdsa_sign private_key, bytes_string
der = Der.new r: r, s: s
inputs.first.unlock_script = "#{der.serialize} #{public_key}"
serialize
end
end
transaction = Transaction.new 1, [input], [output, change], 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment