In [ ]:
import time
import hashlib
import json
import matplotlib.pyplot as plt
import pandas as pd

Proof of Work


In [ ]:
transaction = [
    'A paid B 25 A_public_key', 
    'A paid C 50 A_public_key', 
    'C paid B 10 C_public_key'
]
transaction = json.dumps(transaction).encode()

In [ ]:
difficulty_bits = list(range(0, 8))
time_taken = []
for num_bits in difficulty_bits:
    proved = False
    proof = 0
    start_time = time.time()
    while not proved:
        string = transaction + str(proof).encode()
        current_hash = hashlib.sha256(string).hexdigest()
        if current_hash.startswith('0'*num_bits):
            print(current_hash)
            print(proof)
            proved = True
            time_taken.append(time.time()-start_time)
        proof = proof+1

In [ ]:
plt.scatter(difficulty_bits, time_taken)
plt.xlabel('number of leading zeros')
plt.ylabel('time taken to find proof')
plt.show()

Probability of Attacker catching up with Honest Chain


In [ ]:
import math
q = 0.3
p = 1-q
def factorial(k):
    fac = 1
    for _ in range(1, k+1):
        fac *= _
    return fac
def calculate(z):
    lamda = z * q/p
    sum = 1
    for k in range(z+1):
        sum -= math.pow(lamda, k) * math.exp(- lamda) / factorial(k) * (1 - math.pow((q/p), z-k))
    return sum

for _ in range(0, 30, 5):
    print(_, "\t=> ", round(calculate(_),8))

In [ ]:
round(calculate(10),8)