-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.py
More file actions
198 lines (135 loc) · 6.02 KB
/
blockchain.py
File metadata and controls
198 lines (135 loc) · 6.02 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import functools
import json
from block import Block
from transaction import Transaction
from wallet import Wallet
from utils.hash_utils import hash_block
from utils.verification import Verification
MINING_REWARD = 10
class Blockchain:
def __init__(self, hosting_node_id):
GENESIS_BLOCK = Block(0, "", [], 100, 0)
self.__chain = [GENESIS_BLOCK]
self.__open_transactions = []
self.hosting_node = hosting_node_id
self.fetch_data()
def get_chain(self):
return self.__chain[:]
def get_open_transactions(self):
return self.__open_transactions[:]
def save_data(self):
try:
with open('blockchain.txt', mode='w') as file:
saveable_blockchain = [block.__dict__ for block in [Block(block_el.index, block_el.previous_hash, [tx.__dict__ for tx in block_el.transactions], block_el.proof, block_el.timestamp) for block_el in self.__chain]]
file.write(json.dumps(saveable_blockchain))
file.write('\n')
saveable_transaction = [transaction.__dict__ for transaction in self.__open_transactions]
file.write(json.dumps(saveable_transaction))
except (IOError, IndexError):
print("Saving failed!")
def fetch_data(self):
try:
with open('blockchain.txt', mode='r') as file:
file_content = file.readlines()
self.__chain = json.loads(file_content[0][:-1])
updated_blockchain = []
for block in self.__chain:
converted_transactions = [Transaction(transaction['sender'], transaction['recipient'], transaction['amount'], transaction['signature']) for transaction in block['transactions']]
fetched_block = Block(block['index'], block['previous_hash'], converted_transactions, block['proof'], block['timestamp'])
updated_blockchain.append(fetched_block)
self.__chain = updated_blockchain
open_transactions = json.loads(file_content[1])
updated_transactions = []
for transaction in open_transactions:
fetched_transaction = Transaction(transaction['sender'], transaction['recipient'], transaction['amount'], transaction['signature'])
updated_transactions.append(fetched_transaction)
open_transactions = updated_transactions
except (IOError, IndexError):
print("Handled error...")
finally:
print("Cleanup!")
def proof_of_work(self):
last_block = self.__chain[-1]
last_hash = hash_block(last_block)
proof = 0
while not Verification.valid_proof(self.__open_transactions, last_hash, proof):
proof += 1
return proof
def get_balance(self):
participant = self.hosting_node
tx_sender = [[transaction.amount for transaction in block.transactions if transaction.sender == participant] for block in self.__chain]
open_tx_sender = [transaction.amount for transaction in self.__open_transactions if transaction.sender == participant]
tx_sender.append(open_tx_sender)
amount_sent = functools.reduce(
lambda tx_sum, tx_amount: tx_sum + sum(tx_amount) if len(tx_amount) > 0 else tx_sum + 0, tx_sender, 0)
# amount_sent = 0
#
# for tx in tx_sender:
# if len(tx) > 0:
# amount_sent += tx[0]
tx_recipient = [[transaction.amount for transaction in block.transactions if transaction.recipient == participant] for block in self.__chain]
amount_received = functools.reduce(
lambda tx_sum, tx_amount: tx_sum + sum(tx_amount) if len(tx_amount) > 0 else tx_sum + 0, tx_recipient, 0)
# amount_received = 0
#
# for tx in tx_recipient:
# if len(tx) > 0:
# amount_received += tx[0]
return amount_received - amount_sent
def get_last_blockchain_transaction(self):
if len(self.__chain) < 1:
return None
return self.__chain[-1]
def add_transaction(self, sender, recipient, amount, signature):
if self.hosting_node == None:
return False
transaction = Transaction(sender, recipient, amount, signature)
if Verification.verify_transaction(transaction, self.get_balance):
self.__open_transactions.append(transaction)
# participants.add(sender)
# participants.add(recipient)
self.save_data()
return True
return False
def mine_block(self):
if self.hosting_node == None:
return False
hashed_block = hash_block(self.__chain[-1])
print("Hashed blocks result:" , hashed_block)
proof = self.proof_of_work()
reward_transaction = Transaction('Miner', self.hosting_node, MINING_REWARD, '')
copied_transactions = self.__open_transactions[:]
for transaction in copied_transactions:
if not Wallet.verify_transaction(transaction):
return False
copied_transactions.append(reward_transaction)
block = Block(len(self.__chain), hashed_block, copied_transactions, proof)
self.__chain.append(block)
self.open_transactions = []
self.save_data()
return True
# def verify_blockchain():
# # block_index = 0
# is_valid = True
#
# for block_index in range(len(blockchain)):
# if block_index == 0:
# continue
# elif blockchain[block_index][0] == blockchain[block_index - 1]:
# is_valid = True
# else:
# is_valid = False
# break
# # for block in blockchain:
# # if block_index == 0:
# # block_index += 1
# # continue
# # elif block[0] == blockchain[block_index - 1]:
# # is_valid = True
# # else:
# # is_valid = False
# # break
# #
# # block_index += 1
#
# return is_valid