Line data Source code
1 : // Copyright (c) 2017, 2021 Pieter Wuille 2 : // Copyright (c) 2021 The Bitcoin Core developers 3 : // Distributed under the MIT software license, see the accompanying 4 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 5 : 6 : // Bech32 and Bech32m are string encoding formats used in newer 7 : // address types. The outputs consist of a human-readable part 8 : // (alphanumeric), a separator character (1), and a base32 data 9 : // section, the last 6 characters of which are a checksum. The 10 : // module is namespaced under bech32 for historical reasons. 11 : // 12 : // For more information, see BIP 173 and BIP 350. 13 : 14 : #ifndef BITCOIN_BECH32_H 15 : #define BITCOIN_BECH32_H 16 : 17 : #include <stdint.h> 18 : #include <string> 19 : #include <vector> 20 : 21 : namespace bech32 22 : { 23 : 24 : enum class Encoding { 25 : INVALID, //!< Failed decoding 26 : 27 : BECH32, //!< Bech32 encoding as defined in BIP173 28 : BECH32M, //!< Bech32m encoding as defined in BIP350 29 : }; 30 : 31 : /** Encode a Bech32 or Bech32m string. If hrp contains uppercase characters, this will cause an 32 : * assertion error. Encoding must be one of BECH32 or BECH32M. */ 33 : std::string Encode(Encoding encoding, const std::string& hrp, const std::vector<uint8_t>& values); 34 : 35 : struct DecodeResult 36 : { 37 : Encoding encoding; //!< What encoding was detected in the result; Encoding::INVALID if failed. 38 : std::string hrp; //!< The human readable part 39 : std::vector<uint8_t> data; //!< The payload (excluding checksum) 40 : 41 0 : DecodeResult() : encoding(Encoding::INVALID) {} 42 0 : DecodeResult(Encoding enc, std::string&& h, std::vector<uint8_t>&& d) : encoding(enc), hrp(std::move(h)), data(std::move(d)) {} 43 : }; 44 : 45 : /** Decode a Bech32 or Bech32m string. */ 46 : DecodeResult Decode(const std::string& str); 47 : 48 : /** Return the positions of errors in a Bech32 string. */ 49 : std::pair<std::string, std::vector<int>> LocateErrors(const std::string& str); 50 : 51 : } // namespace bech32 52 : 53 : #endif // BITCOIN_BECH32_H