Skip to content

Instantly share code, notes, and snippets.

@fridgerator
Created December 21, 2017 21:59
Show Gist options
  • Save fridgerator/ec8db6ec5e731c816965a546d2da5ef3 to your computer and use it in GitHub Desktop.
Save fridgerator/ec8db6ec5e731c816965a546d2da5ef3 to your computer and use it in GitHub Desktop.
Simple blockchain in crystal
require "secure_random"
require "openssl"
module Blockchain
extend self
@@blocks = Array(String).new
def init_blockchain
data = SecureRandom.hex(8)
timestamp = Time.new
previous_hash = "0"
index = 0
hash_block(data, timestamp, previous_hash, index)
end
def add_new_block(data : String)
index = @@blocks.size
previous_hash = get_last_hash
hash_block(data, Time.new, previous_hash, index)
end
def get_all_blocks
@@blocks
end
private def hash_block(data : String, timestamp : Time, previous_hash : String, index : Int32 | Int64)
hash = ""
noonce = 0
loop do
break if is_hash_valid?(hash)
digest = OpenSSL::Digest.new("SHA256")
digest << "#{data}#{timestamp}#{previous_hash}#{index}#{noonce}"
hash = digest.hexdigest
noonce = noonce + 1
end
@@blocks.push(hash)
end
private def is_hash_valid?(hash)
# difficulty
hash.starts_with?("0000")
end
private def get_last_hash
@@blocks[-1]
end
end
Blockchain.init_blockchain
10.times do
Blockchain.add_new_block(SecureRandom.hex(8))
end
puts Blockchain.get_all_blocks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment