Esempio n. 1
0
    def __init__(self,
                 symbol,
                 rpc_address,
                 rpc_user,
                 rpc_pass,
                 service_id=1,
                 respond_id=None):

        super().__init__(symbol, rpc_address, rpc_user, rpc_pass)

        self.proxy = Proxy(
            'http://%s:%s@%s' %
            (rpc_user, rpc_pass, rpc_address))  # Not thread safe ...
        self.prox2 = Proxy(
            'http://%s:%s@%s' %
            (rpc_user, rpc_pass, rpc_address))  # ... hence needing 2

        self.serviceId = service_id
        self.respondId = respond_id
        self.serviceKey = ''
        self.respondKey = ''

        self.routingTag = ''

        self.ecresolve_tags = []

        # ECC feature flags (based on version number)

        self.fPacketSig = False

        # Caching prior unlock state for post transaction reversion

        self.cached_prior_walletinfo = {}
Esempio n. 2
0
    def start(self, extra_args=None, timewait=None):
        if self.__proxy is not None:
            raise RuntimeError('Already started')

        rpcuser = '******'
        rpcpassword = '******'

        args = [
            self.__zcashd,
            '-datadir=%s' % self.__datadir,
            '-wallet=%s' % self.__wallet,
            '-rpcuser=%s' % rpcuser,
            '-rpcpassword=%s' % rpcpassword,
            '-showmetrics=0',
            '-experimentalfeatures',
            '-zmergetoaddress',
        ]
        if self.__testnet:
            args.append('-testnet=1')
        if extra_args is not None:
            args.extend(extra_args)

        self.__process = subprocess.Popen(args)

        cli_args = [
            self.__zcash_cli,
            '-datadir=%s' % self.__datadir,
            '-rpcuser=%s' % rpcuser,
            '-rpcpassword=%s' % rpcpassword,
            '-rpcwait',
        ]
        if self.__testnet:
            cli_args.append('-testnet=1')
        cli_args.append('getblockcount')

        devnull = open('/dev/null', 'w+', encoding='utf8')
        if os.getenv('PYTHON_DEBUG', ''):
            print(
                'start_node: zcashd started, calling zcash-cli -rpcwait getblockcount'
            )
        subprocess.check_call(cli_args, stdout=devnull)
        if os.getenv('PYTHON_DEBUG', ''):
            print(
                'start_node: calling zcash-cli -rpcwait getblockcount returned'
            )
        devnull.close()

        rpcuserpass = '******' % (rpcuser, rpcpassword)
        rpchost = '127.0.0.1'
        rpcport = 18232 if self.__testnet else 8232

        url = 'http://%s@%s:%d' % (rpcuserpass, rpchost, rpcport)
        if timewait is not None:
            self.__proxy = Proxy(url, timeout=timewait)
        else:
            self.__proxy = Proxy(url)
Esempio n. 3
0
def rpc_connect(rpc_user, rpc_password, port):
    try:
        rpc_connection = Proxy("http://%s:%[email protected]:%d" %
                               (rpc_user, rpc_password, port))
    except Exception as e:
        raise Exception(e)
    return rpc_connection
Esempio n. 4
0
 def def_credentials(chain):
     rpcport = ''
     operating_system = platform.system()
     if operating_system == 'Darwin':
         data_dir = os.path.join(os.environ['HOME'], 'Library',
                                 'Application Support', 'Komodo')
     elif operating_system == 'Linux':
         data_dir = os.path.join(os.environ['HOME'], '.komodo')
     elif operating_system == 'Windows':
         data_dir = os.path.join(os.environ['APPDATA'], 'komodo')
     if chain == 'KMD':
         coin_config_file = os.path.join(data_dir, 'komodo.conf')
     else:
         coin_config_file = os.path.join(data_dir, chain, chain + '.conf')
     with open(coin_config_file, 'r') as f:
         for line in f:
             l = line.rstrip()
             if re.search('rpcuser', l):
                 rpcuser = l.replace('rpcuser='******'')
             elif re.search('rpcpassword', l):
                 rpcpassword = l.replace('rpcpassword='******'')
             elif re.search('rpcport', l):
                 rpcport = l.replace('rpcport=', '')
     if len(rpcport) == 0:
         if chain == 'KMD':
             rpcport = 7771
         else:
             print("rpcport not in conf file, exiting")
             print("check " + coin_config_file)
             exit(1)
     return Proxy(
         conf_file=coin_config_file
     ), rpcport, "http://" + rpcuser + ":" + rpcpassword + "@127.0.0.1:" + str(
         rpcport)
