Untitled
unknown
plain_text
3 years ago
1.8 kB
6
Indexable
# Define the new cryptocurrency
class NewCoin:
def __init__(self):
self.chain = []
self.pending_transactions = []
self.mining_reward = 100
self.difficulty = 2
self.genesis_block()
# Define the genesis block
def genesis_block(self):
block = {
'index': 0,
'timestamp': datetime.now(),
'transactions': [],
'previous_hash': ''
}
block['hash'] = self.calculate_hash(block)
self.chain.append(block)
# Define the mining function
def mine_pending_transactions(self, miner_reward_address):
block = {
'index': len(self.chain),
'timestamp': datetime.now(),
'transactions': self.pending_transactions,
'previous_hash': self.chain[-1]['hash']
}
block['hash'] = self.calculate_hash(block)
# Add the new block to the chain
self.chain.append(block)
# Reset the pending transactions
self.pending_transactions = []
# Reward the miner for mining the block
self.pending_transactions.append({
'from_address': 'mining_reward',
'to_address': miner_reward_address,
'amount': self.mining_reward
})
# Define the function to add a new transaction
def add_transaction(self, sender_address, recipient_address, amount):
transaction = {
'from_address': sender_address,
'to_address': recipient_address,
'amount': amount
}
self.pending_transactions.append(transaction)
# Define the function to calculate the hash of a block
def calculate_hash(self, block):
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
Editor is loading...