-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtc-transaction-builder.py
More file actions
70 lines (60 loc) · 2.19 KB
/
btc-transaction-builder.py
File metadata and controls
70 lines (60 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import requests
from bit import Key
from bit.network import NetworkAPI
def get_user_input():
print("🟢 Bitcoin Transaction Builder")
wif = input("Enter your private key (WIF format): ").strip()
recipient = input("Enter recipient address: ").strip()
amount = float(input("Enter amount to send (BTC): ").strip())
fee = float(input("Enter transaction fee (BTC): ").strip())
return wif, recipient, amount, fee
def fetch_utxos(address):
print("🔍 Fetching UTXOs...")
url = f'https://blockstream.info/api/address/{address}/utxo'
response = requests.get(url)
if response.status_code != 200:
raise Exception("Failed to fetch UTXOs from Blockstream API.")
return response.json()
def build_transaction(wif, recipient, amount, fee):
key = Key(wif)
sender_address = key.address
utxos = fetch_utxos(sender_address)
inputs = []
total_input = 0
for utxo in utxos:
inputs.append({
'txid': utxo['txid'],
'vout': utxo['vout'],
'value': utxo['value'] / 1e8 # Convert from satoshis to BTC
})
total_input += utxo['value'] / 1e8
if total_input >= amount + fee:
break
if total_input < amount + fee:
raise Exception("Not enough balance to cover amount + fee.")
outputs = [
(recipient, amount, 'btc'),
]
change = round(total_input - amount - fee, 8)
if change > 0:
outputs.append((sender_address, change, 'btc'))
print("✍️ Signing and creating transaction...")
tx_hex = key.create_transaction(
outputs=outputs,
unspents=key.get_unspents(), # Optional: Use our UTXOs
fee=fee,
leftover=sender_address,
)
return tx_hex
def main():
try:
wif, recipient, amount, fee = get_user_input()
tx = build_transaction(wif, recipient, amount, fee)
print("\n✅ Transaction Created!")
print("Raw TX (hex):")
print(tx)
print("\n💡 You can broadcast this via: https://blockstream.info/pushtx")
except Exception as e:
print(f"❌ Error: {str(e)}")
if __name__ == "__main__":
main()