/tmp/bitcoin/src/bech32.cpp
Line | Count | Source |
1 | | // Copyright (c) 2017, 2021 Pieter Wuille |
2 | | // Copyright (c) 2021-present 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 | | #include <bech32.h> |
7 | | #include <util/vector.h> |
8 | | |
9 | | #include <array> |
10 | | #include <cassert> |
11 | | #include <optional> |
12 | | |
13 | | namespace bech32 |
14 | | { |
15 | | |
16 | | namespace |
17 | | { |
18 | | |
19 | | typedef std::vector<uint8_t> data; |
20 | | |
21 | | /** The Bech32 and Bech32m character set for encoding. */ |
22 | | const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; |
23 | | |
24 | | /** The Bech32 and Bech32m character set for decoding. */ |
25 | | const int8_t CHARSET_REV[128] = { |
26 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
27 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
28 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
29 | | 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, |
30 | | -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, |
31 | | 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, |
32 | | -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, |
33 | | 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 |
34 | | }; |
35 | | |
36 | | /** We work with the finite field GF(1024) defined as a degree 2 extension of the base field GF(32) |
37 | | * The defining polynomial of the extension is x^2 + 9x + 23. |
38 | | * Let (e) be a root of this defining polynomial. Then (e) is a primitive element of GF(1024), |
39 | | * that is, a generator of the field. Every non-zero element of the field can then be represented |
40 | | * as (e)^k for some power k. |
41 | | * The array GF1024_EXP contains all these powers of (e) - GF1024_EXP[k] = (e)^k in GF(1024). |
42 | | * Conversely, GF1024_LOG contains the discrete logarithms of these powers, so |
43 | | * GF1024_LOG[GF1024_EXP[k]] == k. |
44 | | * The following function generates the two tables GF1024_EXP and GF1024_LOG as constexprs. */ |
45 | | constexpr std::pair<std::array<int16_t, 1023>, std::array<int16_t, 1024>> GenerateGFTables() |
46 | 0 | { |
47 | 0 | // Build table for GF(32). |
48 | 0 | // We use these tables to perform arithmetic in GF(32) below, when constructing the |
49 | 0 | // tables for GF(1024). |
50 | 0 | std::array<int8_t, 31> GF32_EXP{}; |
51 | 0 | std::array<int8_t, 32> GF32_LOG{}; |
52 | 0 |
|
53 | 0 | // fmod encodes the defining polynomial of GF(32) over GF(2), x^5 + x^3 + 1. |
54 | 0 | // Because coefficients in GF(2) are binary digits, the coefficients are packed as 101001. |
55 | 0 | const int fmod = 41; |
56 | 0 |
|
57 | 0 | // Elements of GF(32) are encoded as vectors of length 5 over GF(2), that is, |
58 | 0 | // 5 binary digits. Each element (b_4, b_3, b_2, b_1, b_0) encodes a polynomial |
59 | 0 | // b_4*x^4 + b_3*x^3 + b_2*x^2 + b_1*x^1 + b_0 (modulo fmod). |
60 | 0 | // For example, 00001 = 1 is the multiplicative identity. |
61 | 0 | GF32_EXP[0] = 1; |
62 | 0 | GF32_LOG[0] = -1; |
63 | 0 | GF32_LOG[1] = 0; |
64 | 0 | int v = 1; |
65 | 0 | for (int i = 1; i < 31; ++i) { |
66 | 0 | // Multiplication by x is the same as shifting left by 1, as |
67 | 0 | // every coefficient of the polynomial is moved up one place. |
68 | 0 | v = v << 1; |
69 | 0 | // If the polynomial now has an x^5 term, we subtract fmod from it |
70 | 0 | // to remain working modulo fmod. Subtraction is the same as XOR in characteristic |
71 | 0 | // 2 fields. |
72 | 0 | if (v & 32) v ^= fmod; |
73 | 0 | GF32_EXP[i] = v; |
74 | 0 | GF32_LOG[v] = i; |
75 | 0 | } |
76 | 0 |
|
77 | 0 | // Build table for GF(1024) |
78 | 0 | std::array<int16_t, 1023> GF1024_EXP{}; |
79 | 0 | std::array<int16_t, 1024> GF1024_LOG{}; |
80 | 0 |
|
81 | 0 | GF1024_EXP[0] = 1; |
82 | 0 | GF1024_LOG[0] = -1; |
83 | 0 | GF1024_LOG[1] = 0; |
84 | 0 |
|
85 | 0 | // Each element v of GF(1024) is encoded as a 10 bit integer in the following way: |
86 | 0 | // v = v1 || v0 where v0, v1 are 5-bit integers (elements of GF(32)). |
87 | 0 | // The element (e) is encoded as 1 || 0, to represent 1*(e) + 0. Every other element |
88 | 0 | // a*(e) + b is represented as a || b (a and b are both GF(32) elements). Given (v), |
89 | 0 | // we compute (e)*(v) by multiplying in the following way: |
90 | 0 | // |
91 | 0 | // v0' = 23*v1 |
92 | 0 | // v1' = 9*v1 + v0 |
93 | 0 | // e*v = v1' || v0' |
94 | 0 | // |
95 | 0 | // Where 23, 9 are GF(32) elements encoded as described above. Multiplication in GF(32) |
96 | 0 | // is done using the log/exp tables: |
97 | 0 | // e^x * e^y = e^(x + y) so a * b = EXP[ LOG[a] + LOG [b] ] |
98 | 0 | // for non-zero a and b. |
99 | 0 |
|
100 | 0 | v = 1; |
101 | 0 | for (int i = 1; i < 1023; ++i) { |
102 | 0 | int v0 = v & 31; |
103 | 0 | int v1 = v >> 5; |
104 | 0 |
|
105 | 0 | int v0n = v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(23)) % 31) : 0; |
106 | 0 | int v1n = (v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(9)) % 31) : 0) ^ v0; |
107 | 0 |
|
108 | 0 | v = v1n << 5 | v0n; |
109 | 0 | GF1024_EXP[i] = v; |
110 | 0 | GF1024_LOG[v] = i; |
111 | 0 | } |
112 | 0 |
|
113 | 0 | return std::make_pair(GF1024_EXP, GF1024_LOG); |
114 | 0 | } |
115 | | |
116 | | constexpr auto tables = GenerateGFTables(); |
117 | | constexpr const std::array<int16_t, 1023>& GF1024_EXP = tables.first; |
118 | | constexpr const std::array<int16_t, 1024>& GF1024_LOG = tables.second; |
119 | | |
120 | | /* Determine the final constant to use for the specified encoding. */ |
121 | 62.4k | uint32_t EncodingConstant(Encoding encoding) { |
122 | 62.4k | assert(encoding == Encoding::BECH32 || encoding == Encoding::BECH32M); |
123 | 62.4k | return encoding == Encoding::BECH32 ? 1 : 0x2bc830a3; |
124 | 62.4k | } |
125 | | |
126 | | /** This function will compute what 6 5-bit values to XOR into the last 6 input values, in order to |
127 | | * make the checksum 0. These 6 values are packed together in a single 30-bit integer. The higher |
128 | | * bits correspond to earlier values. */ |
129 | | uint32_t PolyMod(const data& v) |
130 | 61.3k | { |
131 | | // The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an |
132 | | // implicit 1 in front. If the input is [v0,v1,v2,v3,v4], that polynomial is v(x) = |
133 | | // 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4. The implicit 1 guarantees that |
134 | | // [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...]. |
135 | | |
136 | | // The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of |
137 | | // v(x) mod g(x), where g(x) is the Bech32 generator, |
138 | | // 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 |
139 | | // that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a |
140 | | // window of 1023 characters. Among the various possible BCH codes, one was selected to in |
141 | | // fact guarantee detection of up to 4 errors within a window of 89 characters. |
142 | | |
143 | | // Note that the coefficients are elements of GF(32), here represented as decimal numbers |
144 | | // between {}. In this finite field, addition is just XOR of the corresponding numbers. For |
145 | | // example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires |
146 | | // treating the bits of values themselves as coefficients of a polynomial over a smaller field, |
147 | | // GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example, {5} * {26} = |
148 | | // (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 |
149 | | // = a^3 + 1 (mod a^5 + a^3 + 1) = {9}. |
150 | | |
151 | | // During the course of the loop below, `c` contains the bitpacked coefficients of the |
152 | | // polynomial constructed from just the values of v that were processed so far, mod g(x). In |
153 | | // the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of |
154 | | // v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value |
155 | | // for `c`. |
156 | | |
157 | | // The following Sage code constructs the generator used: |
158 | | // |
159 | | // B = GF(2) # Binary field |
160 | | // BP.<b> = B[] # Polynomials over the binary field |
161 | | // F_mod = b**5 + b**3 + 1 |
162 | | // F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition |
163 | | // FP.<x> = F[] # Polynomials over GF(32) |
164 | | // E_mod = x**2 + F.fetch_int(9)*x + F.fetch_int(23) |
165 | | // E.<e> = F.extension(E_mod) # GF(1024) extension field definition |
166 | | // for p in divisors(E.order() - 1): # Verify e has order 1023. |
167 | | // assert((e**p == 1) == (p % 1023 == 0)) |
168 | | // G = lcm([(e**i).minpoly() for i in range(997,1000)]) |
169 | | // print(G) # Print out the generator |
170 | | // |
171 | | // It demonstrates that g(x) is the least common multiple of the minimal polynomials |
172 | | // of 3 consecutive powers (997,998,999) of a primitive element (e) of GF(1024). |
173 | | // That guarantees it is, in fact, the generator of a primitive BCH code with cycle |
174 | | // length 1023 and distance 4. See https://en.wikipedia.org/wiki/BCH_code for more details. |
175 | | |
176 | 61.3k | uint32_t c = 1; |
177 | 3.29M | for (const auto v_i : v) { |
178 | | // We want to update `c` to correspond to a polynomial with one extra term. If the initial |
179 | | // value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to |
180 | | // correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to |
181 | | // process. Simplifying: |
182 | | // c'(x) = (f(x) * x + v_i) mod g(x) |
183 | | // ((f(x) mod g(x)) * x + v_i) mod g(x) |
184 | | // (c(x) * x + v_i) mod g(x) |
185 | | // If c(x) = c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5, we want to compute |
186 | | // c'(x) = (c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5) * x + v_i mod g(x) |
187 | | // = c0*x^6 + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i mod g(x) |
188 | | // = c0*(x^6 mod g(x)) + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i |
189 | | // If we call (x^6 mod g(x)) = k(x), this can be written as |
190 | | // c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x) |
191 | | |
192 | | // First, determine the value of c0: |
193 | 3.29M | uint8_t c0 = c >> 25; |
194 | | |
195 | | // Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i: |
196 | 3.29M | c = ((c & 0x1ffffff) << 5) ^ v_i; |
197 | | |
198 | | // Finally, for each set bit n in c0, conditionally add {2^n}k(x). These constants can be |
199 | | // computed using the following Sage code (continuing the code above): |
200 | | // |
201 | | // for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(g(x) mod x^6), packed in hex integers. |
202 | | // v = 0 |
203 | | // for coef in reversed((F.fetch_int(i)*(G % x**6)).coefficients(sparse=True)): |
204 | | // v = v*32 + coef.integer_representation() |
205 | | // print("0x%x" % v) |
206 | | // |
207 | 3.29M | if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18} |
208 | 3.29M | if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13} |
209 | 3.29M | if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26} |
210 | 3.29M | if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29} |
211 | 3.29M | if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19} |
212 | | |
213 | 3.29M | } |
214 | 61.3k | return c; |
215 | 61.3k | } |
216 | | |
217 | | /** Syndrome computes the values s_j = R(e^j) for j in [997, 998, 999]. As described above, the |
218 | | * generator polynomial G is the LCM of the minimal polynomials of (e)^997, (e)^998, and (e)^999. |
219 | | * |
220 | | * Consider a codeword with errors, of the form R(x) = C(x) + E(x). The residue is the bit-packed |
221 | | * result of computing R(x) mod G(X), where G is the generator of the code. Because C(x) is a valid |
222 | | * codeword, it is a multiple of G(X), so the residue is in fact just E(x) mod G(x). Note that all |
223 | | * of the (e)^j are roots of G(x) by definition, so R((e)^j) = E((e)^j). |
224 | | * |
225 | | * Let R(x) = r1*x^5 + r2*x^4 + r3*x^3 + r4*x^2 + r5*x + r6 |
226 | | * |
227 | | * To compute R((e)^j), we are really computing: |
228 | | * r1*(e)^(j*5) + r2*(e)^(j*4) + r3*(e)^(j*3) + r4*(e)^(j*2) + r5*(e)^j + r6 |
229 | | * |
230 | | * Now note that all of the (e)^(j*i) for i in [5..0] are constants and can be precomputed. |
231 | | * But even more than that, we can consider each coefficient as a bit-string. |
232 | | * For example, take r5 = (b_5, b_4, b_3, b_2, b_1) written out as 5 bits. Then: |
233 | | * r5*(e)^j = b_1*(e)^j + b_2*(2*(e)^j) + b_3*(4*(e)^j) + b_4*(8*(e)^j) + b_5*(16*(e)^j) |
234 | | * where all the (2^i*(e)^j) are constants and can be precomputed. |
235 | | * |
236 | | * Then we just add each of these corresponding constants to our final value based on the |
237 | | * bit values b_i. This is exactly what is done in the Syndrome function below. |
238 | | */ |
239 | 0 | constexpr std::array<uint32_t, 25> GenerateSyndromeConstants() { |
240 | 0 | std::array<uint32_t, 25> SYNDROME_CONSTS{}; |
241 | 0 | for (int k = 1; k < 6; ++k) { |
242 | 0 | for (int shift = 0; shift < 5; ++shift) { |
243 | 0 | int16_t b = GF1024_LOG.at(size_t{1} << shift); |
244 | 0 | int16_t c0 = GF1024_EXP.at((997*k + b) % 1023); |
245 | 0 | int16_t c1 = GF1024_EXP.at((998*k + b) % 1023); |
246 | 0 | int16_t c2 = GF1024_EXP.at((999*k + b) % 1023); |
247 | 0 | uint32_t c = c2 << 20 | c1 << 10 | c0; |
248 | 0 | int ind = 5*(k-1) + shift; |
249 | 0 | SYNDROME_CONSTS[ind] = c; |
250 | 0 | } |
251 | 0 | } |
252 | 0 | return SYNDROME_CONSTS; |
253 | 0 | } |
254 | | constexpr std::array<uint32_t, 25> SYNDROME_CONSTS = GenerateSyndromeConstants(); |
255 | | |
256 | | /** |
257 | | * Syndrome returns the three values s_997, s_998, and s_999 described above, |
258 | | * packed into a 30-bit integer, where each group of 10 bits encodes one value. |
259 | | */ |
260 | 36 | uint32_t Syndrome(const uint32_t residue) { |
261 | | // low is the first 5 bits, corresponding to the r6 in the residue |
262 | | // (the constant term of the polynomial). |
263 | 36 | uint32_t low = residue & 0x1f; |
264 | | |
265 | | // We begin by setting s_j = low = r6 for all three values of j, because these are unconditional. |
266 | 36 | uint32_t result = low ^ (low << 10) ^ (low << 20); |
267 | | |
268 | | // Then for each following bit, we add the corresponding precomputed constant if the bit is 1. |
269 | | // For example, 0x31edd3c4 is 1100011110 1101110100 1111000100 when unpacked in groups of 10 |
270 | | // bits, corresponding exactly to a^999 || a^998 || a^997 (matching the corresponding values in |
271 | | // GF1024_EXP above). In this way, we compute all three values of s_j for j in (997, 998, 999) |
272 | | // simultaneously. Recall that XOR corresponds to addition in a characteristic 2 field. |
273 | 936 | for (int i = 0; i < 25; ++i) { |
274 | 900 | result ^= ((residue >> (5+i)) & 1 ? SYNDROME_CONSTS.at(i) : 0); |
275 | 900 | } |
276 | 36 | return result; |
277 | 36 | } |
278 | | |
279 | | /** Convert to lower case. */ |
280 | | inline unsigned char LowerCase(unsigned char c) |
281 | 55.6k | { |
282 | 55.6k | return (c >= 'A' && c <= 'Z') ? (c - 'A') + 'a' : c; |
283 | 55.6k | } |
284 | | |
285 | | /** Return indices of invalid characters in a Bech32 string. */ |
286 | | bool CheckCharacters(const std::string& str, std::vector<int>& errors) |
287 | 14.0k | { |
288 | 14.0k | bool lower = false, upper = false; |
289 | 654k | for (size_t i = 0; i < str.size(); ++i) { |
290 | 640k | unsigned char c{(unsigned char)(str[i])}; |
291 | 640k | if (c >= 'a' && c <= 'z') { |
292 | 467k | if (upper) { |
293 | 4 | errors.push_back(i); |
294 | 467k | } else { |
295 | 467k | lower = true; |
296 | 467k | } |
297 | 467k | } else if (c >= 'A' && c <= 'Z') { |
298 | 1.97k | if (lower) { |
299 | 28 | errors.push_back(i); |
300 | 1.94k | } else { |
301 | 1.94k | upper = true; |
302 | 1.94k | } |
303 | 170k | } else if (c < 33 || c > 126) { |
304 | 14 | errors.push_back(i); |
305 | 14 | } |
306 | 640k | } |
307 | 14.0k | return errors.empty(); |
308 | 14.0k | } |
309 | | |
310 | | std::vector<unsigned char> PreparePolynomialCoefficients(const std::string& hrp, const data& values) |
311 | 61.3k | { |
312 | 61.3k | data ret; |
313 | 61.3k | ret.reserve(hrp.size() + 1 + hrp.size() + values.size() + CHECKSUM_SIZE); |
314 | | |
315 | | /** Expand a HRP for use in checksum computation. */ |
316 | 294k | for (size_t i = 0; i < hrp.size(); ++i) ret.push_back(hrp[i] >> 5); |
317 | 61.3k | ret.push_back(0); |
318 | 294k | for (size_t i = 0; i < hrp.size(); ++i) ret.push_back(hrp[i] & 0x1f); |
319 | | |
320 | 61.3k | ret.insert(ret.end(), values.begin(), values.end()); |
321 | | |
322 | 61.3k | return ret; |
323 | 61.3k | } |
324 | | |
325 | | /** Verify a checksum. */ |
326 | | Encoding VerifyChecksum(const std::string& hrp, const data& values) |
327 | 13.9k | { |
328 | | // PolyMod computes what value to xor into the final values to make the checksum 0. However, |
329 | | // if we required that the checksum was 0, it would be the case that appending a 0 to a valid |
330 | | // list of values would result in a new valid list. For that reason, Bech32 requires the |
331 | | // resulting checksum to be 1 instead. In Bech32m, this constant was amended. See |
332 | | // https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e for details. |
333 | 13.9k | auto enc = PreparePolynomialCoefficients(hrp, values); |
334 | 13.9k | const uint32_t check = PolyMod(enc); |
335 | 13.9k | if (check == EncodingConstant(Encoding::BECH32)) return Encoding::BECH32; |
336 | 1.05k | if (check == EncodingConstant(Encoding::BECH32M)) return Encoding::BECH32M; |
337 | 17 | return Encoding::INVALID; |
338 | 1.05k | } |
339 | | |
340 | | /** Create a checksum. */ |
341 | | data CreateChecksum(Encoding encoding, const std::string& hrp, const data& values) |
342 | 47.3k | { |
343 | 47.3k | auto enc = PreparePolynomialCoefficients(hrp, values); |
344 | 47.3k | enc.insert(enc.end(), CHECKSUM_SIZE, 0x00); |
345 | 47.3k | uint32_t mod = PolyMod(enc) ^ EncodingConstant(encoding); // Determine what to XOR into those 6 zeroes. |
346 | 47.3k | data ret(CHECKSUM_SIZE); |
347 | 331k | for (size_t i = 0; i < CHECKSUM_SIZE; ++i) { |
348 | | // Convert the 5-bit groups in mod to checksum values. |
349 | 284k | ret[i] = (mod >> (5 * (5 - i))) & 31; |
350 | 284k | } |
351 | 47.3k | return ret; |
352 | 47.3k | } |
353 | | |
354 | | } // namespace |
355 | | |
356 | | /** Encode a Bech32 or Bech32m string. */ |
357 | 47.3k | std::string Encode(Encoding encoding, const std::string& hrp, const data& values) { |
358 | | // First ensure that the HRP is all lowercase. BIP-173 and BIP350 require an encoder |
359 | | // to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the |
360 | | // result will always be invalid. |
361 | 47.3k | for (const char& c : hrp) assert(c < 'A' || c > 'Z'); |
362 | | |
363 | 47.3k | std::string ret; |
364 | 47.3k | ret.reserve(hrp.size() + 1 + values.size() + CHECKSUM_SIZE); |
365 | 47.3k | ret += hrp; |
366 | 47.3k | ret += SEPARATOR; |
367 | 1.90M | for (const uint8_t& i : values) ret += CHARSET[i]; |
368 | 284k | for (const uint8_t& i : CreateChecksum(encoding, hrp, values)) ret += CHARSET[i]; |
369 | 47.3k | return ret; |
370 | 47.3k | } |
371 | | |
372 | | /** Decode a Bech32 or Bech32m string. */ |
373 | 13.9k | DecodeResult Decode(const std::string& str, CharLimit limit) { |
374 | 13.9k | std::vector<int> errors; |
375 | 13.9k | if (!CheckCharacters(str, errors)) return {}; |
376 | 13.9k | size_t pos = str.rfind(SEPARATOR); |
377 | 13.9k | if (str.size() > limit) return {}; |
378 | 13.9k | if (pos == str.npos || pos == 0 || pos + CHECKSUM_SIZE >= str.size()) { |
379 | 11 | return {}; |
380 | 11 | } |
381 | 13.9k | data values(str.size() - 1 - pos); |
382 | 582k | for (size_t i = 0; i < str.size() - 1 - pos; ++i) { |
383 | 568k | unsigned char c = str[i + pos + 1]; |
384 | 568k | int8_t rev = CHARSET_REV[c]; |
385 | | |
386 | 568k | if (rev == -1) { |
387 | 7 | return {}; |
388 | 7 | } |
389 | 568k | values[i] = rev; |
390 | 568k | } |
391 | 13.9k | std::string hrp; |
392 | 13.9k | hrp.reserve(pos); |
393 | 69.5k | for (size_t i = 0; i < pos; ++i) { |
394 | 55.6k | hrp += LowerCase(str[i]); |
395 | 55.6k | } |
396 | 13.9k | Encoding result = VerifyChecksum(hrp, values); |
397 | 13.9k | if (result == Encoding::INVALID) return {}; |
398 | 13.9k | return {result, std::move(hrp), data(values.begin(), values.end() - CHECKSUM_SIZE)}; |
399 | 13.9k | } |
400 | | |
401 | | /** Find index of an incorrect character in a Bech32 string. */ |
402 | 54 | std::pair<std::string, std::vector<int>> LocateErrors(const std::string& str, CharLimit limit) { |
403 | 54 | std::vector<int> error_locations{}; |
404 | | |
405 | 54 | if (str.size() > limit) { |
406 | 4 | error_locations.push_back(static_cast<int>(limit)); |
407 | 4 | return std::make_pair("Bech32 string too long", std::move(error_locations)); |
408 | 4 | } |
409 | | |
410 | 50 | if (!CheckCharacters(str, error_locations)){ |
411 | 14 | return std::make_pair("Invalid character or mixed case", std::move(error_locations)); |
412 | 14 | } |
413 | | |
414 | 36 | size_t pos = str.rfind(SEPARATOR); |
415 | 36 | if (pos == str.npos) { |
416 | 3 | return std::make_pair("Missing separator", std::vector<int>{}); |
417 | 3 | } |
418 | 33 | if (pos == 0 || pos + CHECKSUM_SIZE >= str.size()) { |
419 | 8 | error_locations.push_back(pos); |
420 | 8 | return std::make_pair("Invalid separator position", std::move(error_locations)); |
421 | 8 | } |
422 | | |
423 | 25 | std::string hrp; |
424 | 25 | hrp.reserve(pos); |
425 | 95 | for (size_t i = 0; i < pos; ++i) { |
426 | 70 | hrp += LowerCase(str[i]); |
427 | 70 | } |
428 | | |
429 | 25 | size_t length = str.size() - 1 - pos; // length of data part |
430 | 25 | data values(length); |
431 | 747 | for (size_t i = pos + 1; i < str.size(); ++i) { |
432 | 729 | unsigned char c = str[i]; |
433 | 729 | int8_t rev = CHARSET_REV[c]; |
434 | 729 | if (rev == -1) { |
435 | 7 | error_locations.push_back(i); |
436 | 7 | return std::make_pair("Invalid Base 32 character", std::move(error_locations)); |
437 | 7 | } |
438 | 722 | values[i - pos - 1] = rev; |
439 | 722 | } |
440 | | |
441 | | // We attempt error detection with both bech32 and bech32m, and choose the one with the fewest errors |
442 | | // We can't simply use the segwit version, because that may be one of the errors |
443 | 18 | std::optional<Encoding> error_encoding; |
444 | 36 | for (Encoding encoding : {Encoding::BECH32, Encoding::BECH32M}) { |
445 | 36 | std::vector<int> possible_errors; |
446 | | // Recall that (expanded hrp + values) is interpreted as a list of coefficients of a polynomial |
447 | | // over GF(32). PolyMod computes the "remainder" of this polynomial modulo the generator G(x). |
448 | 36 | auto enc = PreparePolynomialCoefficients(hrp, values); |
449 | 36 | uint32_t residue = PolyMod(enc) ^ EncodingConstant(encoding); |
450 | | |
451 | | // All valid codewords should be multiples of G(x), so this remainder (after XORing with the encoding |
452 | | // constant) should be 0 - hence 0 indicates there are no errors present. |
453 | 36 | if (residue != 0) { |
454 | | // If errors are present, our polynomial must be of the form C(x) + E(x) where C is the valid |
455 | | // codeword (a multiple of G(x)), and E encodes the errors. |
456 | 36 | uint32_t syn = Syndrome(residue); |
457 | | |
458 | | // Unpack the three 10-bit syndrome values |
459 | 36 | int s0 = syn & 0x3FF; |
460 | 36 | int s1 = (syn >> 10) & 0x3FF; |
461 | 36 | int s2 = syn >> 20; |
462 | | |
463 | | // Get the discrete logs of these values in GF1024 for more efficient computation |
464 | 36 | int l_s0 = GF1024_LOG.at(s0); |
465 | 36 | int l_s1 = GF1024_LOG.at(s1); |
466 | 36 | int l_s2 = GF1024_LOG.at(s2); |
467 | | |
468 | | // First, suppose there is only a single error. Then E(x) = e1*x^p1 for some position p1 |
469 | | // Then s0 = E((e)^997) = e1*(e)^(997*p1) and s1 = E((e)^998) = e1*(e)^(998*p1) |
470 | | // Therefore s1/s0 = (e)^p1, and by the same logic, s2/s1 = (e)^p1 too. |
471 | | // Hence, s1^2 == s0*s2, which is exactly the condition we check first: |
472 | 36 | if (l_s0 != -1 && l_s1 != -1 && l_s2 != -1 && (2 * l_s1 - l_s2 - l_s0 + 2046) % 1023 == 0) { |
473 | | // Compute the error position p1 as l_s1 - l_s0 = p1 (mod 1023) |
474 | 14 | size_t p1 = (l_s1 - l_s0 + 1023) % 1023; // the +1023 ensures it is positive |
475 | | // Now because s0 = e1*(e)^(997*p1), we get e1 = s0/((e)^(997*p1)). Remember that (e)^1023 = 1, |
476 | | // so 1/((e)^997) = (e)^(1023-997). |
477 | 14 | int l_e1 = l_s0 + (1023 - 997) * p1; |
478 | | // Finally, some sanity checks on the result: |
479 | | // - The error position should be within the length of the data |
480 | | // - e1 should be in GF(32), which implies that e1 = (e)^(33k) for some k (the 31 non-zero elements |
481 | | // of GF(32) form an index 33 subgroup of the 1023 non-zero elements of GF(1024)). |
482 | 14 | if (p1 < length && !(l_e1 % 33)) { |
483 | | // Polynomials run from highest power to lowest, so the index p1 is from the right. |
484 | | // We don't return e1 because it is dangerous to suggest corrections to the user, |
485 | | // the user should check the address themselves. |
486 | 12 | possible_errors.push_back(str.size() - p1 - 1); |
487 | 12 | } |
488 | | // Otherwise, suppose there are two errors. Then E(x) = e1*x^p1 + e2*x^p2. |
489 | 22 | } else { |
490 | | // For all possible first error positions p1 |
491 | 733 | for (size_t p1 = 0; p1 < length; ++p1) { |
492 | | // We have guessed p1, and want to solve for p2. Recall that E(x) = e1*x^p1 + e2*x^p2, so |
493 | | // s0 = E((e)^997) = e1*(e)^(997^p1) + e2*(e)^(997*p2), and similar for s1 and s2. |
494 | | // |
495 | | // Consider s2 + s1*(e)^p1 |
496 | | // = 2e1*(e)^(999^p1) + e2*(e)^(999*p2) + e2*(e)^(998*p2)*(e)^p1 |
497 | | // = e2*(e)^(999*p2) + e2*(e)^(998*p2)*(e)^p1 |
498 | | // (Because we are working in characteristic 2.) |
499 | | // = e2*(e)^(998*p2) ((e)^p2 + (e)^p1) |
500 | | // |
501 | 715 | int s2_s1p1 = s2 ^ (s1 == 0 ? 0 : GF1024_EXP.at((l_s1 + p1) % 1023)); |
502 | 715 | if (s2_s1p1 == 0) continue; |
503 | 715 | int l_s2_s1p1 = GF1024_LOG.at(s2_s1p1); |
504 | | |
505 | | // Similarly, s1 + s0*(e)^p1 |
506 | | // = e2*(e)^(997*p2) ((e)^p2 + (e)^p1) |
507 | 715 | int s1_s0p1 = s1 ^ (s0 == 0 ? 0 : GF1024_EXP.at((l_s0 + p1) % 1023)); |
508 | 715 | if (s1_s0p1 == 0) continue; |
509 | 713 | int l_s1_s0p1 = GF1024_LOG.at(s1_s0p1); |
510 | | |
511 | | // So, putting these together, we can compute the second error position as |
512 | | // (e)^p2 = (s2 + s1^p1)/(s1 + s0^p1) |
513 | | // p2 = log((e)^p2) |
514 | 713 | size_t p2 = (l_s2_s1p1 - l_s1_s0p1 + 1023) % 1023; |
515 | | |
516 | | // Sanity checks that p2 is a valid position and not the same as p1 |
517 | 713 | if (p2 >= length || p1 == p2) continue; |
518 | | |
519 | | // Now we want to compute the error values e1 and e2. |
520 | | // Similar to above, we compute s1 + s0*(e)^p2 |
521 | | // = e1*(e)^(997*p1) ((e)^p1 + (e)^p2) |
522 | 40 | int s1_s0p2 = s1 ^ (s0 == 0 ? 0 : GF1024_EXP.at((l_s0 + p2) % 1023)); |
523 | 40 | if (s1_s0p2 == 0) continue; |
524 | 40 | int l_s1_s0p2 = GF1024_LOG.at(s1_s0p2); |
525 | | |
526 | | // And compute (the log of) 1/((e)^p1 + (e)^p2)) |
527 | 40 | int inv_p1_p2 = 1023 - GF1024_LOG.at(GF1024_EXP.at(p1) ^ GF1024_EXP.at(p2)); |
528 | | |
529 | | // Then (s1 + s0*(e)^p1) * (1/((e)^p1 + (e)^p2))) |
530 | | // = e2*(e)^(997*p2) |
531 | | // Then recover e2 by dividing by (e)^(997*p2) |
532 | 40 | int l_e2 = l_s1_s0p1 + inv_p1_p2 + (1023 - 997) * p2; |
533 | | // Check that e2 is in GF(32) |
534 | 40 | if (l_e2 % 33) continue; |
535 | | |
536 | | // In the same way, (s1 + s0*(e)^p2) * (1/((e)^p1 + (e)^p2))) |
537 | | // = e1*(e)^(997*p1) |
538 | | // So recover e1 by dividing by (e)^(997*p1) |
539 | 7 | int l_e1 = l_s1_s0p2 + inv_p1_p2 + (1023 - 997) * p1; |
540 | | // Check that e1 is in GF(32) |
541 | 7 | if (l_e1 % 33) continue; |
542 | | |
543 | | // Again, we do not return e1 or e2 for safety. |
544 | | // Order the error positions from the left of the string and return them |
545 | 4 | if (p1 > p2) { |
546 | 0 | possible_errors.push_back(str.size() - p1 - 1); |
547 | 0 | possible_errors.push_back(str.size() - p2 - 1); |
548 | 4 | } else { |
549 | 4 | possible_errors.push_back(str.size() - p2 - 1); |
550 | 4 | possible_errors.push_back(str.size() - p1 - 1); |
551 | 4 | } |
552 | 4 | break; |
553 | 7 | } |
554 | 22 | } |
555 | 36 | } else { |
556 | | // No errors |
557 | 0 | return std::make_pair("", std::vector<int>{}); |
558 | 0 | } |
559 | | |
560 | 36 | if (error_locations.empty() || (!possible_errors.empty() && possible_errors.size() < error_locations.size())) { |
561 | 22 | error_locations = std::move(possible_errors); |
562 | 22 | if (!error_locations.empty()) error_encoding = encoding; |
563 | 22 | } |
564 | 36 | } |
565 | 18 | std::string error_message = error_encoding == Encoding::BECH32M ? "Invalid Bech32m checksum" |
566 | 18 | : error_encoding == Encoding::BECH32 ? "Invalid Bech32 checksum" |
567 | 16 | : "Invalid checksum"; |
568 | | |
569 | 18 | return std::make_pair(error_message, std::move(error_locations)); |
570 | 18 | } |
571 | | |
572 | | } // namespace bech32 |