s_nakamoto
New member
- Messages
- 12
import hashlib
import json
import time
import threading
from ecdsa import SigningKey, VerifyingKey, SECP256k1
import socket
# Blockchain Class
class Blockchain:
def __init__(self):
self.chain = []
self.current_transactions = []
self.create_block(previous_hash='1', proof=100)
def create_block(self, proof, previous_hash):
block = {
'index': len(self.chain) + 1,
'timestamp': time.time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash
}
self.chain.append(block)
self.current_transactions = []
return block
def add_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount
})
return self.last_block['index'] + 1
def proof_of_work(self, last_proof):
proof = 0
while not self.valid_proof(last_proof, proof):
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def hash(block):
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
# Wallet Class
class Wallet:
def __init__(self):
self.private_key = SigningKey.generate(curve=SECP256k1)
self.public_key = self.private_key.get_verifying_key()
self.address = self.generate_address()
def generate_address(self):
hashed_pub_key = hashlib.sha256(self.public_key.to_string()).hexdigest()
return hashed_pub_key[:34]
# Mining Functionality
class Miner:
def __init__(self, blockchain, wallet):
self.blockchain = blockchain
self.wallet = wallet
def mine(self):
while True:
last_block = self.blockchain.last_block
proof = self.blockchain.proof_of_work(last_block['proof'])
self.blockchain.add_transaction(
sender="0", # Mining reward
recipient=self.wallet.address,
amount=1
)
block = self.blockchain.create_block(proof, self.blockchain.hash(last_block))
print(f"New Block Mined: {block}")
# Console Commands Interface
class ConsoleInterface:
def __init__(self, blockchain, wallet):
self.blockchain = blockchain
self.wallet = wallet
def run(self):
while True:
print("\n1. View Blockchain")
print("2. Create Transaction")
print("3. Mine Block")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
self.view_blockchain()
elif choice == "2":
self.create_transaction()
elif choice == "3":
self.mine_block()
elif choice == "4":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
def view_blockchain(self):
print("\nBlockchain:")
for block in self.blockchain.chain:
print(json.dumps(block, indent=4))
def create_transaction(self):
sender = input("Enter sender address: ")
recipient = input("Enter recipient address: ")
amount = float(input("Enter amount: "))
index = self.blockchain.add_transaction(sender, recipient, amount)
print(f"Transaction will be added to Block {index}")
def mine_block(self):
miner = Miner(self.blockchain, self.wallet)
threading.Thread(target=miner.mine).start()
# Main Execution
if __name__ == "__main__":
blockchain = Blockchain()
wallet = Wallet()
console_interface = ConsoleInterface(blockchain, wallet)
console_interface.run()
import json
import time
import threading
from ecdsa import SigningKey, VerifyingKey, SECP256k1
import socket
# Blockchain Class
class Blockchain:
def __init__(self):
self.chain = []
self.current_transactions = []
self.create_block(previous_hash='1', proof=100)
def create_block(self, proof, previous_hash):
block = {
'index': len(self.chain) + 1,
'timestamp': time.time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash
}
self.chain.append(block)
self.current_transactions = []
return block
def add_transaction(self, sender, recipient, amount):
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount
})
return self.last_block['index'] + 1
def proof_of_work(self, last_proof):
proof = 0
while not self.valid_proof(last_proof, proof):
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def hash(block):
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
# Wallet Class
class Wallet:
def __init__(self):
self.private_key = SigningKey.generate(curve=SECP256k1)
self.public_key = self.private_key.get_verifying_key()
self.address = self.generate_address()
def generate_address(self):
hashed_pub_key = hashlib.sha256(self.public_key.to_string()).hexdigest()
return hashed_pub_key[:34]
# Mining Functionality
class Miner:
def __init__(self, blockchain, wallet):
self.blockchain = blockchain
self.wallet = wallet
def mine(self):
while True:
last_block = self.blockchain.last_block
proof = self.blockchain.proof_of_work(last_block['proof'])
self.blockchain.add_transaction(
sender="0", # Mining reward
recipient=self.wallet.address,
amount=1
)
block = self.blockchain.create_block(proof, self.blockchain.hash(last_block))
print(f"New Block Mined: {block}")
# Console Commands Interface
class ConsoleInterface:
def __init__(self, blockchain, wallet):
self.blockchain = blockchain
self.wallet = wallet
def run(self):
while True:
print("\n1. View Blockchain")
print("2. Create Transaction")
print("3. Mine Block")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
self.view_blockchain()
elif choice == "2":
self.create_transaction()
elif choice == "3":
self.mine_block()
elif choice == "4":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
def view_blockchain(self):
print("\nBlockchain:")
for block in self.blockchain.chain:
print(json.dumps(block, indent=4))
def create_transaction(self):
sender = input("Enter sender address: ")
recipient = input("Enter recipient address: ")
amount = float(input("Enter amount: "))
index = self.blockchain.add_transaction(sender, recipient, amount)
print(f"Transaction will be added to Block {index}")
def mine_block(self):
miner = Miner(self.blockchain, self.wallet)
threading.Thread(target=miner.mine).start()
# Main Execution
if __name__ == "__main__":
blockchain = Blockchain()
wallet = Wallet()
console_interface = ConsoleInterface(blockchain, wallet)
console_interface.run()