[code]=inherit<?php[/code]
=inherit=inheritclass =inheritBlock
{
...
=inheritpublic $nonce;
=inheritprivate =inherit=inheritfunction =inheritprepareData=inherit($nonce)
{
=inheritreturn json_encode([
=inherit$this->prevHash,
=inherit$this->timeStamp,
=inherit$this->data,
$nonce,
]);
}
=inheritpublic =inherit=inheritfunction =inheritfindBlockHash=inherit()
{
$found = =inheritfalse;
$condition = =inherit'0000'; =inherit// Hash值前N个字符必须等于$condition
$condlength = strlen($condition);
printf(=inherit"Mining the block containing \"%s\"\n", =inherit$this->data);
=inheritfor ($nonce = =inherit0; $nonce < PHP_INT_MAX; $nonce++) {
$data = =inherit$this->prepareData($nonce);
$hash = hash(=inherit'sha256', $data);
printf(=inherit"\r%d: %s", $nonce, $hash);
=inheritif (substr($hash, =inherit0, $condlength) === $condition) {
$found = =inherittrue;
=inheritbreak;
}
}
=inheritprint(=inherit"\n\n");
=inheritif ($found) {
=inherit$this->nonce = $nonce;
=inherit$this->hash = $hash;
}
=inheritreturn $found;
}
}
[code]=inherit<?php[/code]
=inherit=inheritclass =inheritBlock
{
...
=inheritpublic =inherit=inheritfunction =inherit__construct=inherit($prevHash, $data)
{
=inherit$this->prevHash = $prevHash;
=inherit$this->timeStamp = time();
=inherit$this->data = $data;
=inherit$this->findBlockHash();
}
...
}
[code]=inherit<?php[/code]
=inherit=inheritclass =inheritBlock
{
...
=inheritpublic =inherit=inheritfunction =inheritvalidate=inherit()
{
$condition = =inherit'0000';
$condlength = strlen($condition);
$data = =inherit$this->prepareData(=inherit$this->nonce);
=inheritreturn substr(hash(=inherit'sha256', $data), =inherit0, $condlength) === $condition;
}
}
[code]=inherit<?php[/code]
=inheritinclude(=inherit'blockchain.php');
$bc = =inheritnew Blockchain();
$bc->addBlock(=inherit'This is block1');
$bc->addBlock(=inherit'This is block2');
=inheritforeach ($bc->blocks as $block) {
...
printf(=inherit"PoW: %s\n", $block->validate() ? =inherit'true' : =inherit'false');
...
}
本文为 @ 21CTO 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。