diff --git a/src/Address.php b/src/Address.php index 83eaa4b..ba3a13a 100644 --- a/src/Address.php +++ b/src/Address.php @@ -1,16 +1,27 @@ setPrefix($prefix); + $privateKey = static::removePrefix($privateKey, $this->prefix); $generator = EccFactory::getSecgCurves()->generator256k1(); if (empty ($privateKey)) { $this->privateKey = $generator->createPrivateKey(); @@ -27,25 +38,42 @@ public function __construct(string $privateKey = '') { } } - public function getPrivateKey(): string { - return str_pad(gmp_strval($this->privateKey->getSecret(), 16), self::SIZE, '0', STR_PAD_LEFT); + public function setPrefix(string $prefix = '') + { + $this->prefix = $prefix; } - public function getPublicKey(): string { - $publicKey = $this->privateKey->getPublicKey(); - $publicKeySerializer = new DerPublicKeySerializer(EccFactory::getAdapter()); - return substr($publicKeySerializer->getUncompressedKey($publicKey), 2); + public static function removePrefix(string $any, string $prefix) + { + if (substr($any, 0, strlen($prefix)) === $prefix) { + return substr($any, strlen($prefix)); + } + return $any; } - public function get(): string { - $hash = Keccak::hash(hex2bin($this->getPublicKey()), 256); - return substr($hash, -40); + public static function addPrefix(string $any, string $prefix) + { + if (substr($any, 0, strlen($prefix)) !== $prefix) { + return $prefix . $any; + } + return $any; } - /** - * @var PrivateKeyInterface - */ - private $privateKey; + public function getPrivateKey(): string + { + return static::addPrefix(str_pad(gmp_strval($this->privateKey->getSecret(), 16), self::SIZE, '0', STR_PAD_LEFT), $this->prefix); + } - private const SIZE = 64; + public function get(): string + { + $hash = Keccak::hash(hex2bin(static::removePrefix($this->getPublicKey(),$this->prefix)), 256); + return static::addPrefix(substr($hash, -40), $this->prefix); + } + + public function getPublicKey(): string + { + $publicKey = $this->privateKey->getPublicKey(); + $publicKeySerializer = new DerPublicKeySerializer(EccFactory::getAdapter()); + return static::addPrefix(substr($publicKeySerializer->getUncompressedKey($publicKey), 2), $this->prefix); + } }