Completed
Pull Request — master (#110)
by Ruben de
72:43
created

BlocktrailSDK::price()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Blocktrail\SDK;
4
5
use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
6
use BitWasp\Bitcoin\Bitcoin;
7
use BitWasp\Bitcoin\Crypto\EcAdapter\EcSerializer;
8
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
9
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Signature\CompactSignatureSerializerInterface;
10
use BitWasp\Bitcoin\Crypto\Random\Random;
11
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKey;
12
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKeyFactory;
13
use BitWasp\Bitcoin\MessageSigner\MessageSigner;
14
use BitWasp\Bitcoin\MessageSigner\SignedMessage;
15
use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;
16
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
17
use BitWasp\Bitcoin\Network\NetworkFactory;
18
use BitWasp\Bitcoin\Transaction\TransactionFactory;
19
use BitWasp\Buffertools\Buffer;
20
use BitWasp\Buffertools\BufferInterface;
21
use Blocktrail\CryptoJSAES\CryptoJSAES;
22
use Blocktrail\SDK\Address\AddressReaderBase;
23
use Blocktrail\SDK\Address\BitcoinAddressReader;
24
use Blocktrail\SDK\Address\BitcoinCashAddressReader;
25
use Blocktrail\SDK\Address\CashAddress;
26
use Blocktrail\SDK\Backend\BlocktrailConverter;
27
use Blocktrail\SDK\Backend\BtccomConverter;
28
use Blocktrail\SDK\Backend\ConverterInterface;
29
use Blocktrail\SDK\Bitcoin\BIP32Key;
30
use Blocktrail\SDK\Connection\RestClient;
31
use Blocktrail\SDK\Exceptions\BlocktrailSDKException;
32
use Blocktrail\SDK\Network\BitcoinCash;
33
use Blocktrail\SDK\Connection\RestClientInterface;
34
use Blocktrail\SDK\Network\BitcoinCashRegtest;
35
use Blocktrail\SDK\Network\BitcoinCashTestnet;
36
use Btccom\JustEncrypt\Encryption;
37
use Btccom\JustEncrypt\EncryptionMnemonic;
38
use Btccom\JustEncrypt\KeyDerivation;
39
40
/**
41
 * Class BlocktrailSDK
42
 */
43
class BlocktrailSDK implements BlocktrailSDKInterface {
44
    /**
45
     * @var Connection\RestClientInterface
46
     */
47
    protected $blocktrailClient;
48
49
    /**
50
     * @var Connection\RestClient
51
     */
52
    protected $dataClient;
53
54
    /**
55
     * @var Connection\RestClient
56
     */
57
    protected $btccomRawTxClient;
58
59
    /**
60
     * @var string          currently only supporting; bitcoin
61
     */
62
    protected $network;
63
64
    /**
65 118
     * @var bool
66
     */
67 118
    protected $testnet;
68
69 118
    /**
70 118
     * @var ConverterInterface
71 118
     */
72
    protected $converter;
73
74
    /**
75 118
     * @param   string      $apiKey         the API_KEY to use for authentication
76 118
     * @param   string      $apiSecret      the API_SECRET to use for authentication
77
     * @param   string      $network        the cryptocurrency 'network' to consume, eg BTC, LTC, etc
78 118
     * @param   bool        $testnet        testnet yes/no
79 118
     * @param   string      $apiVersion     the version of the API to consume
80
     * @param   null        $apiEndpoint    overwrite the endpoint used
81
     *                                       this will cause the $network, $testnet and $apiVersion to be ignored!
82
     */
83
    public function __construct($apiKey, $apiSecret, $network = 'BTC', $testnet = false, $apiVersion = 'v1', $apiEndpoint = null) {
84
85
        list ($apiNetwork, $testnet) = Util::parseApiNetwork($network, $testnet);
86
87
        if (is_null($apiEndpoint)) {
88
            $apiEndpoint = getenv('BLOCKTRAIL_SDK_API_ENDPOINT') ?: "https://api.blocktrail.com";
89 118
            $apiEndpoint = "{$apiEndpoint}/{$apiVersion}/{$apiNetwork}/";
90
        }
91 118
92
        $btccomEndpoint = getenv('BLOCKTRAIL_SDK_BTCCOM_API_ENDPOINT') ?: "https://chain.api.btc.com";
93
        $btccomEndpoint = "{$btccomEndpoint}/v3/";
94
95
        // normalize network and set bitcoinlib to the right magic-bytes
96
        list($this->network, $this->testnet, $regtest) = $this->normalizeNetwork($network, $testnet);
97
        $this->setBitcoinLibMagicBytes($this->network, $this->testnet, $regtest);
98
99
        if ($this->testnet && strpos($btccomEndpoint, "tchain") === false) {
100
            $btccomEndpoint = \str_replace("chain", "tchain", $btccomEndpoint);
101 118
        }
102
103 118
        $this->blocktrailClient = new RestClient($apiEndpoint, $apiVersion, $apiKey, $apiSecret);
104 118
        $this->dataClient = new RestClient($btccomEndpoint, $apiVersion, $apiKey, $apiSecret);
105
        $this->btccomRawTxClient = new RestClient(($this->testnet ? "https://tchain.btc.com" : "https://btc.com"), $apiVersion, $apiKey, $apiSecret);
106 118
107 29
        $this->converter = new BtccomConverter();
108
    }
109 118
110
    /**
111 4
     * normalize network string
112 4
     *
113
     * @param $network
114 4
     * @param $testnet
115 4
     * @return array
116
     * @throws \Exception
117
     */
118
    protected function normalizeNetwork($network, $testnet) {
119
        // [name, testnet, network]
120
        return Util::normalizeNetwork($network, $testnet);
121 118
    }
122 118
123
    /**
124
     * set BitcoinLib to the correct magic-byte defaults for the selected network
125
     *
126
     * @param $network
127
     * @param bool $testnet
128
     * @param bool $regtest
129
     */
130
    protected function setBitcoinLibMagicBytes($network, $testnet, $regtest) {
131
132
        if ($network === "bitcoin") {
133
            if ($regtest) {
134
                $useNetwork = NetworkFactory::bitcoinRegtest();
135
            } else if ($testnet) {
136
                $useNetwork = NetworkFactory::bitcoinTestnet();
137
            } else {
138
                $useNetwork = NetworkFactory::bitcoin();
139
            }
140
        } else if ($network === "bitcoincash") {
141
            if ($regtest) {
142
                $useNetwork = new BitcoinCashRegtest();
143
            } else if ($testnet) {
144
                $useNetwork = new BitcoinCashTestnet();
145
            } else {
146
                $useNetwork = new BitcoinCash();
147
            }
148
        }
149
150
        Bitcoin::setNetwork($useNetwork);
0 ignored issues
show
Bug introduced by
The variable $useNetwork does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
151
    }
152
153
    /**
154
     * enable CURL debugging output
155
     *
156
     * @param   bool        $debug
157
     *
158
     * @codeCoverageIgnore
159
     */
160 2
    public function setCurlDebugging($debug = true) {
161 2
        $this->blocktrailClient->setCurlDebugging($debug);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Blocktrail\SDK\Connection\RestClientInterface as the method setCurlDebugging() does only exist in the following implementations of said interface: Blocktrail\SDK\Connection\RestClient.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
162
        $this->dataClient->setCurlDebugging($debug);
163
        $this->btccomRawTxClient->setCurlDebugging($debug);
164
    }
165
166
    /**
167
     * enable verbose errors
168
     *
169
     * @param   bool        $verboseErrors
170
     *
171
     * @codeCoverageIgnore
172
     */
173
    public function setVerboseErrors($verboseErrors = true) {
174
        $this->blocktrailClient->setVerboseErrors($verboseErrors);
175
        $this->dataClient->setVerboseErrors($verboseErrors);
176 1
        $this->btccomRawTxClient->setVerboseErrors($verboseErrors);
177 1
    }
178 1
    
179
    /**
180
     * set cURL default option on Guzzle client
181
     * @param string    $key
182
     * @param bool      $value
183
     *
184
     * @codeCoverageIgnore
185
     */
186
    public function setCurlDefaultOption($key, $value) {
187
        $this->blocktrailClient->setCurlDefaultOption($key, $value);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Blocktrail\SDK\Connection\RestClientInterface as the method setCurlDefaultOption() does only exist in the following implementations of said interface: Blocktrail\SDK\Connection\RestClient.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
188
        $this->dataClient->setCurlDefaultOption($key, $value);
189 1
        $this->btccomRawTxClient->setCurlDefaultOption($key, $value);
190
    }
191 1
192 1
    /**
193 1
     * @return  RestClientInterface
194
     */
195 1
    public function getRestClient() {
196 1
        return $this->blocktrailClient;
197
    }
198
199
    /**
200
     * @return  RestClient
201
     */
202
    public function getDataRestClient() {
203
        return $this->dataClient;
204
    }
205
206
    /**
207 1
     * @param RestClientInterface $restClient
208
     */
209 1
    public function setRestClient(RestClientInterface $restClient) {
210 1
        $this->client = $restClient;
0 ignored issues
show
Bug introduced by
The property client does not seem to exist. Did you mean blocktrailClient?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
211 1
    }
212
213 1
    /**
214 1
     * get a single address
215
     * @param  string $address address hash
216
     * @return array           associative array containing the response
217
     */
218
    public function address($address) {
219
        $response = $this->dataClient->get($this->converter->getUrlForAddress($address));
220
        return $this->converter->convertAddress($response->body());
221
    }
222
223
    /**
224
     * get all transactions for an address (paginated)
225 1
     * @param  string  $address address hash
226
     * @param  integer $page    pagination: page number
227 1
     * @param  integer $limit   pagination: records per page (max 500)
228 1
     * @param  string  $sortDir pagination: sort direction (asc|desc)
229 1
     * @return array            associative array containing the response
230
     */
231 1
    public function addressTransactions($address, $page = 1, $limit = 20, $sortDir = 'asc') {
232 1
        $queryString = [
233
            'page' => $page,
234
            'limit' => $limit,
235
            'sort_dir' => $sortDir
236
        ];
237
        $response = $this->dataClient->get($this->converter->getUrlForAddressTransactions($address), $this->converter->paginationParams($queryString));
238
        return $this->converter->convertAddressTxs($response->body());
239
    }
240
241
    /**
242
     * get all unconfirmed transactions for an address (paginated)
243
     * @param  string  $address address hash
244
     * @param  integer $page    pagination: page number
245
     * @param  integer $limit   pagination: records per page (max 500)
246
     * @param  string  $sortDir pagination: sort direction (asc|desc)
247
     * @return array            associative array containing the response
248
     */
249
    public function addressUnconfirmedTransactions($address, $page = 1, $limit = 20, $sortDir = 'asc') {
250
        $queryString = [
251
            'page' => $page,
252
            'limit' => $limit,
253
            'sort_dir' => $sortDir
254
        ];
255
        $response = $this->dataClient->get($this->converter->getUrlForAddressTransactions($address), $this->converter->paginationParams($queryString));
256
        return $this->converter->convertAddressTxs($response->body());
257
    }
258
259
    /**
260
     * get all unspent outputs for an address (paginated)
261 2
     * @param  string  $address address hash
262 2
     * @param  integer $page    pagination: page number
263
     * @param  integer $limit   pagination: records per page (max 500)
264 2
     * @param  string  $sortDir pagination: sort direction (asc|desc)
265
     * @return array            associative array containing the response
266 2
     */
267
    public function addressUnspentOutputs($address, $page = 1, $limit = 20, $sortDir = 'asc') {
268
        $queryString = [
269
            'page' => $page,
270
            'limit' => $limit,
271
            'sort_dir' => $sortDir
272
        ];
273
        $response = $this->dataClient->get($this->converter->getUrlForAddressUnspent($address), $this->converter->paginationParams($queryString));
274
        return $this->converter->convertAddressUnspentOutputs($response->body(), $address);
275
    }
276 1
277
    /**
278 1
     * get all unspent outputs for a batch of addresses (paginated)
279 1
     *
280 1
     * @param  string[] $addresses
281
     * @param  integer  $page    pagination: page number
282 1
     * @param  integer  $limit   pagination: records per page (max 500)
283 1
     * @param  string   $sortDir pagination: sort direction (asc|desc)
284
     * @return array associative array containing the response
285
     * @throws \Exception
286
     */
287
    public function batchAddressUnspentOutputs($addresses, $page = 1, $limit = 20, $sortDir = 'asc') {
288
        throw new \Exception("deprecated");
289
    }
290 1
291 1
    /**
292 1
     * verify ownership of an address
293
     * @param  string  $address     address hash
294
     * @param  string  $signature   a signed message (the address hash) using the private key of the address
295
     * @return array                associative array containing the response
296
     */
297
    public function verifyAddress($address, $signature) {
298
        if ($this->verifyMessage($address, $address, $signature)) {
299
            return ['result' => true, 'msg' => 'Successfully verified'];
300 1
        } else {
301 1
            return ['result' => false];
302 1
        }
303
    }
304
305
    /**
306
     * get all blocks (paginated)
307
     * @param  integer $page    pagination: page number
308
     * @param  integer $limit   pagination: records per page
309
     * @param  string  $sortDir pagination: sort direction (asc|desc)
310
     * @return array            associative array containing the response
311
     */
312
    public function allBlocks($page = 1, $limit = 20, $sortDir = 'asc') {
313 1
        $queryString = [
314
            'page' => $page,
315 1
            'limit' => $limit,
316 1
            'sort_dir' => $sortDir
317 1
        ];
318
        $response = $this->dataClient->get($this->converter->getUrlForAllBlocks(), $this->converter->paginationParams($queryString));
319 1
        return $this->converter->convertBlocks($response->body());
320 1
    }
321
322
    /**
323
     * get the latest block
324
     * @return array            associative array containing the response
325
     */
326
    public function blockLatest() {
327
        $response = $this->dataClient->get($this->converter->getUrlForBlock("latest"));
328 5
        return $this->converter->convertBlock($response->body());
329 5
    }
330 5
331
    /**
332
     * get an individual block
333
     * @param  string|integer $block    a block hash or a block height
334
     * @return array                    associative array containing the response
335
     */
336
    public function block($block) {
337
        $response = $this->dataClient->get($this->converter->getUrlForBlock($block));
338
        return $this->converter->convertBlock($response->body());
339
    }
340
341
    /**
342
     * get all transaction in a block (paginated)
343
     * @param  string|integer   $block   a block hash or a block height
344
     * @param  integer          $page    pagination: page number
345
     * @param  integer          $limit   pagination: records per page
346
     * @param  string           $sortDir pagination: sort direction (asc|desc)
347
     * @return array                     associative array containing the response
348
     */
349 1
    public function blockTransactions($block, $page = 1, $limit = 20, $sortDir = 'asc') {
350
        $queryString = [
351 1
            'page' => $page,
352 1
            'limit' => $limit,
353
            'sort_dir' => $sortDir
354 1
        ];
355 1
        $response = $this->dataClient->get($this->converter->getUrlForBlockTransaction($block), $this->converter->paginationParams($queryString));
356
        return $this->converter->convertBlockTxs($response->body());
357
    }
358
359
    /**
360
     * get a single transaction
361
     * @param  string $txhash transaction hash
362
     * @return array          associative array containing the response
363 1
     */
364 1
    public function transaction($txhash) {
365 1
        $response = $this->dataClient->get($this->converter->getUrlForTransaction($txhash));
366
        $res = $this->converter->convertTx($response->body(), null);
367
368
        if ($this->converter instanceof BtccomConverter) {
369
            $res['raw'] = $this->btccomRawTxClient->get("/{$txhash}.rawhex")->body();
370
        }
371
372
        return $res;
373
    }
374 1
375
    /**
376 1
     * get a single transaction
377 1
     * @param  string[] $txhashes list of transaction hashes (up to 20)
378
     * @return array[]            array containing the response
379 1
     */
380 1
    public function transactions($txhashes) {
381
        $response = $this->dataClient->get($this->converter->getUrlForTransactions($txhashes));
382
        return $this->converter->convertTxs($response->body());
383
    }
384
    
385
    /**
386
     * get a paginated list of all webhooks associated with the api user
387
     * @param  integer          $page    pagination: page number
388
     * @param  integer          $limit   pagination: records per page
389
     * @return array                     associative array containing the response
390 1
     */
391
    public function allWebhooks($page = 1, $limit = 20) {
392 1
        $queryString = [
393 1
            'page' => $page,
394
            'limit' => $limit
395 1
        ];
396 1
        $response = $this->blocktrailClient->get("webhooks", $this->converter->paginationParams($queryString));
397
        return self::jsonDecode($response->body(), true);
398
    }
399
400
    /**
401
     * get an existing webhook by it's identifier
402
     * @param string    $identifier     a unique identifier associated with the webhook
403
     * @return array                    associative array containing the response
404 1
     */
405 1
    public function getWebhook($identifier) {
406 1
        $response = $this->blocktrailClient->get("webhook/".$identifier);
407
        return self::jsonDecode($response->body(), true);
408
    }
409
410
    /**
411
     * create a new webhook
412
     * @param  string  $url        the url to receive the webhook events
413
     * @param  string  $identifier a unique identifier to associate with this webhook
414
     * @return array               associative array containing the response
415
     */
416 2
    public function setupWebhook($url, $identifier = null) {
417
        $postData = [
418 2
            'url'        => $url,
419 2
            'identifier' => $identifier
420
        ];
421 2
        $response = $this->blocktrailClient->post("webhook", null, $postData, RestClient::AUTH_HTTP_SIG);
422 2
        return self::jsonDecode($response->body(), true);
423
    }
424
425
    /**
426
     * update an existing webhook
427
     * @param  string  $identifier      the unique identifier of the webhook to update
428
     * @param  string  $newUrl          the new url to receive the webhook events
429
     * @param  string  $newIdentifier   a new unique identifier to associate with this webhook
430
     * @return array                    associative array containing the response
431
     */
432 1
    public function updateWebhook($identifier, $newUrl = null, $newIdentifier = null) {
433
        $putData = [
434 1
            'url'        => $newUrl,
435 1
            'identifier' => $newIdentifier
436 1
        ];
437
        $response = $this->blocktrailClient->put("webhook/{$identifier}", null, $putData, RestClient::AUTH_HTTP_SIG);
438 1
        return self::jsonDecode($response->body(), true);
439 1
    }
440
441
    /**
442
     * deletes an existing webhook and any event subscriptions associated with it
443
     * @param  string  $identifier      the unique identifier of the webhook to delete
444
     * @return boolean                  true on success
445
     */
446
    public function deleteWebhook($identifier) {
447
        $response = $this->blocktrailClient->delete("webhook/{$identifier}", null, null, RestClient::AUTH_HTTP_SIG);
448
        return self::jsonDecode($response->body(), true);
449 1
    }
450
451 1
    /**
452 1
     * get a paginated list of all the events a webhook is subscribed to
453 1
     * @param  string  $identifier  the unique identifier of the webhook
454
     * @param  integer $page        pagination: page number
455 1
     * @param  integer $limit       pagination: records per page
456 1
     * @return array                associative array containing the response
457
     */
458
    public function getWebhookEvents($identifier, $page = 1, $limit = 20) {
459
        $queryString = [
460
            'page' => $page,
461
            'limit' => $limit
462
        ];
463
        $response = $this->blocktrailClient->get("webhook/{$identifier}/events", $this->converter->paginationParams($queryString));
464
        return self::jsonDecode($response->body(), true);
465
    }
466
    
467
    /**
468
     * subscribes a webhook to transaction events of one particular transaction
469 1
     * @param  string  $identifier      the unique identifier of the webhook to be triggered
470 1
     * @param  string  $transaction     the transaction hash
471 1
     * @param  integer $confirmations   the amount of confirmations to send.
472 1
     * @return array                    associative array containing the response
473 1
     */
474 1
    public function subscribeTransaction($identifier, $transaction, $confirmations = 6) {
475 1
        $postData = [
476
            'event_type'    => 'transaction',
477
            'transaction'   => $transaction,
478 1
            'confirmations' => $confirmations,
479 1
        ];
480
        $response = $this->blocktrailClient->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
481
        return self::jsonDecode($response->body(), true);
482
    }
483
484
    /**
485
     * subscribes a webhook to transaction events on a particular address
486
     * @param  string  $identifier      the unique identifier of the webhook to be triggered
487 1
     * @param  string  $address         the address hash
488
     * @param  integer $confirmations   the amount of confirmations to send.
489 1
     * @return array                    associative array containing the response
490
     */
491 1
    public function subscribeAddressTransactions($identifier, $address, $confirmations = 6) {
492 1
        $postData = [
493
            'event_type'    => 'address-transactions',
494
            'address'       => $address,
495
            'confirmations' => $confirmations,
496
        ];
497
        $response = $this->blocktrailClient->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
498
        return self::jsonDecode($response->body(), true);
499
    }
500
501 1
    /**
502 1
     * batch subscribes a webhook to multiple transaction events
503 1
     *
504
     * @param  string $identifier   the unique identifier of the webhook
505
     * @param  array  $batchData    A 2D array of event data:
506
     *                              [address => $address, confirmations => $confirmations]
507
     *                              where $address is the address to subscibe to
508
     *                              and optionally $confirmations is the amount of confirmations
509
     * @return boolean              true on success
510
     */
511
    public function batchSubscribeAddressTransactions($identifier, $batchData) {
512 1
        $postData = [];
513 1
        foreach ($batchData as $record) {
514 1
            $postData[] = [
515
                'event_type' => 'address-transactions',
516
                'address' => $record['address'],
517
                'confirmations' => isset($record['confirmations']) ? $record['confirmations'] : 6,
518
            ];
519
        }
520
        $response = $this->blocktrailClient->post("webhook/{$identifier}/events/batch", null, $postData, RestClient::AUTH_HTTP_SIG);
521
        return self::jsonDecode($response->body(), true);
522 1
    }
523 1
524 1
    /**
525
     * subscribes a webhook to a new block event
526
     * @param  string  $identifier  the unique identifier of the webhook to be triggered
527
     * @return array                associative array containing the response
528
     */
529
    public function subscribeNewBlocks($identifier) {
530
        $postData = [
531
            'event_type'    => 'block',
532
        ];
533
        $response = $this->blocktrailClient->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
534
        return self::jsonDecode($response->body(), true);
535
    }
536
537
    /**
538
     * removes an transaction event subscription from a webhook
539
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
540
     * @param  string  $transaction     the transaction hash of the event subscription
541
     * @return boolean                  true on success
542
     */
543
    public function unsubscribeTransaction($identifier, $transaction) {
544 7
        $response = $this->blocktrailClient->delete("webhook/{$identifier}/transaction/{$transaction}", null, null, RestClient::AUTH_HTTP_SIG);
545 7
        return self::jsonDecode($response->body(), true);
546 1
    }
547
548 1
    /**
549 1
     * removes an address transaction event subscription from a webhook
550 1
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
551
     * @param  string  $address         the address hash of the event subscription
552
     * @return boolean                  true on success
553
     */
554 7
    public function unsubscribeAddressTransactions($identifier, $address) {
555 1
        $response = $this->blocktrailClient->delete("webhook/{$identifier}/address-transactions/{$address}", null, null, RestClient::AUTH_HTTP_SIG);
556
        return self::jsonDecode($response->body(), true);
557
    }
558 1
559
    /**
560
     * removes a block event subscription from a webhook
561
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
562 7
     * @return boolean                  true on success
563 1
     */
564
    public function unsubscribeNewBlocks($identifier) {
565
        $response = $this->blocktrailClient->delete("webhook/{$identifier}/block", null, null, RestClient::AUTH_HTTP_SIG);
566 7
        return self::jsonDecode($response->body(), true);
567
    }
568
569
    /**
570 7
     * create a new wallet
571 3
     *   - will generate a new primary seed (with password) and backup seed (without password)
572
     *   - send the primary seed (BIP39 'encrypted') and backup public key to the server
573
     *   - receive the blocktrail co-signing public key from the server
574 7
     *
575 7
     * Either takes one argument:
576 1
     * @param array $options
577
     *
578 6
     * Or takes three arguments (old, deprecated syntax):
579 2
     * (@nonPHP-doc) @param      $identifier
580
     * (@nonPHP-doc) @param      $password
581 4
     * (@nonPHP-doc) @param int  $keyIndex          override for the blocktrail cosigning key to use
0 ignored issues
show
Bug introduced by
There is no parameter named $keyIndex. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
582 4
     *
583
     * @return array[WalletInterface, array]      list($wallet, $backupInfo)
0 ignored issues
show
Documentation introduced by
The doc-type array[WalletInterface, could not be parsed: Expected "]" at position 2, but found "WalletInterface". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
584
     * @throws \Exception
585
     */
586
    public function createNewWallet($options) {
587
        if (!is_array($options)) {
588
            $args = func_get_args();
589 1
            $options = [
590 1
                "identifier" => $args[0],
591
                "password" => $args[1],
592 1
                "key_index" => isset($args[2]) ? $args[2] : null,
593
            ];
594 1
        }
595
596
        if (isset($options['password'])) {
597
            if (isset($options['passphrase'])) {
598 1
                throw new \InvalidArgumentException("Can only provide either passphrase or password");
599 1
            } else {
600 1
                $options['passphrase'] = $options['password'];
601 1
            }
602
        }
603
604
        if (!isset($options['passphrase'])) {
605
            $options['passphrase'] = null;
606 1
        }
607 1
608 1
        if (!isset($options['key_index'])) {
609
            $options['key_index'] = 0;
610
        }
611
612
        if (!isset($options['wallet_version'])) {
613
            $options['wallet_version'] = Wallet::WALLET_VERSION_V3;
614
        }
615
616
        switch ($options['wallet_version']) {
617 1
            case Wallet::WALLET_VERSION_V1:
618
                return $this->createNewWalletV1($options);
619
620
            case Wallet::WALLET_VERSION_V2:
621 1
                return $this->createNewWalletV2($options);
622 1
623 1
            case Wallet::WALLET_VERSION_V3:
624
                return $this->createNewWalletV3($options);
625
626
            default:
627
                throw new \InvalidArgumentException("Invalid wallet version");
628
        }
629 1
    }
630
631
    protected function createNewWalletV1($options) {
632
        $walletPath = WalletPath::create($options['key_index']);
633
634 1
        $storePrimaryMnemonic = isset($options['store_primary_mnemonic']) ? $options['store_primary_mnemonic'] : null;
635 1
636
        if (isset($options['primary_mnemonic']) && isset($options['primary_private_key'])) {
637 1
            throw new \InvalidArgumentException("Can't specify Primary Mnemonic and Primary PrivateKey");
638
        }
639
640
        $primaryMnemonic = null;
641 1
        $primaryPrivateKey = null;
642 1
        if (!isset($options['primary_mnemonic']) && !isset($options['primary_private_key'])) {
643 1
            if (!$options['passphrase']) {
644
                throw new \InvalidArgumentException("Can't generate Primary Mnemonic without a passphrase");
645 1
            } else {
646
                // create new primary seed
647
                /** @var HierarchicalKey $primaryPrivateKey */
648
                list($primaryMnemonic, , $primaryPrivateKey) = $this->newPrimarySeed($options['passphrase']);
649
                if ($storePrimaryMnemonic !== false) {
650
                    $storePrimaryMnemonic = true;
651
                }
652 1
            }
653
        } elseif (isset($options['primary_mnemonic'])) {
654
            $primaryMnemonic = $options['primary_mnemonic'];
655
        } elseif (isset($options['primary_private_key'])) {
656
            $primaryPrivateKey = $options['primary_private_key'];
657 1
        }
658 1
659
        if ($storePrimaryMnemonic && $primaryMnemonic && !$options['passphrase']) {
660
            throw new \InvalidArgumentException("Can't store Primary Mnemonic on server without a passphrase");
661
        }
662 1
663 1
        if ($primaryPrivateKey) {
664
            if (is_string($primaryPrivateKey)) {
665
                $primaryPrivateKey = [$primaryPrivateKey, "m"];
666
            }
667 1
        } else {
668 1
            $primaryPrivateKey = HierarchicalKeyFactory::fromEntropy((new Bip39SeedGenerator())->getSeed($primaryMnemonic, $options['passphrase']));
669 1
        }
670 1
671 1
        if (!$storePrimaryMnemonic) {
672 1
            $primaryMnemonic = false;
673 1
        }
674 1
675
        // create primary public key from the created private key
676
        $path = $walletPath->keyIndexPath()->publicPath();
677
        $primaryPublicKey = BIP32Key::create($primaryPrivateKey, "m")->buildKey($path);
678
679 1
        if (isset($options['backup_mnemonic']) && $options['backup_public_key']) {
680 1
            throw new \InvalidArgumentException("Can't specify Backup Mnemonic and Backup PublicKey");
681
        }
682 1
683 1
        $backupMnemonic = null;
684 1
        $backupPublicKey = null;
685 1
        if (!isset($options['backup_mnemonic']) && !isset($options['backup_public_key'])) {
686 1
            /** @var HierarchicalKey $backupPrivateKey */
687 1
            list($backupMnemonic, , ) = $this->newBackupSeed();
688 1
        } else if (isset($options['backup_mnemonic'])) {
689 1
            $backupMnemonic = $options['backup_mnemonic'];
690 1
        } elseif (isset($options['backup_public_key'])) {
691 1
            $backupPublicKey = $options['backup_public_key'];
692 1
        }
693 1
694 1
        if ($backupPublicKey) {
695
            if (is_string($backupPublicKey)) {
696
                $backupPublicKey = [$backupPublicKey, "m"];
697 1
            }
698
        } else {
699
            $backupPrivateKey = HierarchicalKeyFactory::fromEntropy((new Bip39SeedGenerator())->getSeed($backupMnemonic, ""));
700
            $backupPublicKey = BIP32Key::create($backupPrivateKey->toPublic(), "M");
701 1
        }
702
703 1
        // create a checksum of our private key which we'll later use to verify we used the right password
704 1
        $checksum = $primaryPrivateKey->getPublicKey()->getAddress()->getAddress();
705 1
        $addressReader = $this->makeAddressReader($options);
706
707
        // send the public keys to the server to store them
708
        //  and the mnemonic, which is safe because it's useless without the password
709
        $data = $this->storeNewWalletV1(
710 5
            $options['identifier'],
711 5
            $primaryPublicKey->tuple(),
712
            $backupPublicKey->tuple(),
713
            $primaryMnemonic,
714 5
            $checksum,
715 5
            $options['key_index'],
716
            array_key_exists('segwit', $options) ? $options['segwit'] : false
717
        );
718 2
719 2
        // received the blocktrail public keys
720
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
721 2
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
722
        }, $data['blocktrail_public_keys']);
723
724
        $wallet = new WalletV1(
725 2
            $this,
726 2
            $options['identifier'],
727 1
            $primaryMnemonic,
728
            [$options['key_index'] => $primaryPublicKey],
729 1
            $backupPublicKey,
730
            $blocktrailPublicKeys,
731
            $options['key_index'],
732
            $this->network,
733 2
            $this->testnet,
734
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
735 2
            $addressReader,
736 2
            $checksum
737 2
        );
738 2
739 2
        $wallet->unlock($options);
740 2
741 2
        // return wallet and backup mnemonic
742
        return [
743 2
            $wallet,
744 1
            [
745
                'primary_mnemonic' => $primaryMnemonic,
746
                'backup_mnemonic' => $backupMnemonic,
747 2
                'blocktrail_public_keys' => $blocktrailPublicKeys,
748 1
            ],
749 1
        ];
750
    }
751
752
    public static function randomBits($bits) {
753 1
        return self::randomBytes($bits / 8);
754 1
    }
755
756
    public static function randomBytes($bytes) {
757
        return (new Random())->bytes($bytes)->getBinary();
758
    }
759 1
760 1
    protected function createNewWalletV2($options) {
761
        $walletPath = WalletPath::create($options['key_index']);
762 1
763
        if (isset($options['store_primary_mnemonic'])) {
764
            $options['store_data_on_server'] = $options['store_primary_mnemonic'];
765 2
        }
766 1
767
        if (!isset($options['store_data_on_server'])) {
768
            if (isset($options['primary_private_key'])) {
769 2
                $options['store_data_on_server'] = false;
770 1
            } else {
771
                $options['store_data_on_server'] = true;
772 1
            }
773
        }
774
775
        $storeDataOnServer = $options['store_data_on_server'];
776 2
777
        $secret = null;
778 2
        $encryptedSecret = null;
779 1
        $primarySeed = null;
780
        $encryptedPrimarySeed = null;
781
        $recoverySecret = null;
782
        $recoveryEncryptedSecret = null;
783 2
        $backupSeed = null;
784 2
785
        if (!isset($options['primary_private_key'])) {
786
            $primarySeed = isset($options['primary_seed']) ? $options['primary_seed'] : self::randomBits(256);
787 2
        }
788 2
789 2
        if ($storeDataOnServer) {
790 2
            if (!isset($options['secret'])) {
791 2
                if (!$options['passphrase']) {
792 2
                    throw new \InvalidArgumentException("Can't encrypt data without a passphrase");
793 2
                }
794 2
795 2
                $secret = bin2hex(self::randomBits(256)); // string because we use it as passphrase
796 2
                $encryptedSecret = CryptoJSAES::encrypt($secret, $options['passphrase']);
797
            } else {
798
                $secret = $options['secret'];
799
            }
800
801 2
            $encryptedPrimarySeed = CryptoJSAES::encrypt(base64_encode($primarySeed), $secret);
802 2
            $recoverySecret = bin2hex(self::randomBits(256));
803
804 2
            $recoveryEncryptedSecret = CryptoJSAES::encrypt($secret, $recoverySecret);
805 2
        }
806 2
807 2
        if (!isset($options['backup_public_key'])) {
808 2
            $backupSeed = isset($options['backup_seed']) ? $options['backup_seed'] : self::randomBits(256);
809 2
        }
810 2
811 2
        if (isset($options['primary_private_key'])) {
812 2
            $options['primary_private_key'] = BlocktrailSDK::normalizeBIP32Key($options['primary_private_key']);
813 2
        } else {
814 2
            $options['primary_private_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy(new Buffer($primarySeed)), "m");
815 2
        }
816 2
817 2
        // create primary public key from the created private key
818
        $options['primary_public_key'] = $options['primary_private_key']->buildKey($walletPath->keyIndexPath()->publicPath());
819
820 2
        if (!isset($options['backup_public_key'])) {
821 2
            $options['backup_public_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy(new Buffer($backupSeed)), "m")->buildKey("M");
822 2
        }
823 2
824 2
        // create a checksum of our private key which we'll later use to verify we used the right password
825
        $checksum = $options['primary_private_key']->publicKey()->getAddress()->getAddress();
826
        $addressReader = $this->makeAddressReader($options);
827
828
        // send the public keys and encrypted data to server
829 2
        $data = $this->storeNewWalletV2(
830
            $options['identifier'],
831 2
            $options['primary_public_key']->tuple(),
832 2
            $options['backup_public_key']->tuple(),
833 2
            $storeDataOnServer ? $encryptedPrimarySeed : false,
834 2
            $storeDataOnServer ? $encryptedSecret : false,
835
            $storeDataOnServer ? $recoverySecret : false,
836 2
            $checksum,
837 2
            $options['key_index'],
838
            array_key_exists('segwit', $options) ? $options['segwit'] : false
839
        );
840
841
        // received the blocktrail public keys
842 4
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
843 4
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
844
        }, $data['blocktrail_public_keys']);
845 4
846
        $wallet = new WalletV2(
847
            $this,
848
            $options['identifier'],
849 4
            $encryptedPrimarySeed,
850 4
            $encryptedSecret,
851
            [$options['key_index'] => $options['primary_public_key']],
852
            $options['backup_public_key'],
853 4
            $blocktrailPublicKeys,
854
            $options['key_index'],
855
            $this->network,
856
            $this->testnet,
857 4
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
858
            $addressReader,
859 4
            $checksum
860 4
        );
861 4
862 4
        $wallet->unlock([
863 4
            'passphrase' => isset($options['passphrase']) ? $options['passphrase'] : null,
864 4
            'primary_private_key' => $options['primary_private_key'],
865 4
            'primary_seed' => $primarySeed,
866
            'secret' => $secret,
867 4
        ]);
868 4
869
        // return wallet and mnemonics for backup sheet
870
        return [
871
            $wallet,
872
            [
873
                'encrypted_primary_seed' => $encryptedPrimarySeed ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($encryptedPrimarySeed))) : null,
874 4
                'backup_seed' => $backupSeed ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer($backupSeed)) : null,
