-
Notifications
You must be signed in to change notification settings - Fork 5
/
naivechain.php
216 lines (182 loc) · 6.65 KB
/
naivechain.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
<?php
/*
NaiveChain Implemented in PHP
by Abdurrahman Shofy Adianto [ https://azophy.github.io ]
adapted from Lauri Hartikk's code [ https://github.com/lhartikk/naivechain ]
*/
class Server {
public $peers = [];
public function __construct($selfUrl) {
$this->selfUrl = $selfUrl;
$this->peers = [ $this->selfUrl ];
}
public function broadcast($data) {
foreach ($this->peers as $peer) if ($peer != $this->selfUrl)
{ self::postToUrl($peer, $data); }
}
static function runServer($url, $response) {
$socket = stream_socket_server("tcp://".$url, $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
echo 'server is running on '.$url;
while (true) {
$conn = stream_socket_accept($socket);
$response($conn);
fclose($conn);
}
fclose($socket);
}
}
static function postToUrl($url, $data) {
$client = stream_socket_client("tcp://$url", $errno, $errorMessage);
if ($client === false)
throw new UnexpectedValueException("Failed to connect: $errorMessage");
fwrite($client, json_encode($data));
$res = stream_get_contents($client);
fclose($client);
return $res;
}
}
class Block {
public function __construct($index, $previousHash, $timestamp, $data, $hash) {
$this->index = $index;
$this->previousHash = $previousHash;
$this->timestamp = $timestamp;
$this->data = $data;
$this->hash = $hash;
}
static function calculateHash($index, $previousHash, $timestamp, $data) {
return hash("sha256", $index.$previousHash.$timestamp.$data);
}
public function calculateThisHash() {
return self::calculateHash(
$this->index,
$this->previousHash,
$this->timestamp,
$this->data
);
}
static function parse($arr) {
return new Block(
$arr['index'],
$arr['previousHash'],
$arr['timestamp'],
$arr['data'],
$arr['hash']
);
}
}
class BlockChain {
public $chain = [];
public function __construct($selfUrl) {
$this->selfUrl = $selfUrl;
$this->network = new Server($this->selfUrl);
$this->network->broadcast(['query' => 'sendMeAllBlocks', 'url' => $this->selfUrl ]);
if (count($this->network->peers) <= 1)
$this->chain = [ self::getGenesisBlock() ];
}
static function getGenesisBlock() {
return new Block(0, "0", 1465154705, "my genesis block!!", "816534932c2b7154836da6afc367695e6337db8a921823784c14378abed4f7d7");
}
public function getLatestBlock() {
return $this->chain[count($this->chain)-1];
}
public function addBlock($block) {
if ($this->isValidNewBlock($block, $this->getLatestBlock())) {
$this->chain[] = $block;
}
}
public function generateNextBlock($blockData) {
$previousBlock = $this->getLatestBlock();
$nextIndex = $previousBlock->index + 1;
$nextTimestamp = time() / 1000;
$nextHash = Block::calculateHash($nextIndex, $previousBlock->hash, $nextTimestamp, $blockData);
return new Block($nextIndex, $previousBlock->hash, $nextTimestamp, $blockData, $nextHash);
}
static function isValidNewBlock ($newBlock, $previousBlock) {
if ($previousBlock->index + 1 !== $newBlock->index) {
echo 'invalid index';
return false;
} else if ($previousBlock->hash !== $newBlock->previousHash) {
echo 'invalid previoushash';
return false;
} else if ($newBlock->calculateThisHash() !== $newBlock->hash) {
echo ('invalid hash: ' . $newBlock->calculateThisHash() . ' ' . $newBlock->hash);
return false;
}
return true;
}
static function isValidChain($blockchainToValidate) {
if (json_encode($blockchainToValidate[0]) !== json_encode(self::getGenesisBlock())) {
return false;
}
$tempBlocks = [ $blockchainToValidate[0]] ;
for ($i = 1; $i < count($blockchainToValidate); $i++) {
if (self::isValidNewBlock($blockchainToValidate[$i], $tempBlocks[$i - 1])) {
$tempBlocks[] = $blockchainToValidate[$i];
} else {
return false;
}
}
return true;
}
public function replaceChain($newBlocks) {
if (self::isValidChain($newBlocks) && count($newBlocks) > count($blockchain)) {
echo ('Received blockchain is valid. Replacing current blockchain with received blockchain');
$blockchain = $newBlocks;
$this->network->broadcast(['query' => 'addBlock', 'data' => [ $this->network->getLatestBlock() ] ]);
} else {
echo ('Received blockchain invalid');
}
}
}
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
$server_url = (isset($argv[1])) ? $argv[1] : '127.0.0.1:8000';
$bc = new BlockChain($server_url);
Server::runServer($server_url, function($conn) use ($bc) {
$req = json_decode(fread($conn, 1024), true); print_r($req);
$res = null;
switch ($req['query']) {
case 'blocks': $res = json_encode($bc->chain); break;
case 'sendMeAllBlocks':
Server::postToUrl($req['url'], ['query' => 'addBlock', 'data' => $bc->chain ]);
break;
case 'mineBlock':
$newBlock = $bc->generateNextBlock($req['data']);
$bc->addBlock($newBlock);
$bc->network->broadcast(['query' => 'addBlock', 'data' => [ $newBlock ]]);
$res = ('block added: ' . json_encode($newBlock));
break;
case 'addBlock':
$receivedBlocks = $req['data'];
uasort($receivedBlocks, function($a,$b) { return $a['index']-$b['index'];});
$latestBlockReceived = Block::parse($receivedBlocks[count($receivedBlocks) - 1]);
$latestBlockHeld = $bc->getLatestBlock();
if ($latestBlockReceived->index > $latestBlockHeld->index) {
error_log('blockchain possibly behind. We got: ' . $latestBlockHeld->index . ' Peer got: ' . $latestBlockReceived->index);
if ($latestBlockHeld->hash === $latestBlockReceived->previousHash) {
error_log("We can append the received block to our chain");
$bc->addBlock($latestBlockReceived);
$bc->network->broadcast(['query' => 'addBlock', 'data' => [ $bc->getLatestBlock() ]]);
} else if (count($receivedBlocks) === 1) {
error_log("We have to query the chain from our peer");
$bc->network->broadcast(['query' => 'sendMeAllBlocks', 'url' => $bc->selfUrl ]);
} else {
error_log("Received blockchain is longer than current blockchain");
$bc->replaceChain($receivedBlocks);
}
} else {
error_log('received blockchain is not longer than received blockchain. Do nothing');
}
case 'allPeers':
$res = json_encode($bc->network->peers);
break;
case 'addPeer':
if (!in_array($req['url'], $bc->network->peers)) $bc->network->peers[] = $req['url'];
$res = "success\n";
break;
}
fwrite($conn, $res);
});
}