[code]=inherit<?php[/code]
=inheritinclude(=inherit'block.php');
=inheritinclude(=inherit'CuteDB.php');
=inherit=inheritclass =inheritBlockchain
{
=inheritconst dbFile = =inherit'blockchain';
=inheritconst lastHashField = =inherit'lasthash';
=inheritprivate $_db = =inheritnull;
=inheritprivate $_lastHash = =inheritnull;
=inheritpublic =inherit=inheritfunction =inherit__construct=inherit()
{
=inherit$this->_db = =inheritnew CuteDB();
=inheritif (!=inherit$this->_db->open(Blockchain::dbFile)) {
=inheritexit(=inherit"Failed to create/open blockchian database");
}
=inherit$this->_lastHash = =inherit$this->_db->get(Blockchain::lastHashField);
=inheritif (!=inherit$this->_lastHash) {
$block = =inheritnew Block(=inherit'', =inherit'Genesis Block');
$hash = $block->getBlockHash();
=inherit$this->_db->set($hash, serialize($block));
=inherit$this->_db->set(Blockchain::lastHashField, $hash);
=inherit$this->_lastHash = $hash;
}
}
...
}
[code]=inherit<?php[/code]
=inheritinclude(=inherit'block.php');
=inheritinclude(=inherit'CuteDB.php');
=inherit=inheritclass =inheritBlockchain
{
...
=inheritpublic =inherit=inheritfunction =inheritaddBlock=inherit($data)
{
$newBlock = =inheritnew Block(=inherit$this->_lastHash, $data);
$hash = $newBlock->getBlockHash();
=inherit$this->_db->set($hash, serialize($newBlock));
=inherit$this->_db->set(Blockchain::lastHashField, $hash);
=inherit$this->_lastHash = $hash;
}
}
[code]=inherit<?php[/code]
=inheritinclude(=inherit'block.php');
=inheritinclude(=inherit'CuteDB.php');
=inherit=inheritclass =inheritBlockchain
{
...
=inheritpublic =inherit=inheritfunction =inheritprintBlockchain=inherit()
{
$lastHash = =inherit$this->_lastHash;
=inheritwhile (=inherittrue) {
$block = =inherit$this->_db->get($lastHash);
=inheritif (!$block) {
=inheritbreak;
}
$block = unserialize($block);
printf(=inherit"PrevHash: %s\n", $block->prevHash);
printf(=inherit"Hash: %s\n", $block->hash);
printf(=inherit"Data: %s\n", $block->data);
printf(=inherit"Nonce: %s\n\n\n", $block->nonce);
$lastHash = $block->prevHash;
}
}
}
[code]=inherit<?php[/code]
=inheritinclude(=inherit'blockchain.php');
$bc = =inheritnew Blockchain();
$bc->addBlock(=inherit'This is block1');
$bc->addBlock(=inherit'This is block2');
$bc->printBlockchain();
本文为 @ 21CTO 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。