875
                'recovery_encrypted_secret' => $recoveryEncryptedSecret ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($recoveryEncryptedSecret))) : null,
876
                'encrypted_secret' => $encryptedSecret ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($encryptedSecret))) : null,
877
                'blocktrail_public_keys' => Util::arrayMapWithIndex(function ($keyIndex, BIP32Key $pubKey) {
878 4
                    return [$keyIndex, $pubKey->tuple()];
879 4
                }, $blocktrailPublicKeys),
880 4
            ],
881
        ];
882
    }
883
884 4
    protected function createNewWalletV3($options) {
885 4
        $walletPath = WalletPath::create($options['key_index']);
886 4
887
        if (isset($options['store_primary_mnemonic'])) {
888
            $options['store_data_on_server'] = $options['store_primary_mnemonic'];
889
        }
890
891
        if (!isset($options['store_data_on_server'])) {
892
            if (isset($options['primary_private_key'])) {
893
                $options['store_data_on_server'] = false;
894
            } else {
895 4
                $options['store_data_on_server'] = true;
896 4
            }
897 4
        }
898
899 4
        $storeDataOnServer = $options['store_data_on_server'];
900 4
901
        $secret = null;
902
        $encryptedSecret = null;
903 4
        $primarySeed = null;
904 4
        $encryptedPrimarySeed = null;
905
        $recoverySecret = null;
906
        $recoveryEncryptedSecret = null;
907
        $backupSeed = null;
908
909
        if (!isset($options['primary_private_key'])) {
910 4
            if (isset($options['primary_seed'])) {
911
                if (!$options['primary_seed'] instanceof BufferInterface) {
912
                    throw new \InvalidArgumentException('Primary Seed should be passed as a Buffer');
913
                }
914 4
                $primarySeed = $options['primary_seed'];
915
            } else {
916
                $primarySeed = new Buffer(self::randomBits(256));
917 4
            }
918
        }
919
920
        if ($storeDataOnServer) {
921 4
            if (!isset($options['secret'])) {
922
                if (!$options['passphrase']) {
923 4
                    throw new \InvalidArgumentException("Can't encrypt data without a passphrase");
924 4
                }
925
926
                $secret = new Buffer(self::randomBits(256));
927
                $encryptedSecret = Encryption::encrypt($secret, new Buffer($options['passphrase']), KeyDerivation::DEFAULT_ITERATIONS)
928 4
                    ->getBuffer();
929 4
            } else {
930
                if (!$options['secret'] instanceof Buffer) {
931
                    throw new \RuntimeException('Secret must be provided as a Buffer');
932 4
                }
933 4
934 4
                $secret = $options['secret'];
935 4
            }
936 4
937 4
            $encryptedPrimarySeed = Encryption::encrypt($primarySeed, $secret, KeyDerivation::SUBKEY_ITERATIONS)
938 4
                ->getBuffer();
939 4
            $recoverySecret = new Buffer(self::randomBits(256));
940 4
941 4
            $recoveryEncryptedSecret = Encryption::encrypt($secret, $recoverySecret, KeyDerivation::DEFAULT_ITERATIONS)
942
                ->getBuffer();
943
        }
944
945
        if (!isset($options['backup_public_key'])) {
946 4
            if (isset($options['backup_seed'])) {
947 4
                if (!$options['backup_seed'] instanceof Buffer) {
948
                    throw new \RuntimeException('Backup seed must be an instance of Buffer');
949 4
                }
950 4
                $backupSeed = $options['backup_seed'];
951 4
            } else {
952 4
                $backupSeed = new Buffer(self::randomBits(256));
953 4
            }
954 4
        }
955 4
956 4
        if (isset($options['primary_private_key'])) {
957 4
            $options['primary_private_key'] = BlocktrailSDK::normalizeBIP32Key($options['primary_private_key']);
958 4
        } else {
959 4
            $options['primary_private_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy($primarySeed), "m");
960 4
        }
961 4
962 4
        // create primary public key from the created private key
963
        $options['primary_public_key'] = $options['primary_private_key']->buildKey($walletPath->keyIndexPath()->publicPath());
964
965 4
        if (!isset($options['backup_public_key'])) {
966 4
            $options['backup_public_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy($backupSeed), "m")->buildKey("M");
967 4
        }
968 4
969 4
        // create a checksum of our private key which we'll later use to verify we used the right password
970
        $checksum = $options['primary_private_key']->publicKey()->getAddress()->getAddress();
971
        $addressReader = $this->makeAddressReader($options);
972
973
        // send the public keys and encrypted data to server
974 4
        $data = $this->storeNewWalletV3(
975
            $options['identifier'],
976 4
            $options['primary_public_key']->tuple(),
977 4
            $options['backup_public_key']->tuple(),
978 4
            $storeDataOnServer ? base64_encode($encryptedPrimarySeed->getBinary()) : false,
979 4
            $storeDataOnServer ? base64_encode($encryptedSecret->getBinary()) : false,
980
            $storeDataOnServer ? $recoverySecret->getHex() : false,
981 4
            $checksum,
982 4
            $options['key_index'],
983
            array_key_exists('segwit', $options) ? $options['segwit'] : false
984
        );
985
986
        // received the blocktrail public keys
987
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
988
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
989
        }, $data['blocktrail_public_keys']);
990
991 10
        $wallet = new WalletV3(
992 10
            $this,
993 10
            $options['identifier'],
994
            $encryptedPrimarySeed,
0 ignored issues
show
Bug introduced by
It seems like $encryptedPrimarySeed defined by null on line 904 can be null; however, Blocktrail\SDK\WalletV3::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
995
            $encryptedSecret,
0 ignored issues
show
Bug introduced by
It seems like $encryptedSecret defined by null on line 902 can be null; however, Blocktrail\SDK\WalletV3::__construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
996
            [$options['key_index'] => $options['primary_public_key']],
997 10
            $options['backup_public_key'],
998
            $blocktrailPublicKeys,
999
            $options['key_index'],
1000 10
            $this->network,
1001
            $this->testnet,
1002
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
1003
            $addressReader,
1004
            $checksum
1005
        );
1006 10
1007 10
        $wallet->unlock([
1008 10
            'passphrase' => isset($options['passphrase']) ? $options['passphrase'] : null,
1009 10
            'primary_private_key' => $options['primary_private_key'],
1010
            'primary_seed' => $primarySeed,
1011
            'secret' => $secret,
1012
        ]);
1013
1014
        // return wallet and mnemonics for backup sheet
1015
        return [
1016
            $wallet,
1017
            [
1018
                'encrypted_primary_seed'    => $encryptedPrimarySeed ? EncryptionMnemonic::encode($encryptedPrimarySeed) : null,
1019
                'backup_seed'               => $backupSeed ? MnemonicFactory::bip39()->entropyToMnemonic($backupSeed) : null,
1020
                'recovery_encrypted_secret' => $recoveryEncryptedSecret ? EncryptionMnemonic::encode($recoveryEncryptedSecret) : null,
1021
                'encrypted_secret'          => $encryptedSecret ? EncryptionMnemonic::encode($encryptedSecret) : null,
1022
                'blocktrail_public_keys'    => Util::arrayMapWithIndex(function ($keyIndex, BIP32Key $pubKey) {
1023 1
                    return [$keyIndex, $pubKey->tuple()];
1024
                }, $blocktrailPublicKeys),
1025 1
            ]
1026 1
        ];
1027 1
    }