Esempio n. 5
0
def def_credentials(chain):
    rpcport = '';
    operating_system = platform.system()
    if operating_system == 'Darwin':
        ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo'
    elif operating_system == 'Linux':
        ac_dir = os.environ['HOME'] + '/.komodo'
    elif operating_system == 'Windows':
        ac_dir = '%s/komodo/' % os.environ['APPDATA']
    if chain == 'KMD':
        coin_config_file = str(ac_dir + '/komodo.conf')
    else:
        coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf')
    with open(coin_config_file, 'r') as f:
        for line in f:
            l = line.rstrip()
            if re.search('rpcuser', l):
                rpcuser = l.replace('rpcuser='******'')
            elif re.search('rpcpassword', l):
                rpcpassword = l.replace('rpcpassword='******'')
            elif re.search('rpcport', l):
                rpcport = l.replace('rpcport=', '')
    if len(rpcport) == 0:
        if chain == 'KMD':
            rpcport = 7771
        else:
            print("rpcport not in conf file, exiting")
            print("check " + coin_config_file)
            exit(1)
    return (Proxy("http://%s:%[email protected]:%d" % (rpcuser, rpcpassword, int(rpcport))))
Esempio n. 6
0
def def_credentials(chain):
    rpcport = ''
    ac_dir = def_data_dir()
    if chain == 'KMD':
        coin_config_file = str(ac_dir + '/komodo.conf')
    else:
        coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf')
    with open(coin_config_file, 'r') as f:
        for line in f:
            l = line.rstrip()
            if re.search('rpcuser', l):
                rpcuser = l.replace('rpcuser='******'')
            elif re.search('rpcpassword', l):
                rpcpassword = l.replace('rpcpassword='******'')
            elif re.search('rpcport', l):
                rpcport = l.replace('rpcport=', '')
    if len(rpcport) == 0:
        if chain == 'KMD':
            rpcport = 7771
        else:
            print("rpcport not in conf file, exiting")
            print("check " + coin_config_file)
            exit(1)

    return (Proxy("http://%s:%[email protected]:%d" %
                  (rpcuser, rpcpassword, int(rpcport))))
Esempio n. 7
0
def rpc_connect(rpc_user, rpc_password, server, port):
    try:
        rpc_connection = Proxy("http://%s:%s@%s:%d"%(rpc_user, rpc_password, server, port))
    except Exception as e:
        print(e)
        raise Exception("Connection error! Probably no daemon on selected port.")
    return rpc_connection
Esempio n. 8
0
def set_rpc_proxy(ticker):
    rpcport = ''
    ac_dir = ''
    operating_system = platform.system()
    if operating_system == 'Darwin':
        ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo'
    elif operating_system == 'Linux':
        ac_dir = os.environ['HOME'] + '/.komodo'
    elif operating_system == 'Win64' or operating_system == 'Windows':
        ac_dir = '%s/komodo/' % os.environ['APPDATA']
    if ticker == 'KMD':
        coin_config_file = str(ac_dir + '/komodo.conf')
    else:
        coin_config_file = str(ac_dir + '/' + ticker + '/' + ticker + '.conf')
    with open(coin_config_file, 'r') as f:
        for line in f:
            l = line.rstrip()
            if re.search('rpcuser', l):
                rpcuser = l.replace('rpcuser='******'')
            elif re.search('rpcpassword', l):
                rpcpassword = l.replace('rpcpassword='******'')
            elif re.search('rpcport', l):
                rpcport = l.replace('rpcport=', '')
    if len(rpcport) == 0:
        if ticker == 'KMD':
            rpcport = 7771
        else:
            return

    return Proxy("http://%s:%[email protected]:%d" %
                 (rpcuser, rpcpassword, int(rpcport)))
Esempio n. 9
0
 def __init__(self):
     self.logger = Logger()
     self.mongo = mongo.Mongo(self.logger)
     self.rpc_connection = Proxy(
         f"http://{os.environ['CRYPTO_USER']}:{os.environ['CRYPTO_PASS']}@"
         f"127.0.0.1:{os.environ['CRYPTO_PORT']}")
     self.tx_cache = TxCache()
Esempio n. 10
0
def rpc_connect(rpc_user, rpc_password, port):
    try:
        rpc_connection = Proxy("http://%s:%[email protected]:%d" %
                               (rpc_user, rpc_password, port))
    except Exception:
        raise Exception(
            "Connection error! Probably no daemon on selected port.")
    return rpc_connection
Esempio n. 11
0
def def_credentials(chain):
    rpc = get_rpc_details(chain)
    try:
        rpc_connection = Proxy("http://%s:%[email protected]:%d" %
                               (rpc[0], rpc[1], int(rpc[2])))
    except Exception:
        raise Exception(
            "Connection error! Probably no daemon on selected port.")
    return rpc_connection
Esempio n. 12
0
def rpc_connect(rpc_user, rpc_password, server, port):
    try:
        rpc_connection = Proxy("http://%s:%s@%s:%d" %
                               (rpc_user, rpc_password, server, port))
    except (http.client.CannotSendRequest, http.client.RemoteDisconnected,
            ConnectionRefusedError, OSError):
        raise Exception(
            "Connection error! Probably no daemon on selected port.")
    return rpc_connection
Esempio n. 13
0
def create_proxy(node_params_dictionary):
    try:
        proxy = Proxy("http://%s:%s@%s:%d" % (node_params_dictionary.get('rpc_user'),
                                              node_params_dictionary.get('rpc_password'),
                                              node_params_dictionary.get('rpc_ip'),
                                              node_params_dictionary.get('rpc_port')), timeout=120)
    except Exception as e:
        raise Exception("Connection error! Probably no daemon on selected port. Error: ", e)
    return proxy
