Bitcoin Core  0.18.99
P2P Digital Currency
bech32.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017 Pieter Wuille
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <bech32.h>
6 
7 #include <assert.h>
8 
9 namespace
10 {
11 
12 typedef std::vector<uint8_t> data;
13 
15 const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
16 
18 const int8_t CHARSET_REV[128] = {
19  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
20  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
21  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
22  15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1,
23  -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
24  1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1,
25  -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
26  1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1
27 };
28 
30 data Cat(data x, const data& y)
31 {
32  x.insert(x.end(), y.begin(), y.end());
33  return x;
34 }
35 
39 uint32_t PolyMod(const data& v)
40 {
41  // The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an
42  // implicit 1 in front. If the input is [v0,v1,v2,v3,v4], that polynomial is v(x) =
43  // 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4. The implicit 1 guarantees that
44  // [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...].
45 
46  // The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of
47  // v(x) mod g(x), where g(x) is the Bech32 generator,
48  // x^6 + {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}. g(x) is chosen in such a way
49  // that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a
50  // window of 1023 characters. Among the various possible BCH codes, one was selected to in
51  // fact guarantee detection of up to 4 errors within a window of 89 characters.
52 
53  // Note that the coefficients are elements of GF(32), here represented as decimal numbers
54  // between {}. In this finite field, addition is just XOR of the corresponding numbers. For
55  // example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires
56  // treating the bits of values themselves as coefficients of a polynomial over a smaller field,
57  // GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example, {5} * {26} =
58  // (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 + a^3 + a) = a^6 + a^5 + a^4 + a
59  // = a^3 + 1 (mod a^5 + a^3 + 1) = {9}.
60 
61  // During the course of the loop below, `c` contains the bitpacked coefficients of the
62  // polynomial constructed from just the values of v that were processed so far, mod g(x). In
63  // the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of
64  // v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value
65  // for `c`.
66  uint32_t c = 1;
67  for (const auto v_i : v) {
68  // We want to update `c` to correspond to a polynomial with one extra term. If the initial
69  // value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to
70  // correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to
71  // process. Simplifying:
72  // c'(x) = (f(x) * x + v_i) mod g(x)
73  // ((f(x) mod g(x)) * x + v_i) mod g(x)
74  // (c(x) * x + v_i) mod g(x)
75  // If c(x) = c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5, we want to compute
76  // c'(x) = (c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5) * x + v_i mod g(x)
77  // = c0*x^6 + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i mod g(x)
78  // = c0*(x^6 mod g(x)) + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i
79  // If we call (x^6 mod g(x)) = k(x), this can be written as
80  // c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x)
81 
82  // First, determine the value of c0:
83  uint8_t c0 = c >> 25;
84 
85  // Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i:
86  c = ((c & 0x1ffffff) << 5) ^ v_i;
87 
88  // Finally, for each set bit n in c0, conditionally add {2^n}k(x):
89  if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}
90  if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13}
91  if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26}
92  if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29}
93  if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19}
94  }
95  return c;
96 }
97 
99 inline unsigned char LowerCase(unsigned char c)
100 {
101  return (c >= 'A' && c <= 'Z') ? (c - 'A') + 'a' : c;
102 }
103 
105 data ExpandHRP(const std::string& hrp)
106 {
107  data ret;
108  ret.reserve(hrp.size() + 90);
109  ret.resize(hrp.size() * 2 + 1);
110  for (size_t i = 0; i < hrp.size(); ++i) {
111  unsigned char c = hrp[i];
112  ret[i] = c >> 5;
113  ret[i + hrp.size() + 1] = c & 0x1f;
114  }
115  ret[hrp.size()] = 0;
116  return ret;
117 }
118 
120 bool VerifyChecksum(const std::string& hrp, const data& values)
121 {
122  // PolyMod computes what value to xor into the final values to make the checksum 0. However,
123  // if we required that the checksum was 0, it would be the case that appending a 0 to a valid
124  // list of values would result in a new valid list. For that reason, Bech32 requires the
125  // resulting checksum to be 1 instead.
126  return PolyMod(Cat(ExpandHRP(hrp), values)) == 1;
127 }
128 
130 data CreateChecksum(const std::string& hrp, const data& values)
131 {
132  data enc = Cat(ExpandHRP(hrp), values);
133  enc.resize(enc.size() + 6); // Append 6 zeroes
134  uint32_t mod = PolyMod(enc) ^ 1; // Determine what to XOR into those 6 zeroes.
135  data ret(6);
136  for (size_t i = 0; i < 6; ++i) {
137  // Convert the 5-bit groups in mod to checksum values.
138  ret[i] = (mod >> (5 * (5 - i))) & 31;
139  }
140  return ret;
141 }
142 
143 } // namespace
144 
145 namespace bech32
146 {
147 
149 std::string Encode(const std::string& hrp, const data& values) {
150  // First ensure that the HRP is all lowercase. BIP-173 requires an encoder
151  // to return a lowercase Bech32 string, but if given an uppercase HRP, the
152  // result will always be invalid.
153  for (const char& c : hrp) assert(c < 'A' || c > 'Z');
154  data checksum = CreateChecksum(hrp, values);
155  data combined = Cat(values, checksum);
156  std::string ret = hrp + '1';
157  ret.reserve(ret.size() + combined.size());
158  for (const auto c : combined) {
159  ret += CHARSET[c];
160  }
161  return ret;
162 }
163 
165 std::pair<std::string, data> Decode(const std::string& str) {
166  bool lower = false, upper = false;
167  for (size_t i = 0; i < str.size(); ++i) {
168  unsigned char c = str[i];
169  if (c >= 'a' && c <= 'z') lower = true;
170  else if (c >= 'A' && c <= 'Z') upper = true;
171  else if (c < 33 || c > 126) return {};
172  }
173  if (lower && upper) return {};
174  size_t pos = str.rfind('1');
175  if (str.size() > 90 || pos == str.npos || pos == 0 || pos + 7 > str.size()) {
176  return {};
177  }
178  data values(str.size() - 1 - pos);
179  for (size_t i = 0; i < str.size() - 1 - pos; ++i) {
180  unsigned char c = str[i + pos + 1];
181  int8_t rev = CHARSET_REV[c];
182 
183  if (rev == -1) {
184  return {};
185  }
186  values[i] = rev;
187  }
188  std::string hrp;
189  for (size_t i = 0; i < pos; ++i) {
190  hrp += LowerCase(str[i]);
191  }
192  if (!VerifyChecksum(hrp, values)) {
193  return {};
194  }
195  return {hrp, data(values.begin(), values.end() - 6)};
196 }
197 
198 } // namespace bech32
std::pair< std::string, data > Decode(const std::string &str)
Decode a Bech32 string.
Definition: bech32.cpp:165
std::string Encode(const std::string &hrp, const data &values)
Encode a Bech32 string.
Definition: bech32.cpp:149