Guest User

Blockchain на PHP

a guest
Feb 13th, 2018
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.47 KB | None | 0 0
  1. class Blockchain {
  2.  
  3.     var $BLOCKS = [];
  4.  
  5.     public function __construct() {
  6.         $this->BLOCKS[] = $this->genesisBlock();
  7.     }
  8.  
  9.     function genesisBlock() {
  10.         return ['data' => 'Genesis Blocks', 'hash' => $this->makeSign('Genesis Block')];
  11.     }
  12.  
  13.     function addNewBlock($data) {
  14.         $this->BLOCKS[] = ['data' => $data, 'hash' => $this->makeSign($data . $this->previousHash()), 'previousHash' => $this->previousHash()];
  15.     }
  16.  
  17.     function makeSign($data) {
  18.         return sha1($data);
  19.     }
  20.  
  21.     function previousHash() {
  22.         return $this->BLOCKS[count($this->BLOCKS) - 1]['hash'];
  23.     }
  24.  
  25.     function printAll() {
  26.         print_r($this->BLOCKS);
  27.     }
  28.  
  29.     function changeBlockData($data, $id) {
  30.         $this->BLOCKS[$id]['data'] = $data;
  31.     }
  32.  
  33.     function isValidChain() {
  34.         for ($i = 1; $i < count($this->BLOCKS); $i++) {
  35.             if ($this->BLOCKS[$i]['hash'] != $this->makeSign($this->BLOCKS[$i]['data'] . $this->BLOCKS[$i - 1]['hash']))
  36.                 return false;
  37.  
  38.             if ($this->BLOCKS[$i]['previousHash'] != $this->BLOCKS[$i - 1]['hash'])
  39.                 return false;
  40.         }
  41.  
  42.         return true;
  43.     }
  44.  
  45. }
  46.  
  47. $bc = new Blockchain;
  48. $bc->addNewBlock('{sum:5}');
  49. $bc->addNewBlock('{sum:15}');
  50. $bc->addNewBlock('{sum:56}');
  51.  
  52. //$bc->changeBlockData('{sum:100}', 2);
  53.  
  54. if ($bc->isValidChain())
  55.     echo '<pre>Valid blockchain</pre>';
  56. else
  57.     echo '<pre>Not valid blocks</pre>';
  58.  
  59.  
  60. $bc->printAll();
Add Comment
Please, Sign In to add comment