Created
April 19, 2018 07:25
-
-
Save Pimentoso/9c0cdf92e52a6ff0a61b7c4d153ecb1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# require './blockchain.rb'; Blockchain.demo | |
require 'digest' | |
class Blockchain | |
DIFFICULTY = '00000'.freeze | |
attr_reader :blocks | |
def initialize | |
@blocks = [] | |
data = 'first block ayy lmao' | |
time = Time.now.utc | |
prev_hash = 0 | |
index = 0 | |
hash_block(data, time, prev_hash, index) | |
end | |
def add_block(data) | |
time = Time.now.utc | |
prev_hash = @blocks.last | |
index = @blocks.size | |
hash_block(data, time, prev_hash, index) | |
end | |
def self.demo | |
bc = Blockchain.new | |
bc.add_block('lorem ipsum dolor sit amet') | |
bc.add_block('consectetur adipiscing elit') | |
bc.add_block('sed do eiusmod tempor incididunt') | |
bc.add_block('ut labore et dolore magna aliqua') | |
bc.blocks | |
end | |
private | |
def hash_block(data, time, prev_hash, index) | |
hash = '' | |
nonce = 0 | |
log("hashing block #{index}...") | |
until(is_hash_valid(hash)) | |
hash = Digest::SHA256.hexdigest("#{data}#{time}#{prev_hash}#{index}#{nonce}") | |
nonce += 1 | |
end | |
log("hashed block #{index}: #{nonce} iterations") | |
@blocks << hash | |
end | |
def is_hash_valid(hash) | |
hash.start_with? DIFFICULTY | |
end | |
def log(s) | |
puts s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment