Advertisement
Rikisu

Blockblockchain

Jun 18th, 2021 (edited)
830
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.91 KB | None | 0 0
  1. -- BlockBlockchain ver 0.4
  2. local computer = require("computer")
  3. local c = require("component")
  4. local data = c.data
  5. local internet = c.internet
  6. local os = require("os")
  7.  
  8. Block = {}
  9.  
  10. --Binary to hexadecimal function
  11. function tohex(str)
  12.     return (str:gsub('.', function (c)
  13.         return string.format('%02X', string.byte(c))
  14.     end))
  15. end
  16.  
  17. --Block class
  18. function Block:new(index, timestamp, data, previous_hash)
  19.     newObj = {index = index,
  20.             timestamp = timestamp,
  21.             data = data,
  22.             previous_hash = previous_hash,
  23.             hash = Block:hash_block(index, timestamp, data, previous_hash)}
  24.     print("Hash "..hash) -- схуяли оно только один раз, только при генерации генезис-блока, выполняется
  25.     self.__index = self
  26.     return setmetatable(newObj, self)
  27. end
  28.  
  29. --Generate hash for block
  30. function Block:hash_block(index, timestamp, data, previous_hash)
  31.     return tohex(data.sha256(tostring(index)..
  32.                 tostring(timestamp)..
  33.                 tostring(data)..
  34.                 tostring(previous_hash)))
  35.                
  36. end
  37.  
  38. --Creating genesis (first) block
  39. function create_genesis_block()
  40.     return Block:new(0, computer.uptime(), "start", 0)
  41. end
  42.  
  43. --Generating next block for blockchain
  44. function next_block(last_block)
  45.     local new_index = last_block["index"] + 1
  46.     local new_timestamp = last_block["timestamp"] + computer.uptime()
  47.     local new_data = "Block #"..tostring(new_index)
  48.     local new_hash = last_block["hash"]
  49.     return Block:new(new_index, new_timestamp, new_data, new_hash)
  50. end
  51.  
  52.  
  53.  
  54. --TEST BEGINS HERE
  55. blockchain = {}
  56. blockchain[1] = create_genesis_block()
  57. previous_block = blockchain[#blockchain]
  58. for i=1, 5 do
  59.     block_to_add = next_block(previous_block)
  60.     blockchain[#blockchain+1] = block_to_add
  61.     previous_block = block_to_add
  62.     print("Block #"..block_to_add["index"].." has been created. Hash:" ..tohex(block_to_add["hash"])..". Previous: "..tohex(block_to_add["previous_hash"]))
  63. end
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement