-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm.rb
More file actions
70 lines (59 loc) · 1.31 KB
/
vm.rb
File metadata and controls
70 lines (59 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module Tinycoin::Core
class VM
attr_reader :stack
OP_CODES =
[
"OP_DUP",
"OP_PUSH",
"OP_NOP",
"OP_RETURN"
]
def initialize
@stack = []
end
def execute! parsed_script
do_execute!(@stack, parsed_script)
end
def ret_true?
@stack.size == 1 && @stack[0].to_s.downcase == "true"
end
private
def do_execute! stack, rest_script
return if rest_script.empty?
op = rest_script.first
case op
when /OP_(.+)$/
rest_script = dispatch_opcode(stack, op, rest(rest_script))
else
raise Tinycoin::Errors::InvalidOpcode
end
do_execute!(stack, rest_script)
end
def dispatch_opcode stack, op, rest_script
if OP_CODES.member?(op)
method(op.to_s.downcase).call(stack, rest_script)
else
raise Tinycoin::Errors::InvalidOpcode
end
end
def op_nop stack, rest_script
rest_script
end
def op_push stack, rest_script
stack << rest_script.first
rest(rest_script)
end
def op_return stack, rest_script
stack << "true"
rest_script
end
def op_dup stack, rest_script
tgt = stack.first.dup
stack << tgt
rest_script
end
def rest ary
ary.drop(1)
end
end
end