Skip to content

Commit 5c48bf4

Browse files
committed
pubkey validation
1 parent ede21ba commit 5c48bf4

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

src/AddressSerializer.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ public function __construct(Bitcoin $network = null)
4040
*/
4141
public function hashToAddress(string $hash160, int $prefix): string
4242
{
43+
if (strlen($hash160) != 20) {
44+
throw new \InvalidArgumentException('Invalid hash160 size.');
45+
}
46+
4347
$hash160 = chr($prefix) . $hash160;
4448
$checksum = substr(Utils::hash256($hash160, true), 0, 4);
4549
$address = $hash160 . $checksum;
@@ -54,6 +58,10 @@ public function hashToAddress(string $hash160, int $prefix): string
5458
*/
5559
public function pubKeyToAddress(string $pubKey, int $prefix): string
5660
{
61+
if (!PublicKey::parse($pubKey)->isValid()) {
62+
throw new \InvalidArgumentException('Invalid public key.');
63+
}
64+
5765
return $this->hashToAddress(Utils::hash160($pubKey, true), $prefix);
5866
}
5967

src/PublicKey.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,20 @@ public function isCompressed(): bool
8383
return is_null($this->y);
8484
}
8585

86+
/**
87+
* @return bool
88+
*/
89+
public function isValid(): bool
90+
{
91+
try {
92+
$this->getEccPublicKey();
93+
} catch (\Exception $exception) {
94+
return false;
95+
}
96+
97+
return true;
98+
}
99+
86100
/**
87101
* @return PublicKey
88102
* @throws PublicKeyException
@@ -133,7 +147,7 @@ public function getEccPublicKey(): \Mdanter\Ecc\Crypto\Key\PublicKey
133147
$key = $this;
134148
}
135149

136-
$point = $curve->getPoint($key->getX(), $this->getY());
150+
$point = $curve->getPoint($key->getX(), $key->getY());
137151

138152
return new \Mdanter\Ecc\Crypto\Key\PublicKey($adapter, $generator, $point);
139153
}

tests/PublicKeyTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,12 @@ public function testSerializeCompressed()
7676

7777
$this->assertEquals($pk->serialize(), hex2bin($key));
7878
}
79+
80+
public function testValid()
81+
{
82+
$key = '040a464653204c756b652d4a72206c656176652074686520626c6f636b636861696e20616c6f6e65210a4f682c20616e6420676f642069736e2774207265616c0a';
83+
84+
$pk = PublicKey::parse(hex2bin($key));
85+
$this->assertFalse($pk->isValid());
86+
}
7987
}

0 commit comments

Comments
 (0)