|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace BitWasp\Bitcoin\Networking\Peer; |
|
6
|
|
|
|
|
7
|
|
|
use BitWasp\Bitcoin\Networking\Messages\Factory as MessageFactory; |
|
8
|
|
|
use BitWasp\Bitcoin\Networking\Structure\NetworkAddressInterface; |
|
9
|
|
|
use Evenement\EventEmitter; |
|
10
|
|
|
use React\EventLoop\LoopInterface; |
|
11
|
|
|
use React\Socket\ConnectionInterface; |
|
12
|
|
|
use React\Socket\Server; |
|
13
|
|
|
|
|
14
|
|
|
class Listener extends EventEmitter |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var LoopInterface |
|
18
|
|
|
*/ |
|
19
|
|
|
private $loop; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var MessageFactory |
|
23
|
|
|
*/ |
|
24
|
|
|
private $messageFactory; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @var Server |
|
28
|
|
|
*/ |
|
29
|
|
|
private $server; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @var ConnectionParams |
|
33
|
|
|
*/ |
|
34
|
|
|
private $params; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Listener constructor. |
|
38
|
|
|
* @param ConnectionParams $params |
|
39
|
|
|
* @param MessageFactory $messageFactory |
|
40
|
9 |
|
* @param NetworkAddressInterface $addr |
|
41
|
|
|
* @param LoopInterface $loop |
|
42
|
|
|
*/ |
|
43
|
|
|
public function __construct( |
|
44
|
|
|
ConnectionParams $params, |
|
45
|
|
|
MessageFactory $messageFactory, |
|
46
|
9 |
|
NetworkAddressInterface $addr, |
|
47
|
9 |
|
LoopInterface $loop |
|
48
|
9 |
|
) { |
|
49
|
9 |
|
$this->params = $params; |
|
50
|
|
|
$this->messageFactory = $messageFactory; |
|
51
|
9 |
|
$this->server = $server = new Server("tcp://{$addr->getIp()->getHost()}:{$addr->getPort()}", $loop); |
|
52
|
9 |
|
$this->loop = $loop; |
|
53
|
|
|
|
|
54
|
|
|
$server->on('connection', [$this, 'handleIncomingPeer']); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
9 |
|
* @param ConnectionInterface $connection |
|
59
|
|
|
* @return \React\Promise\Promise|\React\Promise\PromiseInterface |
|
60
|
9 |
|
*/ |
|
61
|
9 |
|
public function handleIncomingPeer(ConnectionInterface $connection) |
|
62
|
9 |
|
{ |
|
63
|
9 |
|
return (new Peer($this->messageFactory, $this->loop)) |
|
64
|
9 |
|
->setupStream($connection) |
|
65
|
9 |
|
->inboundHandshake($connection, $this->params) |
|
66
|
9 |
|
->then( |
|
67
|
6 |
|
function (Peer $peer) { |
|
68
|
|
|
$this->emit('connection', [$peer]); |
|
69
|
|
|
} |
|
70
|
|
|
); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
9 |
|
/** |
|
74
|
|
|
* Shut down the server |
|
75
|
9 |
|
*/ |
|
76
|
9 |
|
public function close() |
|
77
|
|
|
{ |
|
78
|
|
|
$this->server->close(); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|