php实现完整区块链,PHP实现区块链BlockChain
/**
- 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
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 . "
";
echo $new_block->hash . "
";
print_r($new_block);
echo "
";
}
打赏
微信扫一扫,打赏作者吧~
