Completed
Pull Request — master (#386)
by thomas
112:49 queued 42:55
created

InputSigner::solve()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 8

Importance

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