Completed
Pull Request — master (#285)
by thomas
21:56
created

InputSigner   F

Complexity

Total Complexity 90

Size/Duplication

Total Lines 512
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 28

Test Coverage

Coverage 95.05%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 90
lcom 1
cbo 28
dl 0
loc 512
ccs 269
cts 283
cp 0.9505
rs 1.3043
c 5
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
D extractFromValues() 0 39 10
C extractSignatures() 0 66 15
B calculateSignature() 0 25 2
A isFullySigned() 0 4 2
D doSignature() 0 85 14
C sign() 0 57 20
C serializeSignatures() 0 50 12
D serializeSimpleSig() 0 31 9
B sortMultiSigs() 0 24 5

How to fix   Complexity   

Complex Class

Complex classes like InputSigner often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use InputSigner, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace BitWasp\Bitcoin\Transaction\Factory;
4
5
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface;
6
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface;
7
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
8
use BitWasp\Bitcoin\Crypto\Hash;
9
use BitWasp\Bitcoin\Crypto\Random\Rfc6979;
10
use BitWasp\Bitcoin\Key\PublicKeyFactory;
11
use BitWasp\Bitcoin\Script\Classifier\OutputClassifier;
12
use BitWasp\Bitcoin\Script\Opcodes;
13
use BitWasp\Bitcoin\Script\Script;
14
use BitWasp\Bitcoin\Script\ScriptFactory;
15
use BitWasp\Bitcoin\Script\ScriptInfo\Multisig;
16
use BitWasp\Bitcoin\Script\ScriptInterface;
17
use BitWasp\Bitcoin\Script\ScriptWitness;
18
use BitWasp\Bitcoin\Signature\SignatureSort;
19
use BitWasp\Bitcoin\Signature\TransactionSignature;
20
use BitWasp\Bitcoin\Signature\TransactionSignatureFactory;
21
use BitWasp\Bitcoin\Signature\TransactionSignatureInterface;
22
use BitWasp\Bitcoin\Transaction\SignatureHash\Hasher;
23
use BitWasp\Bitcoin\Transaction\SignatureHash\SigHashInterface;
24
use BitWasp\Bitcoin\Transaction\SignatureHash\V1Hasher;
25
use BitWasp\Bitcoin\Transaction\TransactionInterface;
26
use BitWasp\Bitcoin\Transaction\TransactionOutputInterface;
27
use BitWasp\Buffertools\BufferInterface;
28
29
class InputSigner
30
{
31
    /**
32
     * @var EcAdapterInterface
33
     */
34
    private $ecAdapter;
35
36
    /**
37
     * @var ScriptInterface $redeemScript
38
     */
39
    private $redeemScript;
40
41
    /**
42
     * @var ScriptInterface $witnessScript
43
     */
44
    private $witnessScript;
45
46
    /**
47
     * @var TransactionInterface
48
     */
49
    private $tx;
50
51
    /**
52
     * @var int
53
     */
54
    private $nInput;
55
56
    /**
57
     * @var TransactionOutputInterface
58
     */
59
    private $txOut;
60
61
    /**
62
     * @var PublicKeyInterface[]
63
     */
64
    private $publicKeys = [];
65
66
    /**
67
     * @var int
68
     */
69
    private $sigHashType;
70
71
    /**
72
     * @var TransactionSignatureInterface[]
73
     */
74
    private $signatures = [];
75
76
    /**
77
     * @var int
78
     */
79
    private $requiredSigs = 0;
80
81
    /**
82
     * TxInputSigning constructor.
83
     * @param EcAdapterInterface $ecAdapter
84
     * @param TransactionInterface $tx
85
     * @param int $nInput
86
     * @param TransactionOutputInterface $txOut
87
     * @param int $sigHashType
88
     */
89 84
    public function __construct(EcAdapterInterface $ecAdapter, TransactionInterface $tx, $nInput, TransactionOutputInterface $txOut, $sigHashType = SigHashInterface::ALL)
90
    {
91 84
        $this->ecAdapter = $ecAdapter;
92 84
        $this->tx = $tx;
93 84
        $this->nInput = $nInput;
94 84
        $this->txOut = $txOut;
95 84
        $this->sigHashType = $sigHashType;
96 84
        $this->publicKeys = [];
97 84
        $this->signatures = [];
98
99 84
        $this->extractSignatures();
100 84
    }
101
102
    /**
103
     * @param int $sigVersion
104
     * @param $stack
105
     * @param ScriptInterface $scriptCode
106
     * @return \SplObjectStorage
107
     */
108 24
    private function sortMultiSigs($sigVersion, $stack, ScriptInterface $scriptCode)
109
    {
110 24
        if ($sigVersion === 1) {
111 12
            $hasher = new V1Hasher($this->tx, $this->txOut->getValue());
112 12
        } else {
113 12
            $hasher = new Hasher($this->tx);
114
        }
115
116 24
        $sigSort = new SignatureSort($this->ecAdapter);
117 24
        $sigs = new \SplObjectStorage;
118
119 24
        foreach ($stack as $txSig) {
120
            $hash = $hasher->calculate($scriptCode, $this->nInput, $txSig->getHashType());
121
            $linked = $sigSort->link([$txSig->getSignature()], $this->publicKeys, $hash);
122
123
            foreach ($this->publicKeys as $key) {
124
                if ($linked->contains($key)) {
125 6
                    $sigs[$key] = $txSig;
126
                }
127
            }
128 24
        }
129
130 24
        return $sigs;
131
    }
132
133
    /**
134
     * @param string $type
135
     * @param ScriptInterface $scriptCode
136
     * @param BufferInterface[] $stack
137
     * @param int $sigVersion
138
     * @return string
139
     */
140 84
    public function extractFromValues($type, ScriptInterface $scriptCode, array $stack, $sigVersion)
141
    {
142 72
        $size = count($stack);
143 84
        if ($type === OutputClassifier::PAYTOPUBKEYHASH) {
144 30
            $this->requiredSigs = 1;
145 30
            if ($size === 2) {
146 12
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
147 12
                $this->publicKeys = [PublicKeyFactory::fromHex($stack[1], $this->ecAdapter)];
148 12
            }
149 30
        }
150
151 72
        if ($type === OutputClassifier::PAYTOPUBKEY) {
152 12
            $this->requiredSigs = 1;
153 12
            if ($size === 1) {
154 6
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
155 6
            }
156 12
        }
157
158 72
        if ($type === OutputClassifier::MULTISIG) {
159 24
            $info = new Multisig($scriptCode);
160 24
            $this->requiredSigs = $info->getRequiredSigCount();
161 24
            $this->publicKeys = $info->getKeys();
162
163 24
            if ($size > 1) {
164 24
                $vars = [];
165 24
                foreach (array_slice($stack, 1, -1) as $sig) {
166
                    $vars[] = TransactionSignatureFactory::fromHex($sig, $this->ecAdapter);
167 24
                }
168
169 24
                $sigs = $this->sortMultiSigs($sigVersion, $vars, $scriptCode);
170
171 24
                foreach ($this->publicKeys as $idx => $key) {
172 24
                    $this->signatures[$idx] = isset($sigs[$key]) ? $sigs[$key]->getBuffer() : null;
173 24
                }
174 24
            }
175 24
        }
176
177 72
        return $type;
178
    }
179
180
    /**
181
     * @return $this
182
     */
183 84
    public function extractSignatures()
184
    {
185 84
        $type = (new OutputClassifier($this->txOut->getScript()))->classify();
186 84
        $scriptPubKey = $this->txOut->getScript();
187 84
        $scriptSig = $this->tx->getInput($this->nInput)->getScript();
188
189 84
        if ($type === OutputClassifier::PAYTOPUBKEYHASH || $type === OutputClassifier::PAYTOPUBKEY || $type === OutputClassifier::MULTISIG) {
190 42
            $values = [];
191 42
            foreach ($scriptSig->getScriptParser()->decode() as $o) {
192 18
                $values[] = $o->getData();
193 42
            }
194
195 42
            $this->extractFromValues($type, $scriptPubKey, $values, 0);
196 42
        }
197
198 84
        if ($type === OutputClassifier::PAYTOSCRIPTHASH) {
199 24
            $decodeSig = $scriptSig->getScriptParser()->decode();
200 24
            if (count($decodeSig) > 0) {
201 18
                $redeemScript = new Script(end($decodeSig)->getData());
202 18
                $p2shType = (new OutputClassifier($redeemScript))->classify();
203
204 18
                if (count($decodeSig) > 1) {
205 6
                    $decodeSig = array_slice($decodeSig, 0, -1);
206 6
                }
207
208 18
                $internalSig = [];
209 18
                foreach ($decodeSig as $operation) {
210 18
                    $internalSig[] = $operation->getData();
211 18
                }
212
213 18
                $this->redeemScript = $redeemScript;
214 18
                $this->extractFromValues($p2shType, $redeemScript, $internalSig, 0);
215
216 18
                $type = $p2shType;
217 18
            }
218 24
        }
219
220 84
        $witnesses = $this->tx->getWitnesses();
221 84
        if ($type === OutputClassifier::WITNESS_V0_KEYHASH) {
222 12
            $this->requiredSigs = 1;
223 12
            if (isset($witnesses[$this->nInput])) {
224 12
                $witness = $witnesses[$this->nInput];
225 12
                $this->signatures = [TransactionSignatureFactory::fromHex($witness[0], $this->ecAdapter)];
226 12
                $this->publicKeys = [PublicKeyFactory::fromHex($witness[1], $this->ecAdapter)];
227 12
            }
228
229 84
        } else if ($type === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
230 18
            if (isset($witnesses[$this->nInput])) {
231 18
                $witness = $witnesses[$this->nInput];
232 18
                $witCount = count($witnesses[$this->nInput]);
233 18
                if ($witCount > 0) {
234 18
                    $witnessScript = new Script($witness[$witCount - 1]);
235 18
                    $vWitness = $witness->all();
236 18
                    if (count($vWitness) > 1) {
237 18
                        $vWitness = array_slice($witness->all(), 0, -1);
238 18
                    }
239
240 18
                    $witnessType = (new OutputClassifier($witnessScript))->classify();
241 18
                    $this->extractFromValues($witnessType, $witnessScript, $vWitness, 1);
242 18
                    $this->witnessScript = $witnessScript;
243 18
                }
244 18
            }
245 18
        }
246
247 84
        return $this;
248
    }
249
250
    /**
251
     * @param PrivateKeyInterface $key
252
     * @param ScriptInterface $scriptCode
253
     * @param int $sigVersion
254
     * @return TransactionSignature
255
     */
256 84
    public function calculateSignature(PrivateKeyInterface $key, ScriptInterface $scriptCode, $sigVersion)
257
    {
258 84
        if ($sigVersion == 1) {
259 30
            $hasher = new V1Hasher($this->tx, $this->txOut->getValue());
260 30
        } else {
261 54
            $hasher = new Hasher($this->tx);
262
        }
263
264 84
        $hash = $hasher->calculate($scriptCode, $this->nInput, $this->sigHashType);
265
266 84
        return new TransactionSignature(
267 84
            $this->ecAdapter,
268 84
            $this->ecAdapter->sign(
269 84
                $hash,
270 84
                $key,
271 84
                new Rfc6979(
272 84
                    $this->ecAdapter,
273 84
                    $key,
274 84
                    $hash,
275
                    'sha256'
276 84
                )
277 84
            ),
278 84
            $this->sigHashType
279 84
        );
280
    }
281
282
    /**
283
     * @return bool
284
     */
285 78
    public function isFullySigned()
286
    {
287 78
        return $this->requiredSigs !== 0 && $this->requiredSigs === count($this->signatures);
288
    }
289
290
    /**
291
     * The function only returns true when $scriptPubKey could be classified
292
     *
293
     * @param PrivateKeyInterface $key
294
     * @param ScriptInterface $scriptPubKey
295
     * @param string $outputType
296
     * @param BufferInterface[] $results
297
     * @param int $sigVersion
298
     * @return bool
299
     */
300 84
    private function doSignature(PrivateKeyInterface $key, ScriptInterface $scriptPubKey, &$outputType, array &$results, $sigVersion = 0)
301
    {
302 84
        $return = [];
303 84
        $outputType = (new OutputClassifier($scriptPubKey))->classify($return);
304 84
        if ($outputType === OutputClassifier::UNKNOWN) {
305
            throw new \RuntimeException('Cannot sign unknown script type');
306
        }
307
308 84
        if ($outputType === OutputClassifier::PAYTOPUBKEY) {
309 12
            $publicKeyBuffer = $return;
310 12
            $results[] = $publicKeyBuffer;
311 12
            $this->requiredSigs = 1;
312 12
            $publicKey = PublicKeyFactory::fromHex($publicKeyBuffer);
0 ignored issues
show
Bug introduced by
It seems like $publicKeyBuffer defined by $return on line 309 can also be of type array<integer,object<Bit...tools\BufferInterface>> or null; however, BitWasp\Bitcoin\Key\PublicKeyFactory::fromHex() does only seem to accept object<BitWasp\Buffertoo...BufferInterface>|string, 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...
313
314 12
            if ($publicKey->getBinary() === $key->getPublicKey()->getBinary()) {
315 12
                $this->signatures[0] = $this->calculateSignature($key, $scriptPubKey, $sigVersion);
316 12
            }
317
318 12
            return true;
319
        }
320
321 72
        if ($outputType === OutputClassifier::PAYTOPUBKEYHASH) {
322
            /** @var BufferInterface $pubKeyHash */
323 42
            $pubKeyHash = $return;
324 42
            $results[] = $pubKeyHash;
325 42
            $this->requiredSigs = 1;
326 42
            if ($pubKeyHash->getBinary() === $key->getPublicKey()->getPubKeyHash()->getBinary()) {
327 36
                $this->signatures[0] = $this->calculateSignature($key, $scriptPubKey, $sigVersion);
328 36
                $this->publicKeys[0] = $key->getPublicKey();
329 36
            }
330
331 42
            return true;
332
        }
333
334 48
        if ($outputType === OutputClassifier::MULTISIG) {
335 30
            $info = new Multisig($scriptPubKey);
336
337 30
            foreach ($info->getKeys() as $publicKey) {
338 30
                $results[] = $publicKey->getBuffer();
339 30
            }
340
341 30
            $this->publicKeys = $info->getKeys();
342 30
            $this->requiredSigs = $info->getKeyCount();
343
344 30
            foreach ($this->publicKeys as $keyIdx => $publicKey) {
345 30
                if ($publicKey->getBinary() == $key->getPublicKey()->getBinary()) {
346 30
                    $this->signatures[$keyIdx] = $this->calculateSignature($key, $scriptPubKey, $sigVersion);
347 30
                }
348 30
            }
349
350 30
            return true;
351
        }
352
353 42
        if ($outputType === OutputClassifier::PAYTOSCRIPTHASH) {
354
            /** @var BufferInterface $scriptHash */
355 24
            $scriptHash = $return;
356 24
            $results[] = $scriptHash;
357 24
            return true;
358
        }
359
360 30
        if ($outputType === OutputClassifier::WITNESS_V0_KEYHASH) {
361
            /** @var BufferInterface $pubKeyHash */
362 12
            $pubKeyHash = $return;
363 12
            $results[] = $pubKeyHash;
364 12
            $this->requiredSigs = 1;
365
366 12
            if ($pubKeyHash->getBinary() === $key->getPublicKey()->getPubKeyHash()->getBinary()) {
367 12
                $script = ScriptFactory::sequence([Opcodes::OP_DUP, Opcodes::OP_HASH160, $pubKeyHash, Opcodes::OP_EQUALVERIFY, Opcodes::OP_CHECKSIG]);
368 12
                $this->signatures[0] = $this->calculateSignature($key, $script, 1);
369 12
                $this->publicKeys[0] = $key->getPublicKey();
370 12
            }
371
372 12
            return true;
373
        }
374
375 18
        if ($outputType === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
376
            /** @var BufferInterface $scriptHash */
377 18
            $scriptHash = $return;
378 18
            $results[] = $scriptHash;
379
380 18
            return true;
381
        }
382
383
        return false;
384
    }
385
386
    /**
387
     * @param PrivateKeyInterface $key
388
     * @param ScriptInterface|null $redeemScript
389
     * @param ScriptInterface|null $witnessScript
390
     * @return bool
391
     */
392 84
    public function sign(PrivateKeyInterface $key, ScriptInterface $redeemScript = null, ScriptInterface $witnessScript = null)
393
    {
394
        /** @var BufferInterface[] $return */
395 84
        $type = null;
396 84
        $return = [];
397 84
        $solved = $this->doSignature($key, $this->txOut->getScript(), $type, $return, 0);
398
399 84
        if ($solved && $type === OutputClassifier::PAYTOSCRIPTHASH) {
400 24
            $redeemScriptBuffer = $return[0];
401
402 24
            if (!$redeemScript instanceof ScriptInterface) {
403
                throw new \InvalidArgumentException('Must provide redeem script for P2SH');
404
            }
405
406 24
            if (!$redeemScript->getScriptHash()->getBinary() === $redeemScriptBuffer->getBinary()) {
407
                throw new \InvalidArgumentException("Incorrect redeem script - hash doesn't match");
408
            }
409
410 24
            $results = []; // ???
411 24
            $solved = $solved && $this->doSignature($key, $redeemScript, $type, $results, 0) && $type !== OutputClassifier::PAYTOSCRIPTHASH;
412 24
            if ($solved) {
413 24
                $this->redeemScript = $redeemScript;
414 24
            }
415 24
        }
416
417 84
        if ($solved && $type === OutputClassifier::WITNESS_V0_KEYHASH) {
418 12
            $pubKeyHash = $return[0];
419 12
            $witnessScript = ScriptFactory::sequence([Opcodes::OP_DUP, Opcodes::OP_HASH160, $pubKeyHash, Opcodes::OP_EQUALVERIFY, Opcodes::OP_CHECKSIG]);
420 12
            $subType = null;
421 12
            $subResults = [];
422 12
            $solved = $solved && $this->doSignature($key, $witnessScript, $subType, $subResults, 1);
423 84
        } else if ($solved && $type === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
424 18
            $scriptHash = $return[0];
425
426 18
            if (!$witnessScript instanceof ScriptInterface) {
427
                throw new \InvalidArgumentException('Must provide witness script for witness v0 scripthash');
428
            }
429
430 18
            if (!Hash::sha256($witnessScript->getBuffer())->getBinary() === $scriptHash->getBinary()) {
431
                throw new \InvalidArgumentException("Incorrect witness script - hash doesn't match");
432
            }
433
434 18
            $subType = null;
435 18
            $subResults = [];
436
437 18
            $solved = $solved && $this->doSignature($key, $witnessScript, $subType, $subResults, 1)
438 18
                && $subType !== OutputClassifier::PAYTOSCRIPTHASH
439 18
                && $subType !== OutputClassifier::WITNESS_V0_SCRIPTHASH
440 18
                && $subType !== OutputClassifier::WITNESS_V0_KEYHASH;
441
442 18
            if ($solved) {
443 18
                $this->witnessScript = $witnessScript;
444 18
            }
445 18
        }
446
447 84
        return $solved;
448
    }
449
450
    /**
451
     * @param string $outputType
452
     * @param $answer
453
     * @return bool
454
     */
455 84
    private function serializeSimpleSig($outputType, &$answer)
456
    {
457 84
        if ($outputType === OutputClassifier::UNKNOWN) {
458
            throw new \RuntimeException('Cannot sign unknown script type');
459
        }
460
461 84
        if ($outputType === OutputClassifier::PAYTOPUBKEY && $this->isFullySigned()) {
462 12
            $answer = new SigValues(ScriptFactory::sequence([$this->signatures[0]->getBuffer()]), new ScriptWitness([]));
463 12
            return true;
464
        }
465
466 72
        if ($outputType === OutputClassifier::PAYTOPUBKEYHASH && $this->isFullySigned()) {
467 30
            $answer = new SigValues(ScriptFactory::sequence([$this->signatures[0]->getBuffer(), $this->publicKeys[0]->getBuffer()]), new ScriptWitness([]));
468 30
            return true;
469
        }
470
471 48
        if ($outputType === OutputClassifier::MULTISIG) {
472 30
            $sequence = [Opcodes::OP_0];
473 30
            $nPubKeys = count($this->publicKeys);
474 30
            for ($i = 0; $i < $nPubKeys; $i++) {
475 30
                if (isset($this->signatures[$i])) {
476 30
                    $sequence[] = $this->signatures[$i]->getBuffer();
477 30
                }
478 30
            }
479
480 30
            $answer = new SigValues(ScriptFactory::sequence($sequence), new ScriptWitness([]));
481 30
            return true;
482
        }
483
484 42
        return false;
485
    }
486
487
    /**
488
     * @return SigValues
489
     */
490 84
    public function serializeSignatures()
491
    {
492 84
        static $emptyScript = null;
493 84
        static $emptyWitness = null;
494 84
        if (is_null($emptyScript) || is_null($emptyWitness)) {
495 6
            $emptyScript = new Script();
496 6
            $emptyWitness = new ScriptWitness([]);
497 6
        }
498
499
        /** @var BufferInterface[] $return */
500 84
        $outputType = (new OutputClassifier($this->txOut->getScript()))->classify();
501
502
        /** @var SigValues $answer */
503 84
        $answer = new SigValues($emptyScript, $emptyWitness);
504 84
        $serialized = $this->serializeSimpleSig($outputType, $answer);
505
506 84
        $p2sh = false;
507 84
        if (!$serialized && $outputType === OutputClassifier::PAYTOSCRIPTHASH) {
508 24
            $p2sh = true;
509 24
            $outputType = (new OutputClassifier($this->redeemScript))->classify();
510 24
            $serialized = $this->serializeSimpleSig($outputType, $answer);
511 24
        }
512
513 84
        if (!$serialized && $outputType === OutputClassifier::WITNESS_V0_KEYHASH) {
514 12
            $answer = new SigValues($emptyScript, new ScriptWitness([$this->signatures[0]->getBuffer(), $this->publicKeys[0]->getBuffer()]));
515
516 84
        } else if (!$serialized && $outputType === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
517 18
            $outputType = (new OutputClassifier($this->witnessScript))->classify();
518 18
            $serialized = $this->serializeSimpleSig($outputType, $answer);
519
520 18
            if ($serialized) {
521 18
                $data = [];
522 18
                foreach ($answer->getScriptSig()->getScriptParser()->decode() as $o) {
523 18
                    $data[] = $o->getData();
524 18
                }
525
526 18
                $data[] = $this->witnessScript->getBuffer();
527 18
                $answer = new SigValues($emptyScript, new ScriptWitness($data));
528 18
            }
529 18
        }
530
531 84
        if ($p2sh) {
532 24
            $answer = new SigValues(
533 24
                ScriptFactory::create($answer->getScriptSig()->getBuffer())->push($this->redeemScript->getBuffer())->getScript(),
534 24
                $answer->getScriptWitness()
535 24
            );
536 24
        }
537
538 84
        return $answer;
539
    }
540
}
541