Completed
Pull Request — master (#49)
by thomas
18:33 queued 07:32
created

BlocktrailSDK::setRestClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
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\AddressFactory;
6
use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
7
use BitWasp\Bitcoin\Bitcoin;
8
use BitWasp\Bitcoin\Crypto\EcAdapter\EcSerializer;
9
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
10
use BitWasp\Bitcoin\Crypto\EcAdapter\Serializer\Signature\CompactSignatureSerializerInterface;
11
use BitWasp\Bitcoin\Crypto\Random\Random;
12
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKey;
13
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKeyFactory;
14
use BitWasp\Bitcoin\MessageSigner\MessageSigner;
15
use BitWasp\Bitcoin\MessageSigner\SignedMessage;
16
use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;
17
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
18
use BitWasp\Bitcoin\Network\NetworkFactory;
19
use BitWasp\Bitcoin\Transaction\TransactionFactory;
20
use BitWasp\Buffertools\Buffer;
21
use BitWasp\Buffertools\BufferInterface;
22
use Blocktrail\CryptoJSAES\CryptoJSAES;
23
use Blocktrail\SDK\Bitcoin\BIP32Key;
24
use Blocktrail\SDK\Connection\RestClient;
25
use Blocktrail\SDK\Exceptions\BlocktrailSDKException;
26
use Blocktrail\SDK\Connection\RestClientInterface;
27
use Blocktrail\SDK\V3Crypt\Encryption;
28
use Blocktrail\SDK\V3Crypt\EncryptionMnemonic;
29
use Blocktrail\SDK\V3Crypt\KeyDerivation;
30
31
/**
32
 * Class BlocktrailSDK
33
 */
34
class BlocktrailSDK implements BlocktrailSDKInterface {
35
    /**
36
     * @var Connection\RestClientInterface
37
     */
38
    protected $client;
39
40
    /**
41
     * @var string          currently only supporting; bitcoin
42
     */
43
    protected $network;
44
45
    /**
46
     * @var bool
47
     */
48
    protected $testnet;
49
50
    /**
51
     * @param   string      $apiKey         the API_KEY to use for authentication
52
     * @param   string      $apiSecret      the API_SECRET to use for authentication
53
     * @param   string      $network        the cryptocurrency 'network' to consume, eg BTC, LTC, etc
54
     * @param   bool        $testnet        testnet yes/no
55
     * @param   string      $apiVersion     the version of the API to consume
56
     * @param   null        $apiEndpoint    overwrite the endpoint used
57
     *                                       this will cause the $network, $testnet and $apiVersion to be ignored!
58
     */
59 81
    public function __construct($apiKey, $apiSecret, $network = 'BTC', $testnet = false, $apiVersion = 'v1', $apiEndpoint = null) {
60
61 81
        list ($apiNetwork, $testnet) = Util::parseApiNetwork($network, $testnet);
62
63 81
        if (is_null($apiEndpoint)) {
64 81
            $apiEndpoint = getenv('BLOCKTRAIL_SDK_API_ENDPOINT') ?: "https://api.blocktrail.com";
65 81
            $apiEndpoint = "{$apiEndpoint}/{$apiVersion}/{$apiNetwork}/";
66
        }
67
68
        // normalize network and set bitcoinlib to the right magic-bytes
69 81
        list($this->network, $this->testnet) = $this->normalizeNetwork($network, $testnet);
70 81
        $this->setBitcoinLibMagicBytes($this->network, $this->testnet);
71
72 81
        $this->client = new RestClient($apiEndpoint, $apiVersion, $apiKey, $apiSecret);
73 81
    }
74
75
    /**
76
     * normalize network string
77
     *
78
     * @param $network
79
     * @param $testnet
80
     * @return array
81
     * @throws \Exception
82
     */
83 81
    protected function normalizeNetwork($network, $testnet) {
84 81
        return Util::normalizeNetwork($network, $testnet);
85
    }
86
87
    /**
88
     * set BitcoinLib to the correct magic-byte defaults for the selected network
89
     *
90
     * @param $network
91
     * @param $testnet
92
     */
93 81
    protected function setBitcoinLibMagicBytes($network, $testnet) {
94 81
        assert($network == "bitcoin" || $network == "bitcoincash");
95 81
        Bitcoin::setNetwork($testnet ? NetworkFactory::bitcoinTestnet() : NetworkFactory::bitcoin());
96 81
    }
97
98
    /**
99
     * enable CURL debugging output
100
     *
101
     * @param   bool        $debug
102
     *
103
     * @codeCoverageIgnore
104
     */
105
    public function setCurlDebugging($debug = true) {
106
        $this->client->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...
107
    }
108
109
    /**
110
     * enable verbose errors
111
     *
112
     * @param   bool        $verboseErrors
113
     *
114
     * @codeCoverageIgnore
115
     */
116
    public function setVerboseErrors($verboseErrors = true) {
117
        $this->client->setVerboseErrors($verboseErrors);
118
    }
119
    
120
    /**
121
     * set cURL default option on Guzzle client
122
     * @param string    $key
123
     * @param bool      $value
124
     *
125
     * @codeCoverageIgnore
126
     */
127
    public function setCurlDefaultOption($key, $value) {
128
        $this->client->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...
129
    }
130
131
    /**
132
     * @return  RestClientInterface
133
     */
134 2
    public function getRestClient() {
135 2
        return $this->client;
136
    }
137
138
    /**
139
     * @param RestClientInterface $restClient
140
     */
141
    public function setRestClient(RestClientInterface $restClient) {
142
        $this->client = $restClient;
143
    }
144
145
    /**
146
     * get a single address
147
     * @param  string $address address hash
148
     * @return array           associative array containing the response
149
     */
150 1
    public function address($address) {
151 1
        $response = $this->client->get("address/{$address}");
152 1
        return self::jsonDecode($response->body(), true);
153
    }
154
155
    /**
156
     * get all transactions for an address (paginated)
157
     * @param  string  $address address hash
158
     * @param  integer $page    pagination: page number
159
     * @param  integer $limit   pagination: records per page (max 500)
160
     * @param  string  $sortDir pagination: sort direction (asc|desc)
161
     * @return array            associative array containing the response
162
     */
163 1
    public function addressTransactions($address, $page = 1, $limit = 20, $sortDir = 'asc') {
164
        $queryString = [
165 1
            'page' => $page,
166 1
            'limit' => $limit,
167 1
            'sort_dir' => $sortDir
168
        ];
169 1
        $response = $this->client->get("address/{$address}/transactions", $queryString);
170 1
        return self::jsonDecode($response->body(), true);
171
    }
172
173
    /**
174
     * get all unconfirmed transactions for an address (paginated)
175
     * @param  string  $address address hash
176
     * @param  integer $page    pagination: page number
177
     * @param  integer $limit   pagination: records per page (max 500)
178
     * @param  string  $sortDir pagination: sort direction (asc|desc)
179
     * @return array            associative array containing the response
180
     */
181 1
    public function addressUnconfirmedTransactions($address, $page = 1, $limit = 20, $sortDir = 'asc') {
182
        $queryString = [
183 1
            'page' => $page,
184 1
            'limit' => $limit,
185 1
            'sort_dir' => $sortDir
186
        ];
187 1
        $response = $this->client->get("address/{$address}/unconfirmed-transactions", $queryString);
188 1
        return self::jsonDecode($response->body(), true);
189
    }
190
191
    /**
192
     * get all unspent outputs for an address (paginated)
193
     * @param  string  $address address hash
194
     * @param  integer $page    pagination: page number
195
     * @param  integer $limit   pagination: records per page (max 500)
196
     * @param  string  $sortDir pagination: sort direction (asc|desc)
197
     * @return array            associative array containing the response
198
     */
199 1
    public function addressUnspentOutputs($address, $page = 1, $limit = 20, $sortDir = 'asc') {
200
        $queryString = [
201 1
            'page' => $page,
202 1
            'limit' => $limit,
203 1
            'sort_dir' => $sortDir
204
        ];
205 1
        $response = $this->client->get("address/{$address}/unspent-outputs", $queryString);
206 1
        return self::jsonDecode($response->body(), true);
207
    }
208
209
    /**
210
     * get all unspent outputs for a batch of addresses (paginated)
211
     *
212
     * @param  string[] $addresses
213
     * @param  integer  $page    pagination: page number
214
     * @param  integer  $limit   pagination: records per page (max 500)
215
     * @param  string   $sortDir pagination: sort direction (asc|desc)
216
     * @return array associative array containing the response
217
     * @throws \Exception
218
     */
219
    public function batchAddressUnspentOutputs($addresses, $page = 1, $limit = 20, $sortDir = 'asc') {
220
        $queryString = [
221
            'page' => $page,
222
            'limit' => $limit,
223
            'sort_dir' => $sortDir
224
        ];
225
        $response = $this->client->post("address/unspent-outputs", $queryString, ['addresses' => $addresses]);
226
        return self::jsonDecode($response->body(), true);
227
    }
228
229
    /**
230
     * verify ownership of an address
231
     * @param  string  $address     address hash
232
     * @param  string  $signature   a signed message (the address hash) using the private key of the address
233
     * @return array                associative array containing the response
234
     */
235 2
    public function verifyAddress($address, $signature) {
236 2
        $postData = ['signature' => $signature];
237
238 2
        $response = $this->client->post("address/{$address}/verify", null, $postData, RestClient::AUTH_HTTP_SIG);
239
240 2
        return self::jsonDecode($response->body(), true);
241
    }
242
243
    /**
244
     * get all blocks (paginated)
245
     * @param  integer $page    pagination: page number
246
     * @param  integer $limit   pagination: records per page
247
     * @param  string  $sortDir pagination: sort direction (asc|desc)
248
     * @return array            associative array containing the response
249
     */
250 1
    public function allBlocks($page = 1, $limit = 20, $sortDir = 'asc') {
251
        $queryString = [
252 1
            'page' => $page,
253 1
            'limit' => $limit,
254 1
            'sort_dir' => $sortDir
255
        ];
256 1
        $response = $this->client->get("all-blocks", $queryString);
257 1
        return self::jsonDecode($response->body(), true);
258
    }
259
260
    /**
261
     * get the latest block
262
     * @return array            associative array containing the response
263
     */
264 1
    public function blockLatest() {
265 1
        $response = $this->client->get("block/latest");
266 1
        return self::jsonDecode($response->body(), true);
267
    }
268
269
    /**
270
     * get an individual block
271
     * @param  string|integer $block    a block hash or a block height
272
     * @return array                    associative array containing the response
273
     */
274 1
    public function block($block) {
275 1
        $response = $this->client->get("block/{$block}");
276 1
        return self::jsonDecode($response->body(), true);
277
    }
278
279
    /**
280
     * get all transaction in a block (paginated)
281
     * @param  string|integer   $block   a block hash or a block height
282
     * @param  integer          $page    pagination: page number
283
     * @param  integer          $limit   pagination: records per page
284
     * @param  string           $sortDir pagination: sort direction (asc|desc)
285
     * @return array                     associative array containing the response
286
     */
287 1
    public function blockTransactions($block, $page = 1, $limit = 20, $sortDir = 'asc') {
288
        $queryString = [
289 1
            'page' => $page,
290 1
            'limit' => $limit,
291 1
            'sort_dir' => $sortDir
292
        ];
293 1
        $response = $this->client->get("block/{$block}/transactions", $queryString);
294 1
        return self::jsonDecode($response->body(), true);
295
    }
296
297
    /**
298
     * get a single transaction
299
     * @param  string $txhash transaction hash
300
     * @return array          associative array containing the response
301
     */
302 4
    public function transaction($txhash) {
303 4
        $response = $this->client->get("transaction/{$txhash}");
304 4
        return self::jsonDecode($response->body(), true);
305
    }
306
307
    /**
308
     * get a single transaction
309
     * @param  string[] $txhashes list of transaction hashes (up to 20)
310
     * @return array[]            array containing the response
311
     */
312
    public function transactions($txhashes) {
313
        $response = $this->client->get("transactions/" . implode(",", $txhashes));
314
        return self::jsonDecode($response->body(), true);
315
    }
316
    
317
    /**
318
     * get a paginated list of all webhooks associated with the api user
319
     * @param  integer          $page    pagination: page number
320
     * @param  integer          $limit   pagination: records per page
321
     * @return array                     associative array containing the response
322
     */
323 1
    public function allWebhooks($page = 1, $limit = 20) {
324
        $queryString = [
325 1
            'page' => $page,
326 1
            'limit' => $limit
327
        ];
328 1
        $response = $this->client->get("webhooks", $queryString);
329 1
        return self::jsonDecode($response->body(), true);
330
    }
331
332
    /**
333
     * get an existing webhook by it's identifier
334
     * @param string    $identifier     a unique identifier associated with the webhook
335
     * @return array                    associative array containing the response
336
     */
337 1
    public function getWebhook($identifier) {
338 1
        $response = $this->client->get("webhook/".$identifier);
339 1
        return self::jsonDecode($response->body(), true);
340
    }
341
342
    /**
343
     * create a new webhook
344
     * @param  string  $url        the url to receive the webhook events
345
     * @param  string  $identifier a unique identifier to associate with this webhook
346
     * @return array               associative array containing the response
347
     */
348 1
    public function setupWebhook($url, $identifier = null) {
349
        $postData = [
350 1
            'url'        => $url,
351 1
            'identifier' => $identifier
352
        ];
353 1
        $response = $this->client->post("webhook", null, $postData, RestClient::AUTH_HTTP_SIG);
354 1
        return self::jsonDecode($response->body(), true);
355
    }
356
357
    /**
358
     * update an existing webhook
359
     * @param  string  $identifier      the unique identifier of the webhook to update
360
     * @param  string  $newUrl          the new url to receive the webhook events
361
     * @param  string  $newIdentifier   a new unique identifier to associate with this webhook
362
     * @return array                    associative array containing the response
363
     */
364 1
    public function updateWebhook($identifier, $newUrl = null, $newIdentifier = null) {
365
        $putData = [
366 1
            'url'        => $newUrl,
367 1
            'identifier' => $newIdentifier
368
        ];
369 1
        $response = $this->client->put("webhook/{$identifier}", null, $putData, RestClient::AUTH_HTTP_SIG);
370 1
        return self::jsonDecode($response->body(), true);
371
    }
372
373
    /**
374
     * deletes an existing webhook and any event subscriptions associated with it
375
     * @param  string  $identifier      the unique identifier of the webhook to delete
376
     * @return boolean                  true on success
377
     */
378 1
    public function deleteWebhook($identifier) {
379 1
        $response = $this->client->delete("webhook/{$identifier}", null, null, RestClient::AUTH_HTTP_SIG);
380 1
        return self::jsonDecode($response->body(), true);
381
    }
382
383
    /**
384
     * get a paginated list of all the events a webhook is subscribed to
385
     * @param  string  $identifier  the unique identifier of the webhook
386
     * @param  integer $page        pagination: page number
387
     * @param  integer $limit       pagination: records per page
388
     * @return array                associative array containing the response
389
     */
390 2
    public function getWebhookEvents($identifier, $page = 1, $limit = 20) {
391
        $queryString = [
392 2
            'page' => $page,
393 2
            'limit' => $limit
394
        ];
395 2
        $response = $this->client->get("webhook/{$identifier}/events", $queryString);
396 2
        return self::jsonDecode($response->body(), true);
397
    }
398
    
399
    /**
400
     * subscribes a webhook to transaction events of one particular transaction
401
     * @param  string  $identifier      the unique identifier of the webhook to be triggered
402
     * @param  string  $transaction     the transaction hash
403
     * @param  integer $confirmations   the amount of confirmations to send.
404
     * @return array                    associative array containing the response
405
     */
406 1
    public function subscribeTransaction($identifier, $transaction, $confirmations = 6) {
407
        $postData = [
408 1
            'event_type'    => 'transaction',
409 1
            'transaction'   => $transaction,
410 1
            'confirmations' => $confirmations,
411
        ];
412 1
        $response = $this->client->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
413 1
        return self::jsonDecode($response->body(), true);
414
    }
415
416
    /**
417
     * subscribes a webhook to transaction events on a particular address
418
     * @param  string  $identifier      the unique identifier of the webhook to be triggered
419
     * @param  string  $address         the address hash
420
     * @param  integer $confirmations   the amount of confirmations to send.
421
     * @return array                    associative array containing the response
422
     */
423 1
    public function subscribeAddressTransactions($identifier, $address, $confirmations = 6) {
424
        $postData = [
425 1
            'event_type'    => 'address-transactions',
426 1
            'address'       => $address,
427 1
            'confirmations' => $confirmations,
428
        ];
429 1
        $response = $this->client->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
430 1
        return self::jsonDecode($response->body(), true);
431
    }
432
433
    /**
434
     * batch subscribes a webhook to multiple transaction events
435
     *
436
     * @param  string $identifier   the unique identifier of the webhook
437
     * @param  array  $batchData    A 2D array of event data:
438
     *                              [address => $address, confirmations => $confirmations]
439
     *                              where $address is the address to subscibe to
440
     *                              and optionally $confirmations is the amount of confirmations
441
     * @return boolean              true on success
442
     */
443 1
    public function batchSubscribeAddressTransactions($identifier, $batchData) {
444 1
        $postData = [];
445 1
        foreach ($batchData as $record) {
446 1
            $postData[] = [
447 1
                'event_type' => 'address-transactions',
448 1
                'address' => $record['address'],
449 1
                'confirmations' => isset($record['confirmations']) ? $record['confirmations'] : 6,
450
            ];
451
        }
452 1
        $response = $this->client->post("webhook/{$identifier}/events/batch", null, $postData, RestClient::AUTH_HTTP_SIG);
453 1
        return self::jsonDecode($response->body(), true);
454
    }
455
456
    /**
457
     * subscribes a webhook to a new block event
458
     * @param  string  $identifier  the unique identifier of the webhook to be triggered
459
     * @return array                associative array containing the response
460
     */
461 1
    public function subscribeNewBlocks($identifier) {
462
        $postData = [
463 1
            'event_type'    => 'block',
464
        ];
465 1
        $response = $this->client->post("webhook/{$identifier}/events", null, $postData, RestClient::AUTH_HTTP_SIG);
466 1
        return self::jsonDecode($response->body(), true);
467
    }
468
469
    /**
470
     * removes an transaction event subscription from a webhook
471
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
472
     * @param  string  $transaction     the transaction hash of the event subscription
473
     * @return boolean                  true on success
474
     */
475 1
    public function unsubscribeTransaction($identifier, $transaction) {
476 1
        $response = $this->client->delete("webhook/{$identifier}/transaction/{$transaction}", null, null, RestClient::AUTH_HTTP_SIG);
477 1
        return self::jsonDecode($response->body(), true);
478
    }
479
480
    /**
481
     * removes an address transaction event subscription from a webhook
482
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
483
     * @param  string  $address         the address hash of the event subscription
484
     * @return boolean                  true on success
485
     */
486 1
    public function unsubscribeAddressTransactions($identifier, $address) {
487 1
        $response = $this->client->delete("webhook/{$identifier}/address-transactions/{$address}", null, null, RestClient::AUTH_HTTP_SIG);
488 1
        return self::jsonDecode($response->body(), true);
489
    }
490
491
    /**
492
     * removes a block event subscription from a webhook
493
     * @param  string  $identifier      the unique identifier of the webhook associated with the event subscription
494
     * @return boolean                  true on success
495
     */
496 1
    public function unsubscribeNewBlocks($identifier) {
497 1
        $response = $this->client->delete("webhook/{$identifier}/block", null, null, RestClient::AUTH_HTTP_SIG);
498 1
        return self::jsonDecode($response->body(), true);
499
    }
500
501
    /**
502
     * create a new wallet
503
     *   - will generate a new primary seed (with password) and backup seed (without password)
504
     *   - send the primary seed (BIP39 'encrypted') and backup public key to the server
505
     *   - receive the blocktrail co-signing public key from the server
506
     *
507
     * Either takes one argument:
508
     * @param array $options
509
     *
510
     * Or takes three arguments (old, deprecated syntax):
511
     * (@nonPHP-doc) @param      $identifier
512
     * (@nonPHP-doc) @param      $password
513
     * (@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...
514
     *
515
     * @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...
516
     * @throws \Exception
517
     */
518 7
    public function createNewWallet($options) {
519 7
        if (!is_array($options)) {
520 1
            $args = func_get_args();
521
            $options = [
522 1
                "identifier" => $args[0],
523 1
                "password" => $args[1],
524 1
                "key_index" => isset($args[2]) ? $args[2] : null,
525
            ];
526
        }
527
528 7
        if (isset($options['password'])) {
529 1
            if (isset($options['passphrase'])) {
530
                throw new \InvalidArgumentException("Can only provide either passphrase or password");
531
            } else {
532 1
                $options['passphrase'] = $options['password'];
533
            }
534
        }
535
536 7
        if (!isset($options['passphrase'])) {
537 1
            $options['passphrase'] = null;
538
        }
539
540 7
        if (!isset($options['key_index'])) {
541
            $options['key_index'] = 0;
542
        }
543
544 7
        if (!isset($options['wallet_version'])) {
545 3
            $options['wallet_version'] = Wallet::WALLET_VERSION_V3;
546
        }
547
548 7
        switch ($options['wallet_version']) {
549 7
            case Wallet::WALLET_VERSION_V1:
550 1
                return $this->createNewWalletV1($options);
551
552 6
            case Wallet::WALLET_VERSION_V2:
553 2
                return $this->createNewWalletV2($options);
554
555 4
            case Wallet::WALLET_VERSION_V3:
556 4
                return $this->createNewWalletV3($options);
557
558
            default:
559
                throw new \InvalidArgumentException("Invalid wallet version");
560
        }
561
    }
562
563 1
    protected function createNewWalletV1($options) {
564 1
        $walletPath = WalletPath::create($options['key_index']);
565
566 1
        $storePrimaryMnemonic = isset($options['store_primary_mnemonic']) ? $options['store_primary_mnemonic'] : null;
567
568 1
        if (isset($options['primary_mnemonic']) && isset($options['primary_private_key'])) {
569
            throw new \InvalidArgumentException("Can't specify Primary Mnemonic and Primary PrivateKey");
570
        }
571
572 1
        $primaryMnemonic = null;
573 1
        $primaryPrivateKey = null;
574 1
        if (!isset($options['primary_mnemonic']) && !isset($options['primary_private_key'])) {
575 1
            if (!$options['passphrase']) {
576
                throw new \InvalidArgumentException("Can't generate Primary Mnemonic without a passphrase");
577
            } else {
578
                // create new primary seed
579
                /** @var HierarchicalKey $primaryPrivateKey */
580 1
                list($primaryMnemonic, , $primaryPrivateKey) = $this->newPrimarySeed($options['passphrase']);
581 1
                if ($storePrimaryMnemonic !== false) {
582 1
                    $storePrimaryMnemonic = true;
583
                }
584
            }
585
        } elseif (isset($options['primary_mnemonic'])) {
586
            $primaryMnemonic = $options['primary_mnemonic'];
587
        } elseif (isset($options['primary_private_key'])) {
588
            $primaryPrivateKey = $options['primary_private_key'];
589
        }
590
591 1
        if ($storePrimaryMnemonic && $primaryMnemonic && !$options['passphrase']) {
592
            throw new \InvalidArgumentException("Can't store Primary Mnemonic on server without a passphrase");
593
        }
594
595 1
        if ($primaryPrivateKey) {
596 1
            if (is_string($primaryPrivateKey)) {
597 1
                $primaryPrivateKey = [$primaryPrivateKey, "m"];
598
            }
599
        } else {
600
            $primaryPrivateKey = HierarchicalKeyFactory::fromEntropy((new Bip39SeedGenerator())->getSeed($primaryMnemonic, $options['passphrase']));
601
        }
602
603 1
        if (!$storePrimaryMnemonic) {
604
            $primaryMnemonic = false;
605
        }
606
607
        // create primary public key from the created private key
608 1
        $path = $walletPath->keyIndexPath()->publicPath();
609 1
        $primaryPublicKey = BIP32Key::create($primaryPrivateKey, "m")->buildKey($path);
610
611 1
        if (isset($options['backup_mnemonic']) && $options['backup_public_key']) {
612
            throw new \InvalidArgumentException("Can't specify Backup Mnemonic and Backup PublicKey");
613
        }
614
615 1
        $backupMnemonic = null;
616 1
        $backupPublicKey = null;
617 1
        if (!isset($options['backup_mnemonic']) && !isset($options['backup_public_key'])) {
618
            /** @var HierarchicalKey $backupPrivateKey */
619 1
            list($backupMnemonic, , ) = $this->newBackupSeed();
620
        } else if (isset($options['backup_mnemonic'])) {
621
            $backupMnemonic = $options['backup_mnemonic'];
622
        } elseif (isset($options['backup_public_key'])) {
623
            $backupPublicKey = $options['backup_public_key'];
624
        }
625
626 1
        if ($backupPublicKey) {
627
            if (is_string($backupPublicKey)) {
628
                $backupPublicKey = [$backupPublicKey, "m"];
629
            }
630
        } else {
631 1
            $backupPrivateKey = HierarchicalKeyFactory::fromEntropy((new Bip39SeedGenerator())->getSeed($backupMnemonic, ""));
632 1
            $backupPublicKey = BIP32Key::create($backupPrivateKey->toPublic(), "M");
633
        }
634
635
        // create a checksum of our private key which we'll later use to verify we used the right password
636 1
        $checksum = $primaryPrivateKey->getPublicKey()->getAddress()->getAddress();
637
638
        // send the public keys to the server to store them
639
        //  and the mnemonic, which is safe because it's useless without the password
640 1
        $data = $this->storeNewWalletV1($options['identifier'], $primaryPublicKey->tuple(), $backupPublicKey->tuple(), $primaryMnemonic, $checksum, $options['key_index']);
641
642
        // received the blocktrail public keys
643
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
644 1
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
645 1
        }, $data['blocktrail_public_keys']);
646
647 1
        $wallet = new WalletV1(
648 1
            $this,
649 1
            $options['identifier'],
650 1
            $primaryMnemonic,
651 1
            [$options['key_index'] => $primaryPublicKey],
652 1
            $backupPublicKey,
653 1
            $blocktrailPublicKeys,
654 1
            $options['key_index'],
655 1
            $this->network,
656 1
            $this->testnet,
657 1
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
658 1
            $checksum
659
        );
660
661 1
        $wallet->unlock($options);
662
663
        // return wallet and backup mnemonic
664
        return [
665 1
            $wallet,
666
            [
667 1
                'primary_mnemonic' => $primaryMnemonic,
668 1
                'backup_mnemonic' => $backupMnemonic,
669 1
                'blocktrail_public_keys' => $blocktrailPublicKeys,
670
            ],
671
        ];
672
    }
