Completed
Push — 0.0.35 ( b2fc74...d8d049 )
by thomas
28:12 queued 09:10
created

EcAdapterFactory::getSecp256k1()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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