Esempio n. 14
0
 def _proxy_connection(node_params_dictionary):
     try:
         proxy = Proxy("http://%s:%s@%s:%d" %
                       (node_params_dictionary["rpc_user"],
                        node_params_dictionary["rpc_password"],
                        node_params_dictionary["rpc_ip"],
                        node_params_dictionary["rpc_port"]),
                       timeout=120)
         proxy_connected.append(proxy)
     except Exception as e:
         raise Exception(
             "Connection error! Probably no daemon on selected port. Error: ",
             e)
     return proxy
Esempio n. 15
0
    def init_app(self, app):
        """Set up this instance for use with *app*, if no app was passed to
        the constructor.
        """

        self.app = app
        app.wallet_instance = self
        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions['wallet'] = self

        app.config.setdefault(
            'WALLET_RPC_URL',
            '"http://%s:%[email protected]:8332"%("Rpcuser", "Rpcpassword")')
        self.connect = Proxy(app.config['WALLET_RPC_URL'])

        app.context_processor(_wallet_context_processor)
        app.teardown_appcontext(self.teardown)
Esempio n. 16
0
def def_creds(chain):
    rpcport =''
    coin_config_file = ''
    if chain == 'KMD':
        coin_config_file = str(ac_dir + '/komodo.conf')
    elif chain == 'BTC':
        coin_config_file = str(home + '/.bitcoin/bitcoin.conf')
    elif this_node == 'third_party':
        with open(coins_json) as file:
            coins_3p = json.load(file)
        for coin in coins_3p:
            if coin['tag'] == chain:
                coin_config_file = str(home+'/'+coin['datadir']+'/'+coin['conf'])
        if coin_config_file == '':
            coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf')                
    else:
        coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf')
    with open(coin_config_file, 'r') as f:
        for line in f:
            l = line.rstrip()
            if re.search('rpcuser', l):
                rpcuser = l.replace('rpcuser='******'')
            elif re.search('rpcpassword', l):
                rpcpassword = l.replace('rpcpassword='******'')
            elif re.search('rpcport', l):
                rpcport = l.replace('rpcport=', '')
    if len(rpcport) == 0:
        if chain == 'KMD':
            rpcport = 7771
        elif chain == 'KMD':
            rpcport = 8333
        else:
            print("rpcport not in conf file, exiting")
            print("check "+coin_config_file)
            exit(1)
    return(Proxy("http://%s:%[email protected]:%d"%(rpcuser, rpcpassword, int(rpcport))))
Esempio n. 17
0
    print("Transaction confirmed!\n")


def print_balance(rpc_connection_source, rpc_connection_destination):
    balance_source = rpc_connection_source.getbalance()
    balance_destination = rpc_connection_destination.getbalance()
    source_chain_name = rpc_connection_source.getinfo()["name"]
    destination_chain_name = rpc_connection_destination.getinfo()["name"]
    print("Source chain " + source_chain_name + " balance: " +
          str(balance_source))
    print("Destination chain " + destination_chain_name + " balance: " +
          str(balance_destination))


# SET RPC CONNECTION DETAILS HERE
rpc_connection_sourcechain = Proxy("http://%s:%[email protected]:%d" %
                                   ("user", "pass", 30667))
rpc_connection_destinationchain = Proxy("http://%s:%[email protected]:%d" %
                                        ("user", "pass", 50609))
rpc_connection_kmdblockchain = Proxy("http://%s:%[email protected]:%d" %
                                     ("user", "pass", 7771))
# SET ADDRESS AND MIGRATION AMOUNT HERE
address = "RHq3JsvLxU45Z8ufYS6RsDpSG4wi6ucDev"
amount = 0.1

t0 = time.time()

print_balance(rpc_connection_sourcechain, rpc_connection_destinationchain)

print("Sending " + str(amount) + " coins from " + rpc_connection_sourcechain.getinfo()["name"] + " chain " +\
      "to " + rpc_connection_destinationchain.getinfo()["name"] + " chain")
