From 02b30ee2d578576223231b27c0b0853e18eb06aa Mon Sep 17 00:00:00 2001 From: sc0Vu Date: Wed, 20 Dec 2017 14:15:57 +0800 Subject: [PATCH] Add Keccak256 sha3 usage. --- composer.json | 4 +++- src/Utils.php | 40 ++++++++++++++++++++++++++++++++++++++++ test/unit/UtilsTest.php | 16 ++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index b122d7f..761c23e 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,9 @@ ], "minimum-stability": "dev", "require": { - "guzzlehttp/guzzle": "~6.0" + "guzzlehttp/guzzle": "~6.0", + "PHP": "^7.1", + "kornrunner/keccak": "dev-master" }, "require-dev": { "phpunit/phpunit": "~6.0" diff --git a/src/Utils.php b/src/Utils.php index 7cea392..32b33ba 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -1,11 +1,28 @@ + * + * @author Peter Lai + * @license MIT + */ + namespace Web3; use InvalidArgumentException; +use kornrunner\Keccak; class Utils { + /** + * SHA3_NULL_HASH + * + * @const string + */ + const SHA3_NULL_HASH = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; + /** * construct * @@ -49,4 +66,27 @@ class Utils return pack('H*', $hexString); } + + /** + * sha3 + * keccak256 + * + * @param string $value + * @return string + */ + public function sha3($value) + { + if (!is_string($value)) { + throw new InvalidArgumentException('The value to sha3 function must be string.'); + } + if (preg_match('/^0x/', $value) > 0) { + $value = self::hexToBin($value); + } + $hash = Keccak::hash($value, 256); + + if ($hash === self::SHA3_NULL_HASH) { + return null; + } + return '0x' . $hash; + } } \ No newline at end of file diff --git a/test/unit/UtilsTest.php b/test/unit/UtilsTest.php index 2b7b47d..6b5c3b7 100644 --- a/test/unit/UtilsTest.php +++ b/test/unit/UtilsTest.php @@ -62,4 +62,20 @@ class UtilsTest extends TestCase $this->assertEquals($str, '七彩神仙鱼'); } + + /** + * testSha3 + * + * @return void + */ + public function testSha3() + { + $str = Utils::sha3(''); + + $this->assertNull($str); + + $str = Utils::sha3('baz(uint32,bool)'); + + $this->assertEquals(mb_substr($str, 0, 10), '0xcdcd77c0'); + } } \ No newline at end of file