Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Blockchain {
- var $BLOCKS = [];
- public function __construct() {
- $this->BLOCKS[] = $this->genesisBlock();
- }
- function genesisBlock() {
- return ['data' => 'Genesis Blocks', 'hash' => $this->makeSign('Genesis Block')];
- }
- function addNewBlock($data) {
- $this->BLOCKS[] = ['data' => $data, 'hash' => $this->makeSign($data . $this->previousHash()), 'previousHash' => $this->previousHash()];
- }
- function makeSign($data) {
- return sha1($data);
- }
- function previousHash() {
- return $this->BLOCKS[count($this->BLOCKS) - 1]['hash'];
- }
- function printAll() {
- print_r($this->BLOCKS);
- }
- function changeBlockData($data, $id) {
- $this->BLOCKS[$id]['data'] = $data;
- }
- function isValidChain() {
- for ($i = 1; $i < count($this->BLOCKS); $i++) {
- if ($this->BLOCKS[$i]['hash'] != $this->makeSign($this->BLOCKS[$i]['data'] . $this->BLOCKS[$i - 1]['hash']))
- return false;
- if ($this->BLOCKS[$i]['previousHash'] != $this->BLOCKS[$i - 1]['hash'])
- return false;
- }
- return true;
- }
- }
- $bc = new Blockchain;
- $bc->addNewBlock('{sum:5}');
- $bc->addNewBlock('{sum:15}');
- $bc->addNewBlock('{sum:56}');
- //$bc->changeBlockData('{sum:100}', 2);
- if ($bc->isValidChain())
- echo '<pre>Valid blockchain</pre>';
- else
- echo '<pre>Not valid blocks</pre>';
- $bc->printAll();
Add Comment
Please, Sign In to add comment