1028 1
1029 1
    /**
1030 1
     * @param array $bip32Key
1031 1
     * @throws BlocktrailSDKException
1032
     */
1033 1
    private function verifyPublicBIP32Key(array $bip32Key) {
1034 1
        $hk = HierarchicalKeyFactory::fromExtended($bip32Key[0]);
1035 1
        if ($hk->isPrivate()) {
1036
            throw new BlocktrailSDKException('Private key was included in request, abort');
1037
        }
1038
1039
        if (substr($bip32Key[1], 0, 1) === "m") {
1040
            throw new BlocktrailSDKException("Private path was included in the request, abort");
1041
        }
1042
    }
1043
1044
    /**
1045
     * @param array $walletData
1046
     * @throws BlocktrailSDKException
1047
     */
1048
    private function verifyPublicOnly(array $walletData) {
1049
        $this->verifyPublicBIP32Key($walletData['primary_public_key']);
1050
        $this->verifyPublicBIP32Key($walletData['backup_public_key']);
1051
    }
1052
1053 5
    /**
1054
     * create wallet using the API
1055 5
     *
1056
     * @param string    $identifier             the wallet identifier to create
1057 5
     * @param array     $primaryPublicKey       BIP32 extended public key - [key, path]
1058 5
     * @param array     $backupPublicKey        BIP32 extended public key - [backup key, path "M"]
1059 5
     * @param string    $primaryMnemonic        mnemonic to store
1060 5
     * @param string    $checksum               checksum to store
1061 5
     * @param int       $keyIndex               account that we expect to use
1062 5
     * @param bool      $segwit                 opt in to segwit
1063 5
     * @return mixed
1064 5
     */
