Completed
Pull Request — master (#390)
by thomas
439:52 queued 369:32
created

InputSigner::evalPushOnly()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 7
ccs 2
cts 3
cp 0.6667
crap 1.037
rs 9.4285
c 0
b 0
f 0
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\Classifier\OutputData;
13
use BitWasp\Bitcoin\Script\Interpreter\Checker;
14
use BitWasp\Bitcoin\Script\Interpreter\Interpreter;
15
use BitWasp\Bitcoin\Script\Interpreter\Stack;
16
use BitWasp\Bitcoin\Script\Opcodes;
17
use BitWasp\Bitcoin\Script\Script;
18
use BitWasp\Bitcoin\Script\ScriptFactory;
19
use BitWasp\Bitcoin\Script\ScriptInfo\Multisig;
20
use BitWasp\Bitcoin\Script\ScriptInterface;
21
use BitWasp\Bitcoin\Script\ScriptWitness;
22
use BitWasp\Bitcoin\Signature\SignatureSort;
23
use BitWasp\Bitcoin\Signature\TransactionSignature;
24
use BitWasp\Bitcoin\Signature\TransactionSignatureFactory;
25
use BitWasp\Bitcoin\Signature\TransactionSignatureInterface;
26
use BitWasp\Bitcoin\Transaction\SignatureHash\Hasher;
27
use BitWasp\Bitcoin\Transaction\SignatureHash\SigHashInterface;
28
use BitWasp\Bitcoin\Transaction\SignatureHash\V1Hasher;
29
use BitWasp\Bitcoin\Transaction\Transaction;
30
use BitWasp\Bitcoin\Transaction\TransactionInterface;
31
use BitWasp\Bitcoin\Transaction\TransactionOutputInterface;
32
use BitWasp\Buffertools\Buffer;
33
use BitWasp\Buffertools\BufferInterface;
34
35
class InputSigner
36
{
37
    /**
38
     * @var EcAdapterInterface
39
     */
40
    private $ecAdapter;
41
42
    /**
43
     * @var OutputData $scriptPubKey
44
     */
45
    private $scriptPubKey;
46
47
    /**
48
     * @var OutputData $redeemScript
49
     */
50
    private $redeemScript;
51
52
    /**
53
     * @var OutputData $witnessScript
54
     */
55
    private $witnessScript;
56
57
    /**
58
     * @var TransactionInterface
59
     */
60
    private $tx;
61
62
    /**
63
     * @var int
64
     */
65
    private $nInput;
66
67
    /**
68
     * @var TransactionOutputInterface
69
     */
70
    private $txOut;
71
72
    /**
73
     * @var PublicKeyInterface[]
74
     */
75
    private $publicKeys = [];
76
77
    /**
78
     * @var TransactionSignatureInterface[]
79
     */
80
    private $signatures = [];
81
82
    /**
83
     * @var int
84
     */
85
    private $requiredSigs = 0;
86
87
    /**
88
     * @var OutputClassifier
89
     */
90
    private $classifier;
91
92
    /**
93
     * TxInputSigning constructor.
94
     * @param EcAdapterInterface $ecAdapter
95
     * @param TransactionInterface $tx
96
     * @param int $nInput
97 84
     * @param TransactionOutputInterface $txOut
98
     * @param SignData $signData
99 84
     */
100 84
    public function __construct(EcAdapterInterface $ecAdapter, TransactionInterface $tx, $nInput, TransactionOutputInterface $txOut, SignData $signData)
101 84
    {
102 84
        $this->ecAdapter = $ecAdapter;
103 84
        $this->tx = $tx;
104 84
        $this->nInput = $nInput;
105 84
        $this->txOut = $txOut;
106
        $this->classifier = new OutputClassifier();
107 84
        $this->publicKeys = [];
108 84
        $this->signatures = [];
109 84
110
        $this->solve($signData);
111
        $this->extractSignatures();
112
    }
113
114
    /**
115
     * @param int $sigVersion
116
     * @param TransactionSignatureInterface[] $stack
117 24
     * @param ScriptInterface $scriptCode
118
     * @return \SplObjectStorage
119 24
     */
120 24
    private function sortMultiSigs($sigVersion, $stack, ScriptInterface $scriptCode)
121
    {
122 24
        $sigSort = new SignatureSort($this->ecAdapter);
123
        $sigs = new \SplObjectStorage;
124
125
        foreach ($stack as $txSig) {
126
            $hash = $this->calculateSigHash($scriptCode, $txSig->getHashType(), $sigVersion);
127
            $linked = $sigSort->link([$txSig->getSignature()], $this->publicKeys, $hash);
128
            foreach ($this->publicKeys as $key) {
129
                if ($linked->contains($key)) {
130 8
                    $sigs[$key] = $txSig;
131
                }
132 24
            }
133
        }
134
135
        return $sigs;
136
    }
137
138
    /**
139
     * @param string $type
140
     * @param ScriptInterface $scriptCode
141
     * @param BufferInterface[] $stack
142 78
     * @param int $sigVersion
143
     * @return string
144 78
     */
145 78
    public function extractFromValues($type, ScriptInterface $scriptCode, array $stack, $sigVersion)
146 42
    {
147 42
        $size = count($stack);
148 24
        if ($type === OutputClassifier::PAYTOPUBKEYHASH) {
149 24
            $this->requiredSigs = 1;
150 8
            if ($size === 2) {
151 14
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
152
                $this->publicKeys = [PublicKeyFactory::fromHex($stack[1], $this->ecAdapter)];
153 78
            }
154 12
        }
155 12
156 6
        if ($type === OutputClassifier::PAYTOPUBKEY) {
157 2
            $this->requiredSigs = 1;
158 4
            if ($size === 1) {
159
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
160 78
            }
161 24
        }
162 24
163 24
        if ($type === OutputClassifier::MULTISIG) {
164
            $info = new Multisig($scriptCode);
165 24
            $this->requiredSigs = $info->getRequiredSigCount();
166 24
            $this->publicKeys = $info->getKeys();
167 24
168
            if ($size > 1) {
169
                $vars = [];
170
                for ($i = 1, $j = $size - 1; $i < $j; $i++) {
171 24
                    $vars[] = TransactionSignatureFactory::fromHex($stack[$i], $this->ecAdapter);
172 24
                }
173 24
174 8
                $sigs = $this->sortMultiSigs($sigVersion, $vars, $scriptCode);
175 8
                foreach ($this->publicKeys as $idx => $key) {
176 8
                    $this->signatures[$idx] = isset($sigs[$key]) ? $sigs[$key]->getBuffer() : null;
177
                }
178 78
            }
179
        }
180
181
        return $type;
182
    }
183
184
    /**
185
     * @param SignData $signData
186 84
     * @return $this
187
     * @throws \Exception
188 84
     */
189 84
    private function solve(SignData $signData)
190 84
    {
191
        $scriptPubKey = $this->txOut->getScript();
192
        $solution = $this->scriptPubKey = $this->classifier->decode($scriptPubKey);
193
        if ($solution->getType() === OutputClassifier::UNKNOWN) {
194 84
            throw new \RuntimeException('scriptPubKey type is unknown');
195 24
        }
196 24
197
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
198
            $redeemScript = $signData->getRedeemScript();
199 24
            if (!$solution->getSolution()->equals(Hash::sha256ripe160($redeemScript->getBuffer()))) {
200 24
                throw new \Exception('Redeem script doesn\'t match script-hash');
201
            }
202
            $solution = $this->redeemScript = $this->classifier->decode($redeemScript);
203 8
            if (!in_array($solution->getType(), [OutputClassifier::WITNESS_V0_SCRIPTHASH, OutputClassifier::WITNESS_V0_KEYHASH, OutputClassifier::PAYTOPUBKEYHASH , OutputClassifier::PAYTOPUBKEY, OutputClassifier::MULTISIG])) {
204
                throw new \Exception('Unsupported pay-to-script-hash script');
205 84
            }
206 18
        }
207 18
        // WitnessKeyHash doesn't require further solving until signing
208
        if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
209
            $witnessScript = $signData->getWitnessScript();
210 18
            if (!$solution->getSolution()->equals(Hash::sha256($witnessScript->getBuffer()))) {
211 18
                throw new \Exception('Witness script doesn\'t match witness-script-hash');
212
            }
213
            $solution = $this->witnessScript = $this->classifier->decode($witnessScript);
214 6
            if (!in_array($solution->getType(), [OutputClassifier::PAYTOPUBKEYHASH , OutputClassifier::PAYTOPUBKEY, OutputClassifier::MULTISIG])) {
215
                throw new \Exception('Unsupported witness-script-hash script');
216 84
            }
217
        }
218
219
        return $this;
220
    }
