Completed
Push — master ( 9416b8...4b1dff )
by thomas
401:02 queued 398:24
created

InputSigner::evalPushOnly()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 1
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\SigHash;
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
     * @param TransactionOutputInterface $txOut
98
     * @param SignData $signData
99
     */
100 84
    public function __construct(EcAdapterInterface $ecAdapter, TransactionInterface $tx, $nInput, TransactionOutputInterface $txOut, SignData $signData)
101
    {
102 84
        $this->ecAdapter = $ecAdapter;
103 84
        $this->tx = $tx;
104 84
        $this->nInput = $nInput;
105 84
        $this->txOut = $txOut;
106 84
        $this->classifier = new OutputClassifier();
107 84
        $this->publicKeys = [];
108 84
        $this->signatures = [];
109
110 84
        $this->solve($signData);
111 84
        $this->extractSignatures();
112 84
    }
113
114
    /**
115
     * @param int $sigVersion
116
     * @param TransactionSignatureInterface[] $stack
117
     * @param ScriptInterface $scriptCode
118
     * @return \SplObjectStorage
119
     */
120 26
    private function sortMultiSigs($sigVersion, $stack, ScriptInterface $scriptCode)
121
    {
122 24
        $sigSort = new SignatureSort($this->ecAdapter);
123 24
        $sigs = new \SplObjectStorage;
124
125 24
        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
                    $sigs[$key] = $txSig;
131
                }
132
            }
133 8
        }
134
135 26
        return $sigs;
136
    }
137
138
    /**
139
     * @param string $type
140
     * @param ScriptInterface $scriptCode
141
     * @param BufferInterface[] $stack
142
     * @param int $sigVersion
143
     * @return string
144
     */
145 78
    public function extractFromValues($type, ScriptInterface $scriptCode, array $stack, $sigVersion)
146
    {
147 78
        $size = count($stack);
148 78
        if ($type === OutputClassifier::PAYTOPUBKEYHASH) {
149 42
            $this->requiredSigs = 1;
150 42
            if ($size === 2) {
151 24
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
152 24
                $this->publicKeys = [PublicKeyFactory::fromHex($stack[1], $this->ecAdapter)];
153 8
            }
154 14
        }
155
156 78
        if ($type === OutputClassifier::PAYTOPUBKEY) {
157 12
            $this->requiredSigs = 1;
158 12
            if ($size === 1) {
159 6
                $this->signatures = [TransactionSignatureFactory::fromHex($stack[0], $this->ecAdapter)];
160 2
            }
161 4
        }
162
163 78
        if ($type === OutputClassifier::MULTISIG) {
164 24
            $info = new Multisig($scriptCode);
165 24
            $this->requiredSigs = $info->getRequiredSigCount();
166 24
            $this->publicKeys = $info->getKeys();
167
168 24
            if ($size > 1) {
169 24
                $vars = [];
170 24
                for ($i = 1, $j = $size - 1; $i < $j; $i++) {
171
                    $vars[] = TransactionSignatureFactory::fromHex($stack[$i], $this->ecAdapter);
172
                }
173
174 24
                $sigs = $this->sortMultiSigs($sigVersion, $vars, $scriptCode);
175 24
                foreach ($this->publicKeys as $idx => $key) {
176 24
                    $this->signatures[$idx] = isset($sigs[$key]) ? $sigs[$key]->getBuffer() : null;
177 8
                }
178 8
            }
179 8
        }
180
181 78
        return $type;
182
    }
183
184
    /**
185
     * @param SignData $signData
186
     * @return $this
187
     * @throws \Exception
188
     */
189 84
    private function solve(SignData $signData)
190
    {
191 84
        $scriptPubKey = $this->txOut->getScript();
192 84
        $solution = $this->scriptPubKey = $this->classifier->decode($scriptPubKey);
193 84
        if ($solution->getType() === OutputClassifier::UNKNOWN) {
194
            throw new \RuntimeException('scriptPubKey type is unknown');
195
        }
196
197 84
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
198 24
            $redeemScript = $signData->getRedeemScript();
199 24
            if (!$solution->getSolution()->equals(Hash::sha256ripe160($redeemScript->getBuffer()))) {
200
                throw new \Exception('Redeem script doesn\'t match script-hash');
201
            }
202 24
            $solution = $this->redeemScript = $this->classifier->decode($redeemScript);
203 24
            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
            }
