DrMartiner
3/2/2018 - 9:28 PM

btc_send.py

from pywallet import wallet
from transactions import Transactions
from bitcoinrpc.authproxy import AuthServiceProxy

BITCOIND_JSON_RPC_URL = 'http://user:pass@host:8332'


def create_wallet(seed: str=None, network: str='BTC', children=0) -> dict:
    """ Step 1 """
    if not seed:
        seed = wallet.generate_mnemonic()
    return wallet.create_wallet(network=network, seed=seed, children=children)


def create_sign_tx(address_from: str, to: list, wif: str) -> str:
    """
    Step 2 - 1
    to: ('18...6x', 10000) or [('18C...96x', 10000), ('17...105', 20000)]
    """
    transactions = Transactions(
        testnet=False,
        service='daemon',
        username='user',
        password='pass',
        host='host',
        port='8332'
    )
    tx = transactions.create(address_from, to)
    return transactions.sign(tx, wif)


def push_signed_tx(signed_tx_hex: str) -> str:
    """ Step 2 - 2 """
    rpc_connection = AuthServiceProxy(BITCOIND_JSON_RPC_URL)
    return rpc_connection.batch_([['sendrawtransaction', signed_tx_hex]])[0]


def get_balance(target_address: str) -> float:
    """ Step 3 """
    rpc_connection = AuthServiceProxy(BITCOIND_JSON_RPC_URL)
    balances = rpc_connection.batch_([['getreceivedbyaddress', target_address]])
    return balances[0]