Eine einfache Blockchain-Implementierung in PHP
Ein einführendes PHP-Beispiel zum Erstellen von Blöcken, Berechnen von Hashes und Prüfen einer lokalen Kette.
Eine kleine Blockchain in PHP erklärt die Verbindung von Blöcken, Hashes und Proof of Work. Dies ist ein Lernbeispiel: Es hält eine einzelne Kette im Speicher und enthält weder signierte Transaktionen noch ein dezentrales Netzwerk.
1. Die Klasse Block definieren
Jeder Block enthält Daten, Zeitstempel, Nonce, Hash des vorherigen Blocks und seinen eigenen Hash. mine() sucht einen Hash mit der geforderten Anzahl führender Nullen.
<?php
class Block {
public int $timestamp;
public int $nonce = 0;
public string $hash;
public function __construct(
public string $data,
public string $previousHash = '0'
) {
$this->timestamp = time();
$this->hash = $this->calculateHash();
}
public function calculateHash(): string {
return hash('sha256', $this->previousHash . '|' .
$this->timestamp . '|' . $this->data . '|' . $this->nonce);
}
public function mine(int $difficulty): void {
$prefix = str_repeat('0', $difficulty);
while (substr($this->hash, 0, $difficulty) !== $prefix) {
$this->nonce++;
$this->hash = $this->calculateHash();
}
}
}
2. Die Klasse Blockchain definieren
Die Kette erstellt einen Genesis-Block und verknüpft jeden neuen Block mit dem Vorgänger. isValid() prüft Hashes, Verbindungen und den Proof of Work jedes Blocks.
class Blockchain {
public array $chain = [];
public int $difficulty = 2;
public function __construct() {
$genesis = new Block('Genesis Block');
$genesis->mine($this->difficulty);
$this->chain[] = $genesis;
}
public function addBlock(string $data): void {
$block = new Block($data, $this->chain[count($this->chain) - 1]->hash);
$block->mine($this->difficulty);
$this->chain[] = $block;
}
public function isValid(): bool {
foreach ($this->chain as $index => $block) {
if ($block->hash !== $block->calculateHash()) return false;
if (substr($block->hash, 0, $this->difficulty) !==
str_repeat('0', $this->difficulty)) return false;
if ($index === 0) {
if ($block->previousHash !== '0') return false;
} elseif ($block->previousHash !== $this->chain[$index - 1]->hash) {
return false;
}
}
return true;
}
}
3. Die Kette testen
Fügen Sie zwei Blöcke hinzu und ändern Sie anschließend die Daten des ersten. Die zweite Prüfung ergibt false.
$chain = new Blockchain();
$chain->addBlock('Alice sends 10 coins to Bob');
$chain->addBlock('Bob sends 5 coins to Carol');
var_dump($chain->isValid()); // true
$chain->chain[1]->data = 'Alice sends 1000 coins to Bob';
var_dump($chain->isValid()); // false
Dies ist keine einsatzfähige Kryptowährung: Es fehlen digitale Signaturen, Transaktionsregeln, dauerhafte Speicherung, Konsens zwischen Knoten und Schutz gegen zahlreiche Angriffe.
Teilen
Was ist Ihre Reaktion?
Gefällt mir
0
Gefällt mir nicht
0
Liebe
0
Lustig
0
Wütend
0
Traurig
0
Wow
0