1065
    public function storeNewWalletV1($identifier, $primaryPublicKey, $backupPublicKey, $primaryMnemonic, $checksum, $keyIndex, $segwit = false) {
1066 5
        $data = [
1067 5
            'identifier' => $identifier,
1068 5
            'primary_public_key' => $primaryPublicKey,
1069
            'backup_public_key' => $backupPublicKey,
1070
            'primary_mnemonic' => $primaryMnemonic,
1071
            'checksum' => $checksum,
1072
            'key_index' => $keyIndex,
1073
            'segwit' => $segwit,
1074
        ];
1075
        $this->verifyPublicOnly($data);
1076
        $response = $this->blocktrailClient->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
1077
        return self::jsonDecode($response->body(), true);
1078
    }
1079
1080
    /**
1081
     * create wallet using the API
1082
     *
1083
     * @param string $identifier       the wallet identifier to create
1084
     * @param array  $primaryPublicKey BIP32 extended public key - [key, path]
1085
     * @param array  $backupPublicKey  BIP32 extended public key - [backup key, path "M"]
1086 4
     * @param        $encryptedPrimarySeed
1087
     * @param        $encryptedSecret
1088
     * @param        $recoverySecret
1089 4
     * @param string $checksum         checksum to store
1090
     * @param int    $keyIndex         account that we expect to use
1091 4
     * @param bool   $segwit           opt in to segwit
1092 4
     * @return mixed
1093 4
     * @throws \Exception
1094 4
     */
1095 4
    public function storeNewWalletV2($identifier, $primaryPublicKey, $backupPublicKey, $encryptedPrimarySeed, $encryptedSecret, $recoverySecret, $checksum, $keyIndex, $segwit = false) {
1096 4
        $data = [
1097 4
            'identifier' => $identifier,
1098 4
            'wallet_version' => Wallet::WALLET_VERSION_V2,
1099
            'primary_public_key' => $primaryPublicKey,
1100
            'backup_public_key' => $backupPublicKey,
1101 4
            'encrypted_primary_seed' => $encryptedPrimarySeed,
1102 4
            'encrypted_secret' => $encryptedSecret,
1103 4
            'recovery_secret' => $recoverySecret,
1104
            'checksum' => $checksum,
1105
            'key_index' => $keyIndex,
1106
            'segwit' => $segwit,
1107
        ];
1108
        $this->verifyPublicOnly($data);
1109
        $response = $this->blocktrailClient->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
1110
        return self::jsonDecode($response->body(), true);
1111
    }
1112
1113
    /**
1114
     * create wallet using the API
1115 5
     *
1116
     * @param string $identifier       the wallet identifier to create
1117 5
     * @param array  $primaryPublicKey BIP32 extended public key - [key, path]
1118 5
     * @param array  $backupPublicKey  BIP32 extended public key - [backup key, path "M"]
1119
     * @param        $encryptedPrimarySeed
1120
     * @param        $encryptedSecret
1121 5
     * @param        $recoverySecret
1122 5
     * @param string $checksum         checksum to store
1123
     * @param int    $keyIndex         account that we expect to use
1124
     * @param bool   $segwit           opt in to segwit
1125
     * @return mixed
1126
     * @throws \Exception
1127
     */
1128
    public function storeNewWalletV3($identifier, $primaryPublicKey, $backupPublicKey, $encryptedPrimarySeed, $encryptedSecret, $recoverySecret, $checksum, $keyIndex, $segwit = false) {
1129 23
1130 23
        $data = [
1131 4
            'identifier' => $identifier,
1132 4
            'wallet_version' => Wallet::WALLET_VERSION_V3,
1133 3
            'primary_public_key' => $primaryPublicKey,
1134
            'backup_public_key' => $backupPublicKey,
1135 4
            'encrypted_primary_seed' => $encryptedPrimarySeed,
1136
            'encrypted_secret' => $encryptedSecret,
1137 19
            'recovery_secret' => $recoverySecret,
1138
            'checksum' => $checksum,
1139
            'key_index' => $keyIndex,
1140
            'segwit' => $segwit,
1141
        ];
1142
1143
        $this->verifyPublicOnly($data);
1144
        $response = $this->blocktrailClient->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
1145
        return self::jsonDecode($response->body(), true);
1146
    }
1147
1148
    /**
1149
     * upgrade wallet to use a new account number
1150
     *  the account number specifies which blocktrail cosigning key is used
1151
     *
1152
     * @param string    $identifier             the wallet identifier to be upgraded
1153
     * @param int       $keyIndex               the new account to use
1154
     * @param array     $primaryPublicKey       BIP32 extended public key - [key, path]
1155
     * @return mixed
1156
     */
1157
    public function upgradeKeyIndex($identifier, $keyIndex, $primaryPublicKey) {
1158
        $data = [
1159
            'key_index' => $keyIndex,
1160
            'primary_public_key' => $primaryPublicKey
1161
        ];
1162
1163
        $response = $this->blocktrailClient->post("wallet/{$identifier}/upgrade", null, $data, RestClient::AUTH_HTTP_SIG);
1164 23
        return self::jsonDecode($response->body(), true);
1165 23
    }
1166 1
1167
    /**
1168 1
     * @param array $options
1169 1
     * @return AddressReaderBase
1170
     */
1171
    private function makeAddressReader(array $options) {
1172
        if ($this->network == "bitcoincash") {
1173 23
            $useCashAddress = false;
1174 23
            if (array_key_exists("use_cashaddress", $options) && $options['use_cashaddress']) {
1175 23
                $useCashAddress = true;
1176 23
            }
1177 23
            return new BitcoinCashAddressReader($useCashAddress);
1178
        } else {
1179
            return new BitcoinAddressReader();
1180 23
        }
1181 23
    }
1182
1183
    /**
1184
     * initialize a previously created wallet
1185 23
     *
1186 1
     * Takes an options object, or accepts identifier/password for backwards compatiblity.
1187 1
     *
1188
     * Some of the options:
1189 1
     *  - "readonly/readOnly/read-only" can be to a boolean value,
1190 1
     *    so the wallet is loaded in read-only mode (no private key)
1191
     *  - "check_backup_key" can be set to your own backup key:
1192
     *    Format: ["M', "xpub..."]
1193
     *    Setting this will allow the SDK to check the server hasn't
1194 23
     *    a different key (one it happens to control)
1195
1196 23
     * Either takes one argument:
1197 23
     * @param array $options
1198 17
     *
1199 17
     * Or takes two arguments (old, deprecated syntax):
1200 17
     * (@nonPHP-doc) @param string    $identifier             the wallet identifier to be initialized
0 ignored issues
show
Bug introduced by
There is no parameter named $identifier. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1201 17
     * (@nonPHP-doc) @param string    $password               the password to decrypt the mnemonic with
0 ignored issues
show
Bug introduced by
There is no parameter named $password. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1202 17
     *
1203 17
     * @return WalletInterface
1204 17
     * @throws \Exception
1205 17
     */
