blockstream-electrs/tools/client.py

64 lines
1.8 KiB
Python
Raw Normal View History

2018-04-25 19:44:36 +00:00
import hashlib
2018-04-30 11:37:23 +00:00
import json
2018-04-25 19:44:36 +00:00
import sys
from logbook import Logger, StreamHandler
from pycoin.coins.bitcoin.networks import BitcoinMainnet
import pycoin.ui.key_from_text
import pycoin.key
2018-04-30 11:37:23 +00:00
import socket
2018-04-25 19:44:36 +00:00
script_for_address = BitcoinMainnet.ui.script_for_address
log = Logger(__name__)
2018-05-02 10:42:13 +00:00
class Connection:
def __init__(self, addr):
self.s = socket.create_connection(addr)
self.f = self.s.makefile('r')
self.id = 0
def call(self, method, *args):
req = {
'id': self.id,
'method': method,
'params': list(args),
}
msg = json.dumps(req) + '\n'
self.s.sendall(msg.encode('ascii'))
return json.loads(self.f.readline())
2018-04-25 19:44:36 +00:00
2018-05-02 10:42:13 +00:00
def main():
conn = Connection(('localhost', 50001))
2018-04-25 19:44:36 +00:00
xpub, = sys.argv[1:]
total = 0
k = pycoin.ui.key_from_text.key_from_text(xpub)
for change in (0, 1):
empty = 0
for n in range(100):
address = k.subkey(change).subkey(n).address()
script = script_for_address(address)
script_hash = hashlib.sha256(script).digest()
2018-05-02 10:42:13 +00:00
reply = conn.call('blockchain.scripthash.get_balance',
script_hash[::-1].hex())
res = reply['result']
confirmed = res['confirmed'] / 1e8
total += confirmed
if confirmed:
2018-04-25 19:44:36 +00:00
log.info('{}/{} => {} has {:11.8f} BTC',
2018-05-02 10:42:13 +00:00
change, n, address, confirmed)
2018-04-25 19:44:36 +00:00
empty = 0
else:
empty += 1
if empty >= 10:
break
2018-05-02 10:42:13 +00:00
log.info('{}', conn.call('blockchain.scripthash.get_history', script_hash[::-1].hex()))
2018-04-25 19:44:36 +00:00
log.info('total balance: {} BTC', total)
if __name__ == '__main__':
with StreamHandler(sys.stderr, level='INFO').applicationbound():
main()