51行程式碼實現簡單的PHP區塊鏈
阿新 • • 發佈:2020-10-21
<?php /** * 簡單的PHP區塊鏈 * @author Yoper * @PHP技術交流QQ群 370648191 * @Email [email protected] * @wechat YoperMan */ namespace common\library\block; /** * 區塊結構 */ 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); } } /** * 創世區塊 * @return \common\library\block\block */ function create_genesis_block(){ return new \common\library\block\block(0, time(),"第一個區塊",0,0); } /** * 挖礦,生成下一個區塊 * 這應該是一個複雜的演算法,但為了簡單,我們這裡挖到前1位是數字就挖礦成功。 * @param \common\library\block\block $last_block_obj * @return bool|block */ function dig(\common\library\block\block $last_block_obj){ $random_str = $last_block_obj->hash.get_random(); $index=$last_block_obj->index+1; $timestamp=time(); $data='I am block '.$index; $block_obj = new \common\library\block\block($index,$timestamp,$data,$random_str,$last_block_obj->hash); //前一位不是數字 if(!is_numeric($block_obj->hash{2})){ return false; } //數數字,返回塊 return $block_obj; } /** * 驗證區塊 * 這也是一個複雜的過程,為了簡單,我們這裡直接返回正確 * @param array $data * @return bool */ function verify(\common\library\block\block $last_block_obj){ return true; } /** * 生成隨機字串 * @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=[\common\library\block\create_genesis_block()]; print_r($blockchain); //模擬生成其他區塊,我們直接迴圈生成。實際中,還需要跟蹤網際網路上多臺機器上鍊的變化,像比特幣會有工作量證明等演算法,達到條件了才生成區塊等 //我們的鏈是一個數組,實際生產中應該儲存下來 $previous_block = $blockchain[0]; for($i=0;$i<=1;$i++){ if(!($new_block=dig($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/>"; }
(轉自 51行程式碼實現簡單的PHP區塊鏈)[https://blog.csdn.net/chenyoper/article/details/79250889]