Completed
Push — master ( 2acf03...097f65 )
by thomas
26:40 queued 23:22
created

InputSigner::serializeSimpleSig()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 9.0101

Importance

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