1206 17
    public function initWallet($options) {
1207 17
        if (!is_array($options)) {
1208 17
            $args = func_get_args();
1209 17
            $options = [
1210 17
                "identifier" => $args[0],
1211
                "password" => $args[1],
1212 17
            ];
1213 6
        }
1214 2
1215 2
        $identifier = $options['identifier'];
1216 2
        $readonly = isset($options['readonly']) ? $options['readonly'] :
1217 2
                    (isset($options['readOnly']) ? $options['readOnly'] :
1218 2
                        (isset($options['read-only']) ? $options['read-only'] :
1219 2
                            false));
1220 2
1221 2
        // get the wallet data from the server
1222 2
        $data = $this->getWallet($identifier);
1223 2
        if (!$data) {
1224 2
            throw new \Exception("Failed to get wallet");
1225 2
        }
1226 2
1227 2
        if (array_key_exists('check_backup_key', $options)) {
1228
            if (!is_string($options['check_backup_key'])) {
1229 2
                throw new \RuntimeException("check_backup_key should be a string (the xpub)");
1230 4
            }
1231 4
            if ($options['check_backup_key'] !== $data['backup_public_key'][0]) {
1232
                throw new \RuntimeException("Backup key returned from server didn't match our own");
1233
            }
1234
        }
1235
1236
        $addressReader = $this->makeAddressReader($options);
1237 4
1238
        switch ($data['wallet_version']) {
1239
            case Wallet::WALLET_VERSION_V1:
1240 4
                $wallet = new WalletV1(
1241
                    $this,
1242
                    $identifier,
1243
                    isset($options['primary_mnemonic']) ? $options['primary_mnemonic'] : $data['primary_mnemonic'],
1244
                    $data['primary_public_keys'],
1245
                    $data['backup_public_key'],
1246
                    $data['blocktrail_public_keys'],
1247 4
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1248
                    $this->network,
1249
                    $this->testnet,
1250 4
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1251 4
                    $addressReader,
1252 4
                    $data['checksum']
1253 4
                );
1254 4
                break;
1255 4
            case Wallet::WALLET_VERSION_V2:
1256 4
                $wallet = new WalletV2(
1257 4
                    $this,
1258 4
                    $identifier,
1259 4
                    isset($options['encrypted_primary_seed']) ? $options['encrypted_primary_seed'] : $data['encrypted_primary_seed'],
1260 4
                    isset($options['encrypted_secret']) ? $options['encrypted_secret'] : $data['encrypted_secret'],
1261 4
                    $data['primary_public_keys'],
1262 4
                    $data['backup_public_key'],
1263 4
                    $data['blocktrail_public_keys'],
1264
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1265 4
                    $this->network,
1266
                    $this->testnet,
1267
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1268
                    $addressReader,
1269
                    $data['checksum']
1270 23
                );
1271 23
                break;
1272
            case Wallet::WALLET_VERSION_V3:
1273
                if (isset($options['encrypted_primary_seed'])) {
1274 23
                    if (!$options['encrypted_primary_seed'] instanceof Buffer) {
1275
                        throw new \InvalidArgumentException('Encrypted PrimarySeed must be provided as a Buffer');
1276
                    }
1277
                    $encryptedPrimarySeed = $data['encrypted_primary_seed'];
1278
                } else {
1279
                    $encryptedPrimarySeed = new Buffer(base64_decode($data['encrypted_primary_seed']));
1280
                }
1281
1282
                if (isset($options['encrypted_secret'])) {
1283 23
                    if (!$options['encrypted_secret'] instanceof Buffer) {
1284 23
                        throw new \InvalidArgumentException('Encrypted secret must be provided as a Buffer');
1285 23
                    }
1286
1287
                    $encryptedSecret = $data['encrypted_secret'];
1288
                } else {
1289
                    $encryptedSecret = new Buffer(base64_decode($data['encrypted_secret']));
1290
                }
1291
1292
                $wallet = new WalletV3(
1293
                    $this,
1294
                    $identifier,
1295 3
                    $encryptedPrimarySeed,
1296 3
                    $encryptedSecret,
1297 3
                    $data['primary_public_keys'],
1298
                    $data['backup_public_key'],
1299
                    $data['blocktrail_public_keys'],
1300
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1301
                    $this->network,
1302
                    $this->testnet,
1303
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1304
                    $addressReader,
1305
                    $data['checksum']
1306
                );
1307
                break;
1308
            default:
1309
                throw new \InvalidArgumentException("Invalid wallet version");
1310
        }
1311 10
1312 10
        if (!$readonly) {
1313 10
            $wallet->unlock($options);
1314 10
        }
1315 10
1316 10
        return $wallet;
1317
    }
1318
1319
    /**
1320
     * get the wallet data from the server
1321
     *
1322
     * @param string    $identifier             the identifier of the wallet
1323
     * @return mixed
1324
     */
1325
    public function getWallet($identifier) {
1326
        $response = $this->blocktrailClient->get("wallet/{$identifier}", null, RestClient::AUTH_HTTP_SIG);
1327 1
        return self::jsonDecode($response->body(), true);
1328 1
    }
1329
1330 1
    /**
1331
     * update the wallet data on the server
1332
     *
1333
     * @param string    $identifier
1334
     * @param $data
1335
     * @return mixed
1336
     */
1337
    public function updateWallet($identifier, $data) {
1338
        $response = $this->blocktrailClient->post("wallet/{$identifier}", null, $data, RestClient::AUTH_HTTP_SIG);
1339
        return self::jsonDecode($response->body(), true);
1340
    }
1341
1342
    /**
1343 1
     * delete a wallet from the server
1344 1
     *  the checksum address and a signature to verify you ownership of the key of that checksum address
1345
     *  is required to be able to delete a wallet
1346 1
     *
1347
     * @param string    $identifier             the identifier of the wallet
1348
     * @param string    $checksumAddress        the address for your master private key (and the checksum used when creating the wallet)
1349
     * @param string    $signature              a signature of the checksum address as message signed by the private key matching that address
1350
     * @param bool      $force                  ignore warnings (such as a non-zero balance)
1351
     * @return mixed
1352
     */
1353
    public function deleteWallet($identifier, $checksumAddress, $signature, $force = false) {
1354
        $response = $this->blocktrailClient->delete("wallet/{$identifier}", ['force' => $force], [
1355
            'checksum' => $checksumAddress,
1356
            'signature' => $signature
1357
        ], RestClient::AUTH_HTTP_SIG, 360);
1358
        return self::jsonDecode($response->body(), true);
1359 1
    }
1360
1361
    /**
1362 1
     * create new backup key;
1363
     *  1) a BIP39 mnemonic
1364 1
     *  2) a seed from that mnemonic with a blank password
1365
     *  3) a private key from that seed
1366 1
     *
1367
     * @return array [mnemonic, seed, key]
1368 1
     */
1369
    protected function newBackupSeed() {
1370
        list($backupMnemonic, $backupSeed, $backupPrivateKey) = $this->generateNewSeed("");
1371
1372 1
        return [$backupMnemonic, $backupSeed, $backupPrivateKey];
1373
    }
1374 1
1375
    /**
1376
     * create new primary key;
1377
     *  1) a BIP39 mnemonic
1378
     *  2) a seed from that mnemonic with the password
1379
     *  3) a private key from that seed
1380
     *
1381
     * @param string    $passphrase             the password to use in the BIP39 creation of the seed
1382
     * @return array [mnemonic, seed, key]
1383
     * @TODO: require a strong password?
1384 1
     */
1385 1
    protected function newPrimarySeed($passphrase) {
1386 1
        list($primaryMnemonic, $primarySeed, $primaryPrivateKey) = $this->generateNewSeed($passphrase);
1387 1
1388
        return [$primaryMnemonic, $primarySeed, $primaryPrivateKey];
1389
    }
1390
1391
    /**
1392 1
     * create a new key;
1393
     *  1) a BIP39 mnemonic
1394
     *  2) a seed from that mnemonic with the password
1395
     *  3) a private key from that seed
1396
     *
1397
     * @param string    $passphrase             the password to use in the BIP39 creation of the seed
1398
     * @param string    $forceEntropy           forced entropy instead of random entropy for testing purposes
1399
     * @return array
1400
     */
1401 9
    protected function generateNewSeed($passphrase = "", $forceEntropy = null) {
1402 9
        // generate master seed, retry if the generated private key isn't valid (FALSE is returned)
1403 9
        do {
1404
            $mnemonic = $this->generateNewMnemonic($forceEntropy);
1405
1406
            $seed = (new Bip39SeedGenerator)->getSeed($mnemonic, $passphrase);
1407
1408
            $key = null;
1409
            try {
1410
                $key = HierarchicalKeyFactory::fromEntropy($seed);
1411
            } catch (\Exception $e) {
1412
                // try again
1413
            }
1414
        } while (!$key);
1415
1416 1
        return [$mnemonic, $seed, $key];
1417 1
    }
1418 1
1419
    /**
1420
     * generate a new mnemonic from some random entropy (512 bit)
1421
     *
1422
     * @param string    $forceEntropy           forced entropy instead of random entropy for testing purposes
1423
     * @return string
1424
     * @throws \Exception
1425
     */
1426
    protected function generateNewMnemonic($forceEntropy = null) {
1427
        if ($forceEntropy === null) {
1428
            $random = new Random();
1429 16
            $entropy = $random->bytes(512 / 8);
1430 16
        } else {
1431 16
            $entropy = $forceEntropy;
1432
        }
1433
1434
        return MnemonicFactory::bip39()->entropyToMnemonic($entropy);
0 ignored issues
show
Bug introduced by
It seems like $entropy defined by $forceEntropy on line 1431 can also be of type string; however, BitWasp\Bitcoin\Mnemonic...ic::entropyToMnemonic() does only seem to accept object<BitWasp\Buffertools\BufferInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1435
    }
1436
1437
    /**
1438
     * get the balance for the wallet
1439
     *
1440
     * @param string    $identifier             the identifier of the wallet
1441
     * @return array
1442 1
     */
1443 1
    public function getWalletBalance($identifier) {
1444 1
        $response = $this->blocktrailClient->get("wallet/{$identifier}/balance", null, RestClient::AUTH_HTTP_SIG);
1445
        return self::jsonDecode($response->body(), true);
1446
    }
1447
1448
    /**
1449
     * get a new derivation number for specified parent path
1450
     *  eg; m/44'/1'/0/0 results in m/44'/1'/0/0/0 and next time in m/44'/1'/0/0/1 and next time in m/44'/1'/0/0/2
1451
     *
1452
     * returns the path
1453
     *
1454
     * @param string    $identifier             the identifier of the wallet
1455
     * @param string    $path                   the parent path for which to get a new derivation
1456
     * @return string
1457
     */
1458 4
    public function getNewDerivation($identifier, $path) {
1459
        $result = $this->_getNewDerivation($identifier, $path);
1460 4
        return $result['path'];
1461 4
    }
