Difficulty: bound per-block EMA moves, add a difficulty floor, and preserve state across restarts

Ouverte
#187 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

@anshulchikhale30-p y travaille déjà.

Depuis le 15/11/2026.

  • #188 par @anshulchikhale30-p — ouverte

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
25/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
À l'abandon
Stack technique
python
Domaine
backend

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

bug documentation enhancement

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

  1. The per-block target change is unbounded. _next_target computes

    new_target = (target * int(avg_block_time)) // self.target_block_time
    

    and 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_TARGET in 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.

  2. 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.

  3. Difficulty state is lost on restart. persistence.load() constructs a fresh Blockchain() and replaces only .chain and .state. current_target and avg_block_time keep 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: False
    

    The node resumes at genesis difficulty instead of the difficulty it had reached.

  4. The difficulty configuration is not persisted. target_block_time and alpha are re-read from whichever genesis.json is in the working directory during load(). 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 = 25 and clamp every EMA result to +/-25% of the previous target.
  • Add MIN_DIFFICULTY_FLOOR_DIVISOR = 4. The easiest allowed target becomes min(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 rebuild avg_block_time and the next target. Call it from load().
  • Do not revalidate historical targets during that replay, so snapshots produced by older retarget rules still load.
  • Persist target_block_time and alpha in the SQLite metadata table and restore them before recomputation. Legacy JSON snapshots without this metadata continue to load.
  • Validate target_block_time and alpha when reading genesis.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 = 0 would 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 by load() preserves current_target, avg_block_time, target_block_time, and alpha exactly.
  • 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 / alpha values 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

  • pytest focused on tests/test_target.py, tests/test_persistence.py, tests/test_persistence_extra.py, and tests/test_chain_extra.py.
  • Full suite matches the origin/main baseline (only the two pre-existing environment-related tests/test_contract_calls.py failures 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

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de StabilityNexus/MiniChain

Toutes les issues de StabilityNexus/MiniChain

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.