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