1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BitWasp\Bitcoin\Crypto\EcAdapter; |
6
|
|
|
|
7
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface; |
8
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Adapter\EcAdapter as PhpEcc; |
9
|
|
|
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Adapter\EcAdapter as Secp256k1; |
10
|
|
|
use BitWasp\Bitcoin\Math\Math; |
11
|
|
|
use Composer\Semver\Semver; |
12
|
|
|
use Mdanter\Ecc\Primitives\GeneratorPoint; |
13
|
|
|
|
14
|
|
|
class EcAdapterFactory |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var EcAdapterInterface |
18
|
|
|
*/ |
19
|
|
|
private static $adapter; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var |
23
|
|
|
*/ |
24
|
|
|
private static $context; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param int|null $flags |
28
|
|
|
* @return resource |
29
|
|
|
*/ |
30
|
|
|
public static function getSecp256k1Context(int $flags = null) |
31
|
|
|
{ |
32
|
|
|
if (!extension_loaded('secp256k1')) { |
33
|
|
|
throw new \RuntimeException('Secp256k1 not installed'); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (self::$context === null) { |
37
|
|
|
self::$context = secp256k1_context_create($flags ?: SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return self::$context; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param Math $math |
45
|
|
|
* @param GeneratorPoint $generator |
46
|
|
|
* @return EcAdapterInterface |
47
|
|
|
*/ |
48
|
|
|
public static function getAdapter(Math $math, GeneratorPoint $generator): EcAdapterInterface |
49
|
|
|
{ |
50
|
|
|
if (self::$adapter !== null) { |
51
|
|
|
return self::$adapter; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
if (extension_loaded('secp256k1') && Semver::satisfies(phpversion('secp256k1'), "~0.1.0")) { |
55
|
|
|
self::$adapter = self::getSecp256k1($math, $generator); |
56
|
|
|
} else { |
57
|
|
|
self::$adapter = self::getPhpEcc($math, $generator); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return self::$adapter; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param EcAdapterInterface $ecAdapter |
65
|
|
|
*/ |
66
|
|
|
public static function setAdapter(EcAdapterInterface $ecAdapter) |
67
|
|
|
{ |
68
|
|
|
self::$adapter = $ecAdapter; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param Math $math |
73
|
|
|
* @param GeneratorPoint $generator |
74
|
|
|
* @return PhpEcc |
75
|
|
|
*/ |
76
|
|
|
public static function getPhpEcc(Math $math, GeneratorPoint $generator): PhpEcc |
77
|
|
|
{ |
78
|
|
|
return new PhpEcc($math, $generator); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @param Math $math |
83
|
|
|
* @param GeneratorPoint $generator |
84
|
|
|
* @return Secp256k1 |
85
|
|
|
*/ |
86
|
|
|
public static function getSecp256k1(Math $math, GeneratorPoint $generator): Secp256k1 |
87
|
|
|
{ |
88
|
|
|
return new Secp256k1($math, $generator, self::getSecp256k1Context()); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|