Esempio n. 18
0
class ZcashNode(object):
    def __init__(self, args, zcashd=None, zcash_cli=None):
        if zcashd is None:
            zcashd = os.getenv('ZCASHD', 'zcashd')
        if zcash_cli is None:
            zcash_cli = os.getenv('ZCASHCLI', 'zcash-cli')

        self.__datadir = args.datadir
        self.__wallet = args.wallet
        self.__testnet = not args.mainnet
        self.__zcashd = zcashd
        self.__zcash_cli = zcash_cli
        self.__process = None
        self.__proxy = None

        self.automated = args.automate
        self.use_faucet = args.faucet

    def start(self, extra_args=None, timewait=None):
        if self.__proxy is not None:
            raise RuntimeError('Already started')

        rpcuser = '******'
        rpcpassword = '******'

        args = [
            self.__zcashd,
            '-datadir=%s' % self.__datadir,
            '-wallet=%s' % self.__wallet,
            '-rpcuser=%s' % rpcuser,
            '-rpcpassword=%s' % rpcpassword,
            '-showmetrics=0',
            '-experimentalfeatures',
            '-zmergetoaddress',
        ]
        if self.__testnet:
            args.append('-testnet=1')
        if extra_args is not None:
            args.extend(extra_args)

        self.__process = subprocess.Popen(args)

        cli_args = [
            self.__zcash_cli,
            '-datadir=%s' % self.__datadir,
            '-rpcuser=%s' % rpcuser,
            '-rpcpassword=%s' % rpcpassword,
            '-rpcwait',
        ]
        if self.__testnet:
            cli_args.append('-testnet=1')
        cli_args.append('getblockcount')

        devnull = open('/dev/null', 'w+', encoding='utf8')
        if os.getenv('PYTHON_DEBUG', ''):
            print(
                'start_node: zcashd started, calling zcash-cli -rpcwait getblockcount'
            )
        subprocess.check_call(cli_args, stdout=devnull)
        if os.getenv('PYTHON_DEBUG', ''):
            print(
                'start_node: calling zcash-cli -rpcwait getblockcount returned'
            )
        devnull.close()

        rpcuserpass = '******' % (rpcuser, rpcpassword)
        rpchost = '127.0.0.1'
        rpcport = 18232 if self.__testnet else 8232

        url = 'http://%s@%s:%d' % (rpcuserpass, rpchost, rpcport)
        if timewait is not None:
            self.__proxy = Proxy(url, timeout=timewait)
        else:
            self.__proxy = Proxy(url)

    def stop(self):
        if self.__proxy is None:
            raise RuntimeError('Not running')

        self.__proxy.stop()
        self.__process.wait()
        self.__proxy = None
        self.__process = None

    def __getattr__(self, name):
        if self.__proxy is None:
            raise RuntimeError('Not running')

        return self.__proxy.__getattr__(name)
Esempio n. 19
0
#!/usr/bin/env python3
# coding: UTF-8

import datetime
import settings
import argparse
import pathlib
import logging
import signal
import time
import sys

from slickrpc import Proxy
from slickrpc import exc

proxy = Proxy('http://%s:%s@%s' %
              (settings.rpc_user, settings.rpc_pass, settings.rpc_address))

################################################################################
## SyncMonApp class ############################################################
################################################################################


class SyncMonApp:
    def __init__(self):

        pass

    ############################################################################

    def run(self):
Esempio n. 20
0
from lib import rpclib
from slickrpc import Proxy
import requests
import json

rpc_user = "******"
rpc_password = "******"
port = 24708

rpc_connect = rpc_connection = Proxy("http://%s:%[email protected]:%d" %
                                     (rpc_user, rpc_password, port))

address = "RXju6We6DDK9EYhrAVBZVXNAFbA5czw7yK"

url = "http://seed.juicydev.coingateways.com:24711/insight-api-komodo/addrs/RS7y4zjQtcNv7inZowb8M6bH3ytS1moj9A/utxo"

try:
    res = requests.get(url)
except Exception as e:
    print(e)

to_python = json.loads(res.text)

count = 0

list_of_ids = []
list_of_vouts = []
amount = 0

for objects in to_python:
    if (objects['amount'] < 0.01) and count < 10:
Esempio n. 21
0
#To use this test run in the terminal:
#                 $:     python3 test_rpc.py 
from slickrpc import Proxy

rpc_user="******"
rpc_password="******"
rpc_host="127.0.0.1"
rpc_port="8332"

bitcoin = Proxy("http://%s:%[email protected]:8332"%(rpc_user, rpc_password))
hex = bitcoin.getrawtransaction ("a9a9db6b085df091ea1491e57df9177d128f6650ec9405148c9c2b64a835e88e", False,
                                 #"00000000e6f2148b04603d41257bb25b984787f6e5d0aadbfcda1b517806f9df"
                                 )
decoded_tx = bitcoin.decoderawtransaction (hex)
print(decoded_tx)

transactions = bitcoin.listtransactions("bc1qfm5repssqrnx9twvzw4glkcmk4z0gha5lnaeyp")
print(transactions)




Esempio n. 22
0
from slickrpc import Proxy; 
from time import sleep

p = Proxy(service_url='http://*****:*****@127.0.0.1:24127');

#print(p.masternode("outputs"))

def get_collat(p, unspent, pw):
    '''
    take a list of unspent outputs and return a list of 
    tx to make at least 1 collateral sized output
    If it's not possible return empty list
    '''
    p.walletpassphrase(pw, 1) 
    inputs = []
    total = 0
    keychain = []
    keys = []
    for u in unspent:
        inputs.append({'txid':u['txid'], 'vout':u['vout']})
        total += u['amount']
        privkey = p.dumpprivkey(r['address'])
        keychain.append(privkey) 
        if privkey in keys:
            keys[privkey] += 1
        else:
            keys[privkey] = 1

        if collat > MN_COLLAT:
            return [inputs, keychain]
    return []
