1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BitWasp\Bitcoin\Script; |
6
|
|
|
|
7
|
|
|
use BitWasp\Buffertools\BufferInterface; |
8
|
|
|
|
9
|
|
|
class WitnessProgram |
10
|
|
|
{ |
11
|
|
|
const V0 = 0; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var int |
15
|
|
|
*/ |
16
|
|
|
private $version; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var BufferInterface |
20
|
|
|
*/ |
21
|
|
|
private $program; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var |
25
|
|
|
*/ |
26
|
|
|
private $outputScript; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* WitnessProgram constructor. |
30
|
|
|
* @param int $version |
31
|
|
|
* @param BufferInterface $program |
32
|
|
|
*/ |
33
|
312 |
|
public function __construct(int $version, BufferInterface $program) |
34
|
|
|
{ |
35
|
312 |
|
if ($this->version < 0 || $this->version > 16) { |
36
|
|
|
throw new \RuntimeException("Invalid witness program version"); |
37
|
|
|
} |
38
|
|
|
|
39
|
312 |
|
if ($this->version === 0 && ($program->getSize() !== 20 && $program->getSize() !== 32)) { |
40
|
|
|
throw new \RuntimeException('Invalid size for V0 witness program - must be 20 or 32 bytes'); |
41
|
|
|
} |
42
|
|
|
|
43
|
312 |
|
$this->version = $version; |
44
|
312 |
|
$this->program = $program; |
45
|
312 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param BufferInterface $program |
49
|
|
|
* @return WitnessProgram |
50
|
|
|
*/ |
51
|
25 |
|
public static function v0(BufferInterface $program): WitnessProgram |
52
|
|
|
{ |
53
|
25 |
|
if ($program->getSize() === 20) { |
54
|
1 |
|
return new self(self::V0, $program); |
55
|
24 |
|
} else if ($program->getSize() === 32) { |
56
|
24 |
|
return new self(self::V0, $program); |
57
|
|
|
} else { |
58
|
|
|
throw new \RuntimeException('Invalid size for V0 witness program - must be 20 or 32 bytes'); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return int |
64
|
|
|
*/ |
65
|
279 |
|
public function getVersion(): int |
66
|
|
|
{ |
67
|
279 |
|
return $this->version; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return BufferInterface |
72
|
|
|
*/ |
73
|
275 |
|
public function getProgram(): BufferInterface |
74
|
|
|
{ |
75
|
275 |
|
return $this->program; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return ScriptInterface |
80
|
|
|
*/ |
81
|
29 |
|
public function getScript(): ScriptInterface |
82
|
|
|
{ |
83
|
29 |
|
if (null === $this->outputScript) { |
84
|
28 |
|
$this->outputScript = ScriptFactory::sequence([encodeOpN($this->version), $this->program]); |
85
|
|
|
} |
86
|
|
|
|
87
|
29 |
|
return $this->outputScript; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|