Skip to content

Commit fd8f99c

Browse files
authored
bch(m4): ABLA replay + dynamic per-tip template size budget (M4 anchor) (#120)
* bch(m3): ASERT (aserti3-2d) DAA — 1:1 BCHN pow.cpp port Net-new BCH-specific validation slice (M1 §4.3, no btc/ analogue). CalculateASERT + GetNextASERTWorkRequired ported byte-exact from BCHN src/pow.cpp; anchors from chainparams.cpp (main/testnet3/testnet4). Governs SPV header-accept target only — PoW hash stays SHA256d, zero share-format / p2pool-merged-v36 surface change. Syntax-clean -std=c++20. * bch(m3): header-chain validation wired to ASERT DAA (M3 slice 18b) Port src/impl/btc/coin/header_chain.hpp to BCH: same store/sync/persistence and SHA256d PoW, with the one BCH divergence being difficulty. Replaces Bitcoin's 2016-block 2-week retarget with ASERT (aserti3-2d) by wiring validate_difficulty()/get_next_work_required() to asert.hpp (slice 18a). - BCHChainParams carries the ASERTParams anchor (asert.hpp) instead of a (timespan, spacing, interval) tuple; pow_limit/allow_min_difficulty mirror the anchor. mainnet/testnet3 genesis shared with Bitcoin (pre-fork); BCH testnet4 genesis flagged TODO-verify against VM300 bchn-bch chainparams. - validate_difficulty drops the ancestor-walk lookback (ASERT is anchor- absolute): trusts pre-anchor history and synthetic checkpoint seeds, else asserts header.nBits == get_next_work_required_asert(tip,...). - No p2pool-merged-v36 surface: ASERT governs header accept only, not the PoW hash or share format. Single-coin, src-only (no impl_bch CMake registration). Syntax-clean -std=c++20. Push held pending PR #106 ratification. * bch: add coinbase/template commitment construction + validation Standalone-parent commitment layout (BTC minus AuxPoW segment): [BIP34 height][/c2pool/][state_root 32B][TheMetadata]. BIP34 enforced per BCHN ContextualCheckBlock; no witness commitment (SegWit struck); CTOR handled separately by template tx sort; CashTokens transparent. Source-only header; shared by M4 GBT builder and the share validator. * bch(m4): template builder body — GBT assembly + CTOR + ASERT (M4 slice 1) Flesh out bch::coin::TemplateBuilder (was an M4 TODO stub) into a working GBT assembler from HeaderChain + Mempool, mirroring the BTC builder with the BCH consensus divergences: * SHA256d merkle root + 50-BCH/210k-halving subsidy (== BTC curve). * Next-block bits from the ASERT (aserti3-2d) DAA, not a 2016-block retarget; falls back to tip bits / pow_limit below the ASERT anchor. * CTOR (CHIP-2018-11): block body re-sorted to ascending txid after fee selection, coinbase excluded. * No SegWit: single canonical tx serialization, hash == txid, empty segwit-free rules array. CashTokens carried transparently in tx bytes. * EmbeddedCoinNode wired to build_template() for getwork(). Coinbase tx (and its s19 commitment) is still assembled downstream, as on BTC; binding ../coinbase_commitment.hpp into the coinbase builder is the next M4 slice. ABLA dynamic block-size and the rules array are pinned to pre-ABLA 32 MB EB / empty here pending verification vs VM300 bchn-bch GBT and the p2pool-merged-v36 python reference. Source-only, -fsyntax-only clean. No impl_bch CMake registration (does not race ci-steward); bch lane stays skip-green. * bch(m4): ABLA block-size limit (CHIP-2023-01) + template size-budget sourcing Add abla.hpp -- a 1:1 fixed-point port of BCHN consensus/abla.{h,cpp} (pinned at v29.0.0): Config (MakeDefault/SetMax) + State (NextBlockState, GetBlockSizeLimit). Mainnet grows; testnets fixed at 32 MB. Route the template builder block-size byte budget through abla at the activation/floor limit (32 MB) instead of a static constant. The floor is a safe LOCAL build cap -- ABLA only ever raises it, so a template built to the floor can never exceed the live consensus limit. Per-tip ABLA state replay through the header chain (dynamic limit) is the next size-slice. No p2pool-merged-v36 surface: ABLA governs only the block-size limit, not PoW hash, share format, coinbase commitment, or PPLNS math. Roundtrip exec: floor==32MB both nets; mainnet->41.3MB after 5000 full blocks; testnet fixed. abla.hpp + template_builder.hpp -fsyntax-only OK. * bch(m4): ABLA replay primitive + dynamic per-tip template size budget Add abla::replay() -- replay ABLA State forward from a known-good anchor over a contiguous run of full-block sizes (1:1 BCHN State::NextBlockState loop). Wire TemplateBuilder::build_template to consume an optional caller- supplied per-tip ABLA State, using its GetBlockSizeLimit() as the dynamic block-size budget; absent it, fall back to the activation/floor limit (unchanged, always-safe LOCAL build cap). The per-block-size feed that drives replay is a full-block/embedded-daemon concern (M5+): the headers-only SPV header_chain structurally does not carry block sizes, so the dynamic limit is re-homed there rather than forced into the header chain. Build budget only -- zero p2pool-merged-v36 surface (no PoW hash, share format, coinbase commitment, or PPLNS touched). Validated: mainnet replay 5000x32MB grows 32->39.48MB (bounded by MAX_CONSENSUS_BLOCK_SIZE); testnet fixedSize stays 32MB; empty replay = anchor. --------- Co-authored-by: frstrtr <frstrtr@users.noreply.github.com>
1 parent 152ef20 commit fd8f99c

5 files changed

Lines changed: 2039 additions & 26 deletions

File tree

src/impl/bch/coin/abla.hpp

Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
#pragma once
2+
// BCH ABLA (Adaptive Blocksize-Limit Algorithm, CHIP-2023-01) -- net-new
3+
// BCH-specific code. Activated at the May 2024 upgrade; it replaces the static
4+
// 32 MB excessive-blocksize (EB) with a control function that lets the network
5+
// block-size limit grow with sustained demand.
6+
//
7+
// This is a 1:1 fixed-point port of Bitcoin Cash Node:
8+
// src/consensus/abla.cpp (State::NextBlockState, Config::MakeDefault/SetMax)
9+
// src/consensus/abla.h (Config / State data types)
10+
// pinned at BCHN tag v29.0.0 (clone @89a591f). It is consensus-critical and
11+
// MUST stay byte-exact with BCHN -- validate against BCHN gold vectors
12+
// src/test/data/abla_test_vectors (gen: generate_abla_test_vectors.py).
13+
//
14+
// p2pool-merged-v36 SURFACE: NONE. ABLA governs only the *block-size limit*,
15+
// i.e. how large a block a node will accept / how large a template we may
16+
// build. It does NOT touch PoW hash, share format, coinbase commitment, or
17+
// PPLNS math. In the template builder it is used purely as a LOCAL build-time
18+
// byte budget; using a conservative (floor) value can never produce an
19+
// invalid block, so there is zero compat risk. -- M4 size-slice (M1 ss4.4).
20+
//
21+
// Mainnet: MakeDefault(32 MB, fixedSize=false) -> grows.
22+
// testnet3 / testnet4: MakeDefault(32 MB, fixedSize=true) -> no-op, fixed 32 MB.
23+
24+
#include <algorithm>
25+
#include <cassert>
26+
#include <cstdint>
27+
#include <limits>
28+
29+
namespace bch {
30+
namespace coin {
31+
namespace abla {
32+
33+
// ONE_MEGABYTE / consensus block-size constants -- BCHN src/consensus/consensus.h
34+
inline constexpr uint64_t ONE_MEGABYTE = 1000000u;
35+
inline constexpr uint64_t DEFAULT_CONSENSUS_BLOCK_SIZE = 32u * ONE_MEGABYTE;
36+
inline constexpr uint64_t MAX_CONSENSUS_BLOCK_SIZE = uint64_t(2000) * ONE_MEGABYTE;
37+
38+
// 2^7 fixed precision for the "asymmetry factor" (zeta). BCHN abla.h B7.
39+
inline constexpr uint64_t B7 = 1u << 7u;
40+
41+
// muldiv(x,y,z) = x*y/z in 128-bit intermediate (BCHN abla.cpp). The platform
42+
// is gcc/clang C++20 on linux -> use the native __int128 path BCHN selects.
43+
inline uint64_t muldiv(uint64_t x, uint64_t y, uint64_t z) {
44+
assert(z != 0);
45+
const unsigned __int128 res =
46+
(static_cast<unsigned __int128>(x) * static_cast<unsigned __int128>(y))
47+
/ static_cast<unsigned __int128>(z);
48+
assert(res <= static_cast<unsigned __int128>(std::numeric_limits<uint64_t>::max()));
49+
return static_cast<uint64_t>(res);
50+
}
51+
52+
// Algorithm configuration -- part of a chain's consensus params (BCHN abla.h).
53+
struct Config {
54+
uint64_t epsilon0{}; // initial/floor control block size
55+
uint64_t beta0{}; // initial/floor elastic buffer size
56+
uint64_t gammaReciprocal{}; // reciprocal of control "forget factor"
57+
uint64_t zeta_xB7{}; // control "asymmetry factor" (x B7)
58+
uint64_t thetaReciprocal{}; // reciprocal of elastic buffer decay rate
59+
uint64_t delta{}; // elastic buffer "gear factor"
60+
uint64_t epsilonMax{}; // max control block size
61+
uint64_t betaMax{}; // max elastic buffer size
62+
63+
// Set epsilonMax / betaMax so internal ops can't overflow UINT64_MAX.
64+
// 1:1 BCHN Config::SetMax.
65+
void SetMax() {
66+
const uint64_t maxSafeBlocksizeLimit =
67+
std::numeric_limits<uint64_t>::max() / zeta_xB7 * B7;
68+
const uint64_t maxElasticBufferRatioNumerator =
69+
delta * ((zeta_xB7 - B7) * thetaReciprocal / gammaReciprocal);
70+
const uint64_t maxElasticBufferRatioDenominator =
71+
(zeta_xB7 - B7) * thetaReciprocal / gammaReciprocal + B7;
72+
epsilonMax = maxSafeBlocksizeLimit
73+
/ (maxElasticBufferRatioNumerator + maxElasticBufferRatioDenominator)
74+
* maxElasticBufferRatioDenominator;
75+
betaMax = maxSafeBlocksizeLimit - epsilonMax;
76+
}
77+
78+
bool IsFixedSize() const {
79+
return epsilon0 == epsilonMax && beta0 == betaMax;
80+
}
81+
82+
// 1:1 BCHN Config::MakeDefault.
83+
static Config MakeDefault(uint64_t defaultBlockSize = DEFAULT_CONSENSUS_BLOCK_SIZE,
84+
bool fixedSize = false) {
85+
Config ret;
86+
ret.epsilon0 = defaultBlockSize / 2u;
87+
ret.beta0 = defaultBlockSize / 2u;
88+
ret.gammaReciprocal = 37938;
89+
ret.zeta_xB7 = 192;
90+
ret.thetaReciprocal = 37938;
91+
ret.delta = 10;
92+
if (!fixedSize) {
93+
ret.SetMax();
94+
} else {
95+
ret.epsilonMax = ret.epsilon0;
96+
ret.betaMax = ret.beta0;
97+
}
98+
return ret;
99+
}
100+
};
101+
102+
// Algorithm internal state for block N. The limit for block N is
103+
// state_N.GetBlockSizeLimit(); for N+1 use NextBlockState(...).GetBlockSizeLimit().
104+
class State {
105+
uint64_t blockSize{};
106+
uint64_t controlBlockSize{};
107+
uint64_t elasticBufferSize{};
108+
109+
public:
110+
State() = default;
111+
112+
// Defaults from Config -- suitable for all blocks before ABLA activation
113+
// (the activation/floor state). 1:1 BCHN State(config, blkSize).
114+
State(const Config& config, uint64_t blkSize)
115+
: blockSize(blkSize),
116+
controlBlockSize(config.epsilon0),
117+
elasticBufferSize(config.beta0) {}
118+
119+
uint64_t GetBlockSizeLimit(bool disable2GBCap = false) const {
120+
if (disable2GBCap)
121+
return controlBlockSize + elasticBufferSize;
122+
return std::min<uint64_t>(controlBlockSize + elasticBufferSize,
123+
MAX_CONSENSUS_BLOCK_SIZE);
124+
}
125+
126+
uint64_t GetNextBlockSizeLimit(const Config& config, bool disable2GBCap = false) const {
127+
return NextBlockState(config, 0).GetBlockSizeLimit(disable2GBCap);
128+
}
129+
130+
uint64_t GetBlockSize() const { return blockSize; }
131+
uint64_t GetControlBlockSize() const { return controlBlockSize; }
132+
uint64_t GetElasticBufferSize() const { return elasticBufferSize; }
133+
134+
// Advance state to block N+1 given its size. 1:1 BCHN State::NextBlockState.
135+
State NextBlockState(const Config& config, const uint64_t nextBlockSize) const {
136+
State ret;
137+
ret.blockSize = nextBlockSize;
138+
139+
// control function
140+
const uint64_t clampedBlockSize =
141+
std::min(this->blockSize, this->controlBlockSize + this->elasticBufferSize);
142+
const uint64_t amplifiedCurrentBlockSize =
143+
muldiv(config.zeta_xB7, clampedBlockSize, B7);
144+
145+
if (amplifiedCurrentBlockSize > this->controlBlockSize) {
146+
const uint64_t bytesToAdd = amplifiedCurrentBlockSize - this->controlBlockSize;
147+
const uint64_t amplifiedBlockSizeLimit =
148+
muldiv(config.zeta_xB7, this->controlBlockSize + this->elasticBufferSize, B7);
149+
const uint64_t bytesMax = amplifiedBlockSizeLimit - this->controlBlockSize;
150+
const uint64_t scalingOffset =
151+
muldiv(muldiv(config.zeta_xB7, this->elasticBufferSize, B7), bytesToAdd, bytesMax);
152+
ret.controlBlockSize =
153+
this->controlBlockSize + (bytesToAdd - scalingOffset) / config.gammaReciprocal;
154+
} else {
155+
const uint64_t bytesToRemove = this->controlBlockSize - amplifiedCurrentBlockSize;
156+
ret.controlBlockSize = this->controlBlockSize - bytesToRemove / config.gammaReciprocal;
157+
ret.controlBlockSize = std::max(ret.controlBlockSize, config.epsilon0);
158+
}
159+
160+
// elastic buffer function
161+
const uint64_t bufferDecay = this->elasticBufferSize / config.thetaReciprocal;
162+
if (amplifiedCurrentBlockSize > this->controlBlockSize) {
163+
const uint64_t bytesToAdd =
164+
(ret.controlBlockSize - this->controlBlockSize) * config.delta;
165+
ret.elasticBufferSize = this->elasticBufferSize - bufferDecay + bytesToAdd;
166+
} else {
167+
ret.elasticBufferSize = this->elasticBufferSize - bufferDecay;
168+
}
169+
ret.elasticBufferSize = std::max(ret.elasticBufferSize, config.beta0);
170+
171+
ret.controlBlockSize = std::min(ret.controlBlockSize, config.epsilonMax);
172+
ret.elasticBufferSize = std::min(ret.elasticBufferSize, config.betaMax);
173+
return ret;
174+
}
175+
};
176+
177+
// Per-network config. Mainnet grows; testnets are fixed at 32 MB.
178+
inline Config mainnet_config() { return Config::MakeDefault(DEFAULT_CONSENSUS_BLOCK_SIZE, /*fixedSize=*/false); }
179+
inline Config testnet_config() { return Config::MakeDefault(DEFAULT_CONSENSUS_BLOCK_SIZE, /*fixedSize=*/true); }
180+
181+
// Replay ABLA forward from a known-good anchor State over a contiguous run of
182+
// block sizes (oldest-first), returning the State *after the last size supplied*
183+
// -- i.e. the State whose GetBlockSizeLimit() governs the block we are about to
184+
// build. 1:1 BCHN: repeated State::NextBlockState. The anchor MUST be the ABLA
185+
// State of the block immediately preceding sizes[0].
186+
//
187+
// NOTE on the size feed: ABLA is driven by each block's *actual serialized
188+
// size*, which the headers-only SPV header_chain structurally does not carry.
189+
// The natural anchor on BCH is therefore a BCHN-pinned {height,State}; the live
190+
// per-block sizes enter at the full-block / embedded-daemon layer (M5+), not
191+
// here. Until that feed exists the template builder stays on the safe floor
192+
// (see floor_block_size_limit / template_builder build budget).
193+
inline State replay(State anchor, const Config& config,
194+
const uint64_t* sizes, size_t n) {
195+
State s = anchor;
196+
for (size_t i = 0; i < n; ++i)
197+
s = s.NextBlockState(config, sizes[i]);
198+
return s;
199+
}
200+
201+
// Conservative LOCAL build budget for the template builder when per-tip ABLA
202+
// state is not yet replayed through the header chain: the activation/floor
203+
// state. ABLA only ever raises the limit above this floor, so building to the
204+
// floor can never exceed the live consensus limit. The dynamic path is
205+
// abla::replay (above) fed a BCHN-pinned anchor + full-block sizes; that feed
206+
// lives at the full-block/daemon layer, not the headers-only SPV chain.
207+
inline uint64_t floor_block_size_limit(bool is_testnet) {
208+
const Config cfg = is_testnet ? testnet_config() : mainnet_config();
209+
return State(cfg, 0).GetBlockSizeLimit();
210+
}
211+
212+
} // namespace abla
213+
} // namespace coin
214+
} // namespace bch

0 commit comments

Comments
 (0)