samjaninf
8/16/2018 - 5:33 PM

A very basic implementation of a blockchain in Julia.

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