Esempio n. 23
0
class eccoinNode(cryptoNode):

    version_min = 30000
    version_max = 99999
    win_zmq_bug = 30300

    version_fPacketSig = 30300

    serviceIdx = count(start=1)
    respondIdx = count(start=1)

    ############################################################################

    def __init__(self,
                 symbol,
                 rpc_address,
                 rpc_user,
                 rpc_pass,
                 service_id=1,
                 respond_id=None):

        super().__init__(symbol, rpc_address, rpc_user, rpc_pass)

        self.proxy = Proxy(
            'http://%s:%s@%s' %
            (rpc_user, rpc_pass, rpc_address))  # Not thread safe ...
        self.prox2 = Proxy(
            'http://%s:%s@%s' %
            (rpc_user, rpc_pass, rpc_address))  # ... hence needing 2

        self.serviceId = service_id
        self.respondId = respond_id
        self.serviceKey = ''
        self.respondKey = ''

        self.routingTag = ''

        self.ecresolve_tags = []

        # ECC feature flags (based on version number)

        self.fPacketSig = False

        # Caching prior unlock state for post transaction reversion

        self.cached_prior_walletinfo = {}

    ############################################################################

    def __getattr__(self, method):

        return getattr(self.proxy, method)

    ############################################################################

    def initialise(self):

        try:

            info = self.proxy.getnetworkinfo()

        except ValueError:

            raise cryptoNodeException(
                'Failed to connect - error in rpcuser or rpcpassword for eccoin'
            )

        except pycurl.error:

            raise cryptoNodeException(
                'Failed to connect - check that eccoin daemon is running')

        except exc.RpcInWarmUp:

            raise cryptoNodeException(
                'Failed to connect -  eccoin daemon is starting but not ready - try again after 60 seconds'
            )

        except exc.RpcMethodNotFound:

            raise cryptoNodeException(
                'RPC getnetworkinfo unavailable for {} daemon'.format(
                    self.symbol))

        # ECC daemon version checking and feature enablement

        if not self.version_min <= info['version'] <= self.version_max:

            raise cryptoNodeException(
                'eccoind version {} not supported - please run a version in the range {}-{}'
                .format(info['version'], self.version_min, self.version_max))

        if (info['version'] == self.win_zmq_bug) and (sys.platform
                                                      in ['win32', 'cygwin']):

            raise cryptoNodeException(
                'eccoind version {} not supported on Windows - please upgrade'.
                format(info['version']))

        self.fPacketSig = info['version'] >= self.version_fPacketSig

        # ECC messaging buffer setup

        try:

            self.routingTag = self.proxy.getroutingpubkey()

            if self.serviceId:

                self.serviceKey = self.proxy.registerbuffer(self.serviceId)

            if self.respondId:

                self.respondKey = self.proxy.registerbuffer(self.respondId)

        except exc.RpcInternalError:

            raise cryptoNodeException(
                'API Buffer was not correctly unregistered or another instance running - try again after 60 seconds'
            )

        # ZMQ detection and configuration loading

        try:

            zmqnotifications = self.proxy.getzmqnotifications()

        except pycurl.error:

            raise cryptoNodeException(
                'Blockchain node for {} not available or incorrectly configured'
                .format(self.symbol))

        except (exc.RpcMethodNotFound, ValueError):

            zmqnotifications = []

        for zmqnotification in zmqnotifications:

            if zmqnotification['type'] == 'pubhashblock':

                self.zmqAddress = zmqnotification['address']

        # Load ecresolve routing tags and setup routes for subsequent ecc network name resolution

        self.ecresolve_tags = self.get_ecresolve_tags()

        route = []

        for tag in self.ecresolve_tags:

            try:

                self.proxy.findroute(tag)

                route.append(self.proxy.haveroute(tag))

            except exc.RpcInvalidAddressOrKey:

                raise cryptoNodeException(
                    'Routing tag for ecresolve has invalid base64 encoding : {}'
                    .format(tag))

        if not any(route):

            raise cryptoNodeException(
                'No route available to ecresolve across all {} configured routing tags'
                .format(len(self.ecresolve_tags)))

    ############################################################################

    def refresh(self):

        self.blocks = self.proxy.getblockcount()
        self.peers = self.proxy.getconnectioncount()

    ############################################################################

    def get_balance(self):

        return self.proxy.getbalance()

    ############################################################################

    def get_unlocked_balance(self):

        return self.proxy.getbalance()

    ############################################################################

    def get_unconfirmed_balance(self):

        return self.proxy.getunconfirmedbalance()

    ############################################################################

    def get_new_address(self):

        return self.proxy.getnewaddress()

    ############################################################################

    def wallet_locked(self, cache_prior_state=False):

        info = self.proxy.getwalletinfo()

        if cache_prior_state and info.keys() >= {
                'unlocked_until', 'staking_only_unlock'
        }:

            self.cached_prior_walletinfo = info.copy()

        if 'unlocked_until' in info:

            if 'staking_only_unlock' in info:

                return info['staking_only_unlock'] or (info['unlocked_until']
                                                       == 0)

            else:

                return info['unlocked_until'] == 0

        return False  # unencrypted wallet

    ############################################################################

    def unlock_wallet(self, passphrase, seconds, staking=False):

        try:

            self.proxy.walletpassphrase(passphrase, seconds, staking)

        except exc.RpcWalletPassphraseIncorrect:

            return False

        else:

            # Cache passphrase for later call to revert_wallet_lock

            if self.cached_prior_walletinfo:

                self.cached_prior_walletinfo['passphrase'] = passphrase

            return True

    ############################################################################

    def revert_wallet_lock(self):

        if self.cached_prior_walletinfo and 'passphrase' in self.cached_prior_walletinfo:

            if self.cached_prior_walletinfo['unlocked_until'] > 0:

                seconds = self.cached_prior_walletinfo['unlocked_until'] - int(
                    time.time())

                self.unlock_wallet(
                    self.cached_prior_walletinfo['passphrase'], seconds,
                    self.cached_prior_walletinfo['staking_only_unlock'])

                self.cached_prior_walletinfo.clear()

    ############################################################################

    def send_to_address(self, address, amount, comment):

        try:

            txid = self.proxy.sendtoaddress(address, amount, comment)

        except exc.RpcWalletUnlockNeeded:

            raise cryptoNodeException('Wallet locked - please unlock')

        except exc.RpcWalletInsufficientFunds:

            raise cryptoNodeException('Insufficient funds in wallet')

        except exc.RpcTypeError:

            raise cryptoNodeException('Invalid amount')

        except exc.RpcWalletError:

            raise cryptoNodeException('Amount too small')

        else:

            return txid

    ############################################################################

    def reset_service_buffer_timeout(self):

        if self.serviceKey:

            try:

                bufferSig = self.prox2.buffersignmessage(
                    self.serviceKey, 'ResetBufferTimeout')

                self.prox2.resetbuffertimeout(self.serviceId, bufferSig)

            except pycurl.error:

                self.serviceKey = ''

                raise cryptoNodeException(
                    'Failed to connect - check that eccoin daemon is running')

            return True

        return False

    ############################################################################

    def reset_respond_buffer_timeout(self):

        if self.respondKey:

            try:

                bufferSig = self.prox2.buffersignmessage(
                    self.respondKey, 'ResetBufferTimeout')

                self.prox2.resetbuffertimeout(self.respondId, bufferSig)

            except pycurl.error:

                self.serviceKey = ''

                raise cryptoNodeException(
                    'Failed to connect - check that eccoin daemon is running')

            return True

        return False

    ############################################################################

    def reset_buffer_timeouts(self):

        serviceResult = self.reset_service_buffer_timeout()

        respondResult = self.reset_respond_buffer_timeout()

        return serviceResult or respondResult  # OR semantics because the return value is used to gate timer setup

    ############################################################################

    def get_ecresolve_tags(self):

        domain = 'ecchat.io'

        # TODO - Make this daemon version dependent ref new RPC

        tags = []

        try:

            resolved = dns.resolver.resolve(domain, 'TXT')

        except:

            raise cryptoNodeException(
                'Error while resolving ecresolve routing tags from {} TXT record'
                .format(domain))

        for entry in resolved:

            decoded_entry = entry.to_text()[1:-1].split('=', 1)

            if (len(decoded_entry) == 2) and (decoded_entry[0] == 'ecresolve'):

                tags.append(decoded_entry[1])

        return tags

    ############################################################################

    def setup_route(self, targetRoute):

        try:

            self.proxy.findroute(targetRoute)

            isRoute = self.proxy.haveroute(targetRoute)

        except exc.RpcInvalidAddressOrKey:

            raise cryptoNodeException(
                'Routing tag has invalid base64 encoding : {}'.format(
                    targetRoute))

        if not isRoute:

            raise cryptoNodeException(
                'No route available to : {}'.format(targetRoute))

    ############################################################################

    def send_packet(self, dest_key, protocol_id, data):

        if self.fPacketSig:

            signature = self.proxy.tagsignmessage(data)

            self.proxy.sendpacket(dest_key, protocol_id, data, self.routingTag,
                                  signature)

        else:

            self.proxy.sendpacket(dest_key, protocol_id, data)

    ############################################################################

    def get_service_buffer(self):

        if self.serviceKey:

            bufferCmd = 'GetBufferRequest:' + str(self.serviceId) + str(
                next(self.serviceIdx))

            bufferSig = self.proxy.buffersignmessage(self.serviceKey,
                                                     bufferCmd)

            eccbuffer = self.proxy.getbuffer(self.serviceId, bufferSig)

            return eccbuffer

        else:

            return None

    ############################################################################

    def get_respond_buffer(self):

        if self.respondKey:

            bufferCmd = 'GetBufferRequest:' + str(self.respondId) + str(
                next(self.respondIdx))

            bufferSig = self.proxy.buffersignmessage(self.respondKey,
                                                     bufferCmd)

            eccbuffer = self.proxy.getbuffer(self.respondId, bufferSig)

            return eccbuffer

        else:

            return None

    ############################################################################

    def get_buffer(self, protocol_id=1):

        if protocol_id == self.serviceId:

            return self.get_service_buffer()

        if protocol_id == self.respondId:

            return self.get_respond_buffer()

        return None

    ############################################################################

    def shutdown(self):

        if self.serviceKey:

            bufferSig = self.proxy.buffersignmessage(self.serviceKey,
                                                     'ReleaseBufferRequest')

            self.proxy.releasebuffer(self.serviceId, bufferSig)

            self.serviceKey = ''

        if self.respondKey:

            bufferSig = self.proxy.buffersignmessage(self.respondKey,
                                                     'ReleaseBufferRequest')

            self.proxy.releasebuffer(self.respondId, bufferSig)

            self.respondKey = ''
