<?php // call init() to create a new empty chain. // call add(something) to add a new item // call verify() to check integrity // call show() to list payloads and hashes // // works similar via cli: `./blockchain.php init` etc. function init(){ $payload = microtime(true) . rand(0, PHP_INT_MAX); file_put_contents('chain', serialize([ [ 'payload' => 'root', 'parenthash' => null, 'payloadhash' => hash('sha256', $payload) ] ])); } function add($input){ $chain = unserialize(file_get_contents('chain')); $parent = end($chain); $chain[] = [ 'payload' => $input, 'parenthash' => hash('sha256', $parent['payloadhash'] . "|" . $parent['parenthash']), 'payloadhash' => hash('sha256', serialize($input)) ]; file_put_contents('chain', serialize($chain)); } function verify($quiet = true){ $chain = unserialize(file_get_contents('chain')); foreach($chain as $i => $item){ if($i > 0){ $lasthash = hash('sha256', $lastitem['payloadhash'] . "|" . $lastitem['parenthash']); if($quiet === false){echo $item['parenthash'] . PHP_EOL;} if($lasthash !== $item['parenthash']){ if($quiet === false){echo ' Link ERR' . PHP_EOL;} return false; }elseif($quiet === false){ if($quiet === false){echo ' Link OK' . PHP_EOL;} } if($item['payloadhash'] === hash('sha256', serialize($item['payload']))) { if($quiet === false){echo ' Block OK' . PHP_EOL;} }else{ if($quiet === false){echo ' Block ERR' . PHP_EOL;} return false; } } $lastitem = $item; } return true; } function show(){ $chain = unserialize(file_get_contents('chain')); foreach($chain as $i => $item){ if($i === 0) { echo '<root>' . PHP_EOL; }else{ echo $item['parenthash'] . PHP_EOL; } echo ' ' . $item['payload'] . PHP_EOL; echo ' ' . $item['payloadhash'] . PHP_EOL; } } if($argc > 1){ switch($argv[1]){ case 'init': init(); echo 'done'.PHP_EOL; break; case 'add': if(!verify()){ echo 'Chain corrupt!' . PHP_EOL; exit(1); } add($argv[2]); echo 'done'.PHP_EOL; break; case 'verify': if(verify(false)){ echo 'Chain OK'; }else{ echo 'Chain corrupt!'; } echo PHP_EOL; break; case 'show': show(); echo PHP_EOL; break; } }
Headerbild: unsplash-logoKaley Dykstra Icons made by Dave Gandy from www.flaticon.com is licensed by CC 3.0 BY
Headerbild: unsplash-logoKaley Dykstra
Icons made by Dave Gandy from www.flaticon.com is licensed by CC 3.0 BY