forked from openblockchains/programming-blockchains
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_with_proof_of_work.rb
58 lines (41 loc) · 1.53 KB
/
block_with_proof_of_work.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
require 'digest'
require 'pp' ## pp = pretty print
class Block
attr_reader :data
attr_reader :hash
attr_reader :nonce # number used once - lucky (mining) lottery number
def initialize(data)
@data = data
@nonce, @hash = compute_hash_with_proof_of_work
end
def compute_hash_with_proof_of_work( difficulty='00' )
nonce = 0
loop do
hash = Digest::SHA256.hexdigest( "#{nonce}#{data}" )
if hash.start_with?( difficulty )
return [nonce,hash] ## bingo! proof of work if hash starts with leading zeros (00)
else
nonce += 1 ## keep trying (and trying and trying)
end
end # loop
end # method compute_hash_with_proof_of_work
end # class Block
pp Block.new( 'Hello, Cryptos!' )
pp Block.new( 'Hello, Cryptos! - Hello, Cryptos! - Hello, Cryptos!' )
pp Block.new( 'Your Name Here' )
pp Block.new( 'Data Data Data Data' )
pp Block.new( <<TXT )
Data Data Data Data Data Data
Data Data Data Data Data Data
Data Data Data Data Data Data
Data Data Data Data Data Data
Data Data Data Data Data Data
TXT
p Digest::SHA256.hexdigest( "0Hello, Cryptos!" )
p Digest::SHA256.hexdigest( "1Hello, Cryptos!" )
p Digest::SHA256.hexdigest( "2Hello, Cryptos!" )
p Digest::SHA256.hexdigest( "143Hello, Cryptos!" )
p Digest::SHA256.hexdigest( '26762Hello, Cryptos!' )
p Digest::SHA256.hexdigest( '68419Hello, Cryptos! - Hello, Cryptos! - Hello, Cryptos!' )
p Digest::SHA256.hexdigest( '23416Your Name Here' )
p Digest::SHA256.hexdigest( '15353Data Data Data Data' )