4 from electrum import Interface
5 from electrum import bitcoin, Transaction
8 def get_transaction(interface, tx_hash, tx_height):
9 raw_tx = interface.synchronous_get([(
10 'blockchain.transaction.get', [tx_hash, tx_height])])[0]
11 tx = Transaction(raw_tx)
15 def get_history(interface, addr):
16 transactions = interface.synchronous_get([(
17 'blockchain.address.get_history', [addr])])[0]
18 transactions.sort(key=lambda x: x["height"])
19 return [(i["tx_hash"], i["height"]) for i in transactions]
22 def get_addr_balance(interface, address):
24 h = get_history(interface, address)
28 received_coins = [] # list of coins received at address
32 for tx_hash, tx_height in h:
33 transactions[(tx_hash, tx_height)] = get_transaction(
34 interface, tx_hash, tx_height)
36 for tx_hash, tx_height in h:
37 tx = transactions[(tx_hash, tx_height)]
40 update_tx_outputs(tx, prevout_values)
41 for i, (addr, value) in enumerate(tx.outputs):
43 key = tx_hash + ':%d' % i
44 received_coins.append(key)
46 for tx_hash, tx_height in h:
47 tx = transactions[(tx_hash, tx_height)]
52 for item in tx.inputs:
53 addr = item.get('address')
55 key = item['prevout_hash'] + ':%d' % item['prevout_n']
56 value = prevout_values.get(key)
57 if key in received_coins:
59 for i, (addr, value) in enumerate(tx.outputs):
60 key = tx_hash + ':%d' % i
70 def update_tx_outputs(tx, prevout_values):
71 for i, (addr, value) in enumerate(tx.outputs):
72 key = tx.hash() + ':%d' % i
73 prevout_values[key] = value
77 interface = Interface()
79 c, u = get_addr_balance(interface, address)
81 print("Balance - confirmed: %d (%.8f BTC), unconfirmed: %d (%.8f BTC)" %
82 (c, c / 100000000., u, u / 100000000.))
84 if __name__ == "__main__":
88 print "usage: get_balance <bitcoin_address>"