206 8
        }
207
        // WitnessKeyHash doesn't require further solving until signing
208 84
        if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
209 18
            $witnessScript = $signData->getWitnessScript();
210 18
            if (!$solution->getSolution()->equals(Hash::sha256($witnessScript->getBuffer()))) {
211
                throw new \Exception('Witness script doesn\'t match witness-script-hash');
212
            }
213 18
            $solution = $this->witnessScript = $this->classifier->decode($witnessScript);
214 18
            if (!in_array($solution->getType(), [OutputClassifier::PAYTOPUBKEYHASH , OutputClassifier::PAYTOPUBKEY, OutputClassifier::MULTISIG])) {
215
                throw new \Exception('Unsupported witness-script-hash script');
216
            }
217 6
        }
218
219 84
        return $this;
220
    }
221
222
    /**
223
     * @return $this
224
     */
225 84
    public function extractSignatures()
226
    {
227 84
        $solution = $this->scriptPubKey;
228 84
        $scriptSig = $this->tx->getInput($this->nInput)->getScript();
229 84
        if (in_array($solution->getType(), [OutputClassifier::PAYTOPUBKEYHASH , OutputClassifier::PAYTOPUBKEY, OutputClassifier::MULTISIG])) {
230 42
            $this->extractFromValues($solution->getType(), $solution->getScript(), $this->evalPushOnly($scriptSig), 0);
231 14
        }
232
233 84
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
234 24
            $stack = $this->evalPushOnly($scriptSig);
235 24
            if (count($stack) > 0) {
236 18
                $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
                    throw new \RuntimeException('Redeem script from scriptSig doesn\'t match script-hash');
239
                }
240
241 18
                $solution = $this->redeemScript;
242 18
                $this->extractFromValues($solution->getType(), $solution->getScript(), array_slice($stack, 0, -1), 0);
243 6
            }
244 8
        }
245
246 84
        $witnesses = $this->tx->getWitnesses();
247 84
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
248 12
            $wit = isset($witnesses[$this->nInput]) ? $witnesses[$this->nInput]->all() : [];
249 12
            $keyHashCode = ScriptFactory::scriptPubKey()->payToPubKeyHashFromHash($solution->getSolution());
250 12
            $this->extractFromValues(OutputClassifier::PAYTOPUBKEYHASH, $keyHashCode, $wit, 1);
251 80
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
252 18
            if (isset($witnesses[$this->nInput])) {
253 18
                $witness = $witnesses[$this->nInput];
254 18
                $witCount = count($witnesses[$this->nInput]);
255 18
                if ($witCount > 0) {
256 18
                    if (!$witness[$witCount - 1]->equals($this->witnessScript->getScript()->getBuffer())) {
257
                        throw new \RuntimeException('Redeem script from scriptSig doesn\'t match script-hash');
258
                    }
259
260 18
                    $solution = $this->witnessScript;
261 18
                    $this->extractFromValues($solution->getType(), $solution->getScript(), array_slice($witness->all(), 0, -1), 1);
262 6
                }
263 6
            }
264 6
        }
265
266 84
        return $this;
267
    }
268
269
    /**
270
     * @param ScriptInterface $scriptCode
271
     * @param int $sigHashType
272
     * @param int $sigVersion
273
     * @return BufferInterface
274
     */
275 84
    public function calculateSigHash(ScriptInterface $scriptCode, $sigHashType, $sigVersion)
276
    {
277 84
        if ($sigVersion === 1) {
278 30
            $hasher = new V1Hasher($this->tx, $this->txOut->getValue());
279 10
        } else {
280 54
            $hasher = new Hasher($this->tx);
281
        }
282
283 84
        return $hasher->calculate($scriptCode, $this->nInput, $sigHashType);
284
    }
285
286
    /**
287
     * @param PrivateKeyInterface $key
288
     * @param ScriptInterface $scriptCode
289
     * @param int $sigHashType
290
     * @param int $sigVersion
291
     * @return TransactionSignature
292
     */
293 84
    public function calculateSignature(PrivateKeyInterface $key, ScriptInterface $scriptCode, $sigHashType, $sigVersion)
