4 from electrum import Interface
5 from electrum import bitcoin, Transaction, Network
9 def get_transaction(network, tx_hash, tx_height):
10 raw_tx = network.synchronous_get([(
11 'blockchain.transaction.get', [tx_hash, tx_height])])[0]
12 tx = Transaction(raw_tx)
16 def get_history(network, addr):
17 transactions = network.synchronous_get([(
18 'blockchain.address.get_history', [addr])])[0]
19 transactions.sort(key=lambda x: x["height"])
20 return [(i["tx_hash"], i["height"]) for i in transactions]
23 def get_addr_balance(network, address):
25 h = get_history(network, address)
29 received_coins = [] # list of coins received at address
33 for tx_hash, tx_height in h:
34 transactions[(tx_hash, tx_height)] = get_transaction(
35 network, tx_hash, tx_height)
37 for tx_hash, tx_height in h:
38 tx = transactions[(tx_hash, tx_height)]
41 update_tx_outputs(tx, prevout_values)
42 for i, (addr, value) in enumerate(tx.outputs):
44 key = tx_hash + ':%d' % i
45 received_coins.append(key)
47 for tx_hash, tx_height in h:
48 tx = transactions[(tx_hash, tx_height)]
53 for item in tx.inputs:
54 addr = item.get('address')
56 key = item['prevout_hash'] + ':%d' % item['prevout_n']
57 value = prevout_values.get(key)
58 if key in received_coins:
60 for i, (addr, value) in enumerate(tx.outputs):
61 key = tx_hash + ':%d' % i
71 def update_tx_outputs(tx, prevout_values):
72 for i, (addr, value) in enumerate(tx.outputs):
73 key = tx.hash() + ':%d' % i
74 prevout_values[key] = value
79 network.start(wait=True)
80 c, u = get_addr_balance(network, address)
82 print("Balance - confirmed: %d (%.8f BTC), unconfirmed: %d (%.8f BTC)" %
83 (c, c / 100000000., u, u / 100000000.))
85 if __name__ == "__main__":
89 print "usage: get_balance <bitcoin_address>"