1462
1463
    /**
1464 4
     * get a new derivation number for specified parent path
1465 4
     *  eg; m/44'/1'/0/0 results in m/44'/1'/0/0/0 and next time in m/44'/1'/0/0/1 and next time in m/44'/1'/0/0/2
1466 4
     *
1467 4
     * @param string    $identifier             the identifier of the wallet
1468 4
     * @param string    $path                   the parent path for which to get a new derivation
1469
     * @return mixed
1470 4
     */
1471
    public function _getNewDerivation($identifier, $path) {
1472
        $response = $this->blocktrailClient->post("wallet/{$identifier}/path", null, ['path' => $path], RestClient::AUTH_HTTP_SIG);
1473
        return self::jsonDecode($response->body(), true);
1474
    }
1475
1476
    /**
1477 4
     * get the path (and redeemScript) to specified address
1478
     *
1479 4
     * @param string $identifier
1480 4
     * @param string $address
1481
     * @return array
1482 4
     * @throws \Exception
1483
     */
1484
    public function getPathForAddress($identifier, $address) {
1485
        $response = $this->blocktrailClient->post("wallet/{$identifier}/path_for_address", null, ['address' => $address], RestClient::AUTH_HTTP_SIG);
1486
        return self::jsonDecode($response->body(), true)['path'];
1487 4
    }
1488
1489
    /**
1490
     * send the transaction using the API
1491
     *
1492
     * @param string       $identifier     the identifier of the wallet
1493
     * @param string|array $rawTransaction raw hex of the transaction (should be partially signed)
1494
     * @param array        $paths          list of the paths that were used for the UTXO
1495
     * @param bool         $checkFee       let the server verify the fee after signing
1496
     * @param null         $twoFactorToken
1497
     * @return string                                the complete raw transaction
1498
     * @throws \Exception
1499
     */
1500
    public function sendTransaction($identifier, $rawTransaction, $paths, $checkFee = false, $twoFactorToken = null) {
1501
        $data = [
1502
            'paths' => $paths,
1503
            'two_factor_token' => $twoFactorToken,
1504
        ];
1505
1506
        if (is_array($rawTransaction)) {
1507
            if (array_key_exists('base_transaction', $rawTransaction)
1508
            && array_key_exists('signed_transaction', $rawTransaction)) {
1509
                $data['base_transaction'] = $rawTransaction['base_transaction'];
1510
                $data['signed_transaction'] = $rawTransaction['signed_transaction'];
1511
            } else {
1512
                throw new \RuntimeException("Invalid value for transaction. For segwit transactions, pass ['base_transaction' => '...', 'signed_transaction' => '...']");
1513
            }
1514
        } else {
1515
            $data['raw_transaction'] = $rawTransaction;
1516
        }
1517
1518
        // dynamic TTL for when we're signing really big transactions
1519
        $ttl = max(5.0, count($paths) * 0.25) + 4.0;
1520 12
1521
        $response = $this->blocktrailClient->post("wallet/{$identifier}/send", ['check_fee' => (int)!!$checkFee], $data, RestClient::AUTH_HTTP_SIG, $ttl);
1522 12
        $signed = self::jsonDecode($response->body(), true);
1523 12
1524 12
        if (!$signed['complete'] || $signed['complete'] == 'false') {
1525
            throw new \Exception("Failed to completely sign transaction");
1526
        }
1527 12
1528 1
        // create TX hash from the raw signed hex
1529
        return TransactionFactory::fromHex($signed['hex'])->getTxId()->getHex();
1530
    }
1531 12
1532 12
    /**
1533 12
     * use the API to get the best inputs to use based on the outputs
1534 12
     *
1535 12
     * the return array has the following format:
1536
     * [
1537
     *  "utxos" => [
1538 6
     *      [
1539
     *          "hash" => "<txHash>",
1540
     *          "idx" => "<index of the output of that <txHash>",
1541
     *          "scriptpubkey_hex" => "<scriptPubKey-hex>",
1542
     *          "value" => 32746327,
1543
     *          "address" => "1address",
1544
     *          "path" => "m/44'/1'/0'/0/13",
1545
     *          "redeem_script" => "<redeemScript-hex>",
1546
     *      ],
1547
     *  ],
1548
     *  "fee"   => 10000,
1549
     *  "change"=> 1010109201,
1550
     * ]
1551
     *
1552
     * @param string   $identifier              the identifier of the wallet
1553
     * @param array    $outputs                 the outputs you want to create - array[address => satoshi-value]
1554
     * @param bool     $lockUTXO                when TRUE the UTXOs selected will be locked for a few seconds
1555
     *                                          so you have some time to spend them without race-conditions
1556
     * @param bool     $allowZeroConf
1557
     * @param string   $feeStrategy
1558
     * @param null|int $forceFee
1559
     * @return array
1560
     * @throws \Exception
1561
     */
1562
    public function coinSelection($identifier, $outputs, $lockUTXO = false, $allowZeroConf = false, $feeStrategy = Wallet::FEE_STRATEGY_OPTIMAL, $forceFee = null) {
1563
        $args = [
1564
            'lock' => (int)!!$lockUTXO,
1565
            'zeroconf' => (int)!!$allowZeroConf,
1566
            'fee_strategy' => $feeStrategy,
1567
        ];
1568
1569
        if ($forceFee !== null) {
1570
            $args['forcefee'] = (int)$forceFee;
1571
        }
1572
1573
        $response = $this->blocktrailClient->post(
1574 3
            "wallet/{$identifier}/coin-selection",
1575 3
            $args,
1576 3
            $outputs,
1577
            RestClient::AUTH_HTTP_SIG
1578
        );
1579
1580
        return self::jsonDecode($response->body(), true);
1581
    }
1582
1583
    /**
1584 1
     *
1585 1
     * @param string   $identifier the identifier of the wallet
1586 1
     * @param bool     $allowZeroConf
1587
     * @param string   $feeStrategy
1588
     * @param null|int $forceFee
1589
     * @param int      $outputCnt
1590
     * @return array
1591
     * @throws \Exception
1592
     */
1593
    public function walletMaxSpendable($identifier, $allowZeroConf = false, $feeStrategy = Wallet::FEE_STRATEGY_OPTIMAL, $forceFee = null, $outputCnt = 1) {
1594
        $args = [
1595
            'zeroconf' => (int)!!$allowZeroConf,
1596
            'fee_strategy' => $feeStrategy,
1597 1
            'outputs' => $outputCnt,
1598 1
        ];
1599 1
1600
        if ($forceFee !== null) {
1601
            $args['forcefee'] = (int)$forceFee;
1602
        }
1603
1604
        $response = $this->blocktrailClient->get(
1605
            "wallet/{$identifier}/max-spendable",
1606
            $args,
1607
            RestClient::AUTH_HTTP_SIG
1608
        );
1609 1
1610 1
        return self::jsonDecode($response->body(), true);
1611 1
    }
1612
1613
    /**
1614
     * @return array        ['optimal_fee' => 10000, 'low_priority_fee' => 5000]
1615
     */
1616
    public function feePerKB() {
1617
        $response = $this->blocktrailClient->get("fee-per-kb");
1618
        return self::jsonDecode($response->body(), true);
1619
    }
1620
1621
    /**
1622
     * get the current price index
1623
     *
1624
     * @return array        eg; ['USD' => 287.30]
1625
     */
1626
    public function price() {
1627
        $response = $this->blocktrailClient->get("price");
1628
        return self::jsonDecode($response->body(), true);
1629
    }
1630
1631
    /**
1632
     * setup webhook for wallet
1633
     *
1634
     * @param string    $identifier         the wallet identifier for which to create the webhook
1635
     * @param string    $webhookIdentifier  the webhook identifier to use
1636
     * @param string    $url                the url to receive the webhook events
1637
     * @return array
1638
     */
1639
    public function setupWalletWebhook($identifier, $webhookIdentifier, $url) {
1640
        $response = $this->blocktrailClient->post("wallet/{$identifier}/webhook", null, ['url' => $url, 'identifier' => $webhookIdentifier], RestClient::AUTH_HTTP_SIG);
1641
        return self::jsonDecode($response->body(), true);
1642
    }
1643
1644
    /**
1645
     * delete webhook for wallet
1646
     *
1647
     * @param string    $identifier         the wallet identifier for which to delete the webhook
1648
     * @param string    $webhookIdentifier  the webhook identifier to delete
1649
     * @return array
1650 1
     */
1651
    public function deleteWalletWebhook($identifier, $webhookIdentifier) {
1652 1
        $response = $this->blocktrailClient->delete("wallet/{$identifier}/webhook/{$webhookIdentifier}", null, null, RestClient::AUTH_HTTP_SIG);
1653 1
        return self::jsonDecode($response->body(), true);
1654 1
    }
1655
1656 1
    /**
1657 1
     * lock a specific unspent output
1658
     *
1659
     * @param     $identifier
1660
     * @param     $txHash
1661
     * @param     $txIdx
1662
     * @param int $ttl
1663
     * @return bool
1664
     */
1665
    public function lockWalletUTXO($identifier, $txHash, $txIdx, $ttl = 3) {
1666
        $response = $this->blocktrailClient->post("wallet/{$identifier}/lock-utxo", null, ['hash' => $txHash, 'idx' => $txIdx, 'ttl' => $ttl], RestClient::AUTH_HTTP_SIG);
1667
        return self::jsonDecode($response->body(), true)['locked'];
1668
    }
1669 1
1670
    /**
1671 1
     * unlock a specific unspent output
1672 1
     *
1673 1
     * @param     $identifier
1674
     * @param     $txHash
1675 1
     * @param     $txIdx
1676 1
     * @return bool
1677
     */
1678
    public function unlockWalletUTXO($identifier, $txHash, $txIdx) {
1679
        $response = $this->blocktrailClient->post("wallet/{$identifier}/unlock-utxo", null, ['hash' => $txHash, 'idx' => $txIdx], RestClient::AUTH_HTTP_SIG);
1680
        return self::jsonDecode($response->body(), true)['unlocked'];
1681
    }
1682
1683
    /**
1684
     * get all transactions for wallet (paginated)
1685
     *
1686
     * @param  string  $identifier  the wallet identifier for which to get transactions
1687
     * @param  integer $page        pagination: page number
1688
     * @param  integer $limit       pagination: records per page (max 500)
1689 1
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1690
     * @return array                associative array containing the response
1691 1
     */
1692 1
    public function walletTransactions($identifier, $page = 1, $limit = 20, $sortDir = 'asc') {
1693 1
        $queryString = [
1694 1
            'page' => $page,
1695
            'limit' => $limit,
1696 1
            'sort_dir' => $sortDir
1697 1
        ];
1698
        $response = $this->blocktrailClient->get("wallet/{$identifier}/transactions", $this->converter->paginationParams($queryString), RestClient::AUTH_HTTP_SIG);
1699
        return self::jsonDecode($response->body(), true);
1700
    }