294
    {
295 84
        $hash = $this->calculateSigHash($scriptCode, $sigHashType, $sigVersion);
296 84
        $ecSignature = $this->ecAdapter->sign($hash, $key, new Rfc6979($this->ecAdapter, $key, $hash, 'sha256'));
297 84
        return new TransactionSignature($this->ecAdapter, $ecSignature, $sigHashType);
298
    }
299
300
    /**
301
     * @return bool
302
     */
303 54
    public function isFullySigned()
304
    {
305 54
        return $this->requiredSigs !== 0 && $this->requiredSigs === count($this->signatures);
306
    }
307
308
    /**
309
     * The function only returns true when $scriptPubKey could be classified
310
     *
311
     * @param PrivateKeyInterface $key
312
     * @param OutputData $solution
313
     * @param int $sigHashType
314
     * @param int $sigVersion
315
     */
316 84
    private function doSignature(PrivateKeyInterface $key, OutputData $solution, $sigHashType, $sigVersion = 0)
317
    {
318 84
        if ($solution->getType() === OutputClassifier::PAYTOPUBKEY) {
319 12
            if (!$key->getPublicKey()->getBuffer()->equals($solution->getSolution())) {
320
                throw new \RuntimeException('Signing with the wrong private key');
321
            }
322 12
            $this->signatures[0] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
323 12
            $this->publicKeys[0] = $key->getPublicKey();
324 12
            $this->requiredSigs = 1;
325 76
        } else if ($solution->getType() === OutputClassifier::PAYTOPUBKEYHASH) {
326 42
            if (!$key->getPubKeyHash()->equals($solution->getSolution())) {
327
                throw new \RuntimeException('Signing with the wrong private key');
328
            }
329 42
            $this->signatures[0] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
330 42
            $this->publicKeys[0] = $key->getPublicKey();
331 42
            $this->requiredSigs = 1;
332 44
        } else if ($solution->getType() === OutputClassifier::MULTISIG) {
333 30
            $info = new Multisig($solution->getScript());
334 30
            $this->publicKeys = $info->getKeys();
335 30
            $this->requiredSigs = $info->getRequiredSigCount();
336
337 30
            $myKey = $key->getPublicKey()->getBuffer();
338 30
            $signed = false;
339 30
            foreach ($info->getKeys() as $keyIdx => $publicKey) {
340 30
                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...
341 30
                    $this->signatures[$keyIdx] = $this->calculateSignature($key, $solution->getScript(), $sigHashType, $sigVersion);
342 30
                    $signed = true;
343 10
                }
344 10
            }
345
346 30
            if (!$signed) {
347 20
                throw new \RuntimeException('Signing with the wrong private key');
348
            }
349 10
        } else {
350
            throw new \RuntimeException('Cannot sign unknown script type');
351
        }
352 84
    }
353
354
    /**
355
     * @param PrivateKeyInterface $key
356
     * @param int $sigHashType
357
     * @return bool
358
     */
359 84
    public function sign(PrivateKeyInterface $key, $sigHashType = SigHashInterface::ALL)
360
    {
361 84
        if ($this->scriptPubKey->canSign()) {
362 42
            $this->doSignature($key, $this->scriptPubKey, $sigHashType, 0);
363 42
            return true;
364
        }
365 42
        $solution = $this->scriptPubKey;
366 42
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
367 24
            if ($this->redeemScript->canSign()) {
368 12
                $this->doSignature($key, $this->redeemScript, $sigHashType, 0);
369 12
                return true;
370
            }
371 12
            $solution = $this->redeemScript;
372 4
        }
373
374 30
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
375 12
            $keyHashScript = ScriptFactory::scriptPubKey()->payToPubKeyHashFromHash($solution->getSolution());
376 12
            $this->doSignature($key, $this->classifier->decode($keyHashScript), $sigHashType, 1);
377 12
            return true;
378 18
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
379 38
            if ($this->witnessScript->canSign()) {
380 18
                $this->doSignature($key, $this->witnessScript, $sigHashType, 1);
381 18
                return true;
382
            }
383
        }
384
385
        return false;
386
    }
387
388
    /**
389
     * @param string $outputType
390
     * @return BufferInterface[]
391
     */
392 84
    private function serializeSolution($outputType)
