-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.php
45 lines (38 loc) · 909 Bytes
/
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
<?php
require_once("./block.php");
class BlockChain
{
public function __construct()
{
$this->chain = [$this->createGenesisBlock()];
$this->difficulty = 4;
}
public function createGenesisBlock()
{
return new Block(0, strtotime("01/01/2017"), "Genesis Block");
}
public function getLatestBlock()
{
return $this->chain[count($this->chain)-1];
}
public function addBlock($newBlock)
{
$newBlock->previousHash = $this->getLatestBlock()->hash;
$newBlock->mineBlock($this->difficulty);
array_push($this->chain, $newBlock);
}
public function isChainValid()
{
for ($i = 1; $i < count($this->chain); $i++) {
$currentBlock = $this->chain[$i];
$previousHash = $this->chain[$i-1];
if ($currentBlock->hash !== $currentBlock->calculateHash()) {
return false;
}
if ($currentBlock->previousHash !== $previousHash->hash) {
return false;
}
}
return true;
}
}