496931b3808e07905b9aeb41b1af66f475a6077d
[electrum-nvc.git] / scripts / get_balance
1 #!/usr/bin/env python
2
3 import sys
4 from electrum import Interface
5 from electrum import bitcoin, Transaction
6
7
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)
12     return tx
13
14
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]
20
21
22 def get_addr_balance(interface, address):
23     prevout_values = {}
24     h = get_history(interface, address)
25     if h == ['*']:
26         return 0, 0
27     c = u = 0
28     received_coins = []   # list of coins received at address
29     transactions = {}
30
31     # fetch transactions
32     for tx_hash, tx_height in h:
33         transactions[(tx_hash, tx_height)] = get_transaction(
34             interface, tx_hash, tx_height)
35
36     for tx_hash, tx_height in h:
37         tx = transactions[(tx_hash, tx_height)]
38         if not tx:
39             continue
40         update_tx_outputs(tx, prevout_values)
41         for i, (addr, value) in enumerate(tx.outputs):
42             if addr == address:
43                 key = tx_hash + ':%d' % i
44                 received_coins.append(key)
45
46     for tx_hash, tx_height in h:
47         tx = transactions[(tx_hash, tx_height)]
48         if not tx:
49             continue
50         v = 0
51
52         for item in tx.inputs:
53             addr = item.get('address')
54             if addr == address:
55                 key = item['prevout_hash'] + ':%d' % item['prevout_n']
56                 value = prevout_values.get(key)
57                 if key in received_coins:
58                     v -= value
59         for i, (addr, value) in enumerate(tx.outputs):
60             key = tx_hash + ':%d' % i
61             if addr == address:
62                 v += value
63         if tx_height:
64             c += v
65         else:
66             u += v
67     return c, u
68
69
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
74
75
76 def main(address):
77     interface = Interface()
78     interface.start()
79     c, u = get_addr_balance(interface, address)
80
81     print("Balance - confirmed: %d (%.8f BTC), unconfirmed: %d (%.8f BTC)" %
82           (c, c / 100000000., u, u / 100000000.))
83
84 if __name__ == "__main__":
85     try:
86         address = sys.argv[1]
87     except:
88         print "usage: get_balance <bitcoin_address>"
89         sys.exit(1)
90     main(address)