The following looks simple, but the link above shows how much work I've done in advanced techniques
like a variable averaging window, hash-attack detection using statistics, least-squares slope prediction,
significant-slope-change detection, mixtures of avg and median, recent-blocks-more-heavily-weighted, and
"discrete D/T averaging" as a hashrate measurement. I was able to get all of them only as good as simple
averaging, and none of them better than simply going to a smaller N for averaging.
# Gandalf's difficulty algorithm v1. "Hash attacks shall not pass!" # This is Zawy v1b with low N=8 (and X=5) # Timestamp manipulation protection is not needed due to limits on next_D. # Negative timestamps must be allowed. # 0.92 keeps avg solvetime on track but makes median come out 8% low. I can't find a fix. # Increase N to 30 if you want correct avg & median, but expect 10% of blocks in small # coins to be stolen. Median mixed in w/ avg will not help. # Do not use sum(D's) * T / [max(timestamp)-min(timestamp)] method. # 5% block solvetimes are > 5x target solvetime under constant HEAVY attack. # 1.3% block solvetimes > 5x target solvetime when hashrate is constant. # 3% of blocks will be < 0.5x or > 2x the correct difficulty on accident. # When N=15 these numbers are 5%,, 1%, and 0.5%. https://github.com/seredat/karbowanec/commit/231db5270acb2e673a641a1800be910ce345668a next_D = avg(last 8 Ds) * T / avg(last 8 solvetimes] *0.92; next_D = 1.6*previous_D if next_D/previous_D > 1.6; next_D = 0.63*previous_D if next_D/previous_D < 0.63;
The only potential problem I see is that the D will swing below 0.5 the correct D a lot, attracting an attack.
But they can only get ~4 blocks at low difficulty. A question I need an answer to is this: how short of an
attack can an attacker tolerate before it is not worth switching to the coin? I can go to N=5 which will
result in a lot of D < 0.33 correct D, which is really attractive, but is worth 3 blocks for them to switch coins?