221
222 84
    /**
223
     * @return $this
224 84
     */
225 84
    public function extractSignatures()
226 84
    {
227 42
        $solution = $this->scriptPubKey;
228 42
        $scriptSig = $this->tx->getInput($this->nInput)->getScript();
229 18
        if (in_array($solution->getType(), [OutputClassifier::PAYTOPUBKEYHASH , OutputClassifier::PAYTOPUBKEY, OutputClassifier::MULTISIG])) {
230 14
            $this->extractFromValues($solution->getType(), $solution->getScript(), $this->evalPushOnly($scriptSig), 0);
231 42
        }
232 14
233
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
234 84
            $stack = $this->evalPushOnly($scriptSig);
235 24
            if (count($stack) > 0) {
236 24
                $redeemScript = new Script(end($stack));
0 ignored issues
show
Security Bug introduced by
It seems like end($stack) targeting end() can also be of type false; however, BitWasp\Bitcoin\Script\Script::__construct() does only seem to accept null|object<BitWasp\Buffertools\BufferInterface>, did you maybe forget to handle an error condition?
Loading history...
237 18
                if (!$redeemScript->getBuffer()->equals($this->redeemScript->getScript()->getBuffer())) {
0 ignored issues
show
Documentation introduced by
$this->redeemScript->getScript()->getBuffer() is of type object<BitWasp\Buffertools\Buffer>, but the function expects a object<self>.

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...
238 18
                    throw new \RuntimeException('Redeem script from scriptSig doesn\'t match script-hash');
239
                }
240
241
                $solution = $this->redeemScript;
242 18
                $this->extractFromValues($solution->getType(), $solution->getScript(), array_slice($stack, 0, -1), 0);
243 18
            }
244
        }