Esempio n. 24
0
#!/usr/bin/env python3

import datetime

from slickrpc import Proxy
from slickrpc.exc import RpcException

TIME_STARTED = datetime.datetime.now()

zcash_proxy = Proxy("http://%s:%[email protected]:%s" %
    (
        "rpcuser",
        "rpcpass",
        "8232")
    )

def call_rpc(name, args=[]):
    print("%s: ./zcash-cli %s %s" %
        (
            datetime.datetime.now() - TIME_STARTED,
            name, 
            ' '.join([str(arg) for arg in args]))
        )
    try:
        return zcash_proxy.__getattr__(name)(*args)
    except RpcException as e:
        print("RpcException: %s" % (e))
        return None

# Call "help" to generate a list of rpcs
help_rpc_output = call_rpc("help")
Esempio n. 25
0
#!/usr/bin/env python
from json import loads, dumps
from sys import exit, argv
import base64
import urllib.request

from slickrpc import Proxy
bitcoin = Proxy("http://%s:%[email protected]:44444" % ("user", "password"))

# Electrum checkpoints are blocks 2015, 2015 + 2016, 2015 + 2016*2, ...
i = 2015
INTERVAL = 2016


# From electrum.
def bits_to_target(bits):
    bitsN = (bits >> 24) & 0xff
    if not (bitsN >= 0x03 and bitsN <= 0x1e):
        raise BaseException("First part of bits should be in [0x03, 0x1e]")
    bitsBase = bits & 0xffffff
    if not (bitsBase >= 0x8000 and bitsBase <= 0x7fffff):
        raise BaseException(
            "Second part of bits should be in [0x8000, 0x7fffff]")
    return bitsBase << (8 * (bitsN - 3))


