Hello,
I've started a step-by-step guide that shows you how ot build
blockchains in ruby from scratch.
Starting with (crypto) hashes...
require 'digest'
Digest::SHA256.hexdigest( 'Hello, Cryptos!' )
resulting in
#=> "33eedea60b0662c66c289ceba71863a864cf84b00e10002ca1069bf58f9362d5"
And building up to blocks with proof-of-work, timestamps, and more:
require 'digest'
require 'pp' ## pp = pretty print
class Block
attr_reader :data
attr_reader :prev
attr_reader :difficulty
attr_reader :time
attr_reader :nonce # number used once - lucky (mining) lottery number
def hash
Digest::SHA256.hexdigest( "#{nonce}#{time}#{difficulty}#{prev}#{data}" )
end
def initialize(data, prev, difficulty: '0000' )
@data = data
@prev = prev
@difficulty = difficulty
@nonce, @time = compute_hash_with_proof_of_work( difficulty )
end
def compute_hash_with_proof_of_work( difficulty='00' )
nonce = 0
time = Time.now.to_i
loop do
hash = Digest::SHA256.hexdigest(
"#{nonce}#{time}#{difficulty}#{prev}#{data}" )
if hash.start_with?( difficulty )
return [nonce,time] ## 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
Proof of the pudding. Let's build a new (more secure) blockchain
from scratch (zero). Genesis!
b0 = Block.new( 'Hello, Cryptos!',
'0000000000000000000000000000000000000000000000000000000000000000' )
#=> #<Block:0x4d00700
# @data="Hello, Cryptos!",
# @difficulty="0000",
# @nonce=215028,
# @prev="0000000000000000000000000000000000000000000000000000000000000000",
# @time=1521292321>
Let's mine (build) some more blocks linked (chained) together with
crypto hashes:
b1 = Block.new( 'Hello, Cryptos! - Hello, Cryptos!', b0.hash )
#=> #<Block:0x4ed7940
# @data="Hello, Cryptos! - Hello, Cryptos!",
# @difficulty="0000",
# @nonce=3264,
# @prev="0000071b9c71675db90b0bb819236d76be97ac75f9f379d078456495133b18c6",
# @time=1521292325>
More @ https://github.com/openblockchains/programming-blockchains-step-by-step
Cheers. Prost. Happy blockchaining.