245 6
246 6
        $witnesses = $this->tx->getWitnesses();
247
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
248 18
            $wit = isset($witnesses[$this->nInput]) ? $witnesses[$this->nInput]->all() : [];
249 18
            $keyHashCode = ScriptFactory::scriptPubKey()->payToPubKeyHashFromHash($solution->getSolution());
250 6
            $this->extractFromValues(OutputClassifier::PAYTOPUBKEYHASH, $keyHashCode, $wit, 1);
251 8
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
252
            if (isset($witnesses[$this->nInput])) {
253 84
                $witness = $witnesses[$this->nInput];
254 84
                $witCount = count($witnesses[$this->nInput]);
255 12
                if ($witCount > 0) {
256 12
                    if (!$witness[$witCount - 1]->equals($this->witnessScript->getScript()->getBuffer())) {
257 12
                        throw new \RuntimeException('Redeem script from scriptSig doesn\'t match script-hash');
258 80
                    }
259 18
260 18
                    $solution = $this->witnessScript;
261 18
                    $this->extractFromValues($solution->getType(), $solution->getScript(), array_slice($witness->all(), 0, -1), 1);
262 18
                }
263 18
            }
264
        }
265
266
        return $this;
267 18
    }
268 18
269 6
    /**
270 6
     * @param ScriptInterface $scriptCode
271 6
     * @param int $sigHashType
272
     * @param int $sigVersion
273 84
     * @return BufferInterface
274
     */
275
    public function calculateSigHash(ScriptInterface $scriptCode, $sigHashType, $sigVersion)
276
    {
277
        if ($sigVersion === 1) {
278
            $hasher = new V1Hasher($this->tx, $this->txOut->getValue());
279
        } else {
280
            $hasher = new Hasher($this->tx);
281
        }
282 84
283
        return $hasher->calculate($scriptCode, $this->nInput, $sigHashType);
284 84
    }
285 30
286 10
    /**
287 54
     * @param PrivateKeyInterface $key
288
     * @param ScriptInterface $scriptCode
289
     * @param int $sigHashType
290 84
     * @param int $sigVersion
291
     * @return TransactionSignature
292
     */
293
    public function calculateSignature(PrivateKeyInterface $key, ScriptInterface $scriptCode, $sigHashType, $sigVersion)