checkpoints = []
block_count = bitcoin.getblockcount()

print('Blocks: {}'.format(block_count))
while True:
Esempio n. 26
0
            else:
                already_choosen_ips = []
                for j in range(3):
                    connect_ip = random.choice(ips_of_running_servers)
                    if connect_ip in already_choosen_ips:
                        connect_ip = random.choice(ips_of_running_servers)
                    else:
                        already_choosen_ips.append(connect_ip)
                for ip in already_choosen_ips:
                    daemon_args.append("-addnode=" + ip + ":6000")
        subprocess.call(daemon_args)
        time.sleep(3)

# creating rpc proxies for all nodes
for i in range(dexp2p_clients_to_start):
    rpcport = 7000 + i
    globals()['proxy_%s' % i] = Proxy("http://%s:%[email protected]:%d" %
                                      ("test", "test", int(rpcport)))
    try:
        dex_stats_output = globals()['proxy_%s' % i].DEX_stats()
        print(dex_stats_output)
    except Exception as e:
        print(e)

# since connection ports were chosen randomly let's try to interconnect orphan nodes
for i in range(dexp2p_clients_to_start):
    connections_amount = globals()['proxy_%s' % i].getinfo()["connections"]
    print(connections_amount)

print("All nodes started (hopefully) - you can proceed to loading test")
Esempio n. 27
0
class bitcoinNode(cryptoNode):

    ############################################################################

    def __init__(self, symbol, rpc_address, rpc_user, rpc_pass):

        super().__init__(symbol, rpc_address, rpc_user, rpc_pass)

        self.proxy = Proxy('http://%s:%s@%s' %
                           (rpc_user, rpc_pass, rpc_address))

    ############################################################################

    def __getattr__(self, method):

        return getattr(self.proxy, method)

    ############################################################################

    def initialise(self):

        try:

            info = self.proxy.getnetworkinfo()

        except ValueError:

            raise cryptoNodeException(
                'Failed to connect - error in rpcuser or rpcpassword for {} daemon'
                .format(self.symbol))

        except pycurl.error:

            raise cryptoNodeException(
                'Failed to connect - check that {} daemon is running'.format(
                    self.symbol))

        except exc.RpcInWarmUp:

            raise cryptoNodeException(
                'Failed to connect - {} daemon is starting but not ready - try again after 60 seconds'
                .format(self.symbol))

        except exc.RpcMethodNotFound:

            raise cryptoNodeException(
                'RPC getnetworkinfo unavailable for {} daemon'.format(
                    self.symbol))

        try:

            zmqnotifications = self.proxy.getzmqnotifications()

        except pycurl.error:

            raise cryptoNodeException(
                'Blockchain node for {} not available or incorrectly configured'
                .format(self.symbol))

        except (exc.RpcMethodNotFound, ValueError):

            zmqnotifications = []

        for zmqnotification in zmqnotifications:

            if zmqnotification['type'] == 'pubhashblock':

                self.zmqAddress = zmqnotification['address']

    ############################################################################

    def refresh(self):

        self.blocks = self.proxy.getblockcount()
        self.peers = self.proxy.getconnectioncount()

    ############################################################################

    def get_balance(self):

        try:

            result = self.proxy.getbalance()

        except exc.RpcException as error:

            raise cryptoNodeException('{} daemon returned error: {}'.format(
                self.symbol, str(error)))

        else:

            return result

    ############################################################################

    def get_unlocked_balance(self):

        try:

            result = self.proxy.getbalance()

        except exc.RpcException as error:

            raise cryptoNodeException('{} daemon returned error: {}'.format(
                self.symbol, str(error)))

        else:

            return result

    ############################################################################

    def get_unconfirmed_balance(self):

        try:

            result = self.proxy.getunconfirmedbalance()

        except exc.RpcException as error:

            raise cryptoNodeException('{} daemon returned error: {}'.format(
                self.symbol, str(error)))

        else:

            return result

    ############################################################################

    def get_new_address(self):

        return self.proxy.getnewaddress()

    ############################################################################

    def wallet_locked(self, cache_prior_state=False):

        info = self.proxy.getwalletinfo()

        if 'unlocked_until' in info:

            return info['unlocked_until'] == 0

        return False

    ############################################################################

    def unlock_wallet(self, passphrase, seconds, staking=False):

        try:

            self.proxy.walletpassphrase(passphrase, seconds)

        except exc.RpcWalletPassphraseIncorrect:

            return False

        else:

            return True

    ############################################################################

    def revert_wallet_lock(self):

        pass

    ############################################################################

    def send_to_address(self, address, amount, comment):

        try:

            txid = self.proxy.sendtoaddress(address, amount, comment)

        except exc.RpcWalletUnlockNeeded:

            raise cryptoNodeException('Wallet locked - please unlock')

        except exc.RpcWalletInsufficientFunds:

            raise cryptoNodeException('Insufficient funds in wallet')

        except exc.RpcTypeError:

            raise cryptoNodeException('Invalid amount')

        except exc.RpcWalletError:

            raise cryptoNodeException('Amount too small')

        else:

            return txid

    ############################################################################

    def shutdown(self):

        pass
                time.sleep(15)
            else:
                print("Transactinon broadcasted on destination chain")
                dest_tx_list.append(sent_itx)
                is_broadcasted = True
                break
        else:
            print("Too many attempts. Bye bye.")
            sys.exit()
    return is_broadcasted


# SET RPC CONNECTION DETAILS HERE
rpc_connection_sourcechain = Proxy(
    "http://%s:%[email protected]:%d" %
    ("user1531394351",
     "pass24e95276e008e3f6176b672631a89beef6959ce9dae44f8bdb7a92e5ca41e56c77",
     30667))
rpc_connection_destinationchain = Proxy(
    "http://%s:%[email protected]:%d" %
    ("user2491106895",
     "pass253372aea1796039438e3e3c240a39cec6f9aa11cff7bc3d3c29ab93c0e985d73e",
     50609))
rpc_connection_kmdblockchain = Proxy("http://%s:%[email protected]:%d" %
                                     ("tony", "156ewr", 7771))
# SET ADDRESS AND MIGRATION AMOUNT HERE
address = "RSbcG63XbgfAwmFmPA362d4zqLb31hJiyt"
amount = 2
migrations_amount = 500

# preparing UTXOs if there is not enough
Esempio n. 29
0
    def __init__(self, symbol, rpc_address, rpc_user, rpc_pass):

        super().__init__(symbol, rpc_address, rpc_user, rpc_pass)

        self.proxy = Proxy('http://%s:%s@%s' %
                           (rpc_user, rpc_pass, rpc_address))
Esempio n. 30
0
# Cron for dump MN and Gov Info

from slickrpc import Proxy
import datetime
import json
import sys

rpc_user = "******"
rpc_password = "******"

rpc_con = Proxy("http://%s:%[email protected]:9846" % (rpc_user, rpc_password))


def dump_mn_info():
    """Get Masternodes info"""
    mn = rpc_con.masternode("list", "full")
    # format
    # 'status protocol payee lastseen activeseconds lastpaidtime lastpaidblock IP'
    result = """
    {
      "data": [
    """
    for k in mn.keys():
        cr = mn[k].split(" ")
        cr = filter(lambda a: a != "", cr)
        cr[3] = datetime.datetime.fromtimestamp(int(
            cr[3])).strftime('%Y-%m-%d %H:%M:%S')
        cr[4] = str(datetime.timedelta(seconds=int(cr[4])))
        cr[5] = datetime.datetime.fromtimestamp(int(
            cr[5])).strftime('%Y-%m-%d %H:%M:%S')
        result += "\n %s," % json.dumps(cr)