Skip to content

Instantly share code, notes, and snippets.

@icostan
Created November 14, 2018 08:09
Show Gist options
  • Save icostan/b6c036e3613f1aa5d2d2168f902677f0 to your computer and use it in GitHub Desktop.
Save icostan/b6c036e3613f1aa5d2d2168f902677f0 to your computer and use it in GitHub Desktop.
class Struct
OPCODES = {
'OP_DUP' => 0x76,
'OP_HASH160' => 0xA9,
'OP_EQUAL' => 0x87,
'OP_EQUALVERIFY' => 0x88,
'OP_CHECKSIG' => 0xAC
}.freeze
def opcode(token)
raise "opcode #{token} not found" unless OPCODES.include?(token)
OPCODES[token].to_s 16
end
def data(token)
bin_size = hex_size token
byte_to_hex(bin_size) + token
end
def hex_size(hex)
[hex].pack('H*').size
end
def to_hex(binary_bytes)
binary_bytes.unpack('H*').first
end
def hash_to_hex(value)
to_hex [value].pack('H*').reverse
end
def int_to_hex(value)
to_hex [value].pack('V')
end
def byte_to_hex(value)
to_hex [value].pack('C')
end
def long_to_hex(value)
to_hex [value].pack('Q<')
end
def script_to_hex(script_string)
script_string.split.map { |token| token.start_with?('OP') ? opcode(token) : data(token) }.join
end
def sha256(hex)
Digest::SHA256.hexdigest([hex].pack('H*'))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment