PHP区块链简易账本实现
2026/6/1 23:06:13 网站建设 项目流程

PHP区块链简易账本实现

区块链是一种分布式账本技术。PHP可以实现简单的区块链演示系统。今天说说PHP中区块链的核心概念和简单实现。

区块链的核心是区块的链式结构。每个区块包含数据、时间戳、哈希值和前一个区块的哈希值。

```php
class Block
{
public int $index;
public string $previousHash;
public string $timestamp;
public array $data;
public string $hash;
public int $nonce;

public function __construct(int $index, string $previousHash, array $data)
{
$this->index = $index;
$this->previousHash = $previousHash;
$this->timestamp = date('Y-m-d H:i:s');
$this->data = $data;
$this->nonce = 0;
$this->hash = $this->calculateHash();
}

public function calculateHash(): string
{
return hash('sha256',
$this->index .
$this->previousHash .
$this->timestamp .
json_encode($this->data) .
$this->nonce
);
}

public function mine(int $difficulty): void
{
$target = str_repeat('0', $difficulty);
while (substr($this->hash, 0, $difficulty) !== $target) {
$this->nonce++;
$this->hash = $this->calculateHash();
}
echo "区块 #{$this->index} 已挖出 (nonce: {$this->nonce})\n";
}
}

class Blockchain
{
private array $chain;
private int $difficulty;

public function __construct(int $difficulty = 4)
{
$this->difficulty = $difficulty;
$this->chain = [$this->createGenesisBlock()];
}

private function createGenesisBlock(): Block
{
return new Block(0, '0', ['genesis' => '创世区块']);
}

public function getLastBlock(): Block
{
return $this->chain[count($this->chain) - 1];
}

public function addBlock(array $data): void
{
$lastBlock = $this->getLastBlock();
$block = new Block($lastBlock->index + 1, $lastBlock->hash, $data);
$block->mine($this->difficulty);
$this->chain[] = $block;
}

public function isValid(): bool
{
for ($i = 1; $i < count($this->chain); $i++) {
$previous = $this->chain[$i - 1];
$current = $this->chain[$i];

if ($current->hash !== $current->calculateHash()) return false;
if ($current->previousHash !== $previous->hash) return false;
}
return true;
}

public function getChain(): array
{
return $this->chain;
}

public function tamper(int $index, array $newData): void
{
if (isset($this->chain[$index])) {
$this->chain[$index]->data = $newData;
echo "区块 #{$index} 已被篡改!\n";
}
}
}

$blockchain = new Blockchain(3);

$blockchain->addBlock(['from' => '张三', 'to' => '李四', 'amount' => 100]);
$blockchain->addBlock(['from' => '李四', 'to' => '王五', 'amount' => 50]);
$blockchain->addBlock(['from' => '张三', 'to' => '王五', 'amount' => 75]);

echo "\n区块链是否有效: " . ($blockchain->isValid() ? '是' : '否') . "\n\n";

// 显示区块
foreach ($blockchain->getChain() as $block) {
echo "区块 #{$block->index}\n";
echo " 时间: {$block->timestamp}\n";
echo " 数据: " . json_encode($block->data) . "\n";
echo " 哈希: {$block->hash}\n";
echo " 前哈希: {$block->previousHash}\n\n";
}

// 尝试篡改
echo "尝试篡改数据...\n";
$blockchain->tamper(1, ['from' => '张三', 'to' => '李四', 'amount' => 99999]);
echo "区块链是否有效: " . ($blockchain->isValid() ? '是' : '否') . "\n";
?>
>

基于区块链的简易供应链溯源系统:

```php
class SupplyChainItem
{
public function __construct(
public string $id,
public string $name,
public string $origin,
public string $owner,
public array $transactions = []
) {}
}

class SupplyChainBlockchain
{
private Blockchain $blockchain;
private PDO $pdo;

public function __construct(PDO $pdo)
{
$this->blockchain = new Blockchain(2);
$this->pdo = $pdo;
$this->initTable();
}

private function initTable(): void
{
$this->pdo->exec("
CREATE TABLE IF NOT EXISTS supply_chain (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id VARCHAR(50) NOT NULL,
product_name VARCHAR(200),
action VARCHAR(50),
from_party VARCHAR(100),
to_party VARCHAR(100),
location VARCHAR(200),
block_index INT,
block_hash VARCHAR(64),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_product (product_id)
)
");
}

public function registerProduct(string $productId, string $name, string $origin, string $producer): void
{
$data = [
'action' => '生产',
'product_id' => $productId,
'name' => $name,
'from' => '',
'to' => $producer,
'location' => $origin,
];

$this->blockchain->addBlock($data);
$this->recordToDatabase($productId, $name, '生产', '', $producer, $origin);
}

public function transfer(string $productId, string $from, string $to, string $location): void
{
$data = [
'action' => '转移',
'product_id' => $productId,
'from' => $from,
'to' => $to,
'location' => $location,
];

$this->blockchain->addBlock($data);
$this->recordToDatabase($productId, '', '转移', $from, $to, $location);
}

public function trace(string $productId): array
{
$stmt = $this->pdo->prepare("
SELECT * FROM supply_chain
WHERE product_id = ?
ORDER BY created_at ASC
");
$stmt->execute([$productId]);
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);

$trace = [];
foreach ($records as $record) {
$trace[] = [
'time' => $record['created_at'],
'action' => $record['action'],
'from' => $record['from_party'],
'to' => $record['to_party'],
'location' => $record['location'],
'block_hash' => $record['block_hash'],
];
}

return $trace;
}

private function recordToDatabase(string $productId, string $name, string $action, string $from, string $to, string $location): void
{
$lastBlock = $this->blockchain->getLastBlock();

$stmt = $this->pdo->prepare("
INSERT INTO supply_chain (product_id, product_name, action, from_party, to_party, location, block_index, block_hash)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->execute([$productId, $name, $action, $from, $to, $location, $lastBlock->index, $lastBlock->hash]);
}
}

$pdo = new PDO('mysql:host=localhost;dbname=blockchain', 'root', '');
$supplyChain = new SupplyChainBlockchain($pdo);

$supplyChain->registerProduct('PROD-001', '有机大米', '黑龙江五常', '五常农场');
$supplyChain->transfer('PROD-001', '五常农场', '加工厂', '哈尔滨加工区');
$supplyChain->transfer('PROD-001', '加工厂', '批发商', '北京物流中心');
$supplyChain->transfer('PROD-001', '批发商', '零售商', '上海超市');

echo "产品溯源:\n";
$trace = $supplyChain->trace('PROD-001');
foreach ($trace as $step) {
echo " {$step['time']} {$step['action']}: {$step['from']} -> {$step['to']} ({$step['location']})\n";
}
?>

PHP的区块链实现虽然不能用于生产环境,但可以帮助理解区块链的核心原理。工作量证明、链式结构、数据不可篡改是区块链的三大核心特征。在实际应用中,区块链适合需要多方互信的场景,如供应链溯源、电子存证、数字资产等。PHP在区块链应用中可以承担上层应用的开发工作,底层区块链网络通常使用专业平台。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询