Skip to content

Commit

Permalink
feat: implement PublicKey#fromMultiSignatureAsset (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
faustbrian authored Nov 19, 2020
1 parent 0964beb commit 8fe4b62
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"php": "^7.2",
"bitwasp/bitcoin": "^1.0",
"kodekeep/binary": "^1.0",
"kodekeep/bytebuffer": "^1.0"
"kodekeep/bytebuffer": "^1.0",
"simplito/elliptic-php": "^1.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.16",
Expand Down
24 changes: 24 additions & 0 deletions src/Identities/PublicKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use BitWasp\Bitcoin\Crypto\EcAdapter\EcAdapterFactory;
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PublicKey as EcPublicKey;
use BitWasp\Bitcoin\Key\Factory\PublicKeyFactory;
use Elliptic\EC;

/**
* This is the public key class.
Expand All @@ -37,6 +38,29 @@ public static function fromPassphrase(string $passphrase): EcPublicKey
return PrivateKey::fromPassphrase($passphrase)->getPublicKey();
}

/**
* Create a public key instance from a multi-signature asset.
*
* @param int $min
* @param array $publicKeys
*
* @return \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PublicKey
*/
public static function fromMultiSignatureAsset(int $min, array $publicKeys): EcPublicKey
{
$minKey = static::fromPassphrase('0'.dechex($min));
$keys = [$minKey->getHex(), ...$publicKeys];

$curve = (new EC('secp256k1'))->curve;
$P = $curve->jpoint(null, null, null);

foreach ($keys as $publicKey) {
$P = $P->add($curve->decodePoint($publicKey, 'hex'));
}

return static::fromHex(bin2hex(implode(array_map('chr', $P->encodeCompressed(true)))));
}

/**
* Create a public key instance from a hex string.
*
Expand Down
15 changes: 15 additions & 0 deletions tests/Unit/Identities/PublicKeyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ public function it_should_get_the_public_key_from_passphrase()
$this->assertSame($fixture['data']['publicKey'], $actual->getHex());
}

/** @test */
public function it_should_get_the_public_key_from_a_multi_signature_asset()
{
$actual = TestClass::fromMultiSignatureAsset(3, [
TestClass::fromPassphrase('secret 1')->getHex(),
TestClass::fromPassphrase('secret 2')->getHex(),
TestClass::fromPassphrase('secret 3')->getHex(),
]);

$this->assertSame(
'0279f05076556da7173610a7676399c3620276ebbf8c67552ad3b1f26ec7627794',
$actual->getHex()
);
}

/** @test */
public function it_should_get_the_public_key_from_hex()
{
Expand Down

0 comments on commit 8fe4b62

Please sign in to comment.