0) { [$num, $rem] = [gmp_div_q($num, 58), gmp_intval(gmp_mod($num, 58))]; $encoded = $alphabet[$rem].$encoded; } for ($i = 0, $len = strlen($bytes); $i < $len && $bytes[$i] === "\x00"; $i++) { $encoded = '1'.$encoded; } return $encoded; } public static function base58CheckToHex(string $address): string { $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; $num = gmp_init(0); for ($i = 0, $len = strlen($address); $i < $len; $i++) { $pos = strpos($alphabet, $address[$i]); if ($pos === false) { throw new RuntimeException('Invalid base58 character'); } $num = gmp_add(gmp_mul($num, 58), $pos); } $hex = gmp_strval($num, 16); if (strlen($hex) % 2 !== 0) { $hex = '0'.$hex; } // leading ones => leading zero bytes for ($i = 0, $len = strlen($address); $i < $len && $address[$i] === '1'; $i++) { $hex = '00'.$hex; } $bin = hex2bin($hex); if ($bin === false || strlen($bin) < 5) { throw new RuntimeException('Invalid address payload'); } $payload = substr($bin, 0, -4); $checksum = substr($bin, -4); $expected = substr(hash('sha256', hash('sha256', $payload, true), true), 0, 4); if (! hash_equals($expected, $checksum)) { throw new RuntimeException('Invalid address checksum'); } return bin2hex($payload); } }