1 | <?php |
||
2 | |||
3 | namespace LaravelCryptoStats\Services; |
||
4 | |||
5 | class EthereumValidator |
||
6 | { |
||
7 | /** |
||
8 | * Checks if the given string is an address. |
||
9 | * |
||
10 | * @method isAddress |
||
11 | * |
||
12 | * @param {String} $address the given HEX adress |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
13 | * |
||
14 | * @return {Boolean} |
||
0 ignored issues
–
show
|
|||
15 | */ |
||
16 | public static function isAddress($address) |
||
17 | { |
||
18 | if (!preg_match('/^(0x)?[0-9a-f]{40}$/i', $address)) { |
||
19 | // check if it has the basic requirements of an address |
||
20 | return false; |
||
21 | } elseif (!preg_match('/^(0x)?[0-9a-f]{40}$/', $address) || preg_match('/^(0x)?[0-9A-F]{40}$/', $address)) { |
||
22 | // If it's all small caps or all all caps, return true |
||
23 | return true; |
||
24 | } else { |
||
25 | // Otherwise check each case |
||
26 | return self::isChecksumAddress($address); |
||
27 | } |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Checks if the given string is a checksummed address. |
||
32 | * |
||
33 | * @method isChecksumAddress |
||
34 | * |
||
35 | * @param {String} $address the given HEX adress |
||
0 ignored issues
–
show
|
|||
36 | * |
||
37 | * @return {Boolean} |
||
0 ignored issues
–
show
|
|||
38 | */ |
||
39 | public static function isChecksumAddress($address) |
||
40 | { |
||
41 | // Check each case |
||
42 | $address = str_replace('0x', '', $address); |
||
43 | $addressHash = hash('sha3-256', strtolower($address)); |
||
44 | $addressArray = str_split($address); |
||
45 | $addressHashArray = str_split($addressHash); |
||
46 | |||
47 | for ($i = 0; $i < 40; $i++) { |
||
48 | // the nth letter should be uppercase if the nth digit of casemap is 1 |
||
49 | if ((intval($addressHashArray[$i], 16) > 7 && strtoupper($addressArray[$i]) !== $addressArray[$i]) || (intval($addressHashArray[$i], 16) <= 7 && strtolower($addressArray[$i]) !== $addressArray[$i])) { |
||
50 | return false; |
||
51 | } |
||
52 | } |
||
53 | |||
54 | return true; |
||
55 | } |
||
56 | } |
||
57 |