forked from Bit-Wasp/bitcoin-php
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRegtestBitcoinFactory.php
119 lines (101 loc) · 2.76 KB
/
RegtestBitcoinFactory.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
<?php
declare(strict_types=1);
namespace BitWasp\Bitcoin\RpcTest;
use BitWasp\Bitcoin\Crypto\Random\Random;
use BitWasp\Bitcoin\Network\NetworkFactory;
class RegtestBitcoinFactory
{
const TESTS_DIR = "BITCOIND_TEST_DIR";
const BITCOIND = "BITCOIND_PATH";
/**
* @var array|false|null|string
*/
private $testsDirPath;
/**
* @var array|false|null|string
*/
private $bitcoindPath;
/**
* @var string[]
*/
private $testDir = [];
/**
* @var RpcServer[]
*/
private $server = [];
/**
* @var \BitWasp\Bitcoin\Network\NetworkInterface
*/
private $network;
/**
* @var RpcCredential
*/
private $credential;
public function __construct()
{
$this->testsDirPath = $this->envOrDefault("BITCOIND_TEST_DIR", "/tmp");
$this->bitcoindPath = $this->envOrDefault("BITCOIND_PATH");
if (null === $this->bitcoindPath) {
throw new \RuntimeException("Missing BITCOIND_PATH variable");
}
$this->network = NetworkFactory::bitcoinTestnet();
$this->credential = new RpcCredential("127.0.0.1", 18332, "rpcuser", "rpcpass", false);
}
/**
* @param string $var
* @param string|null $default
* @return string
*/
private function envOrDefault(string $var, string $default = null): string
{
$value = getenv($var);
if (in_array($value, [null, false, ""])) {
$value = $default;
}
return $value;
}
/**
* @return string
* @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
*/
protected function createRandomTestDir(): string
{
$this->testDir[] = $dir = $this->testsDirPath . "/" . (new Random())->bytes(5)->getHex();
if (!mkdir($dir)) {
throw new \RuntimeException("Failed to create test dir!");
}
return $dir;
}
/**
* @param array $options
* @return RpcServer
* @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
*/
public function startBitcoind($options = []): RpcServer
{
$testDir = $this->createRandomTestDir();
$rpcServer = new RpcServer($this->bitcoindPath, $testDir, $this->network, $this->credential, $options);
$rpcServer->start();
$this->server[] = $rpcServer;
return $rpcServer;
}
/**
*
*/
protected function cleanup()
{
$servers = 0;
$dirs = 0;
foreach ($this->server as $server) {
if ($server->isRunning()) {
$servers++;
$server->destroy();
}
}
echo "Cleaned up {$servers} servers, and {$dirs} directories\n";
}
public function __destruct()
{
$this->cleanup();
}
}