Bitcoin Forum
June 24, 2024, 07:05:04 PM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: constructs a correct raw Coinbase transaction format suitable for a miner  (Read 47 times)
detmm244 (OP)
Newbie
*
Offline Offline

Activity: 3
Merit: 1


View Profile
June 16, 2024, 07:01:50 AM
Last edit: June 16, 2024, 08:02:21 AM by detmm244
 #1

How to miner make own  Coinbase transaction , how to set current block_reward
My code is the correct format or not ? What I with my code ?  Anyone fix my code?

run this code
Code:
import hashlib
import base58

# Miner's address (example address in base58 format)
miner_address_base58 = "1ASzaPvnM5BM2HE5VF1VCgkwX6yUWvJTvW"

# Decode the base58 address to get the raw bytes (RIPEMD-160 hash)
miner_address_raw = base58.b58decode(miner_address_base58)

# Current block reward (3.12500000 BTC in Satoshis)
block_reward = int(3.125 * 10**8)  # BTC to Satoshis conversion

# Constructing the coinbase transaction
coinbase_transaction = {
    "version": 1,
    "inputs": [
        {
            "previous_output": {
                "hash": "0" * 64,  # Null hash for coinbase transaction
                "index": 4294967295  # Maximum value for coinbase input
            },
            "script": bytes.fromhex(f"03ffffffff{len(miner_address_raw):02x}{miner_address_raw.hex()}"),
            "sequence": 0
        }
    ],
    "outputs": [
        {
            "value": block_reward,
            "script": b""
        }
    ],
    "locktime": 0
}

# Serialize the transaction
def serialize_transaction(transaction):
    tx_hex = ""
    tx_hex += transaction["version"].to_bytes(4, byteorder="little", signed=False).hex()
    tx_hex += len(transaction["inputs"]).to_bytes(1, byteorder="little", signed=False).hex()

    for inp in transaction["inputs"]:
        tx_hex += inp["previous_output"]["hash"]
        tx_hex += inp["previous_output"]["index"].to_bytes(4, byteorder="little", signed=False).hex()
        script_len = len(inp["script"])
        tx_hex += script_len.to_bytes(1, byteorder="little", signed=False).hex()
        tx_hex += inp["script"].hex()
        tx_hex += inp["sequence"].to_bytes(4, byteorder="little", signed=False).hex()

    tx_hex += len(transaction["outputs"]).to_bytes(1, byteorder="little", signed=False).hex()

    for out in transaction["outputs"]:
        tx_hex += out["value"].to_bytes(8, byteorder="little", signed=False).hex()
        script_len = len(out["script"])
        tx_hex += script_len.to_bytes(1, byteorder="little", signed=False).hex()
        tx_hex += out["script"].hex()

    tx_hex += transaction["locktime"].to_bytes(4, byteorder="little", signed=False).hex()

    return tx_hex.upper()  # Return as uppercase hex string for consistency

serialized_transaction = serialize_transaction(coinbase_transaction)

# Print the raw serialized transaction
print("Raw Coinbase transaction:", serialized_transaction)

# Double SHA-256 hash of the serialized transaction
hash_first = hashlib.sha256(bytes.fromhex(serialized_transaction)).digest()
transaction_hash = hashlib.sha256(hash_first).hexdigest()

# Print the resulting transaction hash
print("Coinbase transaction hash:", transaction_hash)


python coinbase.py
#output

Raw Coinbase transaction: 01000000010000000000000000000000000000000000000000000000000000000000000000FFFFF FFF1F03FFFFFFFF190067A397CAEFF97B4CD72E20F5445D0CAF108B01BC563A4B9F000000000120 5FA012000000000000000000
Coinbase transaction hash: c8baebf962d63c5853e166a845321be4faaf5080a19020ca9effa93910ce6282


Code:
import requests

def get_current_block_reward():
    url = 'https://blockchain.info/q/bcperblock'
    response = requests.get(url)
    if response.status_code == 200:
        block_reward = float(response.text)
        return block_reward
    else:
        print(f"Failed to fetch block reward. Status code: {response.status_code}")
        return None

# Example usage
block_reward = get_current_block_reward()
if block_reward:
    print(f"Current block reward for Bitcoin: {block_reward} BTC")

#output
Current block reward for Bitcoin: 3.125 BTC


EDIT:
2nd code
Code:
import hashlib
import base58

def int2lehex(value, width):
    """
    Convert an unsigned integer to a little endian ASCII hex string.

    Args:
        value (int): value
        width (int): byte width

    Returns:
        string: ASCII hex string
    """
    return value.to_bytes(width, byteorder='little').hex()

def bitcoinaddress2hash160(addr):
    """
    Convert a Base58 Bitcoin address to its Hash-160 ASCII hex string.

    Args:
        addr (string): Base58 Bitcoin address

    Returns:
        string: Hash-160 ASCII hex string
    """
    table = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
    hash160 = 0
    addr = addr[::-1]
    for i, c in enumerate(addr):
        hash160 += (58 ** i) * table.find(c)
    hash160 = "{:050x}".format(hash160)
    return hash160[2:50 - 8]

def tx_encode_coinbase_height(height):
    """
    Encode the coinbase height, as per BIP 34.

    Args:
        height (int): height of the mined block

    Returns:
        string: encoded height as an ASCII hex string
    """
    width = (height.bit_length() + 7) // 8
    return bytes([width]).hex() + int2lehex(height, width)