393
    {
394 84
        if ($outputType === OutputClassifier::PAYTOPUBKEY) {
395 12
            return [$this->signatures[0]->getBuffer()];
396 72
        } else if ($outputType === OutputClassifier::PAYTOPUBKEYHASH) {
397 42
            return [$this->signatures[0]->getBuffer(), $this->publicKeys[0]->getBuffer()];
398 30
        } else if ($outputType === OutputClassifier::MULTISIG) {
399 30
            $sequence = [new Buffer()];
400 30
            for ($i = 0, $nPubKeys = count($this->publicKeys); $i < $nPubKeys; $i++) {
401 30
                if (isset($this->signatures[$i])) {
402 30
                    $sequence[] = $this->signatures[$i]->getBuffer();
403 10
                }
404 10
            }
405
406 30
            return $sequence;
407
        } else {
408
            throw new \RuntimeException('Cannot serialize this script sig');
409
        }
410
    }
411
412
    /**
413
     * @param ScriptInterface $script
414
     * @param int $flags
415
     * @return \BitWasp\Buffertools\BufferInterface[]
416
     */
417 66
    private function evalPushOnly(ScriptInterface $script, $flags = Interpreter::VERIFY_NONE)
418
    {
419 66
        $stack = new Stack();
420 66
        $interpreter = new Interpreter();
421 66
        $interpreter->evaluate($script, $stack, 0, $flags | Interpreter::VERIFY_SIGPUSHONLY, new Checker($this->ecAdapter, new Transaction(), 0, 0));
422 66
        return $stack->all();
423
    }
424
425
    /**
426
     * @param BufferInterface[] $buffers
427
     * @return ScriptInterface
428
     */
429
    public function pushAll(array $buffers)
430
    {
431 54
        return ScriptFactory::sequence(array_map(function ($buffer) {
432 54
            if (!($buffer instanceof BufferInterface)) {
433
                throw new \RuntimeException('Script contained a non-push opcode');
434
            }
435
436 54
            $size = $buffer->getSize();
437 54
            if ($size === 0) {
438 18
                return Opcodes::OP_0;
439
            }
440
441 54
            $first = ord($buffer->getBinary());
442 54
            if ($size === 1 && $first >= 1 && $first <= 16) {
443
                return \BitWasp\Bitcoin\Script\encodeOpN($first);
444
            } else {
445 54
                return $buffer;
446
            }
447 54
        }, $buffers));
448
    }
449
450
    /**
451
     * @return SigValues
452
     */
453 84
    public function serializeSignatures()
454
    {
455 84
        static $emptyScript = null;
456 84
        static $emptyWitness = null;
457 84
        if (is_null($emptyScript) || is_null($emptyWitness)) {
458 6
            $emptyScript = new Script();
459 6
            $emptyWitness = new ScriptWitness([]);
460 2
        }
461
462 84
        $scriptSig = $emptyScript;
463 84
        $witness = [];
464 84
        $solution = $this->scriptPubKey;
465 84
        if ($solution->canSign()) {
466 42
            $scriptSig = $this->pushAll($this->serializeSolution($this->scriptPubKey->getType()));
467 14
        }
468
469 84
        $p2sh = false;
470 84
        if ($solution->getType() === OutputClassifier::PAYTOSCRIPTHASH) {
471 24
            $p2sh = true;
472 24
            if ($this->redeemScript->canSign()) {
473 12
                $scriptSig = $this->pushAll($this->serializeSolution($this->redeemScript->getType()));
474 4
            }
475 24
            $solution = $this->redeemScript;
476 8
        }
477
478 84
        if ($solution->getType() === OutputClassifier::WITNESS_V0_KEYHASH) {
479 12
            $scriptSig = $emptyScript;
480 12
            $witness = $this->serializeSolution(OutputClassifier::PAYTOPUBKEYHASH);
481 76
        } else if ($solution->getType() === OutputClassifier::WITNESS_V0_SCRIPTHASH) {
482 18
            if ($this->witnessScript->canSign()) {
483 18
                $scriptSig = $emptyScript;
484 18
                $witness = $this->serializeSolution($this->witnessScript->getType());
485 18
                $witness[] = $this->witnessScript->getScript()->getBuffer();
486 6
            }
487 6
        }
488
489 84
        if ($p2sh) {
490 24
            $scriptSig = ScriptFactory::create($scriptSig->getBuffer())->push($this->redeemScript->getScript()->getBuffer())->getScript();
491 8
        }
492
493 84
        return new SigValues($scriptSig, new ScriptWitness($witness));
494
    }
495
}
496