#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import time
import json

block = {
        'block_id': 1,
        'difficulty': '00000'
        }


def proof_of_work(block):
    start_time = time.time()
    sha_block = hashlib.sha256(block).digest()
    
    json_block = json.loads(block)
    diffu = json_block['difficulty']

    proof = 0
    while True:
        work = hashlib.sha256(sha_block + str(proof)).hexdigest()
        if work.startswith(diffu):
            finished_time = time.time()
            done_time = finished_time - start_time
            
            print '-------------------'
            print 'Difficulty:', diffu
            print 'Proof Number:', proof
            print 'Time:', done_time
            print '-------------------'
            
            break
        else:
            proof += 1

    return (block, proof)


def verify_work(data):
    block, proof = data
    sha_block = hashlib.sha256(block).digest()
    
    json_block = json.loads(block)
    work = hashlib.sha256(sha_block + str(proof)).hexdigest()

    if work.startswith(str(json_block['difficulty'])):
        return True  # Accepted
    else:
        return False # Rejected



working = proof_of_work(json.dumps(block))
verified  = verify_work(working)

if verified:
    print 'Block has been accepted!'
else:
    print 'Block has been rejected!'