294
    {
295
        $hash = $this->calculateSigHash($scriptCode, $sigHashType, $sigVersion);
296
        $ecSignature = $this->ecAdapter->sign($hash, $key, new Rfc6979($this->ecAdapter, $key, $hash, 'sha256'));
297
        return new TransactionSignature($this->ecAdapter, $ecSignature, $sigHashType);
298
    }
299
300 84
    /**
301
     * @return bool
302 84
     */
303 84
    public function isFullySigned()
304 84
    {
305
        return $this->requiredSigs !== 0 && $this->requiredSigs === count($this->signatures);
306
    }
307
308
    /**
309
     * The function only returns true when $scriptPubKey could be classified
310 54
     *
311
     * @param PrivateKeyInterface $key
312 54
     * @param OutputData $solution
313
     * @param int $sigHashType
314
     * @param int $sigVersion
315
     */
316
    private function doSignature(PrivateKeyInterface $key, OutputData $solution, $sigHashType, $sigVersion)
317
    {
318
        if ($solution->getType() === OutputClassifier::PAYTOPUBKEY) {
319
            if (!$key->getPublicKey()->getBuffer()->equals($solution->getSolution())) {
320
                throw new \RuntimeException('Signing with the wrong private key');
321
            }
322
            $this->signatures[0] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
323 84
            $this->publicKeys[0] = $key->getPublicKey();
324
            $this->requiredSigs = 1;
325 84
        } else if ($solution->getType() === OutputClassifier::PAYTOPUBKEYHASH) {
326 12
            if (!$key->getPubKeyHash()->equals($solution->getSolution())) {
327
                throw new \RuntimeException('Signing with the wrong private key');
328
            }
329 12
            $this->signatures[0] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
330 12
            $this->publicKeys[0] = $key->getPublicKey();
331 12
            $this->requiredSigs = 1;
332 76
        } else if ($solution->getType() === OutputClassifier::MULTISIG) {
333 42
            $info = new Multisig($solution->getScript());
334
            $this->publicKeys = $info->getKeys();
335
            $this->requiredSigs = $info->getRequiredSigCount();
336 42
            $myKey = $key->getPublicKey()->getBuffer();
337 42
            $signed = false;
338 42
            foreach ($info->getKeys() as $keyIdx => $publicKey) {
339 44
                if ($publicKey->getBuffer()->equals($myKey)) {
0 ignored issues
show
Documentation introduced by
$myKey is of type object<BitWasp\Buffertools\BufferInterface>, but the function expects a object<self>.

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...
340 30
                    $this->signatures[$keyIdx] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
341 30
                    $signed = true;
342 30
                }
343
            }
344 30
345 30
            if (!$signed) {
346 30
                print_r($myKey->getHex());
347 30
                echo '--'.PHP_EOl;
348 30
                foreach ($info->getKeys() as $key) {
349 30
                    echo $key->getHex().PHP_EOL;
350 10
                }
351 10
                throw new \RuntimeException('Signing with the wrong private key');
352
            }
353 30
        } else {
354 20
            throw new \RuntimeException('Cannot sign unknown script type');
355
        }
356 10
    }
357 2
358
    /**
359 84
     * @param PrivateKeyInterface $key
360
     * @param int $sigHashType
361
     * @return bool
362
     */
363
    public function sign(PrivateKeyInterface $key, $sigHashType = SigHashInterface::ALL)
364
    {
365
        if ($this->scriptPubKey->canSign()) {
366 84
            $this->doSignature($key, $this->scriptPubKey, $sigHashType, 0);
367
            return true;
368 84
        }
369 42
        $solution = $this->scriptPubKey;
370 42
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
371
            if ($this->redeemScript->canSign()) {
372 42
                $this->doSignature($key, $this->redeemScript, $sigHashType, 0);
373 42
                return true;
374 24
            }
375 12
            $solution = $this->redeemScript;
376 12
        }
377
378 12
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
379 4
            $keyHashScript = ScriptFactory::scriptPubKey()->payToPubKeyHashFromHash($solution->getSolution());
380
            $this->doSignature($key, $this->classifier->decode($keyHashScript), $sigHashType, 1);
381 30
            return true;
382 12
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
383 12
            if ($this->witnessScript->canSign()) {
384 12
                $this->doSignature($key, $this->witnessScript, $sigHashType, 1);
385 18
                return true;
386 18
            }
387 18
        }
388 18
389
        return false;
390
    }
391
392
    /**
393
     * @param string $outputType
394
     * @return BufferInterface[]
395
     */
