Skip to content

Commit

Permalink
Fix 14
Browse files Browse the repository at this point in the history
1. Return Buffer([]) when input is 0, negative number, null.
2. Add tests for issue 14.
  • Loading branch information
sc0Vu committed Jun 10, 2018
1 parent 930dbea commit 961dbb8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/RLP.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions test/unit/RLPTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 961dbb8

Please sign in to comment.