Skip to content

Instantly share code, notes, and snippets.

@jnewbery
Created March 13, 2021 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewbery/df4e38a494b0d4d3213e974b6f539a59 to your computer and use it in GitHub Desktop.
Save jnewbery/df4e38a494b0d4d3213e974b6f539a59 to your computer and use it in GitHub Desktop.
Simulate the number of expected number of duplicate nonces in the Bitcoin block chain
#include <algorithm>
#include <iostream>
#include <random>
constexpr uint16_t REPEATS{100};
constexpr uint32_t BLOCK_HEIGHT{674293};
uint16_t run(int seed)
{
std::seed_seq seq{seed};
std::vector<uint32_t> nonces(BLOCK_HEIGHT);
seq.generate(nonces.begin(), nonces.end()); // seed_seq.generate() generates a sequence of 32 bit outputs
std::sort(nonces.begin(), nonces.end());
uint16_t duplicates{0};
auto it = nonces.begin();
while (it != nonces.end()) {
auto next = it + 1;
if (next != nonces.end() && *it == *next) ++duplicates;
it = next;
}
return duplicates;
}
int main()
{
float total{0};
for (auto i=0; i<REPEATS; ++i) {
auto result = run(i);
std::cout << result << std::endl;
total += result;
}
std::cout << "Average = " << total / REPEATS << std::endl;
return 0;
}
@jnewbery
Copy link
Author

Wow. Thanks for the detailed reply!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment