Skip to content

Instantly share code, notes, and snippets.

@shaunakpp

shaunakpp/snake_coin.rb

Last active Nov 23, 2018
Embed
What would you like to do?
Basic Blockchain Implementation in Ruby
require 'digest'
# A Snake Coin Block, stores data and it's hashed content
class Block
attr_reader :index, :timestamp, :data, :previous_hash, :hash
def initialize(index, timestamp, data, previous_hash)
@index = index
@timestamp = timestamp
@data = data
@previous_hash = previous_hash
end
def hash
to_digest = (index.to_s + timestamp.to_s + data + previous_hash)
@hash ||= Digest::SHA2.hexdigest(to_digest)
end
end
# A Blockchain implementation for Snake coin
class BlockChain
attr_accessor :block_chain
def initialize
@block_chain = [create_genesis_block]
end
def add(data = "Hey I'm block #{last_block.index + 1}")
block_to_add = new_block(data)
@block_chain << block_to_add
puts "Block #{block_to_add.index} has been added to the block chain"
puts "Hash: #{block_to_add.hash}"
end
def last_block
@block_chain.last
end
private
def create_genesis_block
Block.new(
0,
Time.now.to_i.to_s,
'Genesis Block',
'0'
)
end
def new_block(data)
Block.new(
last_block.index + 1,
Time.now.to_i,
data,
last_block.previous_hash
)
end
end
block_chain = BlockChain.new
10.times { block_chain.add }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.