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
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
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
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](https://bitcointalk.org/Smileys/default/huh.gif)