Module: Runar::SDK::ANFInterpreter
- Defined in:
- lib/runar/sdk/anf_interpreter.rb
Constant Summary collapse
- IMPLICIT_PARAMS =
Implicit params injected by the compiler — never required from the caller.
%w[_changePKH _changeAmount _newAmount txPreimage].freeze
- MAX_LOOP_ITERATIONS =
Maximum number of iterations allowed for a single loop node.
Bitcoin Script loops (unrolled at compile time) are bounded by script size limits. A count above this threshold in the ANF IR almost certainly indicates a malformed or adversarially crafted artifact rather than a legitimate contract. Capping here prevents the interpreter from hanging or consuming unbounded memory when simulating state transitions.
65_536
Class Method Summary collapse
-
.bin2num_int(hex_str) ⇒ Integer
Convert a little-endian sign-magnitude hex string to an integer.
-
.compute_new_state(anf, method_name, current_state, args, max_loop_iterations: MAX_LOOP_ITERATIONS) ⇒ Hash
Compute the new state after executing a contract method.
-
.eval_bin_op(op, left, right, result_type = nil) ⇒ Object
Evaluate a binary operation on two values.
-
.eval_bindings(bindings, env, state_delta, anf = nil) ⇒ Object
Walk a list of ANF bindings, updating env with each result.
-
.eval_bytes_bin_op(op, left, right) ⇒ Object
Binary op for byte strings (hex-encoded).
-
.eval_bytes_unary_op(op, operand) ⇒ Object
Unary op for byte strings.
-
.eval_call(func, args) ⇒ Object
Evaluate a call to a built-in function.
-
.eval_method_call(_obj, method_name, args, caller_env = nil, state_delta = nil, anf = nil) ⇒ Object
Evaluate a call to a private method defined in the ANF IR.
-
.eval_unary_op(op, operand, result_type = nil) ⇒ Object
Evaluate a unary operation on a value.
-
.eval_value(value, env, state_delta, anf = nil) ⇒ Object
Evaluate a single ANF value node, dispatching on its kind.
-
.find_public_method(anf, method_name) ⇒ Hash?
Find a public method by name in the ANF IR.
-
.hash_fn(name, input_val) ⇒ String
Compute a named hash function over hex-encoded input.
-
.integer_log2(v) ⇒ Integer
Integer base-2 logarithm (floor).
-
.integer_sqrt(v) ⇒ Integer
Integer square root using Newton’s method (matching the Python reference).
-
.is_truthy(v) ⇒ Boolean
Determine truthiness of a value using Runar/Bitcoin Script semantics.
-
.num2bin_hex(n, byte_len) ⇒ String
Convert an integer to a little-endian sign-magnitude hex string.
-
.to_int(v) ⇒ Integer
Convert any value to an Integer.
-
.truncate_div(a, b) ⇒ Integer
Integer division truncating toward zero (matching JS/Bitcoin semantics).
-
.truncate_mod(a, b) ⇒ Integer
Modulo matching truncation toward zero.
Class Method Details
.bin2num_int(hex_str) ⇒ Integer
Convert a little-endian sign-magnitude hex string to an integer.
639 640 641 642 643 644 645 646 647 648 649 650 651 652 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 639 def bin2num_int(hex_str) return 0 if hex_str.nil? || hex_str.empty? result_bytes = hex_str.scan(/../).map { |h| h.to_i(16) } return 0 if result_bytes.empty? negative = (result_bytes.last & 0x80) != 0 result_bytes[-1] &= 0x7f result = 0 result_bytes.each_with_index { |b, i| result |= b << (8 * i) } negative ? -result : result end |
.compute_new_state(anf, method_name, current_state, args, max_loop_iterations: MAX_LOOP_ITERATIONS) ⇒ Hash
Compute the new state after executing a contract method.
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 48 def compute_new_state(anf, method_name, current_state, args, max_loop_iterations: MAX_LOOP_ITERATIONS) method = find_public_method(anf, method_name) unless method raise ArgumentError, "computeNewState: method '#{method_name}' not found in ANF IR" end # Store the configurable loop limit for use in eval_value. Thread.current[:runar_max_loop_iterations] = max_loop_iterations # Initialize environment with property values. env = {} Array(anf['properties']).each do |prop| name = prop['name'] env[name] = current_state.fetch(name, prop['initialValue']) end # Load method params, skipping implicit compiler-injected ones. Array(method['params']).each do |param| pname = param['name'] next if IMPLICIT_PARAMS.include?(pname) next unless args.key?(pname) || args.key?(pname.to_sym) env[pname] = args.key?(pname) ? args[pname] : args[pname.to_sym] end state_delta = {} eval_bindings(Array(method['body']), env, state_delta, anf) current_state.merge(state_delta) ensure Thread.current[:runar_max_loop_iterations] = nil end |
.eval_bin_op(op, left, right, result_type = nil) ⇒ Object
Evaluate a binary operation on two values.
When result_type is ‘bytes’, or both operands are strings, byte semantics are used. Otherwise numeric (bigint) semantics apply.
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 218 def eval_bin_op(op, left, right, result_type = nil) if result_type == 'bytes' || (left.is_a?(String) && right.is_a?(String)) return eval_bytes_bin_op(op, (left || '').to_s, (right || '').to_s) end l = to_int(left) r = to_int(right) case op when '+' then l + r when '-' then l - r when '*' then l * r when '/' then r == 0 ? 0 : truncate_div(l, r) when '%' then r == 0 ? 0 : truncate_mod(l, r) when '==', '===' then l == r when '!=', '!==' then l != r when '<' then l < r when '<=' then l <= r when '>' then l > r when '>=' then l >= r when '&&', 'and' then is_truthy(left) && is_truthy(right) when '||', 'or' then is_truthy(left) || is_truthy(right) when '&' then l & r when '|' then l | r when '^' then l ^ r when '<<' then l << r when '>>' then l >> r else 0 end end |
.eval_bindings(bindings, env, state_delta, anf = nil) ⇒ Object
Walk a list of ANF bindings, updating env with each result.
89 90 91 92 93 94 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 89 def eval_bindings(bindings, env, state_delta, anf = nil) bindings.each do |binding| val = eval_value(binding['value'], env, state_delta, anf) env[binding['name']] = val end end |
.eval_bytes_bin_op(op, left, right) ⇒ Object
Binary op for byte strings (hex-encoded).
281 282 283 284 285 286 287 288 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 281 def eval_bytes_bin_op(op, left, right) case op when '+' then left + right # concatenation when '==', '===' then left == right when '!=', '!==' then left != right else '' end end |
.eval_bytes_unary_op(op, operand) ⇒ Object
Unary op for byte strings.
319 320 321 322 323 324 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 319 def eval_bytes_unary_op(op, operand) return operand unless op == '~' hex_str = (operand || '').to_s [hex_str].pack('H*').bytes.map { |b| (~b) & 0xff }.pack('C*').unpack1('H*') end |
.eval_call(func, args) ⇒ Object
Evaluate a call to a built-in function.
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 336 def eval_call(func, args) case func # Mock crypto — always return true in simulation. when 'checkSig', 'checkMultiSig', 'checkPreimage' true # Real hash functions. when 'sha256' then hash_fn('sha256', args[0]) when 'hash256' then hash_fn('hash256', args[0]) when 'hash160' then hash_fn('hash160', args[0]) when 'ripemd160' then hash_fn('ripemd160', args[0]) # Assert — no-op in simulation. when 'assert' nil # Byte operations. when 'num2bin' n = to_int(args[0]) length = to_int(args[1]).to_i num2bin_hex(n, length) when 'bin2num' bin2num_int((args[0] || '').to_s) when 'cat' (args[0] || '').to_s + (args[1] || '').to_s when 'substr' hex_str = (args[0] || '').to_s start = to_int(args[1]).to_i length = to_int(args[2]).to_i hex_str[start * 2, length * 2] || '' when 'reverseBytes' hex_str = (args[0] || '').to_s hex_str.scan(/../).reverse.join when 'len' hex_str = (args[0] || '').to_s hex_str.length / 2 # Math built-ins. when 'abs' to_int(args[0]).abs when 'min' [to_int(args[0]), to_int(args[1])].min when 'max' [to_int(args[0]), to_int(args[1])].max when 'within' x = to_int(args[0]) x >= to_int(args[1]) && x < to_int(args[2]) when 'safediv' d = to_int(args[1]) d == 0 ? 0 : truncate_div(to_int(args[0]), d) when 'safemod' d = to_int(args[1]) d == 0 ? 0 : truncate_mod(to_int(args[0]), d) when 'clamp' v = to_int(args[0]) lo = to_int(args[1]) hi = to_int(args[2]) v < lo ? lo : v > hi ? hi : v when 'sign' v = to_int(args[0]) v > 0 ? 1 : v < 0 ? -1 : 0 when 'pow' base = to_int(args[0]) exp = to_int(args[1]) exp < 0 ? 0 : base**exp when 'sqrt' v = to_int(args[0]) integer_sqrt(v) when 'gcd' a = to_int(args[0]).abs b = to_int(args[1]).abs a, b = b, a % b while b != 0 a when 'divmod' a = to_int(args[0]) b = to_int(args[1]) b == 0 ? 0 : truncate_div(a, b) when 'log2' v = to_int(args[0]) integer_log2(v) when 'bool' is_truthy(args[0]) ? 1 : 0 when 'mulDiv' truncate_div(to_int(args[0]) * to_int(args[1]), to_int(args[2])) when 'percentOf' truncate_div(to_int(args[0]) * to_int(args[1]), 10_000) # Preimage intrinsics — return dummy values in simulation. when 'extractOutputHash', 'extractAmount' '00' * 32 else nil end end |
.eval_method_call(_obj, method_name, args, caller_env = nil, state_delta = nil, anf = nil) ⇒ Object
Evaluate a call to a private method defined in the ANF IR.
Creates a new child environment with property values from the caller, maps positional args to the method’s params, evaluates the body, propagates any state mutations back to the caller, and returns the value of the last binding.
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 471 def eval_method_call(_obj, method_name, args, caller_env = nil, state_delta = nil, anf = nil) return nil unless anf && method_name private_method = Array(anf['methods']).find do |m| m['name'] == method_name && !m['isPublic'] end return nil unless private_method # Build a new env seeded with property values from the caller. new_env = {} if caller_env Array(anf['properties']).each do |prop| name = prop['name'] new_env[name] = caller_env[name] if caller_env.key?(name) end end # Map positional args to the method's declared params. params = Array(private_method['params']) params.each_with_index do |param, i| new_env[param['name']] = args[i] if i < args.length end body = Array(private_method['body']) child_delta = {} eval_bindings(body, new_env, child_delta, anf) # Propagate state mutations back to the caller environment. state_delta&.merge!(child_delta) if caller_env child_delta.each { |k, v| caller_env[k] = v } end body.empty? ? nil : new_env[body.last['name']] end |
.eval_unary_op(op, operand, result_type = nil) ⇒ Object
Evaluate a unary operation on a value.
300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 300 def eval_unary_op(op, operand, result_type = nil) if result_type == 'bytes' return eval_bytes_unary_op(op, operand) end val = to_int(operand) case op when '-' then -val when '!', 'not' then !is_truthy(operand) when '~' then ~val else val end end |
.eval_value(value, env, state_delta, anf = nil) ⇒ Object
Evaluate a single ANF value node, dispatching on its kind.
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 104 def eval_value(value, env, state_delta, anf = nil) kind = value['kind'].to_s case kind when 'load_param', 'load_prop' env[value['name']] when 'load_const' v = value['value'] # Handle @ref: aliases — resolve to the named env variable. v.is_a?(String) && v.start_with?('@ref:') ? env[v[5..]] : v when 'bin_op' eval_bin_op( value['op'], env[value['left']], env[value['right']], value['result_type'] ) when 'unary_op' eval_unary_op( value['op'], env[value['operand']], value['result_type'] ) when 'call' call_args = Array(value['args']).map { |a| env[a] } eval_call(value['func'], call_args) when 'method_call' call_args = Array(value['args']).map { |a| env[a] } eval_method_call(env[value['object']], value['method'], call_args, env, state_delta, anf) when 'if' cond = env[value['cond']] branch = is_truthy(cond) ? value['then'] : value['else'] child_env = env.dup eval_bindings(Array(branch), child_env, state_delta, anf) env.merge!(child_env) branch && !branch.empty? ? child_env[branch.last['name']] : nil when 'loop' count = (value['count'] || 0).to_i limit = Thread.current[:runar_max_loop_iterations] || MAX_LOOP_ITERATIONS if count > limit raise "ANF interpreter: loop count #{count} exceeds maximum of #{limit}" end body = Array(value['body']) iter_var = value['iterVar'].to_s last_val = nil count.times do |i| env[iter_var] = i loop_env = env.dup eval_bindings(body, loop_env, state_delta, anf) env.merge!(loop_env) last_val = body.empty? ? nil : loop_env[body.last['name']] end last_val when 'assert' nil when 'update_prop' new_val = env[value['value']] env[value['name']] = new_val state_delta[value['name']] = new_val nil when 'add_output' # Map stateValues to mutable properties in declaration order. state_values = Array(value['stateValues']) if state_values.any? && anf mutable_props = Array(anf['properties']) .reject { |p| p['readonly'] } .map { |p| p['name'] } state_values.each_with_index do |sv, i| next if i >= mutable_props.length resolved = env[sv] prop_name = mutable_props[i] env[prop_name] = resolved state_delta[prop_name] = resolved end end nil when 'check_preimage', 'deserialize_state', 'get_state_script', 'add_raw_output' # On-chain-only operations — skip in simulation. nil else nil end end |
.find_public_method(anf, method_name) ⇒ Hash?
Find a public method by name in the ANF IR.
699 700 701 702 703 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 699 def find_public_method(anf, method_name) Array(anf['methods']).find do |m| m['name'] == method_name && m['isPublic'] end end |
.hash_fn(name, input_val) ⇒ String
Compute a named hash function over hex-encoded input.
517 518 519 520 521 522 523 524 525 526 527 528 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 517 def hash_fn(name, input_val) hex_str = (input_val || '').to_s data = [hex_str].pack('H*') case name when 'sha256' then Digest::SHA256.hexdigest(data) when 'hash256' then Digest::SHA256.hexdigest(Digest::SHA256.digest(data)) when 'ripemd160' then Digest::RMD160.hexdigest(data) when 'hash160' then Digest::RMD160.hexdigest(Digest::SHA256.digest(data)) else '' end end |
.integer_log2(v) ⇒ Integer
Integer base-2 logarithm (floor).
678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 678 def integer_log2(v) return 0 if v <= 0 bits = 0 x = v while x > 1 x >>= 1 bits += 1 end bits end |
.integer_sqrt(v) ⇒ Integer
Integer square root using Newton’s method (matching the Python reference).
662 663 664 665 666 667 668 669 670 671 672 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 662 def integer_sqrt(v) return 0 if v <= 0 x = v y = (x + 1) / 2 while y < x x = y y = (x + v / x) / 2 end x end |
.is_truthy(v) ⇒ Boolean
Determine truthiness of a value using Runar/Bitcoin Script semantics.
Matches on-chain Bitcoin Script OP_IF semantics for truthiness. A value is falsy if it is empty, all-zero bytes, or negative zero (0x80).
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 568 def is_truthy(v) # rubocop:disable Naming/PredicateName case v when TrueClass then true when FalseClass then false when Integer then v != 0 when Float then v != 0.0 when String return false if v.empty? return false if v == '0' || v == 'false' # Hex-encoded byte string: apply Bitcoin Script semantics if v.length.even? && v.match?(/\A[0-9a-fA-F]*\z/) bytes = [v].pack('H*').bytes return false if bytes.empty? # All-zero bytes: falsy (e.g. "00", "0000") return false if bytes.all?(&:zero?) # Negative zero: all zeros except last byte is 0x80 (e.g. "80", "0080") return false if bytes[0...-1].all?(&:zero?) && bytes[-1] == 0x80 end true else false end end |
.num2bin_hex(n, byte_len) ⇒ String
Convert an integer to a little-endian sign-magnitude hex string.
This matches Bitcoin Script’s num2bin semantics: the sign bit occupies the MSB of the last byte, and the value is padded (or truncated) to the requested byte length.
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 604 def num2bin_hex(n, byte_len) return '00' * byte_len if n == 0 negative = n < 0 abs_n = n.abs result_bytes = [] tmp = abs_n while tmp > 0 result_bytes << (tmp & 0xff) tmp >>= 8 end # Encode sign bit into the last byte, adding an extra byte if needed. if negative if (result_bytes.last & 0x80) == 0 result_bytes[-1] |= 0x80 else result_bytes << 0x80 end else result_bytes << 0x00 if (result_bytes.last & 0x80) != 0 end # Pad to requested length, then truncate. result_bytes << 0x00 while result_bytes.length < byte_len result_bytes = result_bytes[0, byte_len] result_bytes.map { |b| format('%02x', b) }.join end |
.to_int(v) ⇒ Integer
Convert any value to an Integer.
Handles Ruby Integer, Float, Boolean, and String (including “42n” BigInt notation from JSON serialization).
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 541 def to_int(v) case v when Integer then v when TrueClass then 1 when FalseClass then 0 when Float then v.to_i when String # "42n" format from JSON serialized bigints. if v.match?(/\A-?\d+n\z/) v.chomp('n').to_i elsif v.match?(/\A-?\d+\z/) v.to_i else 0 end else 0 end end |
.truncate_div(a, b) ⇒ Integer
Integer division truncating toward zero (matching JS/Bitcoin semantics).
Ruby’s built-in ‘/` floors toward negative infinity; this matches truncation toward zero used by Bitcoin Script and JavaScript.
258 259 260 261 262 263 264 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 258 def truncate_div(a, b) if (a < 0) != (b < 0) && (a % b != 0) (a.to_f / b).truncate else a / b end end |
.truncate_mod(a, b) ⇒ Integer
Modulo matching truncation toward zero.
271 272 273 |
# File 'lib/runar/sdk/anf_interpreter.rb', line 271 def truncate_mod(a, b) a - truncate_div(a, b) * b end |