Skip to content

Commit

Permalink
Merge pull request #31 from sc0Vu/strip-priv-key
Browse files Browse the repository at this point in the history
Strip 0x prefixed private key
  • Loading branch information
sc0Vu authored Nov 15, 2020
2 parents 5b14653 + 534fa0d commit be5a106
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Transaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -374,8 +374,13 @@ public function serialize()
*/
public function sign(string $privateKey)
{
if ($this->util->isHex($privateKey)) {
$privateKey = $this->util->stripZero($privateKey);
$ecPrivateKey = $this->secp256k1->keyFromPrivate($privateKey, 'hex');
} else {
throw new InvalidArgumentException('Private key should be hex encoded string');
}
$txHash = $this->hash(false);
$ecPrivateKey = $this->secp256k1->keyFromPrivate($privateKey, 'hex');
$signature = $ecPrivateKey->sign($txHash, [
'canonical' => true
]);
Expand Down
12 changes: 12 additions & 0 deletions test/unit/TransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ public function testSign()
'data' => '0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675'
]);
$this->assertEquals('f892018609184e72a0008276c094d46e8dd67c5d32be8058bb8eb970870f07244567849184e72aa9d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f07244567523a0a48d3ce9c68bb49825aea5335bd07432823e858e8a504767d08290c28aafddf8a0416c7abc3a67080db0ad07c42de82db4e05518f99595119677398c68d431ab37', $transaction->sign($this->testPrivateKey));

// test different private keys
$tests = [
'fake private key', '0xd0459987fdde1f41e524fddbf4b646cd9d3bea7fd7d63feead3f5dfce6174a3d', 'd0459987fdde1f41e524fddbf4b646cd9d3bea7fd7d63feead3f5dfce6174a3d', 'd0459987fdde1f41e524fddbf4b646cd9d3bea7fd7d63feead3f5dfce6174a'
];
for ($i=0; $i<count($tests); $i++) {
try {
$transaction->sign($tests[$i]);
} catch (\InvalidArgumentException $e) {
$this->assertEquals('Private key should be hex encoded string', $e->getMessage());
}
}
}

/**
Expand Down

0 comments on commit be5a106

Please sign in to comment.