Created
November 16, 2021 19:10
-
-
Save nitishparkar/5094f4b8fbbac919e03b5da2c5d66225 to your computer and use it in GitHub Desktop.
Ruby version of Questbook's "Writing a blockchain in Python"
This file contains hidden or 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 'digest' | |
require 'json' | |
class Chain | |
def initialize | |
@blockchain = [] | |
@pending = [] | |
end | |
def add_block(proof) | |
block = { | |
index: @blockchain.length, | |
timestamp: Time.now, | |
transactions: @pending, | |
proof: proof, | |
prevhash: (@blockchain[-1].nil? ? 'Genesis' : compute_hash(@blockchain[-1])) | |
} | |
@blockchain.push(block) | |
@pending = [] | |
end | |
def add_transaction(sender, recipient, amount) | |
transaction = { | |
sender: sender, | |
recipient: recipient, | |
amount: amount | |
} | |
@pending.push(transaction) | |
end | |
def compute_hash(block) | |
Digest::SHA256.hexdigest(block.to_json) | |
end | |
end | |
chain = Chain.new | |
t1 = chain.add_transaction("Vitalik", "Satoshi", 100) | |
t2 = chain.add_transaction("Satoshi", "Alice", 10) | |
t3 = chain.add_transaction("Alice", "Charlie", 34) | |
chain.add_block(12345) | |
t4 = chain.add_transaction("Bob", "Eve", 23) | |
t5 = chain.add_transaction("Dennis", "Brian", 3) | |
t6 = chain.add_transaction("Ken", "Doug", 88) | |
chain.add_block(6789) | |
puts chain.instance_variable_get(:@blockchain) | |
# Output: | |
=begin | |
{ | |
:index=>0, | |
:timestamp=>2021-11-17 00: 25: 17 +0530, | |
:transactions=>[ | |
{ | |
:sender=>"Vitalik", | |
:recipient=>"Satoshi", | |
:amount=>100 | |
}, | |
{ | |
:sender=>"Satoshi", | |
:recipient=>"Alice", | |
:amount=>10 | |
}, | |
{ | |
:sender=>"Alice", | |
:recipient=>"Charlie", | |
:amount=>34 | |
} | |
], | |
:proof=>12345, | |
:prevhash=>"Genesis" | |
} | |
{ | |
:index=>1, | |
:timestamp=>2021-11-17 00: 25: 17 +0530, | |
:transactions=>[ | |
{ | |
:sender=>"Bob", | |
:recipient=>"Eve", | |
:amount=>23 | |
}, | |
{ | |
:sender=>"Dennis", | |
:recipient=>"Brian", | |
:amount=>3 | |
}, | |
{ | |
:sender=>"Ken", | |
:recipient=>"Doug", | |
:amount=>88 | |
} | |
], | |
:proof=>6789, | |
:prevhash=>"0e98e3e1d8f8c605ba91dfbb98e80efc3f6bf18f03567b8446ffc07f8d9e8dae" | |
} | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment