-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchain.php
More file actions
46 lines (34 loc) · 1.17 KB
/
Copy pathBlockchain.php
File metadata and controls
46 lines (34 loc) · 1.17 KB
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
<?php
class Blockchain {
private $chain;
private $difficulty;
public function __construct() {
$this->chain = [$this->initFirstBlock()];
$this->difficulty = 4; // block is mined when the starting 4 numbers (specified difficulty) of the hash are zeros
}
public function initFirstBlock() {
return new Block(0, time(), 'first data', '0');
}
public function getLastBlock() {
return $this->chain[count($this->chain) - 1];
}
public function add($newblock) {
$newblock->previousHash = $this->getLastBlock()->hash; // Set new block's previous hash as the current latest block
$newblock->mineBlock($this->difficulty);
array_push($this->chain, $newblock);
}
public function isBlockChainValid() {
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;
}
}
?>