673
674 5
    public static function randomBits($bits) {
675 5
        return self::randomBytes($bits / 8);
676
    }
677
678 5
    public static function randomBytes($bytes) {
679 5
        return (new Random())->bytes($bytes)->getBinary();
680
    }
681
682 2
    protected function createNewWalletV2($options) {
683 2
        $walletPath = WalletPath::create($options['key_index']);
684
685 2
        if (isset($options['store_primary_mnemonic'])) {
686
            $options['store_data_on_server'] = $options['store_primary_mnemonic'];
687
        }
688
689 2
        if (!isset($options['store_data_on_server'])) {
690 2
            if (isset($options['primary_private_key'])) {
691 1
                $options['store_data_on_server'] = false;
692
            } else {
693 1
                $options['store_data_on_server'] = true;
694
            }
695
        }
696
697 2
        $storeDataOnServer = $options['store_data_on_server'];
698
699 2
        $secret = null;
700 2
        $encryptedSecret = null;
701 2
        $primarySeed = null;
702 2
        $encryptedPrimarySeed = null;
703 2
        $recoverySecret = null;
704 2
        $recoveryEncryptedSecret = null;
705 2
        $backupSeed = null;
706
707 2
        if (!isset($options['primary_private_key'])) {
708 1
            $primarySeed = isset($options['primary_seed']) ? $options['primary_seed'] : self::randomBits(256);
709
        }
710
711 2
        if ($storeDataOnServer) {
712 1
            if (!isset($options['secret'])) {
713 1
                if (!$options['passphrase']) {
714
                    throw new \InvalidArgumentException("Can't encrypt data without a passphrase");
715
                }
716
717 1
                $secret = bin2hex(self::randomBits(256)); // string because we use it as passphrase
718 1
                $encryptedSecret = CryptoJSAES::encrypt($secret, $options['passphrase']);
719
            } else {
720
                $secret = $options['secret'];
721
            }
722
723 1
            $encryptedPrimarySeed = CryptoJSAES::encrypt(base64_encode($primarySeed), $secret);
724 1
            $recoverySecret = bin2hex(self::randomBits(256));
725
726 1
            $recoveryEncryptedSecret = CryptoJSAES::encrypt($secret, $recoverySecret);
727
        }
728
729 2
        if (!isset($options['backup_public_key'])) {
730 1
            $backupSeed = isset($options['backup_seed']) ? $options['backup_seed'] : self::randomBits(256);
731
        }
732
733 2
        if (isset($options['primary_private_key'])) {
734 1
            $options['primary_private_key'] = BlocktrailSDK::normalizeBIP32Key($options['primary_private_key']);
735
        } else {
736 1
            $options['primary_private_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy(new Buffer($primarySeed)), "m");
737
        }
738
739
        // create primary public key from the created private key
740 2
        $options['primary_public_key'] = $options['primary_private_key']->buildKey($walletPath->keyIndexPath()->publicPath());
741
742 2
        if (!isset($options['backup_public_key'])) {
743 1
            $options['backup_public_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy(new Buffer($backupSeed)), "m")->buildKey("M");
744
        }
745
746
        // create a checksum of our private key which we'll later use to verify we used the right password
747 2
        $checksum = $options['primary_private_key']->publicKey()->getAddress()->getAddress();
748
749
        // send the public keys and encrypted data to server
750 2
        $data = $this->storeNewWalletV2(
751 2
            $options['identifier'],
752 2
            $options['primary_public_key']->tuple(),
753 2
            $options['backup_public_key']->tuple(),
0 ignored issues
show
Documentation introduced by
$options['backup_public_key']->tuple() is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

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...
754 2
            $storeDataOnServer ? $encryptedPrimarySeed : false,
755 2
            $storeDataOnServer ? $encryptedSecret : false,
756 2
            $storeDataOnServer ? $recoverySecret : false,
757 2
            $checksum,
758 2
            $options['key_index']
759
        );
760
761
        // received the blocktrail public keys
762
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
763 2
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
764 2
        }, $data['blocktrail_public_keys']);
765
766 2
        $wallet = new WalletV2(
767 2
            $this,
768 2
            $options['identifier'],
769 2
            $encryptedPrimarySeed,
770 2
            $encryptedSecret,
771 2
            [$options['key_index'] => $options['primary_public_key']],
772 2
            $options['backup_public_key'],
773 2
            $blocktrailPublicKeys,
774 2
            $options['key_index'],
775 2
            $this->network,
776 2
            $this->testnet,
777 2
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
778 2
            $checksum
779
        );
780
781 2
        $wallet->unlock([
782 2
            'passphrase' => isset($options['passphrase']) ? $options['passphrase'] : null,
783 2
            'primary_private_key' => $options['primary_private_key'],
784 2
            'primary_seed' => $primarySeed,
785 2
            'secret' => $secret,
786
        ]);
787
788
        // return wallet and mnemonics for backup sheet
789
        return [
790 2
            $wallet,
791
            [
792 2
                'encrypted_primary_seed' => $encryptedPrimarySeed ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($encryptedPrimarySeed))) : null,
793 2
                'backup_seed' => $backupSeed ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer($backupSeed)) : null,
