Completed
Pull Request — master (#388)
by thomas
316:52 queued 244:52
created

InputSigner::calculateSignature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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