forked from mrsaicharan1/Nebula
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathblockchain.py
More file actions
101 lines (81 loc) · 2.58 KB
/
blockchain.py
File metadata and controls
101 lines (81 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# -*- coding: utf-8 -*-
import hashlib
import json
from textwrap import dedent
from time import time
from uuid import uuid4
class Blockchain(object):
def __init__(self):
self.current_transactions = []
self.chain = []
genesis_block = {
'index': 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': 100,
'previous_hash': 1,
}
genesis_block['hash'] = self.hash(genesis_block)
self.current_transactions = []
self.chain.append(genesis_block)
def new_block(self, proof, previous_hash):
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': self.chain[-1]['hash']
}
# Calculate the hash of this new Block
block['hash'] = self.hash(block)
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def hash(block):
"""
Creates a SHA-256 hash of a Block
"""
block_string = json.dumps(block).encode()
return hashlib.sha256(block_string).hexdigest()
@staticmethod # Hashing algo section
def valid_proof(last_proof, proof):
guess = (str(last_proof)+str(proof)).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:2] == "ff"
@staticmethod
def proof_of_work(last_proof):
"""
Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
- p is the previous proof, and p' is the new proof
:param last_proof: <int>
:return: <int>
"""
proof = 0
while True:
guess = (str(last_proof)+str(proof)).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
if guess_hash[:2] == "ff":
break
proof += 1
print(dedent('''
New Proof found!
New Proof: {proof}
Last Proof: {last_proof}
Hash: {guess_hash}
'''))
return proof
"""
Copyright © 2018 FreeFlo . All rights reserved.
"""