Implementation of a simple blockchain in Julia language
In this example, we implement a simplified algorithm for blockchain, the technology underlying cryptocurrencies, distributed ledgers, and data security.
Introduction
A blockchain is a distributed database consisting of interconnected blocks. Each block contains data, a timestamp, and a cryptographic hash of the previous block. This makes the structure protected from fakes and changes: if someone tries to change the data in one of the blocks, they will change its hash, which will affect all subsequent blocks.
In this example, we implement:
- the block structure,
- block hash generation,
- building a block chain,
- checking the integrity of the chain.
This is a simplified version of the blockchain, but it shows the key principles of its operation.
The main part
Installing and connecting the necessary packages
Installing the SHA package needed to calculate hashes
import Pkg; Pkg.add("SHA")
Connecting the SHA package, which allows you to calculate SHA-256 hashes
using SHA
Defining the block structure
Data structure Block it represents a single block in the blockchain.
Contains:
index: block number in the chaintimestamp: block creation timedata: data stored in the blockprevious_hash: hash of the previous blockhash: custom block hash
struct Block
index::Int
timestamp::Float64
data::String
previous_hash::String
hash::String
end
A function for generating a block hash
Function calculate_hash generates a SHA-256 hash based on the block data.
Parameters:
index: block numbertimestamp: creation timedata: content of the blockprevious_hash: hash of the previous block
function calculate_hash(index, timestamp, data, previous_hash)
# Комбинируем данные блока в одну строку
block_data = string(index, timestamp, data, previous_hash)
# Вычисляем и возвращаем хэш SHA-256
return bytes2hex(sha256(block_data))
end
Generation of the first (zero) block — genesis block
Function create_genesis_block creates the first block in the chain — the "genesis block".
It doesn't have a previous hash, so we use an empty string.
function create_genesis_block()
index = 0
timestamp = time() # текущее время
data = "Genesis Block"
previous_hash = "0" # нет предыдущего блока
hash = calculate_hash(index, timestamp, data, previous_hash)
return Block(index, timestamp, data, previous_hash, hash)
end
Creating a new block
Function create_next_block creates a new block based on the previous one.
Parameters:
previous_block: the previous block in the chaindata: data for the new block
function create_next_block(previous_block, data)
index = previous_block.index + 1
timestamp = time()
previous_hash = previous_block.hash
hash = calculate_hash(index, timestamp, data, previous_hash)
return Block(index, timestamp, data, previous_hash, hash)
end
Chain Integrity Check
Function is_chain_valid checks whether the integrity of the blockchain has been violated.
For this:
- Checks whether each hash matches its own data.
- Checks whether the correct address is specified
previous_hashfor each block.
function is_chain_valid(chain::Vector{Block})
for i in 2:length(chain)
current_block = chain[i]
previous_block = chain[i-1]
# Проверяем, соответствует ли хэш блока пересчитанному значению
expected_hash = calculate_hash(
current_block.index,
current_block.timestamp,
current_block.data,
current_block.previous_hash
)
if current_block.hash != expected_hash
println("Нарушена целостность: хэш блока $(current_block.index) не совпадает")
return false
end
# Проверяем, правильно ли указан previous_hash
if current_block.previous_hash != previous_block.hash
println("Нарушена последовательность: предыдущий хэш блока $(current_block.index) не совпадает")
return false
end
end
return true
end
Block Chain creation and testing
Creating a block chain
blockchain = Vector{Block}()
Adding the genesis block
push!(blockchain, create_genesis_block())
Adding several blocks
push!(blockchain, create_next_block(blockchain[end], "Первая транзакция"))
push!(blockchain, create_next_block(blockchain[end], "Вторая транзакция"))
push!(blockchain, create_next_block(blockchain[end], "Третья транзакция"))
Displaying information about the blocks
println("Цепочка блоков:")
for block in blockchain
println("Индекс: $(block.index), Данные: $(block.data), Хэш: $(block.hash), Предыдущий хэш: $(block.previous_hash)")
end
We check the integrity of the chain
println("\nПроверка целостности цепочки: ", is_chain_valid(blockchain) ? "OK" : "Ошибка")
Conclusion
In this example, we implemented a simple version of the blockchain in the Julia language.:
- we have determined the block structure,
- implemented the generation of SHA-256 hashes,
- created the genesis block — the beginning of the chain,
- we learned how to add new blocks,
- we wrote an integrity check for the entire chain.
This helps to understand the basic principles of blockchain technology: how data is interconnected, why it is protected from changes, and how the system can independently verify its correctness.
Such code can be useful for learning the basics of cryptography, distributed systems, and preparing for more complex projects such as creating cryptocurrencies or smart contracts.