Skip to content

Instantly share code, notes, and snippets.

@carchrae
Last active May 18, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carchrae/9a2a66ee8bc6f7025af69d33ea0399b8 to your computer and use it in GitHub Desktop.
Save carchrae/9a2a66ee8bc6f7025af69d33ea0399b8 to your computer and use it in GitHub Desktop.
sending with bitcoind like things
#!/bin/bash
set -v
# description on how this works
# requires the tool `bc` to be installed, and obviously, the coin cli
#
# https://stackoverflow.com/questions/38493893/heres-how-to-send-raw-transaction-btc-using-bitcoin-cli-command
# path to the command you are using
CLI="./bitcoin-cli"
# you may want to set this!
FEE=0.00001
# account or "label" as it is now known
ACCOUNT=$1
# where to send the monies
TO_ADDRESS=$2
# where to send any leftovers - miners get it otherwise
CHANGE_ADDRESS=$3
# you may need to tweak this, it presumes JSON of unspent has the fields listed inside the while loop
TXN="`$CLI listunspent 1 9999999 | grep -B3 -A2 "$ACCOUNT"`"
# total amount in account
TOTAL=0
while read -r TXID; do
read -r VOUT
read -r ADDRESS
read -r ACCOUNT
read -r SCRIPT_PUB_KEY
read -r AMOUNT
read -r line
# extract the tx, vout, and amount of the unspent txn
TXID=$(echo $TXID | cut -d'"' -f 4)
VOUT=$(echo $VOUT | cut -d':' -f 2)
VOUT=${VOUT::-1}
AMOUNT=$(echo $AMOUNT | cut -d':' -f 2)
AMOUNT=${AMOUNT::-1}
# add it to the total amount and inputs
TOTAL=$(echo $AMOUNT + $TOTAL | bc)
INPUTS="{\"txid\":\"$TXID\",\"vout\":$VOUT},$INPUTS"
done <<< "$TXN"
# remove trailing ,
INPUTS=${INPUTS::-1}
# transfer everything! if you don't do this, you'll need to enable the change in line below that calls createrawtransaction
AMOUNT=$TOTAL
#deduct the fee (otherwise miners won't mine it)
AMOUNT=$(echo $AMOUNT - $FEE | bc)
#calculate the change
CHANGE=$(echo $TOTAL - $FEE | bc)
# SEND USING CHANGE
# RAW_TX=$($CLI createrawtransaction "[$INPUTS]" "{\"$TO_ADDRESS\":$AMOUNT, \"$CHANGE_ADDRESS\":$CHANGE}")
# SEND WITHOUT CHANGE - ALL FUNDS SENT
RAW_TX=$($CLI createrawtransaction "[$INPUTS]" "{\"$TO_ADDRESS\":$AMOUNT}")
echo "CHANGE $CHANGE - if you didn't enable CHANGE_ADDRESS you lose this and it goes to the miners. BEWARE"
# this is what it looks like before signing
echo RAW_TX: $RAW_TX
# now sign the transaction - wallet must be unlocked for this to work
SIGN_TX=$($CLI signrawtransaction $RAW_TX | grep "hex" | cut -d'"' -f 4)
echo SIGN_TX: $SIGN_TX
# WHEN YOU ARE SURE YOU WHAT YOU ARE DOING, UNCOMMENT THESE TO EXECUTE THE TX
# TX=$($CLI sendrawtransaction $SIGN_TX)
# echo "sent $AMOUNT in $TX"
echo "read the instructions in the script before using. then delete this, and if you lose funds, it is not my fault!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment