Skip to content

Instantly share code, notes, and snippets.

@david-pm
Created May 29, 2018 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-pm/4791fbb0aa2a0cf4efce9adb044352d3 to your computer and use it in GitHub Desktop.
Save david-pm/4791fbb0aa2a0cf4efce9adb044352d3 to your computer and use it in GitHub Desktop.
blockchain poc in ruby
require 'digest'
class Block
attr_reader :index, :parent, :created_at, :data, :hash
def initialize(index:, data:, parent: '')
@index = index.to_i
@data = data
@parent = parent.empty? ? '0' : parent
@created_at = Time.now.to_s
@hash = hashsum
end
private
def hashsum
hashable = "#{index.to_s} #{parent} #{created_at} #{data.to_s}"
Digest::SHA2.new(256).hexdigest(hashable)
end
end
class Blockchain
def initialize
welcome
@chain = []
add_first_block!
end
# the blockchain shouldn't create the blocks
# not very SOLID but this just a PoC
def add_block(data)
chain << Block.new(index: chain.size, data: data, parent: last_hash)
end
def last_hash
chain.last&.hash || ''
end
def valid?
return true if chain.size <= 1
link = chain.each # coerce to an enumerator
loop do # loops rescue StopIteration errors
previous = link.next
return false if previous.hash != link.next.parent
end
return true
end
def last
chain.last
end
def size
chain.size
end
private
attr_reader :chain
def add_first_block!
chain << Block.new(index: 0, data: 'Genenis Block')
end
def welcome
puts <<~BLCKCHN
Welcome, to Blockchain!
To add to the chain, call `#add_block` and pass in a data\n\n
BLCKCHN
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment