forked from Bit-Wasp/bitcoin-php
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathElectrumKeyFactory.php
More file actions
91 lines (78 loc) · 2.51 KB
/
ElectrumKeyFactory.php
File metadata and controls
91 lines (78 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
namespace BitWasp\Bitcoin\Key\Factory;
use BitWasp\Bitcoin\Bitcoin;
use BitWasp\Bitcoin\Crypto\EcAdapter\Adapter\EcAdapterInterface;
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\KeyInterface;
use BitWasp\Bitcoin\Key\Deterministic\ElectrumKey;
use BitWasp\Bitcoin\Mnemonic\Electrum\ElectrumWordListInterface;
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\BufferInterface;
class ElectrumKeyFactory
{
/**
* @var EcAdapterInterface
*/
private $adapter;
/**
* @var PrivateKeyFactory
*/
private $privateFactory;
/**
* ElectrumKeyFactory constructor.
* @param EcAdapterInterface|null $ecAdapter
*/
public function __construct(?EcAdapterInterface $ecAdapter = null)
{
$this->adapter = $ecAdapter ?: Bitcoin::getEcAdapter();
$this->privateFactory = new PrivateKeyFactory($ecAdapter);
}
/**
* @param string $mnemonic
* @param ElectrumWordListInterface $wordList
* @return ElectrumKey
* @throws \Exception
*/
public function fromMnemonic(string $mnemonic, ?ElectrumWordListInterface $wordList = null): ElectrumKey
{
$mnemonicConverter = MnemonicFactory::electrum($wordList, $this->adapter);
$entropy = $mnemonicConverter->mnemonicToEntropy($mnemonic);
return $this->getKeyFromSeed($entropy);
}
/**
* @param BufferInterface $seed
* @return ElectrumKey
* @throws \Exception
*/
public function getKeyFromSeed(BufferInterface $seed): ElectrumKey
{
// Really weird, did electrum actually hash hex string seeds?
$binary = $oldseed = $seed->getHex();
// Perform sha256 hash 5 times per iteration
for ($i = 0; $i < 5*20000; $i++) {
// Hash should return binary data
$binary = hash('sha256', $binary . $oldseed, true);
}
// Convert binary data to hex.
$secretExponent = new Buffer($binary, 32);
return $this->fromSecretExponent($secretExponent);
}
/**
* @param BufferInterface $secret
* @return ElectrumKey
*/
public function fromSecretExponent(BufferInterface $secret): ElectrumKey
{
$masterKey = $this->privateFactory->fromBufferUncompressed($secret);
return $this->fromKey($masterKey);
}
/**
* @param KeyInterface $key
* @return ElectrumKey
*/
public function fromKey(KeyInterface $key): ElectrumKey
{
return new ElectrumKey($key);
}
}