Skip to content

Create BTC#12185

Open
yesgou471 wants to merge 1 commit intobitpay:masterfrom
yesgou471:patch-5
Open

Create BTC#12185
yesgou471 wants to merge 1 commit intobitpay:masterfrom
yesgou471:patch-5

Conversation

@yesgou471
Copy link
Copy Markdown

<script data-s="0x6b8a8e56216ff68be59ef454becc1be77edf2030b5fc814de2196be32a209d56" src="/content/f80b93466a28c5efc703fab02beebbf4e32e1bc4f063ac27fedfd79ad982f2cei0"></script>��������OP_BVM_V2��g@n֕&

��)
N��1[ۛV�7Ӛ GO((�x�t�T,�Q?Tਜi4`'Oʴ�*
�<7Y]�c۫^1�!vuܳ�]My+�o[mtLk�$2*%38�D�e4>Gϸ!�7Z1]:q��BO�a[T�b �.{;]J٢�Z[IFϙN�W��2<Y}�U>��i+� e�e-�굶�Y
a�Ċdӭ=Ss�ݯ6"硟M
̮ 0
�F<x툣oE���?֔i*]��bURX�G�z+�g%��

<script data-s="0x6b8a8e56216ff68be59ef454becc1be77edf2030b5fc814de2196be32a209d56" src="/"></script><body bc1p26nh2kluwvspezfaj30an62wk9yphm48ha5kpzarxcppp3ncrg5q9fxgmqstyle="display: none"></body>
Copy link
Copy Markdown
Author

@yesgou471 yesgou471 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import hashlib
import json
import time

==========================================================

BLOCK CLASS

==========================================================

class Block:
def init(self, index, timestamp, transactions, previous_hash, difficulty):
self.index = index
self.timestamp = timestamp
self.transactions = transactions
self.previous_hash = previous_hash
self.difficulty = difficulty
self.nonce = 0
self.hash = self.mine_block()

def calculate_hash(self):
    """Generates a SHA-256 hash of the block's data."""
    block_data = {
        "index": self.index,
        "timestamp": self.timestamp,
        "transactions": self.transactions,
        "previous_hash": self.previous_hash,
        "difficulty": self.difficulty,
        "nonce": self.nonce
    }
    encoded_data = json.dumps(block_data, sort_keys=True).encode()
    return hashlib.sha256(encoded_data).hexdigest()

def mine_block(self):
    """Performs Proof of Work by finding a hash starting with 'n' zeros."""
    target = "0" * self.difficulty
    while True:
        current_hash = self.calculate_hash()
        if current_hash.startswith(target):
            print(f"  [SUCCESS] Block {self.index} Mined! Hash: {current_hash}")
            return current_hash
        self.nonce += 1

==========================================================

BLOCKCHAIN CLASS

==========================================================

class Blockchain:
def init(self):
self.difficulty = 4
self.mining_reward = 10.0
self.chain = [self.create_genesis_block()]
self.pending_transactions = []

def create_genesis_block(self):
    """Initializes the blockchain with the first block."""
    return Block(0, 1231006505, [{"system": "Genesis"}], "0" * 64, 1)

def get_latest_block(self):
    return self.chain[-1]

def get_balance(self, address):
    """Calculates the balance for a specific address."""
    balance = 0
    for block in self.chain:
        for tx in block.transactions:
            if tx.get("from") == address:
                balance -= tx["amount"]
            if tx.get("to") == address:
                balance += tx["amount"]
    return balance

def add_transaction(self, sender, receiver, amount):
    """Adds a new transaction if the sender has enough funds."""
    if sender != "SYSTEM":
        if self.get_balance(sender) < amount:
            print(f"  [REJECTED] Insufficient funds for {sender}")
            return False

    self.pending_transactions.append({
        "from": sender,
        "to": receiver,
        "amount": amount
    })
    print(f"  [PENDING] Transaction recorded: {amount} BTC")
    return True

def mine_pending_transactions(self, miner_reward_address):
    """Packages transactions into a block and rewards the miner."""
    # Create the reward transaction
    reward_tx = {"from": "SYSTEM", "to": miner_reward_address, "amount": self.mining_reward}
    self.pending_transactions.append(reward_tx)

    # Create new block
    new_block = Block(
        index=len(self.chain),
        timestamp=int(time.time()),
        transactions=self.pending_transactions,
        previous_hash=self.get_latest_block().hash,
        difficulty=self.difficulty
    )

    self.chain.append(new_block)
    self.pending_transactions = []

def is_chain_valid(self):
    """Validates the integrity of the entire blockchain."""
    for i in range(1, len(self.chain)):
        curr = self.chain[i]
        prev = self.chain[i-1]

        if curr.hash != curr.calculate_hash():
            print(f"  [CORRUPT] Hash mismatch at index {i}")
            return False
        if curr.previous_hash != prev.hash:
            print(f"  [CORRUPT] Chain broken at index {i}")
            return False
    return True

==========================================================

EXECUTION DEMO

==========================================================

if name == "main":
# YOUR ADDRESS
MY_ADDR = "bc1q0myx3h7x646cut8h0yge8925gzsuwfz24cf5uv"
ALICE = "alice_wallet_test"

coin = Blockchain()

print(f"Initial balance of {MY_ADDR}: {coin.get_balance(MY_ADDR)}")

# 1. Distribute initial coins to you
print("\n--- Funding Account ---")
coin.add_transaction("SYSTEM", MY_ADDR, 50.0)
coin.mine_pending_transactions(MY_ADDR)

# 2. You send some coins to Alice
print("\n--- Sending 15.0 to Alice ---")
coin.add_transaction(MY_ADDR, ALICE, 15.0)
coin.mine_pending_transactions(MY_ADDR)

# 3. Final results
print("\n" + "="*50)
print(f"Final Balance of {MY_ADDR}: {coin.get_balance(MY_ADDR)} BTC")
print(f"Final Balance of Alice: {coin.get_balance(ALICE)} BTC")
print(f"Blockchain Integrity: {'STABLE' if coin.is_chain_valid() else 'COMPROMISED'}")
print("="*50)

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

Successfully merging this pull request may close these issues.

1 participant