def tx_make_coinbase(coinbase_script, address, value, height):
    """
    Create a coinbase transaction.

    Args:
        coinbase_script (string): arbitrary script as an ASCII hex string
        address (string): Base58 Bitcoin address
        value (int): coinbase value
        height (int): mined block height

    Returns:
        string: coinbase transaction as an ASCII hex string
    """
    coinbase_script = tx_encode_coinbase_height(height) + coinbase_script
    pubkey_script = "76a914" + bitcoinaddress2hash160(address) + "88ac"

    tx = ""
    # version
    tx += "01000000"
    # in-counter
    tx += "01"
    # input[0] prev hash
    tx += "0" * 64
    # input[0] prev seqnum
    tx += "ffffffff"
    # input[0] script len
    tx += int2lehex(len(coinbase_script) // 2, 1)
    # input[0] script
    tx += coinbase_script
    # input[0] seqnum
    tx += "ffffffff"
    # out-counter
    tx += "01"
    # output[0] value
    tx += int2lehex(value, 8)
    # output[0] script len
    tx += int2lehex(len(pubkey_script) // 2, 1)
    # output[0] script
    tx += pubkey_script
    # lock-time
    tx += "00000000"

    return tx

def tx_compute_hash(tx):
    """
    Compute the SHA256 double hash of a transaction.

    Args:
        tx (string): transaction data as an ASCII hex string

    Returns:
        string: transaction hash as an ASCII hex string
    """
    return hashlib.sha256(hashlib.sha256(bytes.fromhex(tx)).digest()).digest()[::-1].hex()

# Example usage:
miner_address_base58 = "1ASzaPvnM5BM2HE5VF1VCgkwX6yUWvJTvW"
block_reward = int(3.125 * 10**8)  # 3.125 BTC in Satoshis
height = 123456  # Example block height

coinbase_script = "test coinbase script"  # Example coinbase script
coinbase_tx = tx_make_coinbase(coinbase_script.encode().hex(), miner_address_base58, block_reward, height)
coinbase_txid = tx_compute_hash(coinbase_tx)

print("Raw Coinbase Transaction:")
print(coinbase_tx)
print("Coinbase Transaction ID (txid):")
print(coinbase_txid)


Raw Coinbase Transaction:
01000000010000000000000000000000000000000000000000000000000000000000000000fffff fff180340e2017465737420636f696e6261736520736372697074ffffffff01205fa01200000000 1976a91467a397caeff97b4cd72e20f5445d0caf108b01bc88ac00000000
Coinbase Transaction ID (txid):
59ee3ea8f695968beeee8f1504dd59235d7948c2ec03eb60b2754c1bcb1634dd


witch code right one Huh
pooya87
Legendary
*
Offline Offline

Activity: 3486
Merit: 10666



View Profile
June 16, 2024, 02:35:21 PM
Merited by ABCbits (2)
 #2

One problem I see is that your input script should be pushing the block height to the stack and anything else is extra and ignored. You are pushing the address to the stack here which is not needed.

Another problem is in your output. Your only output is missing the script. This is where you should use your address (the corresponding script).
Additionally since nowadays blocks contain transactions with witness, your Coinbase tx must have at least one OP_RETURN output containing the witness merkle root hash. Read more here: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#commitment-structure

Another thing that is not a problem if you are just testing stuff is that you shouldn't hardcode block reward like "3.125 * 10**8". Instead you should compute it based on block height and sum of fees of the txs in the block.

.
.BLACKJACK ♠ FUN.
█████████
██████████████
████████████
█████████████████
████████████████▄▄
░█████████████▀░▀▀
██████████████████
░██████████████
████████████████
░██████████████
████████████
███████████████░██
██████████
CRYPTO CASINO &
SPORTS BETTING
▄▄███████▄▄
▄███████████████▄
███████████████████
█████████████████████
███████████████████████
█████████████████████████
█████████████████████████
█████████████████████████
███████████████████████
█████████████████████
███████████████████
▀███████████████▀
█████████
.
detmm244 (OP)
Newbie
*
Offline Offline

Activity: 3
Merit: 1


View Profile
June 16, 2024, 05:04:41 PM
 #3

One problem I see is that your input script should be pushing the block height to the stack and anything else is extra and ignored. You are pushing the address to the stack here which is not needed.

Another problem is in your output. Your only output is missing the script. This is where you should use your address (the corresponding script).
Additionally since nowadays blocks contain transactions with witness, your Coinbase tx must have at least one OP_RETURN output containing the witness merkle root hash. Read more here: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#commitment-structure

Another thing that is not a problem if you are just testing stuff is that you shouldn't hardcode block reward like "3.125 * 10**8". Instead you should compute it based on block height and sum of fees of the txs in the block.

https://mempool.space/block/0000000000000000000201fa665f016252f14dcd84877ca244a44f197830a910
only one txid to solve block 4aeda5a0f2159f448f7c23b75c62233320cbe9895af0d6f43139baea97c991b2

I know how to mine to solve blocks, but before, how to make my own txid like this 4aeda5a0f2159f448f7c23b75c62233320cbe9895af0d6f43139baea97c991b2

my_addr         ='1ASzaPvnM5BM2HE5VF1VCgkwX6yUWvJTvW'
block_reward = ' '              # how to get correct block reward value
block_height  = 848117  # example
Any_additional_imperfection inside raw txid ??


Can you make python code for the current structure for the coinbase transaction miner? using
I speak a little bit of English.
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!