Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2017, 2021 Pieter Wuille2// Copyright (c) 2021-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <bech32.h>7#include <util/vector.h>9#include <array>10#include <cassert>11#include <optional>13namespace bech3214{16namespace17{19typedef std::vector<uint8_t> data;21/** The Bech32 and Bech32m character set for encoding. */22const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";24/** The Bech32 and Bech32m character set for decoding. */25const 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,2915, -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,311, 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,331, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -134};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 represented40* 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, so43* GF1024_LOG[GF1024_EXP[k]] == k.44* The following function generates the two tables GF1024_EXP and GF1024_LOG as constexprs. */45constexpr std::pair<std::array<int16_t, 1023>, std::array<int16_t, 1024>> GenerateGFTables()46{47// Build table for GF(32).48// We use these tables to perform arithmetic in GF(32) below, when constructing the49// tables for GF(1024).50std::array<int8_t, 31> GF32_EXP{};51std::array<int8_t, 32> GF32_LOG{};53// fmod encodes the defining polynomial of GF(32) over GF(2), x^5 + x^3 + 1.54// Because coefficients in GF(2) are binary digits, the coefficients are packed as 101001.55const int fmod = 41;57// Elements of GF(32) are encoded as vectors of length 5 over GF(2), that is,58// 5 binary digits. Each element (b_4, b_3, b_2, b_1, b_0) encodes a polynomial59// b_4*x^4 + b_3*x^3 + b_2*x^2 + b_1*x^1 + b_0 (modulo fmod).60// For example, 00001 = 1 is the multiplicative identity.61GF32_EXP[0] = 1;62GF32_LOG[0] = -1;63GF32_LOG[1] = 0;64int v = 1;65for (int i = 1; i < 31; ++i) {66// Multiplication by x is the same as shifting left by 1, as67// every coefficient of the polynomial is moved up one place.68v = v << 1;69// If the polynomial now has an x^5 term, we subtract fmod from it70// to remain working modulo fmod. Subtraction is the same as XOR in characteristic71// 2 fields.72if (v & 32) v ^= fmod;73GF32_EXP[i] = v;74GF32_LOG[v] = i;75}77// Build table for GF(1024)78std::array<int16_t, 1023> GF1024_EXP{};79std::array<int16_t, 1024> GF1024_LOG{};81GF1024_EXP[0] = 1;82GF1024_LOG[0] = -1;83GF1024_LOG[1] = 0;85// Each element v of GF(1024) is encoded as a 10 bit integer in the following way:86// v = v1 || v0 where v0, v1 are 5-bit integers (elements of GF(32)).87// The element (e) is encoded as 1 || 0, to represent 1*(e) + 0. Every other element88// a*(e) + b is represented as a || b (a and b are both GF(32) elements). Given (v),89// we compute (e)*(v) by multiplying in the following way:90//91// v0' = 23*v192// v1' = 9*v1 + v093// e*v = v1' || v0'94//95// Where 23, 9 are GF(32) elements encoded as described above. Multiplication in GF(32)96// is done using the log/exp tables:97// e^x * e^y = e^(x + y) so a * b = EXP[ LOG[a] + LOG [b] ]98// for non-zero a and b.100v = 1;101for (int i = 1; i < 1023; ++i) {102int v0 = v & 31;103int v1 = v >> 5;105int v0n = v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(23)) % 31) : 0;106int v1n = (v1 ? GF32_EXP.at((GF32_LOG.at(v1) + GF32_LOG.at(9)) % 31) : 0) ^ v0;108v = v1n << 5 | v0n;109GF1024_EXP[i] = v;110GF1024_LOG[v] = i;111}113return std::make_pair(GF1024_EXP, GF1024_LOG);114}116constexpr auto tables = GenerateGFTables();117constexpr const std::array<int16_t, 1023>& GF1024_EXP = tables.first;118constexpr const std::array<int16_t, 1024>& GF1024_LOG = tables.second;120/* Determine the final constant to use for the specified encoding. */121uint32_t EncodingConstant(Encoding encoding) {122assert(encoding == Encoding::BECH32 || encoding == Encoding::BECH32M);123return encoding == Encoding::BECH32 ? 1 : 0x2bc830a3;124}126/** This function will compute what 6 5-bit values to XOR into the last 6 input values, in order to127* make the checksum 0. These 6 values are packed together in a single 30-bit integer. The higher128* bits correspond to earlier values. */129uint32_t PolyMod(const data& v)130{131// The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an132// 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 that134// [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...].136// The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of137// 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 way139// that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a140// window of 1023 characters. Among the various possible BCH codes, one was selected to in141// fact guarantee detection of up to 4 errors within a window of 89 characters.143// Note that the coefficients are elements of GF(32), here represented as decimal numbers144// between {}. In this finite field, addition is just XOR of the corresponding numbers. For145// example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires146// 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 + a149// = a^3 + 1 (mod a^5 + a^3 + 1) = {9}.151// During the course of the loop below, `c` contains the bitpacked coefficients of the152// polynomial constructed from just the values of v that were processed so far, mod g(x). In153// the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of154// v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value155// for `c`.157// The following Sage code constructs the generator used:158//159// B = GF(2) # Binary field160// BP.<b> = B[] # Polynomials over the binary field161// F_mod = b**5 + b**3 + 1162// F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition163// 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 definition166// 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 generator170//171// It demonstrates that g(x) is the least common multiple of the minimal polynomials172// 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 cycle174// length 1023 and distance 4. See https://en.wikipedia.org/wiki/BCH_code for more details.176uint32_t c = 1;177for (const auto v_i : v) {178// We want to update `c` to correspond to a polynomial with one extra term. If the initial179// value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to180// correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to181// 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 compute186// 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_i189// If we call (x^6 mod g(x)) = k(x), this can be written as190// c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x)192// First, determine the value of c0:193uint8_t c0 = c >> 25;195// Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i:196c = ((c & 0x1ffffff) << 5) ^ v_i;198// Finally, for each set bit n in c0, conditionally add {2^n}k(x). These constants can be199// 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 = 0203// 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//207if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}208if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13}209if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26}210if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29}211if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19}213}214return c;215}217/** Syndrome computes the values s_j = R(e^j) for j in [997, 998, 999]. As described above, the218* 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-packed221* result of computing R(x) mod G(X), where G is the generator of the code. Because C(x) is a valid222* codeword, it is a multiple of G(X), so the residue is in fact just E(x) mod G(x). Note that all223* 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 + r6226*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 + r6229*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 the237* bit values b_i. This is exactly what is done in the Syndrome function below.238*/239constexpr std::array<uint32_t, 25> GenerateSyndromeConstants() {240std::array<uint32_t, 25> SYNDROME_CONSTS{};241for (int k = 1; k < 6; ++k) {242for (int shift = 0; shift < 5; ++shift) {243int16_t b = GF1024_LOG.at(size_t{1} << shift);244int16_t c0 = GF1024_EXP.at((997*k + b) % 1023);245int16_t c1 = GF1024_EXP.at((998*k + b) % 1023);246int16_t c2 = GF1024_EXP.at((999*k + b) % 1023);247uint32_t c = c2 << 20 | c1 << 10 | c0;248int ind = 5*(k-1) + shift;249SYNDROME_CONSTS[ind] = c;250}