Mathematical Reference
Anvil256 — Mathematical Reference
The canonical derivation for every non-trivial construction in the Anvil256 protocol. All claims are proven or bounded explicitly. Informal descriptions are never substituted for formal statements.
Notation
The protocol uses standard mathematical notation throughout. A short legend:
| Symbol | Meaning |
|---|---|
WAD | (Q60.18 unit scale) |
concatenation via abi.encode (ABI-padded, prevents type-collision attacks) | |
keccak256(x) — 256-bit output, modelled as a random oracle | |
| Cascade challenge | |
| Epoch entropy | |
| difficulty at epoch | |
| block reward at epoch — | |
| protocol-owned liquidity reserve mint, before cap truncation | |
| genesis LP seed mint, ANVL | |
| per-miner epoch counter (monotonic, non-transferable) | |
| unique miners in the 256-epoch NCT window | |
| floor function | |
| — clamp to | |
| integer representing a real scaled by | |
| positive integers | |
| the random oracle modelling | |
| probability over uniformly random oracle responses | |
| end of proof |
1. Keccak-Cascade PoW with Temporal Miner Binding
1.1 Motivation: Formal Statement of the Wallet-Rotation Attack
Definition 1.1 (Naive PoW Challenge). Let be the set of miner addresses and be the current epoch. The naive challenge for miner at epoch is:
where is the nonce. A nonce is valid iff .
Observation 1.2 (Zero-Cost Address Rotation). Let be a miner address. Generating a fresh address costs key-derivation operations. The challenge function satisfies:
are independent, identically distributed when and is uniform. Therefore, the adversary can replace with at zero marginal cost and receive a statistically equivalent challenge — no difficulty advantage, but also no penalty. The NCT concentration signal (§2) is then trivially gamed: physical machines can appear as distinct participants with zero additional hashrate cost.
Definition 1.3 (Sybil Cost). The Sybil cost of operating distinct miner identities for one 256-epoch window cycle is the minimum total protocol fee expenditure required to occupy distinct slots in the NCT window. For naive PoW, for all .
1.2 Miner Epoch Counter — Formal Definition
Definition 1.4 (Miner Epoch Counter). The contract maintains a total function defined by:
i.e., the number of successful mine() calls by address up to and
including epoch , read before the increment in the current call.
Solidity representation:
mapping(address => uint64) public minerEpochCount;// γ(m) = minerEpochCount[m] (pre-increment value at mine() call time)Lemma 1.5 (γ-Monotonicity). For all and epochs
: , with strict inequality
iff successfully called mine() in the interval .
Proof. The counter is incremented by exactly 1 on each successful mine()
call (via unchecked { ++minerEpochCount[msg.sender]; }), and is never
decremented. The mapping is not transferable.
Lemma 1.6 (γ-Non-Transferability). For : no sequence of contract calls can produce for any via internal state transfer. The counter is address-keyed and has no setter, no reset, and no cross-address interaction.
1.3 Full Cascade Construction — Formal Definition
Definition 1.7 (Cascade PoW). For epoch , nonce , and caller :
where denotes the difficulty governing epoch — i.e. the
value of currentDifficulty after the PIController adjustment that
fires at the epoch- period boundary (if any). The on-chain
implementation enforces this by running _maybeAdjustDifficulty() before
writing epochEntropy, so always commits to the difficulty
that will be used to validate nonces in epoch .
The nonce is valid iff:
Definition 1.8 (Binding Layers). Each layer binds a distinct security property:
| Layer | Expression | Bound Secret |
|---|---|---|
| Temporal identity: address + history + genesis | ||
| Epoch uniqueness: separates epochs for same miner | ||
| Anti-precompute: live chain state in outer pass |
1.4 Wallet-Rotation Cost — Formal Theorem
Theorem 1.9 (Rotation Cost Lower Bound). Under the random oracle model, the minimum total protocol expenditure for an adversary to maintain independently-challenging miner identities for consecutive epochs is:
where is the window size and \texttt{fee} = \0.10$ per mine.
Proof. Each address must appear in the NCT window at least once per
epochs to maintain a distinct slot (otherwise it is evicted by the circular
buffer). Each window entry requires a successful mine() call at cost
. Fresh addresses (with ) receive no cost reduction
— difficulty is uniform across all callers. Therefore maintaining
distinct addresses for window cycles costs at least
.
Corollary 1.10. For (full Sybil, appearing as all distinct): \text{Cost}(256, W) \geq 256 \times \0.10 = $25.60$ per window cycle. This equals the cost of genuine mining with 256 independent physical miners. Sybil provides no economic advantage.
1.5 Precomputation Impossibility — Theorem and Proof
Theorem 1.11 (Structural Precomputation Impossibility). No probabilistic polynomial-time adversary can produce a valid nonce for epoch before the block at height is finalised by the sequencer, except with probability negligible in the security parameter .
Proof. Let be the target block hash, produced at an unknown future time . A valid nonce satisfies:
where . In the random oracle model, is uniformly distributed over and independent of all values known before is produced. Therefore:
regardless of which selects before is known — this is exactly the probability of a random guess. No precomputed intermediate (including for all in the search space) provides any advantage, because the outer takes as input, which is uniformly random over the precomputed set.
More precisely: for any function computable before time , and any nonce :
since is an independent uniform 256-bit value.
1.6 Gas Accounting
| Operation | Gas |
|---|---|
SLOAD minerEpochCount[m] (warm) | 100 |
SLOAD lastMineBlock (warm) | 100 |
SLOAD currentDifficulty (warm) | 100 |
| for (3 packed args, 96 bytes) | 54 |
| for (2 args, 64 bytes) | 36 |
| for inner cascade pass (2 args, 64 bytes) | 36 |
| for outer cascade pass (2 args, 64 bytes) | 36 |
SSTORE minerEpochCount++ (warm→dirty) | 2,900 |
SSTORE lastMineBlock (warm→dirty) | 2,900 |
| Base ERC-20 mint + event | ~30,000 |
| Window buffer + uniqueCount update (§2.1) | ~12,000 |
| Fee forward + stuck-fee fallback | ~5,500 |
Estimated total mine() gas | ≈ 66,500 gas |
At Base L2 with :
2. Nakamoto Coefficient Throttle (NCT)
2.1 Circular Buffer — Formal Specification
Definition 2.1 (Miner Window). The contract maintains:
- : window size (a power of 2)
- : circular buffer of recent miners
- : write-head pointer (advances mod 256)
- : reference count per address
- : count of distinct addresses in the window
Definition 2.2 (Window Update). On successful mine() by :
where is the indicator function.
Invariant I11. For all reachable states after the first mine:
Proof. At genesis: . After first mine: one address has , so . Each update increments iff a new address enters, and decrements iff an address fully exits. Since is a reference count bounded by , and at most 256 distinct addresses can reside simultaneously in a 256-slot buffer, always. is impossible after the first mine because the writer adds its own address before decrement can eliminate all entries.
2.2 Concentration Factor — Fixed-Point Representation
Definition 2.3. The concentration factor uses filledSlots (the number
of non-empty entries in the window, which grows from to over the first
mines and then stays at ):
In the steady state () this equals . The real-valued concentration factor is .
Boundary cases (steady state):
- : , i.e. — fully distributed
- : , i.e. — fully centralised
Bootstrap suppression. During the first mines (NCT_BOOTSTRAP_SLOTS = 32),
nctSignal() returns regardless of window contents. A single miner must
dominate the early window by necessity — this is not an attack. The NCT penalty
activates only after fills, at which point the window contains meaningful
distribution data. This suppression also ensures
does not produce a spurious concentration signal from an under-filled window.
2.3 NCT Control Signal — Derivation
Definition 2.4 (NCT Signal). With parameters and
, MinerWindow.nctSignal() returns a non-positive raw
signal in Q60.18:
In real units: .
Sign convention — implementation detail. PIController.step() receives
uNct = s_nct (non-positive) and subtracts it from :
uCombined = uPi - uNctClamped // uNctClamped = s_nct ≤ 0Because , this is equivalent to adding a non-negative penalty. Defining the penalty magnitude :
NCT always raises or holds difficulty — it never lowers it. Centralisation () increases , which increases .
Observation 2.5. is monotonically non-decreasing in , equals at (fully distributed), and saturates at for .
2.4 Sybil Cost Analysis — Full Derivation
Setup. Suppose a single adversary controls addresses , each mining with global difficulty . To appear fully distributed (), the adversary needs distinct addresses each holding slot in the 256-slot window.
Cost per window cycle. Each slot evicts the oldest entry after 256 new mines system-wide. The adversary’s addresses must be topped up at rate mine per 256 total mines, per address. In expectation, the adversary pays:
Suppressing NCT entirely requires :
This is identical to the cost of 256 legitimate mines. No economic gain.
Proposition 2.6 (Sybil Equivalence). The per-mine cost of suppressing the NCT signal equals the per-mine cost of legitimate mining:
Therefore the NCT Sybil attack is economically dominated by legitimate mining: the attacker incurs identical cost while receiving NCT pressure identical to the distributed case, and gains no additional reward.
2.5 Stability of NCT Term — Formal Statement
Proposition 2.7. Let (the penalty magnitude, as defined in §2.3) with . The combined control signal:
with remains within for all values of and .
Proof. Since , the outer clamp is sufficient regardless of their sum. The NCT term shifts the operating point of the PI controller by at most units in the positive direction (raising on centralisation), which is within the Lyapunov-stable regime analysed in §3.3.
3. Discrete-Time PI Controller on
3.1 State Space — Formal Definition
Definition 3.1. The PI controller operates on the discrete-time state space , with:
| Variable | Domain | Semantics |
|---|---|---|
| Fractional timing error for period | ||
| Integrator state (anti-windup saturated) | ||
| Proportional-integral control output | ||
| Difficulty at the start of period |
3.2 System Equations — Complete Specification
Definition 3.2. With target window and observed window :
with parameters:
| Symbol | Value | Rationale |
|---|---|---|
| target window | ||
| Proportional gain | ||
| Integral gain; critical damping 10 periods | ||
| Anti-windup saturation bound | ||
| Control output saturation | ||
| Max step | Outer difficulty envelope |
3.3 Lyapunov Stability Certificate
Theorem 3.3 (Asymptotic Stability at Origin). Consider the unsaturated linearised system (i.e., and ). The origin is globally asymptotically stable with Lyapunov function:
Proof. Positive definiteness. for , and . is radially unbounded ( as ).
One-step decrement. At period , assuming (from the plant dynamics) and :
In the unsaturated regime, the PI law gives:
and . Therefore:
Cross-terms in cancel exactly. only when . By LaSalle’s invariance principle (applied to the set ): the largest invariant subset in this set satisfies as well (since implies is constant, and then , driving away from 0 unless too). Therefore the unique invariant set is , confirming global asymptotic stability.
3.4 Justification for vs. Linear Approximation
Proposition 3.4. The multiplicative update is the unique composition law consistent with operating the controller in log-difficulty space.
Proof. Define . The natural additive update in log-space is , i.e.:
The linear approximation introduces a compounding error. Over periods:
The relative error at the boundary :
Over periods this compounds to error
in the aggregate adjustment factor. Exact exp is mandatory for fidelity.
3.5 Fourth-Order Maclaurin Approximation
Definition 3.5. The on-chain exp implementation uses the Taylor polynomial:
Proposition 3.6 (Error Bound). For :
More conservatively, using the Lagrange remainder with :
Both bounds are below — negligible relative to the step resolution implied by .
Fixed-point implementation. All multiplications are in Q60.18:
Overflow condition: ensures
.
At : ,
well within int256 bounds.
4. Q60.18 Fixed-Point Arithmetic
4.1 Representation
Definition 4.1. Q60.18 represents a real number as the integer where . The usable real range is:
All protocol parameters satisfy , so overflow is impossible in the normal operating regime.
4.2 Operation Correctness
| Operation | WAD formula | Exact iff |
|---|---|---|
| always (mod wrapping excluded by bounds) | ||
| always | ||
| intermediate | ||
| Maclaurin, 4 terms | error (§3.5) | |
| 7-step binary search | exact for all |
4.3 log2Floor — Correctness and Complexity
Algorithm 4.2. For , compute :
bits ← 0for s in [128, 64, 32, 16, 8, 4, 2, 1]: if x >> s > 0: bits += s x >>= sreturn bitsProposition 4.3 (Correctness). Algorithm 4.2 returns for all .
Proof. Binary search on the bit-length of : at each step, the
remaining value of is reduced to . After 7 steps
(exhausting the sequence ), bits accumulates
the positions of all set bits from the MSB downward. The result equals the
position of the highest set bit = .
Complexity. Exactly 7 conditional branches; gas independent of input.
5. Protocol Fee Oracle
5.1 Dimensional Derivation
Goal. Express a USD target fee f = \0.10pd = 8p = p_{$} \times 10^8$).
Step-by-step:
Equivalently, expressing :
Sanity check at p_{\} = $2{,}500p = 2{,}500 \times 10^8 = 2.5 \times 10^{11}$):
Integer arithmetic in Solidity. The numerator fits within uint256
(). Division is integer
floor-division, introducing a rounding error of at most ,
which is negligible.
5.2 Oracle Validity — Formal Invariants
Invariant O1 (Positive Answer):
Invariant O2 (Non-Future Timestamp):
Invariant O3 (Freshness):
(ORACLE_MAX_STALENESS = 24 hours in Anvil256.sol.)
Invariant O4 (Decimal Bound):
Invariant O5 (Answered-In-Round Guard):
If answeredInRound < roundId the aggregator is returning a cached answer
from a prior round that has not yet been superseded — treated as stale.
Note on Round ID gaps. Chainlink OCR2 aggregators do not guarantee
contiguous round IDs across phase boundaries. A gap in the sequence of
roundId values (e.g. roundId jumps from 1 to 10 after a phase upgrade)
is not checked — checking it would produce false positives during normal
aggregator upgrades. The answeredInRound < roundId guard (O5) is narrower:
it only rejects rounds where the oracle explicitly signals the answer came
from a prior round, which is a reliable indicator of a stale response.
6. Supply Curve — Complete Verification
6.1 Reward Function — Formal Definition
Definition 6.1. The block reward at epoch is:
where (50 ANVL in wei) and . The operator is the arithmetic right-shift, i.e.:
6.2 Miner-Only Schedule and Actual Supply Cap
Theorem 6.2 (Miner-Only Baseline). The idealized sum of miner rewards over all halving bands approaches ANVL:
Taking the negligible tail as zero for the idealized series:
Integer right-shift truncation (implementation note). The Solidity
implementation uses R(n) = INITIAL_REWARD >> halvings (integer bit-shift).
Due to floor truncation at each shift, the actual total mintable supply across
all 64 halving bands is approximately ANVL — roughly ANVL
below MAX_SUPPLY in the miner-only schedule.
The deployed contract also mints protocol-owned liquidity inside the same cap:
For a non-boundary mine:
At cap boundaries, mine() first truncates to remaining supply and then
truncates to the remaining headroom after the miner reward. Thus the
actual invariant is:
The 10% POL reserve is not inflation outside the cap; it consumes the same cap and therefore causes the cap to be reached earlier than the miner-only terminus.
Residual from finite truncation (idealized):
Moreover, the reward schedule returns zero and mine() reverts with
MiningEnded() at if MAX_SUPPLY has not already stopped
minting earlier.
6.3 Halving Table (Miner-Only Reference)
| Halving | Epoch start | (miner ANVL) | Miner-only cumulative | % of 21 M |
|---|---|---|---|---|
| 0 | 0 | 50.000000 | 10,500,000 | 50.0000% |
| 1 | 210,000 | 25.000000 | 15,750,000 | 75.0000% |
| 2 | 420,000 | 12.500000 | 18,375,000 | 87.5000% |
| 3 | 630,000 | 6.250000 | 19,687,500 | 93.7500% |
| 4 | 840,000 | 3.125000 | 20,343,750 | 96.8750% |
| 5 | 1,050,000 | 1.562500 | 20,671,875 | 98.4375% |
| 7 | 1,470,000 | 0.390625 | 20,917,969 | 99.6094% |
| 10 | 2,100,000 | 0.048828 | 20,989,746 | 99.9512% |
| 14 | 2,940,000 | 0.003051 | 20,999,359 | 99.9969% |
| 32 | 6,720,000 | |||
| 64 | 13,440,000 | 0 (terminus) | 21,000,000 | 100.0000% |
Computation rule: miner-only cumulative supply after halving is: .
Actual totalSupply includes the 1 ANVL genesis LP seed and 10% POL reserve
mints, then applies MAX_SUPPLY truncation.
No calendar projections are provided. The protocol does not compute wall-clock time. Epoch duration is an emergent quantity; multiply epoch count by the observed mean epoch time for any estimate.
7. Controller Interaction — Unified Signal Flow
The three subsystems interact only through :
Each mine(): γ(m)++ [Temporal binding — §1.2] win[h] ← m; h ← (h+1) mod 256 [NCT buffer — §2.1] uniqueCount ← maintained count [NCT signal input — §2.2]
Every 2,016 mines (one period boundary): e[n] ← (T_actual − T) / T [Timing error — §3.2] I[n] ← sat(I[n−1] + e[n], ±I_MAX) [Integrator — §3.2] u_pi ← sat(−(Kp·e + Ki·I), ±0.5) [PI signal — §3.2] k ← filledSlots (grows 0→256) [Bootstrap guard — §2.2] C_wad ← (k × WAD) / uniqueCount [Concentration — §2.2] s_nct ← −min(0.1·(C−1), 0.3) [≤ 0] [Raw NCT from MinerWindow — §2.3] u_nct ← |s_nct| = min(0.1·(C−1), 0.3) [≥ 0] [Penalty magnitude — §2.3] u ← sat(u_pi + u_nct, ±0.5) [Combined — §2.5] D[n+1] ← sat(D[n]·exp4(u), D/4, 4D) [Difficulty update — §3.2] Note: PIController receives s_nct and computes: u = uPi − s_nct = uPi + u_nct
After every mine() (using post-adjustment D[n+1] at period boundaries): ε[n+1] ← H(blockhash(block) ‖ currentDifficulty) [Epoch entropy — §1.3]Critical ordering note. The difficulty adjustment (PIController.step)
occurs before epochEntropy is written. This ensures ε[n+1] commits
to the post-adjustment difficulty D[n+1], not the stale D[n]. This is
the only ordering consistent with Definition 1.7:
where is the difficulty that will govern epoch .
8. References
- Nakamoto, S. Bitcoin: A Peer-to-Peer Electronic Cash System. 2008.
- Åström, K.J. & Murray, R.M. Feedback Systems. Princeton University Press, 2nd ed. 2021.
- Khalil, H.K. Nonlinear Systems. Prentice Hall, 3rd ed. 2002.
- LaSalle, J.P. The Stability of Dynamical Systems. SIAM, 1976.
- NIST FIPS 202. SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions. 2015.
- EIP-2929. Gas Cost Increases for State Access Opcodes. 2021.
- Chainlink Labs. OCR2 Aggregator Architecture. docs.chain.link.