class Block {
public $index;
public $previousHash;
public $timestamp;
public $data;
public $hash;
public function __construct($index, $previousHash, $timestamp, $data) {
$this->index = $index;
$this->previousHash = $previousHash;
$this->timestamp = $timestamp;
$this->data = $data;
$this->hash = $this->calculateHash();
}
public function calculateHash() {
return hash('sha256', $this->index . $this->previousHash . $this->timestamp . json_encode($this->data));
}
}
class Blockchain {
public $chain;
public $difficulty;
public function __construct($difficulty) {
$this->chain = [];
$this->difficulty = $difficulty;
$this->createGenesisBlock();
}
public function createGenesisBlock() {
$genesisBlock = new Block(0, "0", time(), "Genesis Block");
array_push($this->chain, $genesisBlock);
}
public function addBlock($data) {
$previousBlock = end($this->chain);
$newIndex = $previousBlock->index 1;
$newTime = time();
$newBlock = new Block($newIndex, $previousBlock->hash, $newTime, $data);
while (substr($newBlock->hash, 0, $this->difficulty) !== str_repeat('0', $this->difficulty)) {
$newTime ;
$newBlock = new Block($newIndex, $previousBlock->hash, $newTime, $data);
}
array_push($this->chain, $newBlock);
}
}
$myBlockchain = new Blockchain(4);
$myBlockchain->addBlock(["amount" => 10]);
$myBlockchain->addBlock(["amount" => 20]);
foreach ($myBlockchain->chain as $block) {
echo "Index: " . $block->index . "\n";
echo "Previous Hash: " . $block->previousHash . "\n";
echo "Timestamp: " . date("Y-m-d H:i:s", $block->timestamp) . "\n";
echo "Data: " . json_encode($block->data) . "\n";
echo "Hash: " . $block->hash . "\n\n";
}
在上面的代码中,我们定义了一个区块类(Block)和一个区块链类(Blockchain)。每个区块包含索引、前一个区块的哈希、时间戳、数据和当前哈希。在区块链类中,我们创建了一个创世区块,并允许我们添加新的区块。在添加区块的时候,我们使用简单的工作量证明(Proof of Work)机制,通过不断调整区块的时间戳来满足难度要求,确保新块的哈希前面有特定数量的零。