Skip to content

Instantly share code, notes, and snippets.

@sipa

sipa/simul.cpp Secret

Last active February 22, 2019 15:57
Show Gist options
  • Save sipa/0523b510fcb7576511f0f670e0c6c0a5 to your computer and use it in GitHub Desktop.
Save sipa/0523b510fcb7576511f0f670e0c6c0a5 to your computer and use it in GitHub Desktop.
Target adjustment simulation
#include <math.h>
#include <stdio.h>
#include <random>
#define RETARGET_INTERVAL 2016
#define INTERBLOCK_TIME 600
#define PERIODS 10000
static std::random_device rng;
static std::mt19937 gen(rng());
static inline long double time_for_next_block(long double rate) {
std::exponential_distribution<long double> dist(rate);
return dist(gen);
}
int main(void) {
//! The timestamps of the past 2016 blocks
int64_t blocktimes[RETARGET_INTERVAL];
//! The current timestamp
long double ts = 0;
//! The current difficulty (the hashrate is held constant at 1 H/s)
// It doesn't matter what value we start at (it'll converge), but
// we expect a target that corresponds to a rate of one block per
// INTERBLOCK_TIME.
long double target = powl(2.0, 256) / INTERBLOCK_TIME;
for (int j = 0; j < PERIODS; ++j) {
// Adjust difficulty (except in the first period)
if (j > 0) {
int64_t timediff = blocktimes[RETARGET_INTERVAL-1] - blocktimes[0];
target *= timediff;
target /= (INTERBLOCK_TIME*RETARGET_INTERVAL);
}
// Simulate the creation of blocks in that interval
for (int i = 0; i < RETARGET_INTERVAL; ++i) {
ts += time_for_next_block(target / powl(2.0, 256));
// Blocks use the current timestamp
blocktimes[i] = int64_t(ts);
}
}
printf("Average block time %.15Lg\n", ts / (RETARGET_INTERVAL*PERIODS));
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment