Skip to content

Instantly share code, notes, and snippets.

@svaksha
Forked from TestSubjector/Blockchain.jl
Created October 29, 2018 08:19
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 svaksha/8d511c6e54df110af96c85d2b70b33d9 to your computer and use it in GitHub Desktop.
Save svaksha/8d511c6e54df110af96c85d2b70b33d9 to your computer and use it in GitHub Desktop.
A very basic implementation of a blockchain in Julia.
using SHA
"""
An individual block structure
"""
struct Block
index::Int
timestamp::DateTime
data::String
previous_hash::String
hash::String
"""
The constructor which will also create hash for the block.
It will use 256 bit encryption for the blockchain's security needs.
"""
function Block(index, timestamp, data, previous_hash)
hash = sha2_256(string(index, timestamp, data, previous_hash))
new(index, timestamp, data, previous_hash, bytes2hex(hash))
end
end
"""
Add another block to the chain.
You can't have a blockchain with just one block after all.
"""
function next_block(tail_block::Block)
new_index = tail_block.index + 1
return Block(new_index, Dates.now(), string("This is block ",new_index), tail_block.hash)
end
# Create the special first block or the head of the blockchain.
Blockchain = [Block(0, Dates.now(), "Genesis Block", "0")]
println("Genesis Block : 1")
println("Hash :", Blockchain[1].hash)
# Size of the blockchain
Blockchain_limit = 13
# To make addition of blocks to the blockchain non-arbitary (unlike here),
# a proof of work task is required.
for tail = 1:Blockchain_limit
# Link the new block to the chain
append!(Blockchain, [next_block(Blockchain[tail])])
# The details of the block
println("Block : $(tail+1)")
println("Hash :", Blockchain[tail+1].hash)
end
# Reference - https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment