|
| 1 | +#!/usr/bin/env php |
| 2 | +<?php |
| 3 | + |
| 4 | +use React\EventLoop\Factory; |
| 5 | +use React\Http\Server as HttpServer; |
| 6 | +use Psr\Http\Message\ServerRequestInterface; |
| 7 | +use Blockchain\Node\Response\JsonResponse; |
| 8 | +use React\Http\Response; |
| 9 | +use React\Socket\Server; |
| 10 | +use Blockchain\Node; |
| 11 | +use Blockchain\Miner; |
| 12 | +use Blockchain\Blockchain; |
| 13 | +use Blockchain\Block; |
| 14 | +use Blockchain\Miner\HashDifficulty; |
| 15 | + |
| 16 | +require __DIR__.'/../vendor/autoload.php'; |
| 17 | + |
| 18 | +$loop = Factory::create(); |
| 19 | + |
| 20 | +$node = new Node(new Miner(new Blockchain(Block::genesis()), new HashDifficulty\ZeroPrefix())); |
| 21 | + |
| 22 | +$server = new HttpServer(function (ServerRequestInterface $request) use ($node) { |
| 23 | + switch (trim($request->getUri()->getPath(), '/')) { |
| 24 | + case 'blocks': |
| 25 | + return new JsonResponse($node->blocks()); |
| 26 | + case 'mine': |
| 27 | + return new JsonResponse($node->mineBlock($request->getBody()->getContents())); |
| 28 | + case 'peers': |
| 29 | + return new JsonResponse($node->peers()); |
| 30 | + case 'peers/add': |
| 31 | + $data = json_decode($request->getBody()->getContents(), true); |
| 32 | + $node->addPeer(new Node\Peer($data['host'], $data['port'])); |
| 33 | + return new Response(204); |
| 34 | + default: |
| 35 | + return new Response(404); |
| 36 | + } |
| 37 | +}); |
| 38 | + |
| 39 | +$socket = new Server(8080, $loop); |
| 40 | +$server->listen($socket); |
| 41 | + |
| 42 | +echo "Server running at http://127.0.0.1:8080\n"; |
| 43 | + |
| 44 | +$loop->run(); |
0 commit comments