-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathAddress.php
More file actions
89 lines (74 loc) · 2.05 KB
/
Address.php
File metadata and controls
89 lines (74 loc) · 2.05 KB
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
<?php
declare(strict_types=1);
namespace ArkEcosystem\Crypto\Utils;
use ArkEcosystem\Crypto\ByteBuffer\ByteBuffer;
use BitWasp\Buffertools\Buffer;
use kornrunner\Keccak;
class Address
{
private static array $cache = [];
/**
* Validate the given address.
*
* @param string $address
*
* @return bool
*/
public static function validate(string $address): bool
{
// Simple validation to check if the address starts with 0x and is 42 characters long
return preg_match('/^0x[a-fA-F0-9]{40}$/', $address) === 1;
}
/**
* Convert to checksum address.
*
* @param string $address
*
* @return string
*/
public static function toChecksumAddress(string $address): string
{
if (isset(self::$cache[$address])) {
return self::$cache[$address];
}
$rawAddress = strtolower(substr($address, 2));
$hash = Keccak::hash($rawAddress, 256);
$checksumAddress = '0x';
for ($i = 0; $i < 40; $i++) {
if (intval($hash[$i], 16) >= 8) {
$checksumAddress .= strtoupper($rawAddress[$i]);
} else {
$checksumAddress .= $rawAddress[$i];
}
}
self::$cache[$address] = $checksumAddress;
return $checksumAddress;
}
/**
* Convert to hex string without 0x prefix.
*
* @param string $address
*
* @return string
*/
public static function toBufferHexString(string $address): string
{
if (strpos($address, '0x') === 0) {
$address = substr($address, 2);
}
return $address;
return strtolower($address);
}
/**
* Extract the address from a byte buffer.
*
* @param ByteBuffer $buffer
*
* @return string
*/
public static function fromByteBuffer(ByteBuffer $buffer): string
{
$hexAddress = '0x'.(new Buffer(hex2bin($buffer->readHex(20 * 2))))->getHex();
return self::toChecksumAddress($hexAddress);
}
}