Completed
Branch master (56c2f5)
by
unknown
07:05
created

WalletV2::unlock()   F

Complexity

Conditions 18
Paths 2112

Size

Total Lines 62
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 2.9749
c 0
b 0
f 0
cc 18
eloc 34
nc 2112
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Blocktrail\SDK;
4
5
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKey;
6
use BitWasp\Bitcoin\Key\Deterministic\HierarchicalKeyFactory;
7
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
8
use BitWasp\Buffertools\Buffer;
9
use Blocktrail\CryptoJSAES\CryptoJSAES;
10
use Blocktrail\SDK\Bitcoin\BIP32Key;
11
use Blocktrail\SDK\Exceptions\BlocktrailSDKException;
12
use Blocktrail\SDK\Exceptions\WalletDecryptException;
13
14
class WalletV2 extends Wallet {
15
16
    protected $encryptedPrimarySeed;
17
18
    protected $encryptedSecret;
19
20
    protected $secret = null;
21
22
    protected $primarySeed = null;
23
24
    /**
25
     * @param BlocktrailSDKInterface $sdk        SDK instance used to do requests
26
     * @param string                 $identifier identifier of the wallet
27
     * @param string                 $encryptedPrimarySeed
28
     * @param                        $encryptedSecret
29
     * @param BIP32Key[]             $primaryPublicKeys
30
     * @param BIP32Key               $backupPublicKey
31
     * @param BIP32Key[]             $blocktrailPublicKeys
32
     * @param int                    $keyIndex
33
     * @param string                 $network
34
     * @param bool                   $testnet
35
     * @param string                 $checksum
36
     */
37
    public function __construct(BlocktrailSDKInterface $sdk, $identifier, $encryptedPrimarySeed, $encryptedSecret, $primaryPublicKeys, $backupPublicKey, $blocktrailPublicKeys, $keyIndex, $network, $testnet, $checksum) {
38
        $this->encryptedPrimarySeed = $encryptedPrimarySeed;
39
        $this->encryptedSecret = $encryptedSecret;
40
41
        parent::__construct($sdk, $identifier, $primaryPublicKeys, $backupPublicKey, $blocktrailPublicKeys, $keyIndex, $network, $testnet, $checksum);
42
    }
43
44
    /**
45
     * unlock wallet so it can be used for payments
46
     *
47
     * @param          $options ['primary_private_key' => key] OR ['passphrase' => pass]
48
     * @param callable $fn
49
     * @return bool
50
     * @throws \Exception
51
     */
52
    public function unlock($options, callable $fn = null) {
53
        // explode the wallet data
54
        $password = isset($options['passphrase']) ? $options['passphrase'] : (isset($options['password']) ? $options['password'] : null);
55
        $encryptedPrimarySeed = $this->encryptedPrimarySeed;
56
        $encryptedSecret = $this->encryptedSecret;
57
        $primaryPrivateKey = isset($options['primary_private_key']) ? $options['primary_private_key'] : null;
58
59
        if (isset($options['secret'])) {
60
            $this->secret = $options['secret'];
61
        }
62
        if (isset($options['primary_seed'])) {
63
            $this->primarySeed = $options['primary_seed'];
64
        }
65
66
        if (!$primaryPrivateKey) {
67
            if (!$password) {
68
                throw new \InvalidArgumentException("Can't init wallet with Primary Seed without a passphrase");
69
            } else if (!$encryptedSecret) {
70
                throw new \InvalidArgumentException("Can't init wallet with Primary Seed without a encrypted secret");
71
            }
72
        }
73
74
        if ($primaryPrivateKey) {
75
            if (!($primaryPrivateKey instanceof HierarchicalKey) && !($primaryPrivateKey instanceof BIP32Key)) {
76
                $primaryPrivateKey = HierarchicalKeyFactory::fromExtended($primaryPrivateKey);
77
            }
78
        } else {
79
            if (!($this->secret = CryptoJSAES::decrypt($encryptedSecret, $password))) {
80
                throw new WalletDecryptException("Failed to decrypt secret with password");
81
            }
82
83
            // convert the mnemonic to a seed using BIP39 standard
84
            if (!($this->primarySeed = CryptoJSAES::decrypt($encryptedPrimarySeed, $this->secret))) {
85
                throw new WalletDecryptException("Failed to decrypt primary seed with secret");
86
            }
87
88
            $seedBuffer = new Buffer(base64_decode($this->primarySeed));
89
90
            // create BIP32 private key from the seed
91
            $primaryPrivateKey = HierarchicalKeyFactory::fromEntropy($seedBuffer);
92
        }
93
94
        $this->primaryPrivateKey = $primaryPrivateKey instanceof BIP32Key ? $primaryPrivateKey : BIP32Key::create($primaryPrivateKey, "m");
95
96
        // create checksum (address) of the primary privatekey to compare to the stored checksum
97
        $checksum = $this->primaryPrivateKey->publicKey()->getAddress()->getAddress();
98
        if ($checksum != $this->checksum) {
99
            throw new \Exception("Checksum [{$checksum}] does not match [{$this->checksum}], most likely due to incorrect password");
100
        }
101
102
        $this->locked = false;
103
104
        // if the response suggests we should upgrade to a different blocktrail cosigning key then we should
105
        if (isset($data['upgrade_key_index'])) {
0 ignored issues
show
Bug introduced by
The variable $data seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
106
            $this->upgradeKeyIndex($data['upgrade_key_index']);
107
        }
108
109
        if ($fn) {
110
            $fn($this);
111
            $this->lock();
112
        }
113
    }
114
115
    /**
116
     * lock the wallet (unsets primary private key)
117
     *
118
     * @return void
119
     */
120
    public function lock() {
121
        $this->primaryPrivateKey = null;
122
        $this->secret = null;
123
        $this->primarySeed = null;
124
        $this->locked = true;
125
    }
126
127
    /**
128
     * change password that is used to store data encrypted on server
129
     *
130
     * @param $newPassword
131
     * @return array backupInfo
132
     * @throws BlocktrailSDKException
133
     */
134
    public function passwordChange($newPassword) {
135
        if ($this->locked) {
136
            throw new BlocktrailSDKException("Wallet needs to be unlocked to change password");
137
        }
138
139
        if (!$this->secret) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->secret of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
            throw new BlocktrailSDKException("No secret");
141
        }
142
143
        $encryptedSecret = CryptoJSAES::encrypt($this->secret, $newPassword);
144
145
        $this->sdk->updateWallet($this->identifier, ['encrypted_secret' => $encryptedSecret]);
146
147
        $this->encryptedSecret = $encryptedSecret;
148
149
        return [
150
            'encrypted_secret' => MnemonicFactory::bip39()->entropyToMnemonic(new Buffer(base64_decode($this->encryptedSecret))),
151
        ];
152
    }
153
}
154