Difficulty: bound per-block EMA moves, add a difficulty floor, and preserve state across restarts
Maintainers usually reply within 1 day
@anshulchikhale30-p is already working on this.
Since Nov 15, 2026.
- #188 by @anshulchikhale30-p — open
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 25/100
Research direction
Start in the blockchain module where _next_target computes the EMA and clamps only to [MIN_TARGET, MAX_TARGET]; read docs/difficulty.md for the agreed bounds and non-goals. Follow persistence.load() to see how a fresh Blockchain() is built and which fields survive, then check the metadata table handling for persisting target_block_time and alpha. The issue lists the exact test files (tests/test_target.py, tests/test_persistence.py, tests/test_persistence_extra.py, tests/test_chain_extra.py); done means those pass, legacy JSON/SQLite snapshots still load, and the restart reproduction prints matches: True. Note an open PR #188 already targets this, so coordinate before starting.
Written by the indexing model from the issue text.
Description
Summary
MiniChain already adjusts difficulty after every block using an exponential moving average (EMA), but that implementation has four defects. This issue tracks the minimal fix agreed after reviewing #26 and the closed PID attempt #63. The per-block EMA stays; no retarget window or PID controller is added.
Problems
-
The per-block target change is unbounded.
_next_targetcomputesnew_target = (target * int(avg_block_time)) // self.target_block_timeand only clamps the result to
[MIN_TARGET, MAX_TARGET].- With
alpha = 0.5, a 1 ms interval halves the target in one block. - With
alpha = 1, a 1 ms interval divides the target by 10,000. - On the easy side, a long gap (for example a miner withholding blocks, or a node that was offline) can jump the target toward
MAX_TARGETin a single step, after which blocks are trivially cheap to produce.
There is no bound on how far difficulty can move per block, so one timestamp interval can dominate the whole retarget.
- With
-
There is no minimum-difficulty floor. Repeated slow blocks can keep increasing the target up to
MAX_TARGET = 2**256 - 1. Difficulty (1 / target) can therefore approach zero, and a chain can be pushed permanently below its intended security level. -
Difficulty state is lost on restart.
persistence.load()constructs a freshBlockchain()and replaces only.chainand.state.current_targetandavg_block_timekeep their genesis values.Reproduced on
origin/main(e16ae98) after six 1 ms blocks with the default config:before restart: target_ratio=0.109412 avg=5314.879 after restart: target_ratio=1.000000 avg=10000.000 matches: FalseThe node resumes at genesis difficulty instead of the difficulty it had reached.
-
The difficulty configuration is not persisted.
target_block_timeandalphaare re-read from whichevergenesis.jsonis in the working directory duringload(). A node can therefore resume with different consensus parameters from the ones it saved.
Proposed fix
Keep the existing per-block EMA and change only the parts that are wrong:
- Add
MAX_TARGET_CHANGE_PERCENT = 25and clamp every EMA result to +/-25% of the previous target. - Add
MIN_DIFFICULTY_FLOOR_DIVISOR = 4. The easiest allowed target becomesmin(MAX_TARGET, genesis_target * 4), so difficulty never falls below one quarter of the genesis difficulty. - Add
Blockchain.recompute_difficulty_from_chain(), which replays canonical timestamps to rebuildavg_block_timeand the next target. Call it fromload(). - Do not revalidate historical targets during that replay, so snapshots produced by older retarget rules still load.
- Persist
target_block_timeandalphain the SQLitemetadatatable and restore them before recomputation. Legacy JSON snapshots without this metadata continue to load. - Validate
target_block_timeandalphawhen readinggenesis.json.
Scope and non-goals
- No change to block headers, hashing, PoW, or the P2P wire format.
- No fixed
N-block retarget window. - No PID controller. In #26 and #63 PID showed no tracking improvement over the EMA, and a PID with
Ki = Kd = 0would be speculative generality. - Committing the full difficulty configuration to the genesis hash is a follow-up, not part of this fix. It is documented in
docs/difficulty.md.
Acceptance criteria
- The target cannot move by more than 25% in one block for any timestamp interval.
- Difficulty can never fall below one quarter of the genesis difficulty.
-
save()followed byload()preservescurrent_target,avg_block_time,target_block_time, andalphaexactly. - A restored chain accepts the next block at the restored target, not the genesis target.
- Legacy JSON snapshots and SQLite snapshots without difficulty metadata still load and resume correctly.
- Invalid
target_block_time/alphavalues in genesis or persisted metadata are rejected. - Focused tests cover the bound, the floor, restart, legacy snapshots, persisted config, and config validation.
- The algorithm, bounds, restart behavior, and the genesis-hash follow-up are documented.
Verification plan
pytestfocused ontests/test_target.py,tests/test_persistence.py,tests/test_persistence_extra.py, andtests/test_chain_extra.py.- Full suite matches the
origin/mainbaseline (only the two pre-existing environment-relatedtests/test_contract_calls.pyfailures remain). - Re-run the restart reproduction above and assert
matches: True.
References
- Original feature request: #26
- Closed PID attempt: #63
- Dominant language
- Python
- Stars
- 12
- Forks
- 27
- Avg merge
- 2m
- Merged PRs (30d)
- 1
Getting set up
- Ships a Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from StabilityNexus/MiniChain
-
[BUG]: Handle JSON-RPC notifications and empty batches correctlyPossibly taken @Muneerali199 claimed this 10 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
StabilityNexus/MiniChain#177 · 2 comments ·
Maintainers usually reply within 1 day
-
automatic-copyright-year: keep README copyright currentPossibly taken @anshulchikhale30-p claimed this 7 days ago. Opendocumentation enhancement
Difficulty 3/5 Half a day Newbie friendliness 35/100
StabilityNexus/MiniChain#189 ·
Maintainers usually reply within 1 day
-
[BUG]: Blocks on a different parent are classified INVALID and get the sender bannedPossibly taken @kansalakshat claimed this 7 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 35/100
StabilityNexus/MiniChain#185 ·
Maintainers usually reply within 1 day
-
[BUG]: P2P sync downloads full 500-block chunks without headers-first validationPossibly taken @anshulchikhale30-p claimed this 14 days ago. Openbug documentation enhancement
Difficulty 5/5 Over a week Newbie friendliness 25/100
StabilityNexus/MiniChain#178 ·
Maintainers usually reply within 1 day
-
[FEATURE]: Add transaction and receipt lookup RPC methodsPossibly taken @Thushara3005 claimed this 10 days ago. Openenhancement
Difficulty 4/5 3-5 days Newbie friendliness 58/100
StabilityNexus/MiniChain#176 ·
Maintainers usually reply within 1 day
All issues in StabilityNexus/MiniChain
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
huggingface/datasets#9128 ·
Maintainers usually reply within 1 day
-
priority:low ready-for-dev
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
OpenHands/extensions#975 ·
Maintainers usually reply within 1 day
-
Function/dict state handlers can't supply provider-state injected values (`generate.provider_state`)Open
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
pact-foundation/pact-python#1789 ·
Maintainers usually reply within 9 days
-
documentation
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
juandresrodca/AdminForge#66 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day