Comments (1)
I figured it out.... for anyone trying to figure this out also will add what I used below so the search engines pick it up.
# export BITCOIN_NODE_HOST='your_node_ip'
# export BITCOIN_NODE_PORT='your_node_port'
# export BITCOIN_RPC_USERNAME='your_rpc_username'
# export BITCOIN_RPC_PASSWORD='your_rpc_password'
# export MY_BTC_PRIVATE_KEY='your_private_key_here'
# add the above first in your terminal or add to .bashrc
import os
import sys
import json
import requests
from requests.auth import HTTPBasicAuth
from bitcoinlib.wallets import Wallet
from bitcoinlib.transactions import Output
from bitcoinlib.encoding import varstr
# Configuration (use environment variables for sensitive data)
private_key = os.getenv('MY_BTC_PRIVATE_KEY')
wallet_name = 'YOUR_WALLETS_NAME'
sender_address = 'YOUR_BTC_ADDRESS'
recipient_address = 'BTC_ADDRESS_YOUR_SENDING_TO'
amount_to_send_satoshis = int(0.0001 * 100000000)
fee_satoshis = int(0.00014 * 100000000)
message = 'YOUR_MESSAGE'
# RPC configuration
rpc_user = os.getenv('BITCOIN_RPC_USERNAME')
rpc_password = os.getenv('BITCOIN_RPC_PASSWORD')
rpc_url = f"http://{os.getenv('BITCOIN_NODE_HOST')}:{os.getenv('BITCOIN_NODE_PORT')}"
# Load the existing wallet and update UTXOs
try:
wallet = Wallet(wallet_name)
wallet.utxos_update()
utxos = wallet.utxos()
if not utxos:
print("No unspent transaction outputs available.")
sys.exit(1)
except Exception as e:
print(f"Error loading wallet or updating UTXOs: {e}")
sys.exit(1)
# Prepare inputs and outputs for the transaction
try:
inputs = [{'txid': utxo['txid'], 'output_n': utxo['output_n'], 'value': utxo['value']} for utxo in utxos]
print("Inputs prepared for the transaction:", inputs)
standard_output = Output(amount_to_send_satoshis, address=recipient_address)
lock_script = b'j' + varstr(message.encode('utf-8'))
op_return_output = Output(0, lock_script=lock_script)
outputs = [standard_output, op_return_output]
print("Outputs prepared for the transaction:", outputs)
except Exception as e:
print(f"Error preparing inputs or outputs: {e}")
sys.exit(1)
# Create and sign the transaction
try:
tx = wallet.send(outputs, fee=fee_satoshis)
print("\nTransaction created.")
print(f"TXID: {tx.txid}\n")
raw_tx_hex = tx.raw_hex()
print(f"Raw Transaction Hex: {raw_tx_hex}")
# Broadcast the transaction via RPC
headers = {'content-type': 'application/json'}
payload = {
"method": "sendrawtransaction",
"params": [raw_tx_hex],
"jsonrpc": "2.0",
"id": 0,
}
response = requests.post(rpc_url, json=payload, headers=headers, auth=HTTPBasicAuth(rpc_user, rpc_password))
response_json = response.json()
if 'error' in response_json and response_json['error']:
print("Error broadcasting transaction:", response_json['error'])
else:
txid = response_json['result']
print("Transaction broadcasted successfully. TXID:", txid)
except Exception as e:
print(f"\nAn error occurred during transaction creation or broadcast: {e}")
from bitcoinlib.
Related Issues (20)
- how to get taproot address from singlekey? HOT 5
- No connection with local bitcoin node
- BIP39 passphrases get mangled if the string contains only hexadecimal characters HOT 2
- multiple issues when installing followed installation instructions step by step exactly as it said here is the issues that followed HOT 3
- wallet.transactions_update() It's not working as it should. HOT 7
- Use Bitcoin regtest HOT 4
- Errors decoding block HOT 4
- Error on number of transactions retrieved on getblock(i) HOT 7
- I want to generate a taproot wallet, how do I do it? HOT 2
- how to send btc to another?
- BRC20 HOT 1
- Using BIP38 encrypted Private Key throw error HOT 2
- error when parse a raw transation
- Error parsing bitcoin testnet transaction HOT 1
- Asynchronous Version? HOT 1
- Error in transaction parsing: Incorrect pubkeyhash length HOT 8
- Send BTC
- getting error: "no such column: transaction_inputs.witnesses" HOT 5
- Error creating wallet from wif HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from bitcoinlib.