Completed
Branch master (95c3c5)
by
unknown
05:09
created

Mnemonic::decode()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 4
nop 1
1
<?php
2
3
namespace Blocktrail\SDK\V3Crypt;
4
5
use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
6
use BitWasp\Buffertools\Buffer;
7
use BitWasp\Buffertools\BufferInterface;
8
9
class Mnemonic
10
{
11
    const CHUNK_SIZE = 4;
12
    const PADDING_DUMMY = "\x81";
13
14
    /**
15
     * @param string $data
16
     * @return string
17
     */
18
    private static function derivePadding($data) {
19
        if (strlen($data) > 0 && ord($data[0]) > 0x80) {
20
            throw new \RuntimeException('Sanity check: data for mnemonic is not valid');
21
        }
22
23
        $padLen = self::CHUNK_SIZE - (strlen($data) % self::CHUNK_SIZE);
24
        return str_pad('', $padLen, self::PADDING_DUMMY);
25
    }
26
27
    /**
28
     * @param BufferInterface $data
29
     * @return string
30
     */
31
    public static function encode(BufferInterface $data) {
32
        $bip39 = MnemonicFactory::bip39();
33
        $mnemonic = $bip39->entropyToMnemonic(new Buffer(self::derivePadding($data->getBinary()) . $data->getBinary()));
34
35
        try {
36
            $bip39->mnemonicToEntropy($mnemonic);
37
        } catch (\Exception $e) {
38
            throw new \RuntimeException('BIP39 produced an invalid mnemonic');
39
        }
40
41
        return $mnemonic;
42
    }
43
44
    /**
45
     * @param string $mnemonic
46
     * @return BufferInterface
47
     */
48
    public static function decode($mnemonic) {
49
        $bip39 = MnemonicFactory::bip39();
50
        $decoded = $bip39->mnemonicToEntropy($mnemonic)->getBinary();
51
        $padFinish = 0;
52
        while ($decoded[$padFinish] === self::PADDING_DUMMY) {
53
            $padFinish++;
54
        }
55
56
        $data = substr($decoded, $padFinish);
57
        if (self::derivePadding($data) !== substr($decoded, 0, $padFinish)) {
58
            throw new \RuntimeException('The data was incorrectly padded');
59
        }
60
61
        return new Buffer($data);
62
    }
63
}
64