1
// Copyright © 2017 Pieter Wuille
2
// Copyright © 2017-2020 Trust Wallet.
3
//
4
// This file is part of Trust. The full Trust copyright notice, including
5
// terms governing use, modification, and redistribution, is contained in the
6
// file LICENSE at the root of the source code distribution tree.
7

8
#include <cstdint>
9
#include <string>
10
#include <vector>
11

12
namespace TW::Bech32 {
13

14
/// Encodes a Bech32 string.
15
///
16
/// \returns the encoded string, or an empty string in case of failure.
17
std::string encode(const std::string& hrp, const std::vector<uint8_t>& values);
18

19
/// Decodes a Bech32 string.
20
///
21
/// \returns a pair with the human-readable part and the data, or a pair or
22
/// empty collections on failure.
23
std::pair<std::string, std::vector<uint8_t>> decode(const std::string& str);
24

25
/// Converts from one power-of-2 number base to another.
26
template <int frombits, int tobits, bool pad>
27 1
inline bool convertBits(std::vector<uint8_t>& out, const std::vector<uint8_t>& in) {
28 1
    int acc = 0;
29 1
    int bits = 0;
30 1
    const int maxv = (1 << tobits) - 1;
31 1
    const int max_acc = (1 << (frombits + tobits - 1)) - 1;
32 1
    for (const auto& value : in) {
33 1
        acc = ((acc << frombits) | value) & max_acc;
34 1
        bits += frombits;
35 1
        while (bits >= tobits) {
36 1
            bits -= tobits;
37 1
            out.push_back((acc >> bits) & maxv);
38
        }
39
    }
40
    if (pad) {
41 1
        if (bits)
42 1
            out.push_back((acc << (tobits - bits)) & maxv);
43 1
    } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) {
44 1
        return false;
45
    }
46 1
    return true;
47
}
48

49
} // namespace TW::Bech32

Read our documentation on viewing source code .

Loading