-
Notifications
You must be signed in to change notification settings - Fork 4
/
blockchain.py
85 lines (66 loc) · 2.34 KB
/
blockchain.py
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
import hashlib
import time
from dataclasses import dataclass
import copy
from dacite import from_dict
@dataclass
class Transaction:
sender: str
recipient: str
amount: float
@dataclass
class Block:
index: int
transactions: list[Transaction]
proof: int
previous_hash: str
class Blockchain:
def __init__(self, address, difficulty_number, mining_reward):
self.address = address
self.difficulty_number = difficulty_number
self.mining_reward = mining_reward
self.chain = []
self.current_transactions = []
self.players = set()
def create_block(self, index, transactions, proof, previous_hash):
return Block(index, copy.copy(transactions), proof, previous_hash)
def create_transaction(self, sender, recipient, amount):
return Transaction(sender, recipient, amount)
def get_transactions(self):
return self.current_transactions
def current_block(self):
return self.chain[-1]
def add_transaction(self, sender, recipient, amount):
self.current_transactions.append(Transaction(sender, recipient, amount))
def next_index(self):
return len(self.chain) + 1
def get_length(self):
return len(self.chain)
def add_block(self, block):
if self.check_proof(block):
self.chain.append(block)
def add_player(self, address):
self.players.add(address)
def hash_block(self, block):
return hashlib.sha256(str(block).encode()).hexdigest()
def check_proof(self, block):
# Check that the hash of the block ends in difficulty_number many zeros
return False
def mine(self):
# Give yourself a reward at the beginning of the transactions
# Find the right value for proof
# Add the block to the chain
# Clear your current transactions
pass
def validate_chain(self, chain):
# Check that the chain is valid
# The chain is an array of blocks
# You should check that the hashes chain together
# The proofs of work should be valid
return True
def receive_chain(self, chain_raw_json):
chain = [from_dict(Block, b) for b in chain_raw_json]
if self.validate_chain(chain) and len(chain) > self.get_length():
self.chain = chain
return True
return False