You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.7 KiB
PHP
61 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Payment;
|
|
|
|
class TronAddress
|
|
{
|
|
private const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
|
|
public static function isValid($address)
|
|
{
|
|
$address = trim((string) $address);
|
|
if (strlen($address) !== 34 || $address[0] !== 'T') {
|
|
return false;
|
|
}
|
|
|
|
$decoded = self::decodeBase58($address);
|
|
if ($decoded === null || strlen($decoded) !== 25 || ord($decoded[0]) !== 0x41) {
|
|
return false;
|
|
}
|
|
|
|
$payload = substr($decoded, 0, 21);
|
|
$checksum = substr($decoded, 21, 4);
|
|
$expected = substr(hash('sha256', hash('sha256', $payload, true), true), 0, 4);
|
|
return hash_equals($expected, $checksum);
|
|
}
|
|
|
|
private static function decodeBase58($value)
|
|
{
|
|
$bytes = [0];
|
|
$length = strlen($value);
|
|
for ($position = 0; $position < $length; $position++) {
|
|
$digit = strpos(self::ALPHABET, $value[$position]);
|
|
if ($digit === false) {
|
|
return null;
|
|
}
|
|
|
|
$carry = $digit;
|
|
$byteCount = count($bytes);
|
|
for ($index = 0; $index < $byteCount; $index++) {
|
|
$carry += $bytes[$index] * 58;
|
|
$bytes[$index] = $carry & 0xff;
|
|
$carry >>= 8;
|
|
}
|
|
while ($carry > 0) {
|
|
$bytes[] = $carry & 0xff;
|
|
$carry >>= 8;
|
|
}
|
|
}
|
|
|
|
for ($position = 0; $position < $length - 1 && $value[$position] === '1'; $position++) {
|
|
$bytes[] = 0;
|
|
}
|
|
|
|
$decoded = '';
|
|
for ($index = count($bytes) - 1; $index >= 0; $index--) {
|
|
$decoded .= chr($bytes[$index]);
|
|
}
|
|
return $decoded;
|
|
}
|
|
}
|