Completed
Pull Request — master (#662)
by thomas
22:19 queued 14:15
created

HierarchicalKey::derivePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Bitcoin\Key\Deterministic;
6
7
use BitWasp\Bitcoin\Address\BaseAddressCreator;
8
use BitWasp\Bitcoin\Bitcoin;
9
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface;
10
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\KeyInterface;
11
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface;
12
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
13
use BitWasp\Bitcoin\Crypto\Hash;
14
use BitWasp\Bitcoin\Key\KeyToScript\ScriptAndSignData;
15
use BitWasp\Bitcoin\Key\KeyToScript\ScriptDataFactory;
16
use BitWasp\Bitcoin\Network\NetworkInterface;
17
use BitWasp\Bitcoin\Serializer\Key\HierarchicalKey\Base58ExtendedKeySerializer;
18
use BitWasp\Bitcoin\Serializer\Key\HierarchicalKey\ExtendedKeySerializer;
19
use BitWasp\Bitcoin\Util\IntRange;
20
use BitWasp\Buffertools\Buffer;
21
use BitWasp\Buffertools\BufferInterface;
22
23
class HierarchicalKey
24
{
25
    /**
26
     * @var EcAdapterInterface
27
     */
28
    protected $ecAdapter;
29
30
    /**
31
     * @var int
32
     */
33
    private $depth;
34
35
    /**
36
     * @var int
37
     */
38
    private $parentFingerprint;
39
40
    /**
41
     * @var int
42
     */
43
    private $sequence;
44
45
    /**
46
     * @var BufferInterface
47
     */
48
    private $chainCode;
49
50
    /**
51
     * @var KeyInterface
52
     */
53
    private $key;
54
55
    /**
56
     * @var ScriptDataFactory
57
     */
58
    private $scriptDataFactory;
59
60
    /**
61
     * @var ScriptAndSignData|null
62
     */
63
    private $scriptAndSignData;
64
65
    /**
66
     * @param EcAdapterInterface $ecAdapter
67
     * @param ScriptDataFactory $scriptDataFactory
68
     * @param int $depth
69
     * @param int $parentFingerprint
70
     * @param int $sequence
71
     * @param BufferInterface $chainCode
72
     * @param KeyInterface $key
73
     */
74 71
    public function __construct(EcAdapterInterface $ecAdapter, ScriptDataFactory $scriptDataFactory, int $depth, int $parentFingerprint, int $sequence, BufferInterface $chainCode, KeyInterface $key)
75
    {
76 71
        if ($depth < 0 || $depth > IntRange::U8_MAX) {
77
            throw new \InvalidArgumentException('Invalid depth for BIP32 key, must be in range [0 - 255] inclusive');
78
        }
79
80 71
        if ($parentFingerprint < 0 || $parentFingerprint > IntRange::U32_MAX) {
81
            throw new \InvalidArgumentException('Invalid fingerprint for BIP32 key, must be in range [0 - (2^31)-1] inclusive');
82
        }
83
84 71
        if ($sequence < 0 || $sequence > IntRange::U32_MAX) {
85
            throw new \InvalidArgumentException('Invalid sequence for BIP32 key, must be in range [0 - (2^31)-1] inclusive');
86
        }
87
88 71
        if ($chainCode->getSize() !== 32) {
89
            throw new \RuntimeException('Chaincode should be 32 bytes');
90
        }
91
92 71
        if (!$key->isCompressed()) {
93 1
            throw new \InvalidArgumentException('A HierarchicalKey must always be compressed');
94
        }
95
96 70
        $this->ecAdapter = $ecAdapter;
97 70
        $this->depth = $depth;
98 70
        $this->sequence = $sequence;
99 70
        $this->parentFingerprint = $parentFingerprint;
100 70
        $this->chainCode = $chainCode;
101 70
        $this->key = $key;
102 70
        $this->scriptDataFactory = $scriptDataFactory;
103 70
    }
104
105
    /**
106
     * Return the depth of this key. This is limited to 256 sequential derivations.
107
     *
108
     * @return int
109
     */
110 30
    public function getDepth(): int
111
    {
112 30
        return $this->depth;
113
    }
114
115
    /**
116
     * Get the sequence number for this address. Hardened keys are
117
     * created with sequence > 0x80000000. a sequence number lower
118
     * than this can be derived with the public key.
119
     *
120
     * @return int
121
     */
122 25
    public function getSequence(): int
123
    {
124 25
        return $this->sequence;
125
    }
126
127
    /**
128
     * Get the fingerprint of the parent key. For master keys, this is 00000000.
129
     *
130
     * @return int
131
     */
132 26
    public function getFingerprint(): int
133
    {
134 26
        if ($this->getDepth() === 0) {
135 14
            return 0;
136
        }
137
138 22
        return $this->parentFingerprint;
139
    }
140
141
    /**
142
     * Return the fingerprint to be used for child keys.
143
     * @return int
144
     */
145 33
    public function getChildFingerprint(): int
146
    {
147 33
        $pubKeyHash = $this->getPublicKey()->getPubKeyHash();
148 33
        return (int) $pubKeyHash->slice(0, 4)->getInt();
149
    }
150
151
    /**
152
     * Return the chain code - a deterministic 'salt' for HMAC-SHA512
153
     * in child derivations
154
     *
155
     * @return BufferInterface
156
     */
157 24
    public function getChainCode(): BufferInterface
158
    {
159 24
        return $this->chainCode;
160
    }
161
162
    /**
163
     * @return PrivateKeyInterface
164
     */
165 42
    public function getPrivateKey(): PrivateKeyInterface
166
    {
167 42
        if ($this->key->isPrivate()) {
168
            /** @var PrivateKeyInterface $key */
169 40
            $key = $this->key;
170 40
            return $key;
171
        }
172
173 2
        throw new \RuntimeException('Unable to get private key, not known');
174
    }
175
176
    /**
177
     * Get the public key the private key or public key.
178
     *
179
     * @return PublicKeyInterface
180
     */
181 44
    public function getPublicKey(): PublicKeyInterface
182
    {
183 44
        if ($this->isPrivate()) {
184 36
            return $this->getPrivateKey()->getPublicKey();
185
        } else {
186
            /** @var PublicKeyInterface $key */
187 27
            $key = $this->key;
188 27
            return $key;
189
        }
190
    }
191
192
    /**
193
     * @return HierarchicalKey
194
     */
195 21
    public function withoutPrivateKey(): HierarchicalKey
196
    {
197 21
        $clone = clone $this;
198 21
        $clone->key = $clone->getPublicKey();
199 21
        return $clone;
200
    }
201
202
    /**
203
     * @param ScriptDataFactory $factory
204
     * @return HierarchicalKey
205
     */
206 1
    public function withScriptFactory(ScriptDataFactory $factory)
207
    {
208 1
        $clone = clone $this;
209 1
        $clone->scriptDataFactory = $factory;
210 1
        $clone->scriptAndSignData = null; // we cache, don't forget to clear
211 1
        return $clone;
212
    }
213
214
    /**
215
     * @return ScriptDataFactory
216
     */
217 24
    public function getScriptDataFactory()
218
    {
219 24
        return $this->scriptDataFactory;
220
    }
221
222
    /**
223
     * @return \BitWasp\Bitcoin\Key\KeyToScript\ScriptAndSignData
224
     */
225 19
    public function getScriptAndSignData()
226
    {
227 19
        if (null === $this->scriptAndSignData) {
228 19
            $this->scriptAndSignData = $this->scriptDataFactory->convertKey($this->key);
229
        }
230
231 19
        return $this->scriptAndSignData;
232
    }
233
234
    /**
235
     * @param BaseAddressCreator $addressCreator
236
     * @return \BitWasp\Bitcoin\Address\Address
237
     */
238 13
    public function getAddress(BaseAddressCreator $addressCreator)
239
    {
240 13
        return $this->getScriptAndSignData()->getAddress($addressCreator);
241
    }
242
243
    /**
244
     * Return whether this is a private key
245
     *
246
     * @return bool
247
     */
248 48
    public function isPrivate(): bool
249
    {
250 48
        return $this->key->isPrivate();
251
    }
252
253
    /**
254
     * Return whether the key is hardened
255
     *
256
     * @return bool
257
     */
258 2
    public function isHardened(): bool
259
    {
260 2
        return ($this->sequence >> 31) === 1;
261
    }
262
263
    /**
264
     * Create a buffer containing data to be hashed hashed to yield the child offset
265
     *
266
     * @param int $sequence
267
     * @return BufferInterface
268
     * @throws \Exception
269
     */
270 39
    public function getHmacSeed(int $sequence): BufferInterface
271
    {
272 39
        if ($sequence < 0 || $sequence > IntRange::U32_MAX) {
273 6
            throw new \InvalidArgumentException("Sequence is outside valid range, must be >= 0 && <= (2^31)-1");
274
        }
275
276 33
        if (($sequence >> 31) === 1) {
277 30
            if ($this->isPrivate() === false) {
278 2
                throw new \Exception("Can't derive a hardened key without the private key");
279
            }
280
281 28
            $data = "\x00{$this->getPrivateKey()->getBinary()}";
282
        } else {
283 31
            $data = $this->getPublicKey()->getBinary();
284
        }
285
286 31
        return new Buffer($data . pack("N", $sequence));
287
    }
288
289
    /**
290
     * Derive a child key
291
     *
292
     * @param int $sequence
293
     * @return HierarchicalKey
294
     * @throws \Exception
295
     */
296 36
    public function deriveChild(int $sequence): HierarchicalKey
297
    {
298 36
        $nextDepth = $this->depth + 1;
299 36
        if ($nextDepth > 255) {
300
            throw new \InvalidArgumentException('Invalid depth for BIP32 key, cannot exceed 255');
301
        }
302
303 36
        $hash = Hash::hmac('sha512', $this->getHmacSeed($sequence), $this->chainCode);
304 31
        $offset = $hash->slice(0, 32);
305 31
        $chain = $hash->slice(32);
306
307 31
        if (false === $this->ecAdapter->validatePrivateKey($offset)) {
308 1
            return $this->deriveChild($sequence + 1);
309
        }
310
311 31
        $key = $this->isPrivate() ? $this->getPrivateKey() : $this->getPublicKey();
312 31
        $key = $key->tweakAdd($offset->getGmp());
313
314 31
        return new HierarchicalKey(
315 31
            $this->ecAdapter,
316 31
            $this->scriptDataFactory,
317 31
            $nextDepth,
318 31
            $this->getChildFingerprint(),
319 31
            $sequence,
320 31
            $chain,
321 31
            $key
322
        );
323
    }
324
325
    /**
326
     * @param array|\stdClass|\Traversable $list
327
     * @return HierarchicalKey
328
     * @throws \Exception
329
     */
330 26
    public function deriveFromList($list): HierarchicalKey
331
    {
332 26
        if (!is_array($list) && !$list instanceof \Traversable && !$list instanceof \stdClass) {
333
            throw new \InvalidArgumentException('List must be an array or \Traversable');
334
        }
335
336 26
        $key = $this;
337 26
        foreach ($list as $sequence) {
0 ignored issues
show
Bug introduced by
The expression $list of type array|object<Traversable>|object<stdClass> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
338 26
            $key = $key->deriveChild((int) $sequence);
339
        }
340
341 26
        return $key;
342
    }
343
344
    /**
345
     * Decodes a BIP32 path into actual 32bit sequence numbers and derives the child key
346
     *
347
     * @param string $path
348
     * @return HierarchicalKey
349
     * @throws \Exception
350
     */
351 26
    public function derivePath(string $path): HierarchicalKey
352
    {
353 26
        $sequences = new HierarchicalKeySequence();
354 26
        return $this->deriveFromList($sequences->decodePath($path));
355
    }
356
357
    /**
358
     * Serializes the instance according to whether it wraps a private or public key.
359
     * @param NetworkInterface $network
360
     * @return string
361
     */
362 16
    public function toExtendedKey(NetworkInterface $network = null): string
363
    {
364 16
        $network = $network ?: Bitcoin::getNetwork();
365
366 16
        $extendedSerializer = new Base58ExtendedKeySerializer(new ExtendedKeySerializer($this->ecAdapter));
367 16
        $extended = $extendedSerializer->serialize($network, $this);
368 16
        return $extended;
369
    }
370
371
    /**
372
     * Explicitly serialize as a private key. Throws an exception if
373
     * the key isn't private.
374
     *
375
     * @param NetworkInterface $network
376
     * @return string
377
     */
378 16
    public function toExtendedPrivateKey(NetworkInterface $network = null): string
379
    {
380 16
        if (!$this->isPrivate()) {
381 2
            throw new \LogicException('Cannot create extended private key from public');
382
        }
383
384 14
        return $this->toExtendedKey($network);
385
    }
386
387
    /**
388
     * Explicitly serialize as a public key. This will always work.
389
     *
390
     * @param NetworkInterface $network
391
     * @return string
392
     */
393 13
    public function toExtendedPublicKey(NetworkInterface $network = null): string
394
    {
395 13
        return $this->withoutPrivateKey()->toExtendedKey($network);
396
    }
397
}
398