forked from WolfByttner/cryptocurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blockchain.py
69 lines (52 loc) · 2.31 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
from Block import Block
from transaction import Transaction
import time
class Blockchain:
def __init__(self, difficulty=2):
self.chain = [self.create_genesis_block()]
self.difficulty = difficulty
self.pending_transactions = []
self.mining_reward = 100
def create_genesis_block(self):
# Create an initial block with no transactions
return Block("0", [], time.time())
def get_latest_block(self):
return self.chain[-1]
def mine_pending_transactions(self, mining_reward_address):
if not self.pending_transactions:
raise ValueError("No transactions to mine")
reward_tx = Transaction(None, mining_reward_address, self.mining_reward)
block_transactions = self.pending_transactions + [reward_tx]
block = Block(self.get_latest_block().hash, block_transactions, time.time())
block.mine_block(self.difficulty)
print("Block successfully mined!")
self.chain.append(block)
# Clear pending transactions after mining
self.pending_transactions = []
def add_transaction(self, transaction):
if not transaction.sender or not transaction.recipient:
raise ValueError("Transaction must include sender and recipient")
if not transaction.is_valid():
raise ValueError("Cannot add invalid transaction to chain")
sender_balance = self.get_balance(transaction.sender)
if transaction.amount > sender_balance:
raise ValueError(f"Not enough balance. Current balance: {sender_balance}")
self.pending_transactions.append(transaction)
def is_chain_valid(self):
for i in range(1, len(self.chain)):
current_block = self.chain[i]
previous_block = self.chain[i - 1]
if current_block.hash != current_block.calculate_hash():
return False
if current_block.previous_hash != previous_block.hash:
return False
return True
def get_balance(self, address):
balance = 0
for block in self.chain:
for trans in block.transactions:
if trans.sender == address:
balance -= trans.amount
if trans.recipient == address:
balance += trans.amount
return balance