Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Muntaha #510

Open
haseebas0004 opened this issue Dec 22, 2024 · 0 comments
Open

Muntaha #510

haseebas0004 opened this issue Dec 22, 2024 · 0 comments

Comments

@haseebas0004
Copy link

haseebas0004 commented Dec 22, 2024

import hashlib
import datetime

class Block:
def init(self, timestamp, data, previous_hash=''):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
self.nonce = 0 # For proof-of-work

def calculate_hash(self):
    data_string = str(self.timestamp) + str(self.data) + str(self.previous_hash) + str(self.nonce)
    return hashlib.sha256(data_string.encode()).hexdigest()

def mine_block(self, difficulty):
    target = "0" * difficulty
    while self.hash[:difficulty] != target:
        self.nonce += 1
        self.hash = self.calculate_hash()
    print("Block Mined!!! Hash:", self.hash)

class Blockchain:
def init(self):
self.chain = [self.create_genesis_block()]
self.difficulty = 4 # Adjust difficulty for mining time

def create_genesis_block(self):
    return Block(datetime.datetime.now(), "Genesis Block", "0")

def add_block(self, data):
    previous_block = self.chain[-1]
    new_block = Block(datetime.datetime.now(), data, previous_block.hash)
    new_block.mine_block(self.difficulty)
    self.chain.append(new_block)

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

Example Usage:

my_blockchain = Blockchain()
my_blockchain.add_block("Transaction 1: Send 10 BTC to Alice")
my_blockchain.add_block("Transaction 2: Send 5 BTC to Bob")
my_blockchain.add_block("Transaction 3: Send 1 BTC to Charlie")

print("Blockchain Valid?", my_blockchain.is_chain_valid())

Print the blockchain (for demonstration - in real life, this would be a distributed ledger)

for block in my_blockchain.chain:
print("Timestamp:", block.timestamp)
print("Data:", block.data)
print("Hash:", block.hash)
print("Previous Hash:", block.previous_hash)
print("---------------------")

Example of tampering (making the chain invalid)

my_blockchain.chain[1].data = "Tampered Data"

print("Blockchain Valid after tampering?", my_blockchain.is_chain_valid())good luck

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant