Re: Ruby Quiz - Challenge #11 - Blockchain Contracts - Disassemble & Assemble Ethereum Virtual Machine (EVM) Opcodes / Bytecodes

"Frank J. Cameron" <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <[email protected]>
Gerald Bauer wrote:
> Challenge #11 - Blockchain Contracts - Disassemble & Assemble Ethereum
Virtual Machine (EVM) Opcodes / Bytecodes

$ ruby -v lib/011.rb
ruby 2.6.0p0 (2018-12-25 revision 66547) [x86_64-linux]
Run options: --seed 51739
# Running:
...
Finished in 0.009713s, 308.8672 runs/s, 308.8672 assertions/s.
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

$ cat lib/011.rb
# frozen_string_literal: true
require_relative '../011/test.rb'

class RubyQuizTest
  @@op2hex = Ethereum::Opcodes::TABLE
             .transform_values{|v| v.to_s.freeze}

  @@hex2op = Ethereum::Opcodes::TABLE.invert
             .transform_values{|v| v.to_s(16).rjust(2, '0').freeze}

  def disassemble(hex)
    n = 0
    hex.chars.each_slice(2).map{|a,b|
      if n == 0
        c = "#{a}#{b}".to_i(16)
        t = (0x60..0x7f).include?(c) ? "#{n = c - 0x5f; ' 0x'}" : ''
        "\r\n#{@@op2hex[c]}#{t}"
      else
        n -= 1
        "#{a}#{b}"
      end
    }.join[8..]
  end

  def assemble(code)
    code.scan(/^(\w+)(?: 0x(\w+))?\r?$/).map{|a,b|
      "#{@@hex2op[a.intern]}#{b}"
    }.join.prepend('0x')
  end
end

Dir.chdir("#{__dir__}/../011")
RubyQuizTest.new('fjc')



Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.