diff --git a/src/RLP.php b/src/RLP.php index 070b327..317c743 100644 --- a/src/RLP.php +++ b/src/RLP.php @@ -244,16 +244,25 @@ protected function padToEven(string $value) */ protected function toBuffer($input) { - if (is_numeric($input)) { - $gmpInput = gmp_init($input, 10); - return new Buffer('0x' . gmp_strval($gmpInput, 16), 'hex'); - } elseif (is_string($input)) { + if (is_string($input)) { if (strpos($input, '0x') === 0) { // hex string // $input = str_replace('0x', '', $input); return new Buffer($input, 'hex'); } return new Buffer(str_split($input, 1)); + } elseif (is_numeric($input)) { + if (!$input || $input < 0) { + return new Buffer([]); + } + if (is_float($input)) { + $input = number_format($input, 0, '', ''); + var_dump($input); + } + $gmpInput = gmp_init($input, 10); + return new Buffer('0x' . gmp_strval($gmpInput, 16), 'hex'); + } elseif ($input === null) { + return new Buffer([]); } elseif (is_array($input)) { return new Buffer($input); } elseif ($input instanceof Buffer) { diff --git a/test/unit/RLPTest.php b/test/unit/RLPTest.php index 3159a6a..763bb56 100644 --- a/test/unit/RLPTest.php +++ b/test/unit/RLPTest.php @@ -67,6 +67,26 @@ public function testValidRlp() } } + /** + * testIssue14 + * See: https://github.com/web3p/rlp/issues/14 + * You can find test in: https://github.com/ethereum/wiki/wiki/RLP#examples + * + * @return void + */ + public function testIssue14() + { + $rlp = $this->rlp; + $this->assertEquals('c0', $rlp->encode([])->toString('hex')); + $this->assertEquals('80', $rlp->encode(0)->toString('hex')); + $this->assertEquals('80', $rlp->encode(0x0)->toString('hex')); + $this->assertEquals('80', $rlp->encode(-1)->toString('hex')); + $this->assertEquals('80', $rlp->encode(-2)->toString('hex')); + $this->assertEquals('30', $rlp->encode('0')->toString('hex')); + $this->assertEquals('00', $rlp->encode('0x0')->toString('hex')); + $this->assertEquals('80', $rlp->encode(null)->toString('hex')); + } + /** * testInvalidRlp * Try to figure out what invalidrlptest.json is.