-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_build_and_send.py
More file actions
49 lines (40 loc) · 1.96 KB
/
Copy path08_build_and_send.py
File metadata and controls
49 lines (40 loc) · 1.96 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
# SPDX-License-Identifier: MIT
"""08 - Build, sign, and send a transaction using your node's wallet.
The wallet does the hard parts for you: it selects UTXOs, adds a change output, sets a
fee, signs, and broadcasts. This is the simplest correct way to send. For offline,
library-based building (no node), see the JavaScript recipe 08 (bitcoinjs-lib).
Fund your node's wallet first from cypherfaucet.com.
RPC_USER=... RPC_PASS=... python 08_build_and_send.py <address> <amount-in-coins>
The amount is in whole coins (BTC/LTC), matching sendtoaddress. The JavaScript recipe
08 takes satoshis instead.
"""
import sys
import requests
from config import RPC_URL, RPC_USER, RPC_PASS
def rpc(method, params=None):
payload = {"jsonrpc": "1.0", "id": "ex", "method": method, "params": params or []}
try:
r = requests.post(RPC_URL, json=payload, auth=(RPC_USER, RPC_PASS), timeout=30)
except requests.exceptions.RequestException:
raise SystemExit(f"could not reach your node at {RPC_URL}. is it running with RPC "
"enabled? see testnethub.com/run-node")
if r.status_code == 401:
raise SystemExit("the node rejected the login: set RPC_USER / RPC_PASS (see testnethub.com/rpc-safety)")
body = r.json()
if body.get("error"):
raise SystemExit(f"the node rejected the call: {body['error']['message']}")
return body["result"]
if len(sys.argv) < 3:
sys.exit("usage: python 08_build_and_send.py <address> <amount-in-coins>")
address = sys.argv[1]
try:
amount = float(sys.argv[2])
except ValueError:
sys.exit("amount must be a number in coins, e.g. 0.001")
# One call that builds + funds + signs + broadcasts. If you want to see each step,
# the explicit path is: createrawtransaction -> fundrawtransaction ->
# signrawtransactionwithwallet -> sendrawtransaction.
txid = rpc("sendtoaddress", [address, amount])
print(f"sent {amount} to {address}")
print(f"txid: {txid}")
print(f"watch it: python 06_watch.py {txid}")