PHP实现区块链BlockChain
<?php /** * Block Struct */ class block { private $index; private $timestamp; private $data; private $previous_hash; private $random_str; private $hash; public function __construct($index, $timestamp, $data, $random_str, $previous_hash) { $this->index = $index; $this->timestamp = $timestamp; $this->data = $data; $this->previous_hash = $previous_hash; $this->random_str = $random_str; $this->hash = $this->hash_block(); } public function __get($name) { return $this->$name; } private function hash_block() { $str = $this->index . $this->timestamp . $this->data . $this->random_str . $this->previous_hash; return hash("sha256", $str); } } /** * Genesis Block * @return \common\library\block\block */ function create_genesis_block() { return new block(0, time(), "Genesis block", 0, 0); } /** * Mine to produce the next block * The first one is a number on the success of mining * @param block $last_block_obj */ function mine(block $last_block_obj) { $random_str = $last_block_obj->hash . get_random(); $index = $last_block_obj->index + 1; $timestamp = time(); $data = 'This is block ' . $index; $block_obj = new block($index, $timestamp, $data, $random_str, $last_block_obj->hash); if (!is_numeric($block_obj->hash{0})) { return false; } return $block_obj; } /** * Verify the block * For simplicity, just return true * @param array $data */ function verify(block $last_block_obj) { return true; } /** * Generate a random string * @param int $len * @return string */ function get_random($len = 32) { $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $key = ""; for ($i = 0; $i < $len; $i++) { $key.= $str{mt_rand(0, 32)}; } return $key; } header("Content-type:text/html;charset=utf-8"); $blockchain = create_genesis_block(); $previous_block = $blockchain[0]; for ($i = 0; $i <= 10; $i++) { if (!($new_block = mine($previous_block))) { continue; } $blockchain[] = $new_block; $previous_block = $new_block; echo $new_block->index . "<br/>"; echo $new_block->hash . "<br/>"; print_r($new_block); echo "<br/><br/>"; }
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。