搭建一个最简单的区块链吧。代码简单易懂。
<?php
//区域块链
//block 区块
// chain 链
//data
//之前区块的has值
//自己的has值 : 他是由存储在区块链的信息算出来的 (data + 之前数据has)
class Block {
public $data; //传入数据
private $previousMash;
public function __construct($data,$previousMash){
$this->data = $data;
$this->previousMash = $previousMash;
$this->hash = $this->computerHash();
}
//行程has秘钥
public function computerHash(){
return hash('sha256',$this->data);
}
}
//区块-的-链
//生成祖先
class Chain{
public function __construct(){
$this->chain = [$this->bigBang()];
}
//生成祖先数据
public function bigBang(){
return new Block('我是祖先','99999');
}
public function getLatestBlock(){
return $this->chain[count($this->chain)-1];
}
//验证这个区域块链是否合法
//当前数据是否被篡改
//验证区块的previousHash 是否等于priviousHash
public function validateChain(){
if(count($this->chain) === 1){
if($this->chain[0]->hash !== $this->chain[0]->computerHash()){
return false;
}
return true;
}
//this.chain[1] 第二个区块
//我们第二个区域块开始验证
//验证最后一个区块 count($this->chain)-1
for($i = 1;$i<count($this->chain)-1;$i++){
$blockToValidate = $this->chain[$i];
//当前数据有没有被篡改
if($blockToValidate->hash !== $blockToValidate->computerHash()){
echo '数据篡改';
return false;
}
//当前验证区域块previousHash是否等于previous区域块的hash
$previousBlock = $this->chain[$i-1];
if($blockToValidate->previousHash !== $previousBlock->hash){
echo '前后块链断裂';
return false;
}
}
return true;
}
//添加区块到区域块链上
public function addBlockToChain($newBlock){
//data
//找到最后一个block的has
//这个has就是新区域块链的priviousHash
$newBlock->priveiousHash = $this->getLatestBlock()->hash;
$newBlock->hash = $newBlock->computerHash();
array_push($this->chain,$newBlock);
}
}
//生成块
$Block = new Block('转账十元123','123');
// echo '<pre>';
// print_r($Block);
//生成链
// $Chain = new Chain();
// echo '<pre>';
// print_r($Chain);
$Block1 = new Block('转账十元','123');
// echo '<pre>';
// print_r($Block);
$Chain = new Chain();
$Chain ->addBlockToChain($Block);
$Chain ->addBlockToChain($Block1);
echo '<pre>';
print_r($Chain);
// print_r($Chain -> validateChain());
//尝试篡改数据
$Chain->chain[1]->data = '我最好看';
echo '<pre>';
print_r($Chain);
var_dump($Chain -> validateChain());