Difficulty: bound per-block EMA moves, add a difficulty floor, and preserve state across restarts
Les mainteneurs répondent en général sous 1 jour
Évaluation
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Accessibilité débutants
- 25/100
Piste de recherche
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.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
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
- Langage dominant
- Python
- Étoiles
- 12
- Forks
- 27
- Merge moyen
- 2 min
- PR mergées (30 j)
- 1
Préparer son environnement
- Fournit un Dockerfile ou un fichier Docker Compose
- Aucun modèle de pull request
- Lire le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Autres issues de StabilityNexus/MiniChain
-
[BUG]: Handle JSON-RPC notifications and empty batches correctlyPeut-être pris @Muneerali199 l’a pris il y a 10 jours. Ouvertebug
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
StabilityNexus/MiniChain#177 · 2 commentaires ·
Les mainteneurs répondent en général sous 1 jour
-
automatic-copyright-year: keep README copyright currentPeut-être pris @anshulchikhale30-p l’a pris il y a 7 jours. Ouvertedocumentation enhancement
Difficulté 3/5 Une demi-journée Accessibilité débutants 35/100
StabilityNexus/MiniChain#189 ·
Les mainteneurs répondent en général sous 1 jour
-
[BUG]: Blocks on a different parent are classified INVALID and get the sender bannedPeut-être pris @kansalakshat l’a pris il y a 7 jours. Ouvertebug
Difficulté 2/5 1-3 heures Accessibilité débutants 35/100
StabilityNexus/MiniChain#185 ·
Les mainteneurs répondent en général sous 1 jour
-
[BUG]: P2P sync downloads full 500-block chunks without headers-first validationPeut-être pris @anshulchikhale30-p l’a pris il y a 14 jours. Ouvertebug documentation enhancement
Difficulté 5/5 Plus d'une semaine Accessibilité débutants 25/100
StabilityNexus/MiniChain#178 ·
Les mainteneurs répondent en général sous 1 jour
-
[FEATURE]: Add transaction and receipt lookup RPC methodsPeut-être pris @Thushara3005 l’a pris il y a 10 jours. Ouverteenhancement
Difficulté 4/5 3-5 jours Accessibilité débutants 58/100
StabilityNexus/MiniChain#176 ·
Les mainteneurs répondent en général sous 1 jour
Toutes les issues de StabilityNexus/MiniChain
Issues similaires
-
run_gate loads a custom tasks file from outside the working directoryPeut-être pris @Ru0k3 l’a pris aujourd’hui. Ouvertebug
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
MakazhanAlpamys/Soup#3189 · 1 commentaire ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 80/100
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 80/100
nautechsystems/nautilus_trader#5741 ·
Les mainteneurs répondent en général sous 1 jour
-
Difficulté 2/5 1-3 heures Accessibilité débutants 62/100
-
Difficulté 2/5 1-3 heures Accessibilité débutants 78/100
huggingface/datasets#9128 ·
Les mainteneurs répondent en général sous 1 jour