3
3
from time import time
4
4
from uuid import uuid4
5
5
6
+
6
7
class Blockchain :
7
8
def __init__ (self ):
8
9
# Initialize blockchain as an empty list and pending transactions
9
10
self .chain = []
10
11
self .current_transactions = []
11
12
12
13
# Create the genesis block
13
- self .new_block (previous_hash = '1' , proof = 100 )
14
+ self .new_block (previous_hash = "1" , proof = 100 )
14
15
15
16
def new_block (self , proof , previous_hash = None ):
16
17
"""
@@ -20,11 +21,11 @@ def new_block(self, proof, previous_hash=None):
20
21
:return: New Block
21
22
"""
22
23
block = {
23
- ' index' : len (self .chain ) + 1 ,
24
- ' timestamp' : time (),
25
- ' transactions' : self .current_transactions ,
26
- ' proof' : proof ,
27
- ' previous_hash' : previous_hash or self .hash (self .chain [- 1 ])
24
+ " index" : len (self .chain ) + 1 ,
25
+ " timestamp" : time (),
26
+ " transactions" : self .current_transactions ,
27
+ " proof" : proof ,
28
+ " previous_hash" : previous_hash or self .hash (self .chain [- 1 ]),
28
29
}
29
30
30
31
# Reset the current list of transactions
@@ -41,13 +42,11 @@ def new_transaction(self, sender, recipient, amount):
41
42
:param amount: Amount of the transaction
42
43
:return: The index of the block that will hold this transaction
43
44
"""
44
- self .current_transactions .append ({
45
- 'sender' : sender ,
46
- 'recipient' : recipient ,
47
- 'amount' : amount
48
- })
45
+ self .current_transactions .append (
46
+ {"sender" : sender , "recipient" : recipient , "amount" : amount }
47
+ )
49
48
50
- return self .last_block [' index' ] + 1
49
+ return self .last_block [" index" ] + 1
51
50
52
51
@staticmethod
53
52
def hash (block ):
@@ -79,12 +78,12 @@ def proof_of_work(self, last_proof):
79
78
proof = 0
80
79
while self .valid_proof (last_proof , proof ) is False :
81
80
proof += 1
82
-
81
+
83
82
# Add the mining reward here
84
83
self .new_transaction (
85
84
sender = "0" , # System or network
86
85
recipient = "Miner1" , # Replace with the miner's address
87
- amount = 1 # Reward amount
86
+ amount = 1 , # Reward amount
88
87
)
89
88
return proof
90
89
@@ -96,16 +95,17 @@ def valid_proof(last_proof, proof):
96
95
:param proof: Current proof
97
96
:return: True if correct, False if not.
98
97
"""
99
- guess = f' { last_proof } { proof } ' .encode ()
98
+ guess = f" { last_proof } { proof } " .encode ()
100
99
guess_hash = hashlib .sha256 (guess ).hexdigest ()
101
100
return guess_hash [:4 ] == "0000"
102
101
102
+
103
103
# Create a new blockchain instance
104
104
blockchain = Blockchain ()
105
105
106
106
# Example usage: Add a new transaction and mine a new block
107
107
blockchain .new_transaction (sender = "Alice" , recipient = "Bob" , amount = 50 )
108
- last_proof = blockchain .last_block [' proof' ]
108
+ last_proof = blockchain .last_block [" proof" ]
109
109
proof = blockchain .proof_of_work (last_proof )
110
110
block = blockchain .new_block (proof )
111
111
0 commit comments