forked from knowledgearcdotorg/phpblockchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.php
77 lines (67 loc) · 1.73 KB
/
blockchain.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
require_once("./block.php");
/**
* A simple blockchain class with proof-of-work (mining).
*/
class BlockChain
{
/**
* Instantiates a new Blockchain.
*/
public function __construct()
{
$this->chain = [$this->createGenesisBlock()];
$this->difficulty = 4;
}
/**
* Creates the genesis block.
*/
private function createGenesisBlock()
{
return new Block(0, strtotime("2017-01-01"), "Genesis Block");
}
/**
* Gets the last block of the chain.
*/
public function getLastBlock()
{
return $this->chain[count($this->chain)-1];
}
/**
* Pushes a new block onto the chain.
*/
public function push($block)
{
$block->previousHash = $this->getLastBlock()->hash;
$this->mine($block);
array_push($this->chain, $block);
}
/**
* Mines a block.
*/
public function mine($block)
{
while (substr($block->hash, 0, $this->difficulty) !== str_repeat("0", $this->difficulty)) {
$block->nonce++;
$block->hash = $block->calculateHash();
}
echo "Block mined: ".$block->hash."\n";
}
/**
* Validates the blockchain's integrity. True if the blockchain is valid, false otherwise.
*/
public function isValid()
{
for ($i = 1; $i < count($this->chain); $i++) {
$currentBlock = $this->chain[$i];
$previousBlock = $this->chain[$i-1];
if ($currentBlock->hash != $currentBlock->calculateHash()) {
return false;
}
if ($currentBlock->previousHash != $previousBlock->hash) {
return false;
}
}
return true;
}
}