1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BitWasp\Bitcoin\Transaction\Factory; |
4
|
|
|
|
5
|
|
|
use BitWasp\Bitcoin\Collection\Transaction\TransactionWitnessCollection; |
6
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface; |
7
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PrivateKeyInterface; |
8
|
|
|
use BitWasp\Bitcoin\Script\ScriptInterface; |
9
|
|
|
use BitWasp\Bitcoin\Transaction\TransactionFactory; |
10
|
|
|
use BitWasp\Bitcoin\Transaction\TransactionInterface; |
11
|
|
|
use BitWasp\Bitcoin\Transaction\TransactionOutputInterface; |
12
|
|
|
|
13
|
|
|
class Signer |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var EcAdapterInterface |
17
|
|
|
*/ |
18
|
|
|
private $ecAdapter; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var TransactionInterface |
22
|
|
|
*/ |
23
|
|
|
private $tx; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var InputSigner |
27
|
|
|
*/ |
28
|
|
|
private $signatureCreator = []; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* TxWitnessSigner constructor. |
32
|
|
|
* @param TransactionInterface $tx |
33
|
|
|
* @param EcAdapterInterface $ecAdapter |
34
|
|
|
*/ |
35
|
54 |
|
public function __construct(TransactionInterface $tx, EcAdapterInterface $ecAdapter) |
36
|
|
|
{ |
37
|
54 |
|
$this->tx = $tx; |
38
|
54 |
|
$this->ecAdapter = $ecAdapter; |
39
|
54 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param int $nIn |
43
|
|
|
* @param PrivateKeyInterface $key |
44
|
|
|
* @param TransactionOutputInterface $txOut |
45
|
|
|
* @param ScriptInterface|null $redeemScript |
46
|
|
|
* @param ScriptInterface|null $witnessScript |
47
|
|
|
* @return $this |
48
|
|
|
*/ |
49
|
54 |
|
public function sign($nIn, PrivateKeyInterface $key, TransactionOutputInterface $txOut, ScriptInterface $redeemScript = null, ScriptInterface $witnessScript = null) |
50
|
|
|
{ |
51
|
54 |
|
if (!isset($this->signatureCreator[$nIn])) { |
52
|
54 |
|
$this->signatureCreator[$nIn] = new InputSigner($this->ecAdapter, $this->tx, $nIn, $txOut); |
53
|
54 |
|
} |
54
|
|
|
|
55
|
54 |
|
if (!$this->signatureCreator[$nIn]->sign($key, $redeemScript, $witnessScript)) { |
56
|
|
|
throw new \RuntimeException('Unsignable script'); |
57
|
|
|
} |
58
|
|
|
|
59
|
54 |
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return TransactionInterface |
64
|
|
|
*/ |
65
|
54 |
|
public function get() |
66
|
|
|
{ |
67
|
54 |
|
$mutable = TransactionFactory::mutate($this->tx); |
68
|
54 |
|
$witnesses = []; |
69
|
54 |
|
foreach ($mutable->inputsMutator() as $idx => $input) { |
70
|
54 |
|
$sig = $this->signatureCreator[$idx]->serializeSignatures(); |
71
|
54 |
|
$input->script($sig->getScriptSig()); |
72
|
54 |
|
$witnesses[$idx] = $sig->getScriptWitness(); |
73
|
54 |
|
} |
74
|
|
|
|
75
|
54 |
|
if (count($witnesses) > 0) { |
76
|
54 |
|
$mutable->witness(new TransactionWitnessCollection($witnesses)); |
77
|
54 |
|
} |
78
|
|
|
|
79
|
54 |
|
$new = $mutable->done(); |
80
|
54 |
|
return $new; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|