eltneg

Untitled

Oct 13th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.66 KB | None | 0 0
  1. """
  2.    interacts with electrum daemon running on docker
  3. """
  4.  
  5. import json
  6. from requests.exceptions import ConnectionError
  7. from jsonrpcclient.clients.http_client import HTTPClient
  8.  
  9. client = HTTPClient('http://eltneg:[email protected]:7001')
  10.  
  11.  
  12. def get_address_list():
  13.     "Get list of wallet addresses"
  14.     try:
  15.         resp = client.request('listaddresses')
  16.     except ConnectionError as e:
  17.         resp = e
  18.     return resp
  19.  
  20.  
  21. def get_balance():
  22.     "Get balance of the whole wallet"
  23.     try:
  24.         resp = client.request('getbalance')
  25.     except ConnectionError as e:
  26.         resp = e
  27.     return resp
  28.  
  29.  
  30. def is_mine(address):
  31.     "Check if address is in hd wallet"
  32.     try:
  33.         resp = client.request('ismine', address)
  34.     except ConnectionError as e:
  35.         resp = e
  36.     return resp
  37.  
  38.  
  39. def get_unused_addr():
  40.     "Get an unused address, not a new address"
  41.     try:
  42.         resp = client.request('getunusedaddress')
  43.     except ConnectionError as e:
  44.         resp = e
  45.     return resp
  46.  
  47.  
  48. def get_address_balance(address):
  49.     "Get balance of any address"
  50.     try:
  51.         resp = client.request('getaddressbalance', address)
  52.     except ConnectionError as e:
  53.         resp = e
  54.     return resp
  55.  
  56.  
  57. def get_address_history(address):
  58.     try:
  59.         resp = client.request('getaddresshistory', address)
  60.     except ConnectionError as e:
  61.         resp = e
  62.     return resp
  63.  
  64.  
  65. def gettransaction(txn):
  66.     try:
  67.         resp = client.request('gettransaction', txn)
  68.     except ConnectionError as e:
  69.         resp = e
  70.     return resp
  71.  
  72.  
  73. def decode_tnx_hex(txn_hex):
  74.     try:
  75.         resp = client.request('deserialize', txn_hex)
  76.     except ConnectionError as e:
  77.         resp = e
  78.     return resp
  79.  
  80.  
  81. def txn_hash_greater_than_processed_height(address_histories, height=0):
  82.     """returns the list of transaction hashes greater than the processed height and their height"""
  83.     resp = []
  84.     if type(address_histories) == list:
  85.         for history in address_histories:
  86.             if history['height'] > height:
  87.                 resp.append(history)
  88.     else:
  89.         if address_histories['height'] > height:
  90.             resp.append(address_histories)
  91.     return resp
  92.  
  93.  
  94. def total_received(address, height=0, force_return=True):
  95.     """
  96.        Return the total received by an address above a given block height
  97.        >>  if height is suplied, total received after
  98.            the supplied height is returned
  99.        >>  if force return is False, the function will not bother to calculate
  100.            the total received if max height in address transaction history is
  101.            less than supplied height
  102.    """
  103.     # decode txn_hash
  104.     # loop through outputs
  105.     address_history = get_address_history(address)
  106.     if isinstance(address_history, ConnectionError):
  107.         heights = list(tx['height'] for tx in address_history)
  108.         if heights:
  109.             max_height = max(heights)
  110.         else:
  111.             return None  # Address has not received anything anything above previous height
  112.     elif type(address_history) == ConnectionError:
  113.         return None  # find a better way to handle connection error
  114.     else:
  115.         max_height = address_history['height']
  116.     if height and not force_return:
  117.         if max_height <= height:
  118.             return None
  119.     hash_list = txn_hash_greater_than_processed_height(
  120.         address_history, height=height)
  121.     received = 0
  122.     for txn in hash_list:
  123.         txn_hash = txn['tx_hash']
  124.         try:
  125.             hex_value_dict = gettransaction(txn_hash)
  126.             if isinstance(hex_value_dict, ConnectionError):
  127.                 return None
  128.             if hex_value_dict['complete']:
  129.                 hex_value = hex_value_dict['hex']
  130.                 txn_decoded = decode_tnx_hex(hex_value)
  131.                 if isinstance(txn_decoded, ConnectionError):
  132.                     return None
  133.         except Exception as e:
  134.             print(e)
  135.             return None
  136.         for _txn in txn_decoded['outputs']:
  137.             if _txn['address'] == address:
  138.                 received += txn['value']
  139.     return {'total_received': received / 10**8, 'height': max_height}
  140.  
  141.  
  142. def create_new_address():
  143.     "generate new address from pubKey using pybitcointools, no need query daemon"
  144.     pass
  145.  
  146.  
  147. def send(_to, amount):
  148.     try:
  149.         resp = client.request('payto', [_to, amount])
  150.     except ConnectionError as e:
  151.         resp = e
  152.     return resp
  153.  
  154.  
  155. def broadcast(hx):
  156.     try:
  157.         resp = client.request('broadcast', [hx])
  158.     except ConnectionError as e:
  159.         resp = e
  160.     return resp
  161.  
  162.  
  163. def main():
  164.     '''
  165.    """Tests"""
  166.    address = 'mpXbEmKZNdiu8LoRvmAjNhdubh6bRcS1Sc'
  167.    print(get_address_list())
  168.    assert type(get_address_list()) == list
  169.    assert type(get_balance()) == dict
  170.    get_address_balance('mpXbEmKZNdiu8LoRvmAjNhdubh6bRcS1Sc')
  171.    is_mine('mpXbEmKZNdiu8LoRvmAjNhdubh6bRcS1Sc')
  172.    is_mine('mujekfctnb7kLFPp5xY3hPEk5bR9nuqNuZ')
  173.    get_unused_addr()
  174.    histories = get_address_history(address)
  175.    print('type=========', type(histories))
  176.    txn = gettransaction('64d6867629b3db43e67337d334ebd4d599b9a72d087224339b2b521cfa9952ff')
  177.    txn_hex = txn['hex']
  178.    decode_tnx_hex(txn_hex)
  179.    print(txn)
  180.    try:
  181.        assert not isinstance(txn, ConnectionError)
  182.    except AssertionError:
  183.        print("Nework failure")
  184.    '''
  185.     #res = (send('mhtEbsosjxP1U2mWLTobG8Mt58mfrS3ZkU', 0.001))
  186.     # print(json.loads(res.text)['result'])
  187.     #hx = json.loads(res.text)['result']['hex']
  188.     #res = broadcast(hx)
  189.     # print(json.loads(res.text)['result'])
  190.     # print(res.text)
  191.     res = get_balance()
  192.     print(res.text)
  193.  
  194.  
  195. if __name__ == '__main__':
  196.     main()
Advertisement
Add Comment
Please, Sign In to add comment