-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathblockchain.rb
72 lines (58 loc) · 1.58 KB
/
blockchain.rb
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
71
72
class Blockchain
def initialize
@blocks = [Block.first]
@relayed_blocks = []
@callbacks = []
end
def last
@blocks.last
end
def block_at index
@blocks[index]
end
def << block
@blocks << block
end
def process_relayed
if !@relayed_blocks.empty?
if @blocks.last.index >= @relayed_blocks.first.index
while @blocks.last.index >= @relayed_blocks.first.index
index = @relayed_blocks.first.index
our_block = block_at index
if our_block.timestamp > @relayed_blocks.first.timestamp
# pick relayed block
@blocks = @blocks[0..index]
@blocks << @relayed_blocks.shift
puts "Picking relayed block for index #{index}"
else
# pick our block
@relayed_blocks.shift
puts "Picking our block for index #{index}"
end
break if @relayed_blocks.empty?
end
else @blocks.last.index + 1 == @relayed_blocks.first.index
#check prev hash
puts "Adding relayed block for index #{@relayed_blocks.first.index}"
@blocks << @relayed_blocks.shift
end
return true
end
end
def work!
loop do
next if process_relayed
next_block = Block.next self.last, "Transaction Data..."
next if process_relayed
@blocks << next_block
puts "Solved: #{next_block}"
@callbacks.each { |callback| callback.call(next_block) }
end
end
def on_solve &block
@callbacks << block
end
def add_relayed_block block
@relayed_blocks << block
end
end