396
    private function serializeSolution($outputType)
397
    {
398
        if ($outputType === OutputClassifier::PAYTOPUBKEY) {
399 84
            return [$this->signatures[0]->getBuffer()];
400
        } else if ($outputType === OutputClassifier::PAYTOPUBKEYHASH) {
401 84
            return [$this->signatures[0]->getBuffer(), $this->publicKeys[0]->getBuffer()];
402 12
        } else if ($outputType === OutputClassifier::MULTISIG) {
403 72
            $sequence = [new Buffer()];
404 42
            for ($i = 0, $nPubKeys = count($this->publicKeys); $i < $nPubKeys; $i++) {
405 30
                if (isset($this->signatures[$i])) {
406 30
                    $sequence[] = $this->signatures[$i]->getBuffer();
407 30
                }
408 30
            }
409 30
410 10
            return $sequence;
411 10
        } else {
412
            throw new \RuntimeException('Cannot serialize this script sig');
413 30
        }
414
    }
415
416
    /**
417
     * @param ScriptInterface $script
418
     * @param int $flags
419
     * @return \BitWasp\Buffertools\BufferInterface[]
420
     */
421
    private function evalPushOnly(ScriptInterface $script, $flags = Interpreter::VERIFY_NONE)
422
    {
423
        $stack = new Stack();
424
        $interpreter = new Interpreter();
425 54
        $interpreter->evaluate($script, $stack, 0, $flags | Interpreter::VERIFY_SIGPUSHONLY, new Checker($this->ecAdapter, new Transaction(), 0, 0));
426 54
        return $stack->all();
427
    }
428
429
    /**
430 54
     * @param BufferInterface[] $buffers
431 54
     * @return ScriptInterface
432 18
     */
433
    public function pushAll(array $buffers)
434
    {
435 54
        return ScriptFactory::sequence(array_map(function ($buffer) {
436 54
            if (!($buffer instanceof BufferInterface)) {
437
                throw new \RuntimeException('Script contained a non-push opcode');
438
            }
439 54
440
            $size = $buffer->getSize();
441 54
            if ($size === 0) {
442
                return Opcodes::OP_0;
443
            }
444
445
            $first = ord($buffer->getBinary());
446
            if ($size === 1 && $first >= 1 && $first <= 16) {
447 84
                return \BitWasp\Bitcoin\Script\encodeOpN($first);
448
            } else {
449 84
                return $buffer;
450 84
            }
451 84
        }, $buffers));
452 6
    }
453 6
454 2
    /**
455
     * @return SigValues
456 84
     */
457 84
    public function serializeSignatures()
458 84
    {
459 84
        static $emptyScript = null;
460 42
        static $emptyWitness = null;
461 14
        if (is_null($emptyScript) || is_null($emptyWitness)) {
462
            $emptyScript = new Script();
463 84
            $emptyWitness = new ScriptWitness([]);
464 84
        }
465 24
466 24
        $scriptSig = $emptyScript;
467 12
        $witness = [];
468 4
        $solution = $this->scriptPubKey;
469 24
        if ($solution->canSign()) {
470 8
            $scriptSig = $this->pushAll($this->serializeSolution($this->scriptPubKey->getType()));
471
        }
472 84
473 12
        $p2sh = false;
474 12
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
475 76
            $p2sh = true;
476 18
            if ($this->redeemScript->canSign()) {
477 18
                $scriptSig = $this->pushAll($this->serializeSolution($this->redeemScript->getType()));
478 18
            }
479 18
            $solution = $this->redeemScript;
480 6
        }
481 6
482
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
483 84
            $scriptSig = $emptyScript;
484 24
            $witness = $this->serializeSolution(OutputClassifier::PAYTOPUBKEYHASH);
485 8
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
486
            if ($this->witnessScript->canSign()) {
487 84
                $scriptSig = $emptyScript;
488
                $witness = $this->serializeSolution($this->witnessScript->getType());
489
                $witness[] = $this->witnessScript->getScript()->getBuffer();
490
            }
491
        }
492
493
        if ($p2sh) {
494
            $scriptSig = ScriptFactory::create($scriptSig->getBuffer())->push($this->redeemScript->getScript()->getBuffer())->getScript();
495
        }
496
497
        return new SigValues($scriptSig, new ScriptWitness($witness));
498
    }
499
}
500