generated from StabilityNexus/Template-Repo
-
-
Notifications
You must be signed in to change notification settings - Fork 14
PID difficulty adjuster with pure integer arithmetic #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anshulchikhale30-p
wants to merge
30
commits into
StabilityNexus:main
Choose a base branch
from
anshulchikhale30-p:pid-app
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
30 commits
Select commit
Hold shift + click to select a range
b531c45
done
anshulchikhale30-p 34deb5d
Update minichain/chain.py
anshulchikhale30-p 25ee67d
Update minichain/chain.py
anshulchikhale30-p 0fde886
Update minichain/chain.py
anshulchikhale30-p 258342b
Update minichain/pid.py
anshulchikhale30-p 46ae32e
Update test_pid_integration.py
anshulchikhale30-p d911642
Update minichain/pow.py
anshulchikhale30-p af63105
Update tests/test_difficulty.py
anshulchikhale30-p 879a9c1
Update tests/test_difficulty.py
anshulchikhale30-p 08e1cb3
Update test_pid_integration.py
anshulchikhale30-p 88ac5ac
test file under test folder fix
anshulchikhale30-p 7205ce0
Merge branch 'pid-app' of https://github.com/anshulchikhale30-p/MiniC…
anshulchikhale30-p 1b8b76a
fixed
anshulchikhale30-p 57e163a
Update chain.py
anshulchikhale30-p e91af2d
Update test_pid_integration.py
anshulchikhale30-p d83df01
Update test_difficulty.py
anshulchikhale30-p 3a75cdf
Update chain.py
anshulchikhale30-p 5bbc9c6
Update tests/test_difficulty.py
anshulchikhale30-p 1da0818
Update tests/test_pid_integration.py
anshulchikhale30-p e18cfa6
Update tests/test_pid_integration.py
anshulchikhale30-p 5dfeac5
Update tests/test_pid_integration.py
anshulchikhale30-p 70abc1e
Merge branch 'StabilityNexus:main' into pid-app
anshulchikhale30-p ff7fea5
Update test_pid_integration.py
anshulchikhale30-p 504ded0
remove duplicate block of code from 100 to 113
anshulchikhale30-p a329455
Update chain.py
anshulchikhale30-p 046f4f0
Update pow.py
anshulchikhale30-p 0a1cfa9
Update pid.py
anshulchikhale30-p 3f70d4f
Update test_pid_integration.py
anshulchikhale30-p b5b855f
Merge branch 'StabilityNexus:main' into pid-app
anshulchikhale30-p df90e3d
Removed line 66
anshulchikhale30-p File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| """ | ||
| Stateless PID-based Difficulty Adjuster for MiniChain | ||
|
|
||
| CRITICAL: This implementation is 100% STATELESS. | ||
| No memory variables (integral, derivative) that persist between calls. | ||
|
|
||
| Why? If a node restarts, local variables reset to 0, causing the node to calculate | ||
| a radically different difficulty than the network, leading to a hard-fork. | ||
|
|
||
| Solution: Calculate difficulty purely from blockchain timestamps. | ||
| All nodes compute the same result regardless of when they started. | ||
| """ | ||
|
|
||
| from typing import Optional | ||
|
|
||
|
|
||
| class PIDDifficultyAdjuster: | ||
| """ | ||
| Stateless difficulty adjuster using pure calculation from block data. | ||
|
|
||
| 100% Deterministic: Same inputs always produce same outputs | ||
| No Hard-Forks: Nodes get identical results regardless of restart | ||
| Blockchain-Based: Uses immutable timestamps, not local memory | ||
| """ | ||
|
|
||
| SCALE = 1000 # Fixed-point scaling factor for integer math | ||
|
|
||
| def __init__( | ||
| self, | ||
| target_block_time: float = 10.0, | ||
| kp: int = 50, | ||
| ki: int = 5, | ||
| kd: int = 10 | ||
| ): | ||
| """ | ||
| Initialize the stateless PID difficulty adjuster. | ||
|
|
||
| Args: | ||
| target_block_time: Target time for block generation in seconds | ||
| kp: Proportional coefficient (pre-scaled by SCALE). Default 50 = 0.05 | ||
| ki: Integral coefficient (pre-scaled by SCALE). Default 5 = 0.005 | ||
| kd: Derivative coefficient (pre-scaled by SCALE). Default 10 = 0.01 | ||
| """ | ||
| self.target_block_time = target_block_time | ||
| self.kp = kp # Proportional | ||
| self.ki = ki # Integral (smaller - we don't accumulate state) | ||
| self.kd = kd # Derivative (smaller - we don't have history) | ||
|
|
||
| def adjust( | ||
| self, | ||
| current_difficulty: int, | ||
| actual_block_time: Optional[float] = None | ||
| ) -> int: | ||
| """ | ||
| Calculate new difficulty based on CURRENT block time only. | ||
|
|
||
| STATELESS: No memory variables | ||
| - No self.integral (resets on restart → hard-fork) | ||
| - No self.previous_error (resets on restart → hard-fork) | ||
| - No self.last_block_time (resets on restart → hard-fork) | ||
|
|
||
| Pure calculation from current block time and fixed coefficients. | ||
|
|
||
| Args: | ||
| current_difficulty: Current difficulty value | ||
| actual_block_time: Time to mine this block in seconds | ||
|
|
||
| Returns: | ||
| New difficulty value (minimum 1) | ||
| """ | ||
|
|
||
| if actual_block_time is None: | ||
| # If no time provided, make no adjustment (safe default) | ||
| return current_difficulty | ||
|
|
||
| # ===== Fixed-Point Integer Arithmetic ===== | ||
| # Convert times to scaled integers for precise calculation | ||
| actual_block_time_scaled = int(actual_block_time * self.SCALE) | ||
| target_time_scaled = int(self.target_block_time * self.SCALE) | ||
|
|
||
| # Calculate error (positive = too fast, negative = too slow) | ||
| error = target_time_scaled - actual_block_time_scaled | ||
|
|
||
| # ===== Proportional Term Only ===== | ||
| # Without integral/derivative state, we use proportional adjustment | ||
| # This is simpler, deterministic, and stateless | ||
| p_adjustment = (self.kp * error) // self.SCALE | ||
|
|
||
| # ===== Safety Constraint: Limit Change to 10% per Block ===== | ||
| # FIXED: Use integer division (// 10) not float multiplier (* 0.1) | ||
| # This ensures deterministic behavior across all CPUs | ||
| max_delta = max(1, current_difficulty // 10) | ||
|
|
||
| # Clamp adjustment to safety bounds | ||
| clamped_adjustment = max( | ||
| min(p_adjustment, max_delta), | ||
| -max_delta | ||
| ) | ||
|
|
||
| # Calculate new difficulty | ||
| new_difficulty = current_difficulty + clamped_adjustment | ||
|
|
||
| # Return new difficulty (minimum 1) | ||
| return max(1, new_difficulty) | ||
|
|
||
| # NOTE: No reset(), get_state(), or set_state() methods | ||
| # These assume persistent memory, which causes hard-forks! | ||
| # All state is calculated fresh from blockchain data. | ||
|
|
||
|
|
||
| class StatelessPIDDifficultyAdjuster(PIDDifficultyAdjuster): | ||
| """ | ||
| Alternative: If you need more sophisticated PID logic, calculate from BLOCK HISTORY. | ||
|
|
||
| Instead of storing state in memory: | ||
| - Query the last N blocks from the blockchain | ||
| - Calculate integral as sum of recent errors | ||
| - Calculate derivative from last 2 blocks | ||
| - All nodes get identical results (no hard-fork) | ||
|
|
||
| This is the production-safe approach for a real blockchain. | ||
| """ | ||
|
|
||
| def adjust_from_history( | ||
| self, | ||
| current_difficulty: int, | ||
| recent_block_times: list # Last N block times in seconds | ||
| ) -> int: | ||
| """ | ||
| Calculate adjustment using only blockchain history. | ||
|
|
||
| Args: | ||
| current_difficulty: Current difficulty | ||
| recent_block_times: List of recent block times (e.g., last 10 blocks) | ||
|
|
||
| Returns: | ||
| New difficulty based on trend analysis | ||
| """ | ||
| if not recent_block_times: | ||
| return current_difficulty | ||
|
|
||
| # Calculate average time (proportional term) | ||
| avg_time = sum(recent_block_times) / len(recent_block_times) | ||
| error = self.target_block_time - avg_time | ||
|
|
||
| # Simple adjustment based on average deviation | ||
| p_adjustment = int((self.kp * error * self.SCALE) // self.SCALE) | ||
|
|
||
| # Safety constraint | ||
| max_delta = max(1, current_difficulty // 10) | ||
| clamped = max(min(p_adjustment, max_delta), -max_delta) | ||
|
|
||
| new_difficulty = current_difficulty + clamped | ||
| return max(1, new_difficulty) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
since you removed mining_time from here this will cause a type error and breaks p2p sync