4 from electrum import Interface
5 from electrum import bitcoin, Transaction
7 def get_transaction(interface, tx_hash, tx_height):
8 raw_tx = interface.synchronous_get([ ('blockchain.transaction.get',[tx_hash, tx_height]) ])[0]
9 tx = Transaction(raw_tx)
12 def get_history(interface, addr):
13 transactions = interface.synchronous_get([ ('blockchain.address.get_history',[addr]) ])[0]
14 transactions.sort(key=lambda x:x["height"])
15 return [(i["tx_hash"],i["height"]) for i in transactions]
17 def get_addr_balance(interface, address):
19 h = get_history(interface, address)
20 if h == ['*']: return 0, 0
22 received_coins = [] # list of coins received at address
26 for tx_hash, tx_height in h:
27 transactions[(tx_hash, tx_height)] = get_transaction(interface, tx_hash, tx_height)
29 for tx_hash, tx_height in h:
30 tx = transactions[(tx_hash, tx_height)]
32 update_tx_outputs(tx, prevout_values)
33 for i, (addr, value) in enumerate(tx.outputs):
35 key = tx_hash + ':%d'%i
36 received_coins.append(key)
38 for tx_hash, tx_height in h:
39 tx = transactions[(tx_hash, tx_height)]
43 for item in tx.inputs:
44 addr = item.get('address')
46 key = item['prevout_hash'] + ':%d'%item['prevout_n']
47 value = prevout_values.get(key)
48 if key in received_coins:
50 for i, (addr, value) in enumerate(tx.outputs):
51 key = tx_hash + ':%d'%i
60 def update_tx_outputs(tx, prevout_values):
61 for i, (addr, value) in enumerate(tx.outputs):
62 key = tx.hash() + ':%d' % i
63 prevout_values[key] = value
66 interface = Interface()
68 c, u = get_addr_balance(interface, address)
70 print("Final balance: confirmed: %d (%.8f BTC), unconfirmed: %d (%.8f BTC)" %
71 (c, c / 100000000., u, u / 100000000.))
73 if __name__ == "__main__":
77 print "usage: get_balance <bitcoin_address>"