1701
1702
    /**
1703
     * get all addresses for wallet (paginated)
1704
     *
1705
     * @param  string  $identifier  the wallet identifier for which to get addresses
1706
     * @param  integer $page        pagination: page number
1707 2
     * @param  integer $limit       pagination: records per page (max 500)
1708
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1709 2
     * @return array                associative array containing the response
1710 2
     */
1711
    public function walletAddresses($identifier, $page = 1, $limit = 20, $sortDir = 'asc') {
1712 2
        $queryString = [
1713 2
            'page' => $page,
1714
            'limit' => $limit,
1715
            'sort_dir' => $sortDir
1716
        ];
1717
        $response = $this->blocktrailClient->get("wallet/{$identifier}/addresses", $this->converter->paginationParams($queryString), RestClient::AUTH_HTTP_SIG);
1718
        return self::jsonDecode($response->body(), true);
1719
    }
1720
1721
    /**
1722
     * get all UTXOs for wallet (paginated)
1723
     *
1724
     * @param  string  $identifier  the wallet identifier for which to get addresses
1725
     * @param  integer $page        pagination: page number
1726
     * @param  integer $limit       pagination: records per page (max 500)
1727
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1728
     * @param  boolean $zeroconf    include zero confirmation transactions
1729
     * @return array                associative array containing the response
1730
     */
1731
    public function walletUTXOs($identifier, $page = 1, $limit = 20, $sortDir = 'asc', $zeroconf = true) {
1732
        $queryString = [
1733
            'page' => $page,
1734
            'limit' => $limit,
1735
            'sort_dir' => $sortDir,
1736
            'zeroconf' => (int)!!$zeroconf,
1737
        ];
1738
        $response = $this->blocktrailClient->get("wallet/{$identifier}/utxos", $this->converter->paginationParams($queryString), RestClient::AUTH_HTTP_SIG);
1739
        return self::jsonDecode($response->body(), true);
1740
    }
1741
1742
    /**
1743
     * get a paginated list of all wallets associated with the api user
1744
     *
1745
     * @param  integer          $page    pagination: page number
1746
     * @param  integer          $limit   pagination: records per page
1747
     * @return array                     associative array containing the response
1748
     */
1749
    public function allWallets($page = 1, $limit = 20) {
1750
        $queryString = [
1751
            'page' => $page,
1752
            'limit' => $limit
1753
        ];
1754
        $response = $this->blocktrailClient->get("wallets", $this->converter->paginationParams($queryString), RestClient::AUTH_HTTP_SIG);
1755
        return self::jsonDecode($response->body(), true);
1756
    }
1757
1758
    /**
1759
     * send raw transaction
1760
     *
1761
     * @param     $txHex
1762
     * @return bool
1763
     */
1764
    public function sendRawTransaction($txHex) {
1765 1
        $response = $this->blocktrailClient->post("send-raw-tx", null, ['hex' => $txHex], RestClient::AUTH_HTTP_SIG);
1766
        return self::jsonDecode($response->body(), true);
1767
    }
1768
1769 1
    /**
1770 1
     * testnet only ;-)
1771 1
     *
1772
     * @param     $address
1773
     * @param int $amount       defaults to 0.0001 BTC, max 0.001 BTC
1774
     * @return mixed
1775
     * @throws \Exception
1776 1
     */
1777 1
    public function faucetWithdrawal($address, $amount = 10000) {
1778
        $response = $this->blocktrailClient->post("faucet/withdrawl", null, [
1779 1
            'address' => $address,
1780 1
            'amount' => $amount,
1781
        ], RestClient::AUTH_HTTP_SIG);
1782
        return self::jsonDecode($response->body(), true);
1783
    }
1784
1785
    /**
1786
     * Exists for BC. Remove at major bump.
1787
     *
1788
     * @see faucetWithdrawal
1789
     * @deprecated
1790
     * @param     $address
1791 1
     * @param int $amount       defaults to 0.0001 BTC, max 0.001 BTC
1792 1
     * @return mixed
1793
     * @throws \Exception
1794 1
     */
1795 1
    public function faucetWithdrawl($address, $amount = 10000) {
1796
        return $this->faucetWithdrawal($address, $amount);
1797 1
    }
1798
1799 1
    /**
1800 1
     * verify a message signed bitcoin-core style
1801
     *
1802
     * @param  string           $message
1803 1
     * @param  string           $address
1804
     * @param  string           $signature
1805
     * @return boolean
1806
     */
1807
    public function verifyMessage($message, $address, $signature) {
1808
        $adapter = Bitcoin::getEcAdapter();
1809
        $addr = \BitWasp\Bitcoin\Address\AddressFactory::fromString($address);
1810
        if (!$addr instanceof PayToPubKeyHashAddress) {
1811
            throw new \RuntimeException('Can only verify a message with a pay-to-pubkey-hash address');
1812
        }
1813
1814
        /** @var CompactSignatureSerializerInterface $csSerializer */
1815
        $csSerializer = EcSerializer::getSerializer(CompactSignatureSerializerInterface::class, $adapter);
0 ignored issues
show
Documentation introduced by
$adapter is of type object<BitWasp\Bitcoin\C...ter\EcAdapterInterface>, but the function expects a boolean|object<BitWasp\B...\Crypto\EcAdapter\true>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1816
        $signedMessage = new SignedMessage($message, $csSerializer->parse(new Buffer(base64_decode($signature))));
1817
1818
        $signer = new MessageSigner($adapter);
1819
        return $signer->verify($signedMessage, $addr);
1820
    }
1821
1822
    /**
1823
     * Take a base58 or cashaddress, and return only
1824
     * the cash address.
1825
     * This function only works on bitcoin cash.
1826
     * @param string $input
1827
     * @return string
1828
     * @throws BlocktrailSDKException
1829
     */
1830
    public function getLegacyBitcoinCashAddress($input) {
1831
        if ($this->network === "bitcoincash") {
1832
            $address = $this
1833
                ->makeAddressReader([
1834
                    "use_cashaddress" => true
1835 12
                ])
1836 12
                ->fromString($input);
1837
1838
            if ($address instanceof CashAddress) {
1839
                $address = $address->getLegacyAddress();
1840
            }
1841
1842
            return $address->getAddress();
1843
        }
1844
1845 12
        throw new BlocktrailSDKException("Only request a legacy address when using bitcoin cash");
1846 12
    }
1847
1848
    /**
1849
     * convert a Satoshi value to a BTC value
1850
     *
1851
     * @param int       $satoshi
1852
     * @return float
1853
     */
1854
    public static function toBTC($satoshi) {
1855
        return bcdiv((int)(string)$satoshi, 100000000, 8);
1856
    }
1857 32
1858 32
    /**
1859
     * convert a Satoshi value to a BTC value and return it as a string
1860
1861
     * @param int       $satoshi
1862 32
     * @return string
1863
     */
1864 32
    public static function toBTCString($satoshi) {
1865
        return sprintf("%.8f", self::toBTC($satoshi));
1866
    }
1867
1868 32
    /**
1869
     * convert a BTC value to a Satoshi value
1870
     *
1871
     * @param float     $btc
1872
     * @return string
1873
     */
1874
    public static function toSatoshiString($btc) {
1875
        return bcmul(sprintf("%.8f", (float)$btc), 100000000, 0);
1876
    }
1877 18
1878 18
    /**
1879
     * convert a BTC value to a Satoshi value
1880 18
     *
1881 18
     * @param float     $btc
1882 18
     * @return string
1883 18
     */
1884
    public static function toSatoshi($btc) {
1885 18
        return (int)self::toSatoshiString($btc);
1886
    }
1887
1888
    /**
1889
     * json_decode helper that throws exceptions when it fails to decode
1890
     *
1891
     * @param      $json
1892
     * @param bool $assoc
1893
     * @return mixed
1894
     * @throws \Exception
1895
     */
1896
    public static function jsonDecode($json, $assoc = false) {
1897
        if (!$json) {
1898
            throw new \Exception("Can't json_decode empty string [{$json}]");
1899
        }
1900
1901
        $data = json_decode($json, $assoc);
1902
1903
        if ($data === null) {
1904
            throw new \Exception("Failed to json_decode [{$json}]");
1905 26
        }
1906 26
1907 26
        return $data;
1908
    }
1909
1910
    /**
1911
     * sort public keys for multisig script
1912
     *
1913
     * @param PublicKeyInterface[] $pubKeys
1914
     * @return PublicKeyInterface[]
1915 26
     */
1916 26
    public static function sortMultisigKeys(array $pubKeys) {
1917 10
        $result = array_values($pubKeys);
1918
        usort($result, function (PublicKeyInterface $a, PublicKeyInterface $b) {
1919
            $av = $a->getHex();
1920 26
            $bv = $b->getHex();
1921 26
            return $av == $bv ? 0 : $av > $bv ? 1 : -1;
1922 26
        });
1923
1924 26
        return $result;
1925 26
    }
1926
1927
    /**
1928 26
     * read and decode the json payload from a webhook's POST request.
1929
     *
1930
     * @param bool $returnObject    flag to indicate if an object or associative array should be returned
1931
     * @return mixed|null
1932
     * @throws \Exception
1933
     */
1934
    public static function getWebhookPayload($returnObject = false) {
1935
        $data = file_get_contents("php://input");
1936
        if ($data) {
1937
            return self::jsonDecode($data, !$returnObject);
1938
        } else {
1939
            return null;
1940
        }
1941
    }
1942
1943
    public static function normalizeBIP32KeyArray($keys) {
1944
        return Util::arrayMapWithIndex(function ($idx, $key) {
1945
            return [$idx, self::normalizeBIP32Key($key)];
1946
        }, $keys);
1947
    }
1948
1949
    /**
1950
     * @param array|BIP32Key $key
1951
     * @return BIP32Key
1952
     * @throws \Exception
1953
     */
1954
    public static function normalizeBIP32Key($key) {
1955
        if ($key instanceof BIP32Key) {
1956
            return $key;
1957
        }
1958
1959
        if (is_array($key) && count($key) === 2) {
1960
            $path = $key[1];
1961
            $hk = $key[0];
1962
1963
            if (!($hk instanceof HierarchicalKey)) {
1964
                $hk = HierarchicalKeyFactory::fromExtended($hk);
1965
            }
1966
1967
            return BIP32Key::create($hk, $path);
1968
        } else {
1969
            throw new \Exception("Bad Input");
1970
        }
1971
    }
1972
}
1973