Skip to content

Commit d8219af

Browse files
Create solution_rishita.py
added one more optimised solution
1 parent eb50761 commit d8219af

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

solution_rishita.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import hashlib
2+
import json
3+
import time
4+
5+
class Block:
6+
def __init__(self, index, previous_hash, timestamp, data, hash):
7+
self.index = index
8+
self.previous_hash = previous_hash
9+
self.timestamp = timestamp
10+
self.data = data
11+
self.hash = hash
12+
13+
def calculate_hash(index, previous_hash, timestamp, data):
14+
value = str(index) + str(previous_hash) + str(timestamp) + json.dumps(data)
15+
return hashlib.sha256(value.encode('utf-8')).hexdigest()
16+
17+
def create_genesis_block():
18+
return Block(0, "0", int(time.time()), [], "0000000000000000000000000000000000000000000000000000000000000000")
19+
20+
def create_new_block(previous_block, data):
21+
index = previous_block.index + 1
22+
timestamp = int(time.time())
23+
hash = calculate_hash(index, previous_block.hash, timestamp, data)
24+
return Block(index, previous_block.hash, timestamp, data, hash)
25+
26+
# Initialize blockchain with a genesis block
27+
blockchain = [create_genesis_block()]
28+
current_block = blockchain[-1]
29+
30+
# Example data for lost and found system
31+
lost_item_data = {
32+
"item_name": "Phone",
33+
"description": "iPhone X",
34+
"owner_name": "Alice",
35+
"contact_info": "123-456-7890"
36+
}
37+
38+
# Add a lost item to the blockchain
39+
current_block = create_new_block(current_block, lost_item_data)
40+
blockchain.append(current_block)
41+
42+
# Print the blockchain
43+
for block in blockchain:
44+
print(f"Index: {block.index}")
45+
print(f"Previous Hash: {block.previous_hash}")
46+
print(f"Timestamp: {block.timestamp}")
47+
print(f"Data: {json.dumps(block.data)}")
48+
print(f"Hash: {block.hash}\n")

0 commit comments

Comments
 (0)