I've been going through the Bitcoin whitepaper again and this time I decided to take a closer look at the section eleven, Calculations, from page six of the document. In this post we are going to take a closer look at Satoshi's calculations in C. Satoshi wrote the following C function that implements his calculations:
#include <math.h> double AttackerSuccessProbability(double q, int z) { double p = 1.0 - q; double lambda = z * (q / p); double sum = 1.0; int i, k; for (k = 0; k <= z; k++) { double poisson = exp(-lambda); for (i = 1; i <= k; i++) poisson *= lambda / i; sum -= poisson * (1 - pow(q / p, z - k)); } return sum; }
In order to call this function with some arguments and see its result I created a file,
a_prob_sccs.c
in which I called the function AttackerSuccessProbability
within main
. I also added a print statement that explains with what arguments ( 0.49 stands for 49% of nodes) I called AttackerSuccessProbability
:#include<stdio.h> #include<math.h> int main() { double AttackerSuccessProbability(double q, int z) { double p = 1.0 - q; double lambda = z * (q / p); double sum = 1.0; int i, k; for (k = 0; k <= z; k++) { double poisson = exp(-lambda); for (i = 1; i <= k; i++) poisson *= lambda / i; sum -= poisson * (1 - pow(q / p, z - k)); } return sum; } //If the attacker is one block behind and there is 49% of dishonest nodes double prob = AttackerSuccessProbability(0.49, 1); puts("The probability of the success of the attacker when they are 1 block behind the honest 51% majority of nodes:"); printf("%f\n", prob); return 0; }
I use gcc as my C compiler and had to give gcc
-lm
flag. Otherwise I was getting this error.
Compile it with gcc a_prob_sccs.c -lm
and then run it, ./a.out
. Tweak the arguments given to
AttackerSuccessProbability
to see how the probability of the attacker's success changes with the percentage of dishonest nodes and with the number of blocks that the attacker is behind.