Re: Ruby Quiz - Challenge #11 - Blockchain Contracts - Disassemble & Assemble Ethereum Virtual Machine (EVM) Opcodes / Bytecodes
Gerald Bauer <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CAAxEZd_qXpTQAF+eVT-=h0wa7oUBGSODpTG1Ct_jaiSk+ZWMTg@mail.gmail.com> |
Hello,
Wow. Great to see high-speed Ethereum opscode / bytecode assemble
and disassemble versions in ruby.
Thanks again for keeping the ruby quiz going.
For reference here's the test answer from my humble self:
def disassemble( hex ) # returns (code) text with opcodes
hex = hex[2..-1] if hex.start_with?( '0x' ) # cut off leading 0x
bytes = [hex].pack('H*').bytes # convert (hex) string to bytearray
lines = []
while bytes.size > 0
opcode = bytes.shift
ins = Ethereum::Opcodes::TABLE[opcode]
if ins =~ /^PUSH([0-9]+)$/
num = $1.to_i
args_hex = num.times.map { '%02x' % bytes.shift }.join
lines << "#{ins} 0x#{args_hex}"
else
lines << "#{ins}"
end
end
lines.join( "\n" )
end
def assemble( code ) # returns (hex) string
hex = '0x'
words = code.split
words.each do |word|
if word =~ /^0x/
hex << word[2..-1]
else # assume instruction / opcode mnemonic
opcode = Ethereum::Opcodes::REVERSE_TABLE[word.to_sym]
hex << ('%02x' % opcode)
end
end
hex
end
Anyone else? You're (more than) welcome to post your code snippets /
version :-).
Cheers. Prost.
PS: Find the collected code snippets / solutions [1] at the ruby quiz repo.
[1] https://github.com/planetruby/quiz/blob/master/011/solution.rb
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>