From 6d9c35917dd112c41ae8156b05fa6603b7689f14 Mon Sep 17 00:00:00 2001 From: sc0Vu Date: Fri, 5 Jul 2024 15:53:48 +0800 Subject: [PATCH] Return true only when the address is lowercase or in checksum format --- src/Utils.php | 9 +++++---- test/unit/UtilsTest.php | 9 ++++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/Utils.php b/src/Utils.php index 7a5caa1..f0fdd84 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -175,16 +175,14 @@ public static function isNegative($value) * isAddress * * @param string $value - * @return bool + * @return bool true if the address is lowercase or in checksum format otherwise false */ public static function isAddress($value) { if (!is_string($value)) { throw new InvalidArgumentException('The value to isAddress function must be string.'); } - if (preg_match('/^(0x|0X)?[a-f0-9A-F]{40}$/', $value) !== 1) { - return false; - } elseif (preg_match('/^(0x|0X)?[a-f0-9]{40}$/', $value) === 1 || preg_match('/^(0x|0X)?[A-F0-9]{40}$/', $value) === 1) { + if (preg_match('/^(0x)?[a-f0-9]{40}$/', $value) === 1) { return true; } return self::isAddressChecksum($value); @@ -202,6 +200,9 @@ public static function isAddressChecksum($value) throw new InvalidArgumentException('The value to isAddressChecksum function must be string.'); } $value = self::stripZero($value); + if (mb_strlen($value) !== 40) { + return false; + } $hash = self::stripZero(self::sha3(mb_strtolower($value))); for ($i = 0; $i < 40; $i++) { diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index da2e4e7..76244ed 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -232,17 +232,20 @@ public function testIsAddress() $this->assertEquals($isAddress, true); $isAddress = Utils::isAddress('0Xca35b7d915458ef540ade6068dfe2f44e8fa733c'); - $this->assertEquals($isAddress, true); + $this->assertEquals($isAddress, false); $isAddress = Utils::isAddress('0XCA35B7D915458EF540ADE6068DFE2F44E8FA733C'); - $this->assertEquals($isAddress, true); + $this->assertEquals($isAddress, false); $isAddress = Utils::isAddress('0xCA35B7D915458EF540ADE6068DFE2F44E8FA733C'); - $this->assertEquals($isAddress, true); + $this->assertEquals($isAddress, false); $isAddress = Utils::isAddress('0xCA35B7D915458EF540ADE6068DFE2F44E8FA73cc'); $this->assertEquals($isAddress, false); + $isAddress = Utils::isAddress('0xCA35b7d915458Ef540ADE6068DfE2F44E8fA73cC'); + $this->assertEquals($isAddress, true); + $this->expectException(InvalidArgumentException::class); $isAddress = Utils::isAddress(new stdClass); }