794 2
                'recovery_encrypted_secret' => $recoveryEncryptedSecret ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($recoveryEncryptedSecret))) : null,
795 2
                'encrypted_secret' => $encryptedSecret ? MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($encryptedSecret))) : null,
796
                'blocktrail_public_keys' => Util::arrayMapWithIndex(function ($keyIndex, BIP32Key $pubKey) {
797 2
                    return [$keyIndex, $pubKey->tuple()];
798 2
                }, $blocktrailPublicKeys),
799
            ],
800
        ];
801
    }
802
803 4
    protected function createNewWalletV3($options) {
804 4
        $walletPath = WalletPath::create($options['key_index']);
805
806 4
        if (isset($options['store_primary_mnemonic'])) {
807
            $options['store_data_on_server'] = $options['store_primary_mnemonic'];
808
        }
809
810 4
        if (!isset($options['store_data_on_server'])) {
811 4
            if (isset($options['primary_private_key'])) {
812
                $options['store_data_on_server'] = false;
813
            } else {
814 4
                $options['store_data_on_server'] = true;
815
            }
816
        }
817
818 4
        $storeDataOnServer = $options['store_data_on_server'];
819
820 4
        $secret = null;
821 4
        $encryptedSecret = null;
822 4
        $primarySeed = null;
823 4
        $encryptedPrimarySeed = null;
824 4
        $recoverySecret = null;
825 4
        $recoveryEncryptedSecret = null;
826 4
        $backupSeed = null;
827
828 4
        if (!isset($options['primary_private_key'])) {
829 4
            if (isset($options['primary_seed'])) {
830
                if (!$options['primary_seed'] instanceof BufferInterface) {
831
                    throw new \InvalidArgumentException('Primary Seed should be passed as a Buffer');
832
                }
833
                $primarySeed = $options['primary_seed'];
834
            } else {
835 4
                $primarySeed = new Buffer(self::randomBits(256));
836
            }
837
        }
838
839 4
        if ($storeDataOnServer) {
840 4
            if (!isset($options['secret'])) {
841 4
                if (!$options['passphrase']) {
842
                    throw new \InvalidArgumentException("Can't encrypt data without a passphrase");
843
                }
844
845 4
                $secret = new Buffer(self::randomBits(256));
846 4
                $encryptedSecret = Encryption::encrypt($secret, new Buffer($options['passphrase']), KeyDerivation::DEFAULT_ITERATIONS);
847
            } else {
848
                if (!$options['secret'] instanceof Buffer) {
849
                    throw new \RuntimeException('Secret must be provided as a Buffer');
850
                }
851
852
                $secret = $options['secret'];
853
            }
854
855 4
            $encryptedPrimarySeed = Encryption::encrypt($primarySeed, $secret, KeyDerivation::SUBKEY_ITERATIONS);
856 4
            $recoverySecret = new Buffer(self::randomBits(256));
857
858 4
            $recoveryEncryptedSecret = Encryption::encrypt($secret, $recoverySecret, KeyDerivation::DEFAULT_ITERATIONS);
859
        }
860
861 4
        if (!isset($options['backup_public_key'])) {
862 4
            if (isset($options['backup_seed'])) {
863
                if (!$options['backup_seed'] instanceof Buffer) {
864
                    throw new \RuntimeException('Backup seed must be an instance of Buffer');
865
                }
866
                $backupSeed = $options['backup_seed'];
867
            } else {
868 4
                $backupSeed = new Buffer(self::randomBits(256));
869
            }
870
        }
871
872 4
        if (isset($options['primary_private_key'])) {
873
            $options['primary_private_key'] = BlocktrailSDK::normalizeBIP32Key($options['primary_private_key']);
874
        } else {
875 4
            $options['primary_private_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy($primarySeed), "m");
876
        }
877
878
        // create primary public key from the created private key
879 4
        $options['primary_public_key'] = $options['primary_private_key']->buildKey($walletPath->keyIndexPath()->publicPath());
880
881 4
        if (!isset($options['backup_public_key'])) {
882 4
            $options['backup_public_key'] = BIP32Key::create(HierarchicalKeyFactory::fromEntropy($backupSeed), "m")->buildKey("M");
883
        }
884
885
        // create a checksum of our private key which we'll later use to verify we used the right password
886 4
        $checksum = $options['primary_private_key']->publicKey()->getAddress()->getAddress();
887
888
        // send the public keys and encrypted data to server
889 4
        $data = $this->storeNewWalletV3(
890 4
            $options['identifier'],
891 4
            $options['primary_public_key']->tuple(),
892 4
            $options['backup_public_key']->tuple(),
0 ignored issues
show
Documentation introduced by
$options['backup_public_key']->tuple() is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

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...
893 4
            $storeDataOnServer ? base64_encode($encryptedPrimarySeed->getBinary()) : false,
894 4
            $storeDataOnServer ? base64_encode($encryptedSecret->getBinary()) : false,
895 4
            $storeDataOnServer ? $recoverySecret->getHex() : false,
896 4
            $checksum,
897 4
            $options['key_index']
898
        );
899
900
        // received the blocktrail public keys
901
        $blocktrailPublicKeys = Util::arrayMapWithIndex(function ($keyIndex, $pubKeyTuple) {
902 4
            return [$keyIndex, BIP32Key::create(HierarchicalKeyFactory::fromExtended($pubKeyTuple[0]), $pubKeyTuple[1])];
903 4
        }, $data['blocktrail_public_keys']);
904
905 4
        $wallet = new WalletV3(
906 4
            $this,
907 4
            $options['identifier'],
908 4
            $encryptedPrimarySeed,
0 ignored issues
show
Bug introduced by
It seems like $encryptedPrimarySeed defined by null on line 823 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...
909 4
            $encryptedSecret,
0 ignored issues
show
Bug introduced by
It seems like $encryptedSecret defined by null on line 821 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...
910 4
            [$options['key_index'] => $options['primary_public_key']],
911 4
            $options['backup_public_key'],
912 4
            $blocktrailPublicKeys,
913 4
            $options['key_index'],
914 4
            $this->network,
915 4
            $this->testnet,
916 4
            array_key_exists('segwit', $data) ? $data['segwit'] : false,
917 4
            $checksum
918
        );
919
920 4
        $wallet->unlock([
921 4
            'passphrase' => isset($options['passphrase']) ? $options['passphrase'] : null,
922 4
            'primary_private_key' => $options['primary_private_key'],
923 4
            'primary_seed' => $primarySeed,
924 4
            'secret' => $secret,
925
        ]);
926
927
        // return wallet and mnemonics for backup sheet
928
        return [
929 4
            $wallet,
930
            [
931 4
                'encrypted_primary_seed'    => $encryptedPrimarySeed ? EncryptionMnemonic::encode($encryptedPrimarySeed) : null,
932 4
                'backup_seed'               => $backupSeed ? MnemonicFactory::bip39()->entropyToMnemonic($backupSeed) : null,
933 4
                'recovery_encrypted_secret' => $recoveryEncryptedSecret ? EncryptionMnemonic::encode($recoveryEncryptedSecret) : null,
934 4
                'encrypted_secret'          => $encryptedSecret ? EncryptionMnemonic::encode($encryptedSecret) : null,
935
                'blocktrail_public_keys'    => Util::arrayMapWithIndex(function ($keyIndex, BIP32Key $pubKey) {
936 4
                    return [$keyIndex, $pubKey->tuple()];
937 4
                }, $blocktrailPublicKeys),
938
            ]
939
        ];
940
    }
941
942
    /**
943
     * @param array $bip32Key
944
     * @throws BlocktrailSDKException
945
     */
946 10
    private function verifyPublicBIP32Key(array $bip32Key) {
947 10
        $hk = HierarchicalKeyFactory::fromExtended($bip32Key[0]);
948 10
        if ($hk->isPrivate()) {
949
            throw new BlocktrailSDKException('Private key was included in request, abort');
950
        }
951
952 10
        if (substr($bip32Key[1], 0, 1) === "m") {
953
            throw new BlocktrailSDKException("Private path was included in the request, abort");
954
        }
955 10
    }
956
957
    /**
958
     * @param array $walletData
959
     * @throws BlocktrailSDKException
960
     */
961 10
    private function verifyPublicOnly(array $walletData) {
962 10
        $this->verifyPublicBIP32Key($walletData['primary_public_key']);
963 10
        $this->verifyPublicBIP32Key($walletData['backup_public_key']);
964 10
    }
965
966
    /**
967
     * create wallet using the API
968
     *
969
     * @param string    $identifier             the wallet identifier to create
970
     * @param array     $primaryPublicKey       BIP32 extended public key - [key, path]
971
     * @param string    $backupPublicKey        plain public key
972
     * @param string    $primaryMnemonic        mnemonic to store
973
     * @param string    $checksum               checksum to store
974
     * @param int       $keyIndex               account that we expect to use
975
     * @return mixed
976
     */
977 1
    public function storeNewWalletV1($identifier, $primaryPublicKey, $backupPublicKey, $primaryMnemonic, $checksum, $keyIndex) {
978
        $data = [
979 1
            'identifier' => $identifier,
980 1
            'primary_public_key' => $primaryPublicKey,
981 1
            'backup_public_key' => $backupPublicKey,
982 1
            'primary_mnemonic' => $primaryMnemonic,
983 1
            'checksum' => $checksum,
984 1
            'key_index' => $keyIndex
985
        ];
986 1
        $this->verifyPublicOnly($data);
987 1
        $response = $this->client->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
988 1
        return self::jsonDecode($response->body(), true);
989
    }
990
991
    /**
992
     * create wallet using the API
993
     *
994
     * @param string $identifier       the wallet identifier to create
995
     * @param array  $primaryPublicKey BIP32 extended public key - [key, path]
996
     * @param string $backupPublicKey  plain public key
997
     * @param        $encryptedPrimarySeed
998
     * @param        $encryptedSecret
999
     * @param        $recoverySecret
1000
     * @param string $checksum         checksum to store
1001
     * @param int    $keyIndex         account that we expect to use
1002
     * @return mixed
1003
     * @throws \Exception
1004
     */
1005 5
    public function storeNewWalletV2($identifier, $primaryPublicKey, $backupPublicKey, $encryptedPrimarySeed, $encryptedSecret, $recoverySecret, $checksum, $keyIndex) {
1006
        $data = [
1007 5
            'identifier' => $identifier,
1008
            'wallet_version' => Wallet::WALLET_VERSION_V2,
1009 5
            'primary_public_key' => $primaryPublicKey,
1010 5
            'backup_public_key' => $backupPublicKey,
1011 5
            'encrypted_primary_seed' => $encryptedPrimarySeed,
1012 5
            'encrypted_secret' => $encryptedSecret,
1013 5
            'recovery_secret' => $recoverySecret,
1014 5
            'checksum' => $checksum,
1015 5
            'key_index' => $keyIndex
1016
        ];
1017 5
        $this->verifyPublicOnly($data);
1018 5
        $response = $this->client->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
1019 5
        return self::jsonDecode($response->body(), true);
1020
    }
1021
1022
    /**
1023
     * create wallet using the API
1024
     *
1025
     * @param string $identifier       the wallet identifier to create
1026
     * @param array  $primaryPublicKey BIP32 extended public key - [key, path]
1027
     * @param string $backupPublicKey  plain public key
1028
     * @param        $encryptedPrimarySeed
1029
     * @param        $encryptedSecret
1030
     * @param        $recoverySecret
1031
     * @param string $checksum         checksum to store
1032
     * @param int    $keyIndex         account that we expect to use
1033
     * @return mixed
1034
     * @throws \Exception
1035
     */
1036 4
    public function storeNewWalletV3($identifier, $primaryPublicKey, $backupPublicKey, $encryptedPrimarySeed, $encryptedSecret, $recoverySecret, $checksum, $keyIndex) {
1037
1038
        $data = [
1039 4
            'identifier' => $identifier,
1040
            'wallet_version' => Wallet::WALLET_VERSION_V3,
1041 4
            'primary_public_key' => $primaryPublicKey,
1042 4
            'backup_public_key' => $backupPublicKey,
1043 4
            'encrypted_primary_seed' => $encryptedPrimarySeed,
1044 4
            'encrypted_secret' => $encryptedSecret,
1045 4
            'recovery_secret' => $recoverySecret,
1046 4
            'checksum' => $checksum,
1047 4
            'key_index' => $keyIndex
1048
        ];
1049
1050 4
        $this->verifyPublicOnly($data);
1051 4
        $response = $this->client->post("wallet", null, $data, RestClient::AUTH_HTTP_SIG);
1052 4
        return self::jsonDecode($response->body(), true);
1053
    }
1054
1055
    /**
1056
     * upgrade wallet to use a new account number
1057
     *  the account number specifies which blocktrail cosigning key is used
1058
     *
1059
     * @param string    $identifier             the wallet identifier to be upgraded
1060
     * @param int       $keyIndex               the new account to use
1061
     * @param array     $primaryPublicKey       BIP32 extended public key - [key, path]
1062
     * @return mixed
1063
     */
1064 5
    public function upgradeKeyIndex($identifier, $keyIndex, $primaryPublicKey) {
1065
        $data = [
1066 5
            'key_index' => $keyIndex,
1067 5
            'primary_public_key' => $primaryPublicKey
1068
        ];
1069
1070 5
        $response = $this->client->post("wallet/{$identifier}/upgrade", null, $data, RestClient::AUTH_HTTP_SIG);
1071 5
        return self::jsonDecode($response->body(), true);
1072
    }
1073
1074
    /**
1075
     * initialize a previously created wallet
1076
     *
1077
     * Takes an options object, or accepts identifier/password for backwards compatiblity.
1078
     *
1079
     * Some of the options:
1080
     *  - "readonly/readOnly/read-only" can be to a boolean value,
1081
     *    so the wallet is loaded in read-only mode (no private key)
1082
     *  - "check_backup_key" can be set to your own backup key:
1083
     *    Format: ["M', "xpub..."]
1084
     *    Setting this will allow the SDK to check the server hasn't
1085
     *    a different key (one it happens to control)
1086
1087
     * Either takes one argument:
1088
     * @param array $options
1089
     *
1090
     * Or takes two arguments (old, deprecated syntax):
1091
     * (@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...
1092
     * (@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...
1093
     *
1094
     * @return WalletInterface
1095
     * @throws \Exception
1096
     */
1097 16
    public function initWallet($options) {
1098 16
        if (!is_array($options)) {
1099 1
            $args = func_get_args();
1100
            $options = [
1101 1
                "identifier" => $args[0],
1102 1
                "password" => $args[1],
1103
            ];
1104
        }
1105
1106 16
        $identifier = $options['identifier'];
1107 16
        $readonly = isset($options['readonly']) ? $options['readonly'] :
1108 16
                    (isset($options['readOnly']) ? $options['readOnly'] :
1109 16
                        (isset($options['read-only']) ? $options['read-only'] :
1110 16
                            false));
1111
1112
        // get the wallet data from the server
1113 16
        $data = $this->getWallet($identifier);
1114 16
        if (!$data) {
1115
            throw new \Exception("Failed to get wallet");
1116
        }
1117
1118 16
        if (array_key_exists('check_backup_key', $options)) {
1119 1
            if (!is_string($options['check_backup_key'])) {
1120 1
                throw new \RuntimeException("check_backup_key should be a string (the xpub)");
1121
            }
1122 1
            if ($options['check_backup_key'] !== $data['backup_public_key'][0]) {
1123 1
                throw new \RuntimeException("Backup key returned from server didn't match our own");
1124
            }
1125
        }
1126
1127 16
        switch ($data['wallet_version']) {
1128 16
            case Wallet::WALLET_VERSION_V1:
1129 10
                $wallet = new WalletV1(
1130 10
                    $this,
1131 10
                    $identifier,
1132 10
                    isset($options['primary_mnemonic']) ? $options['primary_mnemonic'] : $data['primary_mnemonic'],
1133 10
                    $data['primary_public_keys'],
1134 10
                    $data['backup_public_key'],
1135 10
                    $data['blocktrail_public_keys'],
1136 10
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1137 10
                    $this->network,
1138 10
                    $this->testnet,
1139 10
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1140 10
                    $data['checksum']
1141
                );
1142 10
                break;
1143 6
            case Wallet::WALLET_VERSION_V2:
1144 2
                $wallet = new WalletV2(
1145 2
                    $this,
1146 2
                    $identifier,
1147 2
                    isset($options['encrypted_primary_seed']) ? $options['encrypted_primary_seed'] : $data['encrypted_primary_seed'],
1148 2
                    isset($options['encrypted_secret']) ? $options['encrypted_secret'] : $data['encrypted_secret'],
1149 2
                    $data['primary_public_keys'],
1150 2
                    $data['backup_public_key'],
1151 2
                    $data['blocktrail_public_keys'],
1152 2
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1153 2
                    $this->network,
1154 2
                    $this->testnet,
1155 2
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1156 2
                    $data['checksum']
1157
                );
1158 2
                break;
1159 4
            case Wallet::WALLET_VERSION_V3:
1160 4
                if (isset($options['encrypted_primary_seed'])) {
1161
                    if (!$options['encrypted_primary_seed'] instanceof Buffer) {
1162
                        throw new \InvalidArgumentException('Encrypted PrimarySeed must be provided as a Buffer');
1163
                    }
1164
                    $encryptedPrimarySeed = $data['encrypted_primary_seed'];
1165
                } else {
1166 4
                    $encryptedPrimarySeed = new Buffer(base64_decode($data['encrypted_primary_seed']));
1167
                }
1168
1169 4
                if (isset($options['encrypted_secret'])) {
1170
                    if (!$options['encrypted_secret'] instanceof Buffer) {
1171
                        throw new \InvalidArgumentException('Encrypted secret must be provided as a Buffer');
1172
                    }
1173
1174
                    $encryptedSecret = $data['encrypted_secret'];
1175
                } else {
1176 4
                    $encryptedSecret = new Buffer(base64_decode($data['encrypted_secret']));
1177
                }
1178
1179 4
                $wallet = new WalletV3(
1180 4
                    $this,
1181 4
                    $identifier,
1182 4
                    $encryptedPrimarySeed,
1183 4
                    $encryptedSecret,
1184 4
                    $data['primary_public_keys'],
1185 4
                    $data['backup_public_key'],
1186 4
                    $data['blocktrail_public_keys'],
1187 4
                    isset($options['key_index']) ? $options['key_index'] : $data['key_index'],
1188 4
                    $this->network,
1189 4
                    $this->testnet,
1190 4
                    array_key_exists('segwit', $data) ? $data['segwit'] : false,
1191 4
                    $data['checksum']
1192
                );
1193 4
                break;
1194
            default:
1195
                throw new \InvalidArgumentException("Invalid wallet version");
1196
        }
1197
1198 16
        if (!$readonly) {
1199 16
            $wallet->unlock($options);
1200
        }
1201
1202 16
        return $wallet;
1203
    }
1204
1205
    /**
1206
     * get the wallet data from the server
1207
     *
1208
     * @param string    $identifier             the identifier of the wallet
1209
     * @return mixed
1210
     */
1211 16
    public function getWallet($identifier) {
1212 16
        $response = $this->client->get("wallet/{$identifier}", null, RestClient::AUTH_HTTP_SIG);
1213 16
        return self::jsonDecode($response->body(), true);
1214
    }
1215
1216
    /**
1217
     * update the wallet data on the server
1218
     *
1219
     * @param string    $identifier
1220
     * @param $data
1221
     * @return mixed
1222
     */
1223 3
    public function updateWallet($identifier, $data) {
1224 3
        $response = $this->client->post("wallet/{$identifier}", null, $data, RestClient::AUTH_HTTP_SIG);
1225 3
        return self::jsonDecode($response->body(), true);
1226
    }
1227
1228
    /**
1229
     * delete a wallet from the server
1230
     *  the checksum address and a signature to verify you ownership of the key of that checksum address
1231
     *  is required to be able to delete a wallet
1232
     *
1233
     * @param string    $identifier             the identifier of the wallet
1234
     * @param string    $checksumAddress        the address for your master private key (and the checksum used when creating the wallet)
1235
     * @param string    $signature              a signature of the checksum address as message signed by the private key matching that address
1236
     * @param bool      $force                  ignore warnings (such as a non-zero balance)
1237
     * @return mixed
1238
     */
1239 10
    public function deleteWallet($identifier, $checksumAddress, $signature, $force = false) {
1240 10
        $response = $this->client->delete("wallet/{$identifier}", ['force' => $force], [
1241 10
            'checksum' => $checksumAddress,
1242 10
            'signature' => $signature
1243 10
        ], RestClient::AUTH_HTTP_SIG, 360);
1244 10
        return self::jsonDecode($response->body(), true);
1245
    }
1246
1247
    /**
1248
     * create new backup key;
1249
     *  1) a BIP39 mnemonic
1250
     *  2) a seed from that mnemonic with a blank password
1251
     *  3) a private key from that seed
1252
     *
1253
     * @return array [mnemonic, seed, key]
1254
     */
1255 1
    protected function newBackupSeed() {
1256 1
        list($backupMnemonic, $backupSeed, $backupPrivateKey) = $this->generateNewSeed("");
1257
1258 1
        return [$backupMnemonic, $backupSeed, $backupPrivateKey];
1259
    }
1260
1261
    /**
1262
     * create new primary key;
1263
     *  1) a BIP39 mnemonic
1264
     *  2) a seed from that mnemonic with the password
1265
     *  3) a private key from that seed
1266
     *
1267
     * @param string    $passphrase             the password to use in the BIP39 creation of the seed
1268
     * @return array [mnemonic, seed, key]
1269
     * @TODO: require a strong password?
1270
     */
1271 1
    protected function newPrimarySeed($passphrase) {
1272 1
        list($primaryMnemonic, $primarySeed, $primaryPrivateKey) = $this->generateNewSeed($passphrase);
1273
1274 1
        return [$primaryMnemonic, $primarySeed, $primaryPrivateKey];
1275
    }
1276
1277
    /**
1278
     * create a new key;
1279
     *  1) a BIP39 mnemonic
1280
     *  2) a seed from that mnemonic with the password
1281
     *  3) a private key from that seed
1282
     *
1283
     * @param string    $passphrase             the password to use in the BIP39 creation of the seed
1284
     * @param string    $forceEntropy           forced entropy instead of random entropy for testing purposes
1285
     * @return array
1286
     */
1287 1
    protected function generateNewSeed($passphrase = "", $forceEntropy = null) {
1288
        // generate master seed, retry if the generated private key isn't valid (FALSE is returned)
1289
        do {
1290 1
            $mnemonic = $this->generateNewMnemonic($forceEntropy);
1291
1292 1
            $seed = (new Bip39SeedGenerator)->getSeed($mnemonic, $passphrase);
1293
1294 1
            $key = null;
1295
            try {
1296 1
                $key = HierarchicalKeyFactory::fromEntropy($seed);
1297
            } catch (\Exception $e) {
1298
                // try again
1299
            }
1300 1
        } while (!$key);
1301
1302 1
        return [$mnemonic, $seed, $key];
1303
    }
1304
1305
    /**
1306
     * generate a new mnemonic from some random entropy (512 bit)
1307
     *
1308
     * @param string    $forceEntropy           forced entropy instead of random entropy for testing purposes
1309
     * @return string
1310
     * @throws \Exception
1311
     */
1312 1
    protected function generateNewMnemonic($forceEntropy = null) {
1313 1
        if ($forceEntropy === null) {
1314 1
            $random = new Random();
1315 1
            $entropy = $random->bytes(512 / 8);
1316
        } else {
1317
            $entropy = $forceEntropy;
1318
        }
1319
1320 1
        return MnemonicFactory::bip39()->entropyToMnemonic($entropy);
0 ignored issues
show
Bug introduced by
It seems like $entropy defined by $forceEntropy on line 1317 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...
1321
    }
1322
1323
    /**
1324
     * get the balance for the wallet
1325
     *
1326
     * @param string    $identifier             the identifier of the wallet
1327
     * @return array
1328
     */
1329 9
    public function getWalletBalance($identifier) {
1330 9
        $response = $this->client->get("wallet/{$identifier}/balance", null, RestClient::AUTH_HTTP_SIG);
1331 9
        return self::jsonDecode($response->body(), true);
1332
    }
1333
1334
    /**
1335
     * do HD wallet discovery for the wallet
1336
     *
1337
     * this can be REALLY slow, so we've set the timeout to 120s ...
1338
     *
1339
     * @param string    $identifier             the identifier of the wallet
1340
     * @param int       $gap                    the gap setting to use for discovery
1341
     * @return mixed
1342
     */
1343 2
    public function doWalletDiscovery($identifier, $gap = 200) {
1344 2
        $response = $this->client->get("wallet/{$identifier}/discovery", ['gap' => $gap], RestClient::AUTH_HTTP_SIG, 360.0);
1345 2
        return self::jsonDecode($response->body(), true);
1346
    }
1347
1348
    /**
1349
     * get a new derivation number for specified parent path
1350
     *  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
1351
     *
1352
     * returns the path
1353
     *
1354
     * @param string    $identifier             the identifier of the wallet
1355
     * @param string    $path                   the parent path for which to get a new derivation
1356
     * @return string
1357
     */
1358 1
    public function getNewDerivation($identifier, $path) {
1359 1
        $result = $this->_getNewDerivation($identifier, $path);
1360 1
        return $result['path'];
1361
    }
1362
1363
    /**
1364
     * get a new derivation number for specified parent path
1365
     *  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
1366
     *
1367
     * @param string    $identifier             the identifier of the wallet
1368
     * @param string    $path                   the parent path for which to get a new derivation
1369
     * @return mixed
1370
     */
1371 12
    public function _getNewDerivation($identifier, $path) {
1372 12
        $response = $this->client->post("wallet/{$identifier}/path", null, ['path' => $path], RestClient::AUTH_HTTP_SIG);
1373 12
        return self::jsonDecode($response->body(), true);
1374
    }
1375
1376
    /**
1377
     * get the path (and redeemScript) to specified address
1378
     *
1379
     * @param string $identifier
1380
     * @param string $address
1381
     * @return array
1382
     * @throws \Exception
1383
     */
1384
    public function getPathForAddress($identifier, $address) {
1385
        $response = $this->client->post("wallet/{$identifier}/path_for_address", null, ['address' => $address], RestClient::AUTH_HTTP_SIG);
1386
        return self::jsonDecode($response->body(), true)['path'];
1387
    }
1388
1389
    /**
1390
     * send the transaction using the API
1391
     *
1392
     * @param string         $identifier             the identifier of the wallet
1393
     * @param string|array   $rawTransaction         raw hex of the transaction (should be partially signed)
1394
     * @param array          $paths                  list of the paths that were used for the UTXO
1395
     * @param bool           $checkFee               let the server verify the fee after signing
1396
     * @return string                                the complete raw transaction
1397
     * @throws \Exception
1398
     */
1399 4
    public function sendTransaction($identifier, $rawTransaction, $paths, $checkFee = false) {
1400
        $data = [
1401 4
            'paths' => $paths
1402
        ];
1403
1404 4
        if (is_array($rawTransaction)) {
1405 4
            if (array_key_exists('base_transaction', $rawTransaction)
1406 4
            && array_key_exists('signed_transaction', $rawTransaction)) {
1407 4
                $data['base_transaction'] = $rawTransaction['base_transaction'];
1408 4
                $data['signed_transaction'] = $rawTransaction['signed_transaction'];
1409
            } else {
1410 4
                throw new \RuntimeException("Invalid value for transaction. For segwit transactions, pass ['base_transaction' => '...', 'signed_transaction' => '...']");
1411
            }
1412
        } else {
1413
            $data['raw_transaction'] = $rawTransaction;
1414
        }
1415
1416
        // dynamic TTL for when we're signing really big transactions
1417 4
        $ttl = max(5.0, count($paths) * 0.25) + 4.0;
1418
1419 4
        $response = $this->client->post("wallet/{$identifier}/send", ['check_fee' => (int)!!$checkFee], $data, RestClient::AUTH_HTTP_SIG, $ttl);
1420 3
        $signed = self::jsonDecode($response->body(), true);
1421
1422 3
        if (!$signed['complete'] || $signed['complete'] == 'false') {
1423
            throw new \Exception("Failed to completely sign transaction");
1424
        }
1425
1426
        // create TX hash from the raw signed hex
1427 3
        return TransactionFactory::fromHex($signed['hex'])->getTxId()->getHex();
1428
    }
1429
1430
    /**
1431
     * use the API to get the best inputs to use based on the outputs
1432
     *
1433
     * the return array has the following format:
1434
     * [
1435
     *  "utxos" => [
1436
     *      [
1437
     *          "hash" => "<txHash>",
1438
     *          "idx" => "<index of the output of that <txHash>",
1439
     *          "scriptpubkey_hex" => "<scriptPubKey-hex>",
1440
     *          "value" => 32746327,
1441
     *          "address" => "1address",
1442
     *          "path" => "m/44'/1'/0'/0/13",
1443
     *          "redeem_script" => "<redeemScript-hex>",
1444
     *      ],
1445
     *  ],
1446
     *  "fee"   => 10000,
1447
     *  "change"=> 1010109201,
1448
     * ]
1449
     *
1450
     * @param string   $identifier              the identifier of the wallet
1451
     * @param array    $outputs                 the outputs you want to create - array[address => satoshi-value]
1452
     * @param bool     $lockUTXO                when TRUE the UTXOs selected will be locked for a few seconds
1453
     *                                          so you have some time to spend them without race-conditions
1454
     * @param bool     $allowZeroConf
1455
     * @param string   $feeStrategy
1456
     * @param null|int $forceFee
1457
     * @return array
1458
     * @throws \Exception
1459
     */
1460 11
    public function coinSelection($identifier, $outputs, $lockUTXO = false, $allowZeroConf = false, $feeStrategy = Wallet::FEE_STRATEGY_OPTIMAL, $forceFee = null) {
1461
        $args = [
1462 11
            'lock' => (int)!!$lockUTXO,
1463 11
            'zeroconf' => (int)!!$allowZeroConf,
1464 11
            'fee_strategy' => $feeStrategy,
1465
        ];
1466
1467 11
        if ($forceFee !== null) {
1468
            $args['forcefee'] = (int)$forceFee;
1469
        }
1470
1471 11
        $response = $this->client->post(
1472 11
            "wallet/{$identifier}/coin-selection",
1473 11
            $args,
1474 11
            $outputs,
1475 11
            RestClient::AUTH_HTTP_SIG
1476
        );
1477
1478 5
        return self::jsonDecode($response->body(), true);
1479
    }
1480
1481
    /**
1482
     *
1483
     * @param string   $identifier the identifier of the wallet
1484
     * @param bool     $allowZeroConf
1485
     * @param string   $feeStrategy
1486
     * @param null|int $forceFee
1487
     * @param int      $outputCnt
1488
     * @return array
1489
     * @throws \Exception
1490
     */
1491
    public function walletMaxSpendable($identifier, $allowZeroConf = false, $feeStrategy = Wallet::FEE_STRATEGY_OPTIMAL, $forceFee = null, $outputCnt = 1) {
1492
        $args = [
1493
            'zeroconf' => (int)!!$allowZeroConf,
1494
            'fee_strategy' => $feeStrategy,
1495
            'outputs' => $outputCnt,
1496
        ];
1497
1498
        if ($forceFee !== null) {
1499
            $args['forcefee'] = (int)$forceFee;
1500
        }
1501
1502
        $response = $this->client->get(
1503
            "wallet/{$identifier}/max-spendable",
1504
            $args,
1505
            RestClient::AUTH_HTTP_SIG
1506
        );
1507
1508
        return self::jsonDecode($response->body(), true);
1509
    }
1510
1511
    /**
1512
     * @return array        ['optimal_fee' => 10000, 'low_priority_fee' => 5000]
1513
     */
1514 2
    public function feePerKB() {
1515 2
        $response = $this->client->get("fee-per-kb");
1516 2
        return self::jsonDecode($response->body(), true);
1517
    }
1518
1519
    /**
1520
     * get the current price index
1521
     *
1522
     * @return array        eg; ['USD' => 287.30]
1523
     */
1524 1
    public function price() {
1525 1
        $response = $this->client->get("price");
1526 1
        return self::jsonDecode($response->body(), true);
1527
    }
1528
1529
    /**
1530
     * setup webhook for wallet
1531
     *
1532
     * @param string    $identifier         the wallet identifier for which to create the webhook
1533
     * @param string    $webhookIdentifier  the webhook identifier to use
1534
     * @param string    $url                the url to receive the webhook events
1535
     * @return array
1536
     */
1537 1
    public function setupWalletWebhook($identifier, $webhookIdentifier, $url) {
1538 1
        $response = $this->client->post("wallet/{$identifier}/webhook", null, ['url' => $url, 'identifier' => $webhookIdentifier], RestClient::AUTH_HTTP_SIG);
1539 1
        return self::jsonDecode($response->body(), true);
1540
    }
1541
1542
    /**
1543
     * delete webhook for wallet
1544
     *
1545
     * @param string    $identifier         the wallet identifier for which to delete the webhook
1546
     * @param string    $webhookIdentifier  the webhook identifier to delete
1547
     * @return array
1548
     */
1549 1
    public function deleteWalletWebhook($identifier, $webhookIdentifier) {
1550 1
        $response = $this->client->delete("wallet/{$identifier}/webhook/{$webhookIdentifier}", null, null, RestClient::AUTH_HTTP_SIG);
1551 1
        return self::jsonDecode($response->body(), true);
1552
    }
1553
1554
    /**
1555
     * lock a specific unspent output
1556
     *
1557
     * @param     $identifier
1558
     * @param     $txHash
1559
     * @param     $txIdx
1560
     * @param int $ttl
1561
     * @return bool
1562
     */
1563
    public function lockWalletUTXO($identifier, $txHash, $txIdx, $ttl = 3) {
1564
        $response = $this->client->post("wallet/{$identifier}/lock-utxo", null, ['hash' => $txHash, 'idx' => $txIdx, 'ttl' => $ttl], RestClient::AUTH_HTTP_SIG);
1565
        return self::jsonDecode($response->body(), true)['locked'];
1566
    }
1567
1568
    /**
1569
     * unlock a specific unspent output
1570
     *
1571
     * @param     $identifier
1572
     * @param     $txHash
1573
     * @param     $txIdx
1574
     * @return bool
1575
     */
1576
    public function unlockWalletUTXO($identifier, $txHash, $txIdx) {
1577
        $response = $this->client->post("wallet/{$identifier}/unlock-utxo", null, ['hash' => $txHash, 'idx' => $txIdx], RestClient::AUTH_HTTP_SIG);
1578
        return self::jsonDecode($response->body(), true)['unlocked'];
1579
    }
1580
1581
    /**
1582
     * get all transactions for wallet (paginated)
1583
     *
1584
     * @param  string  $identifier  the wallet identifier for which to get transactions
1585
     * @param  integer $page        pagination: page number
1586
     * @param  integer $limit       pagination: records per page (max 500)
1587
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1588
     * @return array                associative array containing the response
1589
     */
1590 1
    public function walletTransactions($identifier, $page = 1, $limit = 20, $sortDir = 'asc') {
1591
        $queryString = [
1592 1
            'page' => $page,
1593 1
            'limit' => $limit,
1594 1
            'sort_dir' => $sortDir
1595
        ];
1596 1
        $response = $this->client->get("wallet/{$identifier}/transactions", $queryString, RestClient::AUTH_HTTP_SIG);
1597 1
        return self::jsonDecode($response->body(), true);
1598
    }
1599
1600
    /**
1601
     * get all addresses for wallet (paginated)
1602
     *
1603
     * @param  string  $identifier  the wallet identifier for which to get addresses
1604
     * @param  integer $page        pagination: page number
1605
     * @param  integer $limit       pagination: records per page (max 500)
1606
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1607
     * @return array                associative array containing the response
1608
     */
1609 1
    public function walletAddresses($identifier, $page = 1, $limit = 20, $sortDir = 'asc') {
1610
        $queryString = [
1611 1
            'page' => $page,
1612 1
            'limit' => $limit,
1613 1
            'sort_dir' => $sortDir
1614
        ];
1615 1
        $response = $this->client->get("wallet/{$identifier}/addresses", $queryString, RestClient::AUTH_HTTP_SIG);
1616 1
        return self::jsonDecode($response->body(), true);
1617
    }
1618
1619
    /**
1620
     * get all UTXOs for wallet (paginated)
1621
     *
1622
     * @param  string  $identifier  the wallet identifier for which to get addresses
1623
     * @param  integer $page        pagination: page number
1624
     * @param  integer $limit       pagination: records per page (max 500)
1625
     * @param  string  $sortDir     pagination: sort direction (asc|desc)
1626
     * @param  boolean $zeroconf    include zero confirmation transactions
1627
     * @return array                associative array containing the response
1628
     */
1629 1
    public function walletUTXOs($identifier, $page = 1, $limit = 20, $sortDir = 'asc', $zeroconf = true) {
1630
        $queryString = [
1631 1
            'page' => $page,
1632 1
            'limit' => $limit,
1633 1
            'sort_dir' => $sortDir,
1634 1
            'zeroconf' => (int)!!$zeroconf,
1635
        ];
1636 1
        $response = $this->client->get("wallet/{$identifier}/utxos", $queryString, RestClient::AUTH_HTTP_SIG);
1637 1
        return self::jsonDecode($response->body(), true);
1638
    }
1639
1640
    /**
1641
     * get a paginated list of all wallets associated with the api user
1642
     *
1643
     * @param  integer          $page    pagination: page number
1644
     * @param  integer          $limit   pagination: records per page
1645
     * @return array                     associative array containing the response
1646
     */
1647 2
    public function allWallets($page = 1, $limit = 20) {
1648
        $queryString = [
1649 2
            'page' => $page,
1650 2
            'limit' => $limit
1651
        ];
1652 2
        $response = $this->client->get("wallets", $queryString, RestClient::AUTH_HTTP_SIG);
1653 2
        return self::jsonDecode($response->body(), true);
1654
    }
1655
1656
    /**
1657
     * send raw transaction
1658
     *
1659
     * @param     $txHex
1660
     * @return bool
1661
     */
1662
    public function sendRawTransaction($txHex) {
1663
        $response = $this->client->post("send-raw-tx", null, ['hex' => $txHex], RestClient::AUTH_HTTP_SIG);
1664
        return self::jsonDecode($response->body(), true);
1665
    }
1666
1667
    /**
1668
     * testnet only ;-)
1669
     *
1670
     * @param     $address
1671
     * @param int $amount       defaults to 0.0001 BTC, max 0.001 BTC
1672
     * @return mixed
1673
     * @throws \Exception
1674
     */
1675
    public function faucetWithdrawal($address, $amount = 10000) {
1676
        $response = $this->client->post("faucet/withdrawl", null, [
1677
            'address' => $address,
1678
            'amount' => $amount,
1679
        ], RestClient::AUTH_HTTP_SIG);
1680
        return self::jsonDecode($response->body(), true);
1681
    }
1682
1683
    /**
1684
     * Exists for BC. Remove at major bump.
1685
     *
1686
     * @see faucetWithdrawal
1687
     * @deprecated
1688
     * @param     $address
1689
     * @param int $amount       defaults to 0.0001 BTC, max 0.001 BTC
1690
     * @return mixed
1691
     * @throws \Exception
1692
     */
1693
    public function faucetWithdrawl($address, $amount = 10000) {
1694
        return $this->faucetWithdrawal($address, $amount);
1695
    }
1696
1697
    /**
1698
     * verify a message signed bitcoin-core style
1699
     *
1700
     * @param  string           $message
1701
     * @param  string           $address
1702
     * @param  string           $signature
1703
     * @return boolean
1704
     */
1705 1
    public function verifyMessage($message, $address, $signature) {
1706
        // we could also use the API instead of the using BitcoinLib to verify
1707
        // $this->client->post("verify_message", null, ['message' => $message, 'address' => $address, 'signature' => $signature])['result'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1708
1709 1
        $adapter = Bitcoin::getEcAdapter();
1710 1
        $addr = AddressFactory::fromString($address);
1711 1
        if (!$addr instanceof PayToPubKeyHashAddress) {
1712
            throw new \RuntimeException('Can only verify a message with a pay-to-pubkey-hash address');
1713
        }
1714
1715
        /** @var CompactSignatureSerializerInterface $csSerializer */
1716 1
        $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...
1717 1
        $signedMessage = new SignedMessage($message, $csSerializer->parse(new Buffer(base64_decode($signature))));
1718
1719 1
        $signer = new MessageSigner($adapter);
1720 1
        return $signer->verify($signedMessage, $addr);
1721
    }
1722
1723
    /**
1724
     * convert a Satoshi value to a BTC value
1725
     *
1726
     * @param int       $satoshi
1727
     * @return float
1728
     */
1729
    public static function toBTC($satoshi) {
1730
        return bcdiv((int)(string)$satoshi, 100000000, 8);
1731
    }
1732
1733
    /**
1734
     * convert a Satoshi value to a BTC value and return it as a string
1735
1736
     * @param int       $satoshi
1737
     * @return string
1738
     */
1739
    public static function toBTCString($satoshi) {
1740
        return sprintf("%.8f", self::toBTC($satoshi));
1741
    }
1742
1743
    /**
1744
     * convert a BTC value to a Satoshi value
1745
     *
1746
     * @param float     $btc
1747
     * @return string
1748
     */
1749 12
    public static function toSatoshiString($btc) {
1750 12
        return bcmul(sprintf("%.8f", (float)$btc), 100000000, 0);
1751
    }
1752
1753
    /**
1754
     * convert a BTC value to a Satoshi value
1755
     *
1756
     * @param float     $btc
1757
     * @return string
1758
     */
1759 12
    public static function toSatoshi($btc) {
1760 12
        return (int)self::toSatoshiString($btc);
1761
    }
1762
1763
    /**
1764
     * json_decode helper that throws exceptions when it fails to decode
1765
     *
1766
     * @param      $json
1767
     * @param bool $assoc
1768
     * @return mixed
1769
     * @throws \Exception
1770
     */
1771 25
    protected static function jsonDecode($json, $assoc = false) {
1772 25
        if (!$json) {
1773
            throw new \Exception("Can't json_decode empty string [{$json}]");
1774
        }
1775
1776 25
        $data = json_decode($json, $assoc);
1777
1778 25
        if ($data === null) {
1779
            throw new \Exception("Failed to json_decode [{$json}]");
1780
        }
1781
1782 25
        return $data;
1783
    }
1784
1785
    /**
1786
     * sort public keys for multisig script
1787
     *
1788
     * @param PublicKeyInterface[] $pubKeys
1789
     * @return PublicKeyInterface[]
1790
     */
1791 14
    public static function sortMultisigKeys(array $pubKeys) {
1792 14
        $result = array_values($pubKeys);
1793
        usort($result, function (PublicKeyInterface $a, PublicKeyInterface $b) {
1794 14
            $av = $a->getHex();
1795 14
            $bv = $b->getHex();
1796 14
            return $av == $bv ? 0 : $av > $bv ? 1 : -1;
1797 14
        });
1798
1799 14
        return $result;
1800
    }
1801
1802
    /**
1803
     * read and decode the json payload from a webhook's POST request.
1804
     *
1805
     * @param bool $returnObject    flag to indicate if an object or associative array should be returned
1806
     * @return mixed|null
1807
     * @throws \Exception
1808
     */
1809
    public static function getWebhookPayload($returnObject = false) {
1810
        $data = file_get_contents("php://input");
1811
        if ($data) {
1812
            return self::jsonDecode($data, !$returnObject);
1813
        } else {
1814
            return null;
1815
        }
1816
    }
1817
1818
    public static function normalizeBIP32KeyArray($keys) {
1819 19
        return Util::arrayMapWithIndex(function ($idx, $key) {
1820 19
            return [$idx, self::normalizeBIP32Key($key)];
1821 19
        }, $keys);
1822
    }
1823
1824 19
    public static function normalizeBIP32Key($key) {
1825 19
        if ($key instanceof BIP32Key) {
1826 10
            return $key;
1827
        }
1828
1829 19
        if (is_array($key)) {
1830 19
            $path = $key[1];
1831 19
            $key = $key[0];
1832
1833 19
            if (!($key instanceof HierarchicalKey)) {
1834 19
                $key = HierarchicalKeyFactory::fromExtended($key);
1835
            }
1836
1837 19
            return BIP32Key::create($key, $path);
1838
        } else {
1839
            throw new \Exception("Bad Input");
1840
        }
1841
    }
1842
}
1843