-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbech32.php
365 lines (299 loc) · 11 KB
/
bech32.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
class Bech32
{
public const BECH32 = 'bech32';
public const BECH32M = 'bech32m';
public const GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
public const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
public const CHARKEY_KEY = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1
];
/**
* @param string $hrp Human-readable part
* @param int $version Segwit script version
* @param string $program Segwit witness program
* @param string $encoding
* @return string The encoded address
* @throws Exception
*/
public function encodeSegwit(string $hrp, int $version, string $program, string $encoding)
{
$this->validateWitnessProgram($version, $program);
$programChars = array_values(unpack('C*', $program));
$programBits = $this->convertBits($programChars, count($programChars), 8, 5);
$encodeData = array_merge([$version], $programBits);
return $this->encode($hrp, $encodeData, $encoding);
}
/**
* @param string $hrp Human-readable part
* @param string $bech32 Bech32 string to be decoded
* @param string $encoding
* @return array [$version, $program]
* @throws Exception
*/
public function decodeSegwit(string $hrp, string $bech32, string $encoding)
{
list($hrpGot, $data) = $this->decode($bech32, $encoding);
if ($hrpGot !== $hrp) {
throw new Exception('Invalid prefix for address');
}
$dataLen = count($data);
if ($dataLen === 0 || $dataLen > 65) {
throw new Exception("Invalid length for segwit address");
}
$decoded = $this->convertBits(array_slice($data, 1), count($data) - 1, 5, 8, false);
$program = pack("C*", ...$decoded);
$this->validateWitnessProgram($data[0], $program);
return [$data[0], $program];
}
/**
* @param string $hrp
* @param array $combinedDataChars
* @param string $encoding
* @return string
*/
private function encode(string $hrp, array $combinedDataChars, string $encoding)
{
$checksum = $this->createChecksum($hrp, $combinedDataChars, $encoding);
$characters = array_merge($combinedDataChars, $checksum);
$encoded = [];
for ($i = 0, $n = count($characters); $i < $n; $i++) {
$encoded[$i] = self::CHARSET[$characters[$i]];
}
return "{$hrp}1" . implode('', $encoded);
}
/**
* @param string $hrp
* @param int[] $convertedDataChars
* @param string $encoding
* @return int[]
*/
private function createChecksum(string $hrp, array $convertedDataChars, string $encoding)
{
$values = array_merge($this->hrpExpand($hrp, strlen($hrp)), $convertedDataChars);
$polyMod = $this->polyMod(array_merge($values, [0, 0, 0, 0, 0, 0]), count($values) + 6) ^ $this->getEncoding($encoding);
$results = [];
for ($i = 0; $i < 6; $i++) {
$results[$i] = ($polyMod >> 5 * (5 - $i)) & 31;
}
return $results;
}
/**
* Validates a bech32 string and returns [$hrp, $dataChars] if
* the conversion was successful. An exception is thrown on invalid
* data.
*
* @param string $sBech The bech32 encoded string
* @param string $encoding
* @return array Returns [$hrp, $dataChars]
* @throws Exception
*/
private function decode(string $sBech, string $encoding)
{
$length = strlen($sBech);
if ($length > 90) {
throw new Exception('Bech32 string cannot exceed 90 characters in length');
}
return $this->decodeRaw($sBech, $encoding);
}
/**
* @throws Exception
* @param string $sBech The bech32 encoded string
* @param string $encoding
* @return array Returns [$hrp, $dataChars]
*/
private function decodeRaw(string $sBech, string $encoding)
{
$length = strlen($sBech);
if ($length < 8) {
throw new Exception("Bech32 string is too short");
}
$chars = array_values(unpack('C*', $sBech));
$haveUpper = false;
$haveLower = false;
$positionOne = -1;
for ($i = 0; $i < $length; $i++) {
$x = $chars[$i];
if ($x < 33 || $x > 126) {
throw new Exception('Out of range character in bech32 string');
}
if ($x >= 0x61 && $x <= 0x7a) {
$haveLower = true;
}
if ($x >= 0x41 && $x <= 0x5a) {
$haveUpper = true;
$x = $chars[$i] = $x + 0x20;
}
// find location of last '1' character
if ($x === 0x31) {
$positionOne = $i;
}
}
if ($haveUpper && $haveLower) {
throw new Exception('Data contains mixture of higher/lower case characters');
}
if ($positionOne === -1) {
throw new Exception("Missing separator character");
}
if ($positionOne < 1) {
throw new Exception("Empty HRP");
}
if (($positionOne + 7) > $length) {
throw new Exception('Too short checksum');
}
$hrp = pack("C*", ...array_slice($chars, 0, $positionOne));
$data = [];
for ($i = $positionOne + 1; $i < $length; $i++) {
$data[] = ($chars[$i] & 0x80) ? -1 : self::CHARKEY_KEY[$chars[$i]];
}
if (!$this->verifyChecksum($hrp, $data, $encoding)) {
throw new Exception('Invalid bech32 checksum');
}
return [$hrp, array_slice($data, 0, -6)];
}
/**
* Verifies the checksum given $hrp and $convertedDataChars.
*
* @param string $hrp
* @param int[] $convertedDataChars
* @param string $encoding
* @return bool
*/
private function verifyChecksum(string $hrp, array $convertedDataChars, string $encoding)
{
$expandHrp = $this->hrpExpand($hrp, strlen($hrp));
$r = array_merge($expandHrp, $convertedDataChars);
$poly = $this->polyMod($r, count($r));
return $poly === $this->getEncoding($encoding);
}
/**
* Expands the human-readable part into a character array for checksumming.
*
* @param string $hrp
* @param int $hrpLen
* @return int[]
*/
private function hrpExpand(string $hrp, int $hrpLen)
{
$expand1 = [];
$expand2 = [];
for ($i = 0; $i < $hrpLen; $i++) {
$o = ord($hrp[$i]);
$expand1[] = $o >> 5;
$expand2[] = $o & 31;
}
return array_merge($expand1, [0], $expand2);
}
/**
* @param int[] $values
* @param int $numValues
* @return int
*/
private function polyMod(array $values, int $numValues)
{
$chk = 1;
for ($i = 0; $i < $numValues; $i++) {
$top = $chk >> 25;
$chk = ($chk & 0x1ffffff) << 5 ^ $values[$i];
for ($j = 0; $j < 5; $j++) {
$value = (($top >> $j) & 1) ? self::GENERATOR[$j] : 0;
$chk ^= $value;
}
}
return $chk;
}
/**
* Converts words of $fromBits bits to $toBits bits in size.
*
* @param int[] $data Character array of data to convert
* @param int $inLen Number of elements in array
* @param int $fromBits Word (bit count) size of provided data
* @param int $toBits Requested word size (bit count)
* @param bool $pad Whether to pad (only when encoding)
* @return int[]
* @throws Exception
*/
private function convertBits(array $data, int $inLen, int $fromBits, int $toBits, bool $pad = true)
{
$acc = 0;
$bits = 0;
$ret = [];
$maxv = (1 << $toBits) - 1;
$maxacc = (1 << ($fromBits + $toBits - 1)) - 1;
for ($i = 0; $i < $inLen; $i++) {
$value = $data[$i];
if ($value < 0 || $value >> $fromBits) {
throw new Exception('Invalid value for convert bits');
}
$acc = (($acc << $fromBits) | $value) & $maxacc;
$bits += $fromBits;
while ($bits >= $toBits) {
$bits -= $toBits;
$ret[] = (($acc >> $bits) & $maxv);
}
}
if ($pad && $bits) {
$ret[] = ($acc << $toBits - $bits) & $maxv;
} elseif ($bits >= $fromBits || ((($acc << ($toBits - $bits))) & $maxv)) {
throw new Exception('Invalid data');
}
return $ret;
}
/**
* @param int $version
* @param string $program
* @throws Exception
*/
private function validateWitnessProgram(int $version, string $program)
{
if ($version < 0 || $version > 16) {
throw new Exception("Invalid witness version");
}
$sizeProgram = strlen($program);
if ($version === 0) {
if ($sizeProgram !== 20 && $sizeProgram !== 32) {
throw new Exception("Invalid size for V0 witness program");
}
}
if ($sizeProgram < 2 || $sizeProgram > 40) {
throw new Exception("Witness program size was out of valid range");
}
}
private function getEncoding($encoding)
{
if ($encoding === self::BECH32) {
return 1;
}
if ($encoding === self::BECH32M) {
return 0x2bc830a3;
}
return null;
}
}
try {
$bech32 = new Bech32();
// Defina o HRP (prefixo humano legível)
$hrp = 'bc'; // Certifique-se de que seja um HRP válido para Bitcoin, 'bc' é comum
// Gere um programa de testemunha (witness program) aleatório (20 bytes para versão 0)
$version = 0;
$program = hex2bin('fa256ead84fa256ead84fa256ead845afa256ead84fa256ead84fa256ead845a');//random_bytes(32);
// Codifique o endereço segwit usando o HRP, a versão e o programa de testemunha
$address = $bech32->encodeSegwit($hrp, $version, $program, Bech32::BECH32);
// Exiba o endereço gerado
echo "Endereço Segwit: $address\n";
// Decodifique o endereço segwit para verificar se a recuperação do programa de testemunha é bem-sucedida
list($decodedVersion, $decodedProgram) = $bech32->decodeSegwit($hrp, $address, Bech32::BECH32);
// Exiba o programa de testemunha decodificado
echo "Versão decodificada: $decodedVersion\n";
echo "Programa de Testemunha decodificado: " . bin2hex($decodedProgram) . "\n";
} catch (Exception $e) {
// Lidar com exceções, se houver alguma
echo "Erro Bech32: " . $e->getMessage() . "\n";
}