Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- BlockBlockchain ver 0.4
- local computer = require("computer")
- local c = require("component")
- local data = c.data
- local internet = c.internet
- local os = require("os")
- Block = {}
- --Binary to hexadecimal function
- function tohex(str)
- return (str:gsub('.', function (c)
- return string.format('%02X', string.byte(c))
- end))
- end
- --Block class
- function Block:new(index, timestamp, data, previous_hash)
- newObj = {index = index,
- timestamp = timestamp,
- data = data,
- previous_hash = previous_hash,
- hash = Block:hash_block(index, timestamp, data, previous_hash)}
- print("Hash "..hash) -- схуяли оно только один раз, только при генерации генезис-блока, выполняется
- self.__index = self
- return setmetatable(newObj, self)
- end
- --Generate hash for block
- function Block:hash_block(index, timestamp, data, previous_hash)
- return tohex(data.sha256(tostring(index)..
- tostring(timestamp)..
- tostring(data)..
- tostring(previous_hash)))
- end
- --Creating genesis (first) block
- function create_genesis_block()
- return Block:new(0, computer.uptime(), "start", 0)
- end
- --Generating next block for blockchain
- function next_block(last_block)
- local new_index = last_block["index"] + 1
- local new_timestamp = last_block["timestamp"] + computer.uptime()
- local new_data = "Block #"..tostring(new_index)
- local new_hash = last_block["hash"]
- return Block:new(new_index, new_timestamp, new_data, new_hash)
- end
- --TEST BEGINS HERE
- blockchain = {}
- blockchain[1] = create_genesis_block()
- previous_block = blockchain[#blockchain]
- for i=1, 5 do
- block_to_add = next_block(previous_block)
- blockchain[#blockchain+1] = block_to_add
- previous_block = block_to_add
- print("Block #"..block_to_add["index"].." has been created. Hash:" ..tohex(block_to_add["hash"])..". Previous: "..tohex(block_to_add["previous_hash"]))
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement