def setUpClass(cls): stm = shared_dpay_instance() stm.config.refreshBackup() nodelist = NodeList() nodelist.update_nodes(dpay_instance=DPay(node=nodelist.get_nodes( normal=True, appbase=True), num_retries=10)) cls.stm = DPay( node=nodelist.get_nodes(), nobroadcast=True, # We want to bundle many operations into a single transaction bundle=True, num_retries=10 # Overwrite wallet to use this list of wifs only ) cls.testnet = DPay(node="https://testnet.dpaydev.com", nobroadcast=True, bundle=True, num_retries=10) cls.stm.set_default_account("test") set_shared_dpay_instance(cls.stm) # self.stm.newWallet("TestingOneTwoThree") cls.wallet = Wallet(dpay_instance=cls.stm) cls.wallet.wipe(True) cls.wallet.newWallet(pwd="TestingOneTwoThree") cls.wallet.unlock(pwd="TestingOneTwoThree") cls.wallet.addPrivateKey(wif)
def __init__(self, account, lazy=False, full=True, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() self.account = Account(account, full=True, dpay_instance=self.dpay) account_name = self.account["name"] self.identifier = account_name self.dpay.rpc.set_next_node_on_empty_reply(False) if self.dpay.rpc.get_use_appbase(): if "witnesses_voted_for" not in self.account: return limit = self.account["witnesses_voted_for"] witnessess_dict = self.dpay.rpc.list_witness_votes({'start': [account_name], 'limit': limit, 'order': 'by_account_witness'}, api="database")['votes'] witnessess = [] for w in witnessess_dict: witnessess.append(w["witness"]) else: if "witness_votes" not in self.account: return witnessess = self.account["witness_votes"] super(WitnessesVotedByAccount, self).__init__( [ Witness(x, lazy=lazy, full=full, dpay_instance=self.dpay) for x in witnessess ] )
def __init__( self, # accounts=[], on_block=None, only_block_id=False, dpay_instance=None, keep_alive=25 ): # Events Events.__init__(self) self.events = Events() # DPay instance self.dpay = dpay_instance or shared_dpay_instance() # Callbacks if on_block: self.on_block += on_block # Open the websocket self.websocket = DPayWebsocket( urls=self.dpay.rpc.nodes, user=self.dpay.rpc.user, password=self.dpay.rpc.password, only_block_id=only_block_id, on_block=self.process_block, keep_alive=keep_alive )
def __init__(self, dpay_instance=None, *args, **kwargs): self.dpay = dpay_instance or shared_dpay_instance() # Compatibility after name change from wif->keys if "wif" in kwargs and "keys" not in kwargs: kwargs["keys"] = kwargs["wif"] master_password_set = False if "keys" in kwargs: self.setKeys(kwargs["keys"]) else: """ If no keys are provided manually we load the SQLite keyStorage """ from .storage import (keyStorage, MasterPassword) self.MasterPassword = MasterPassword master_password_set = True self.keyStorage = keyStorage if "token" in kwargs: self.setToken(kwargs["token"]) else: """ If no keys are provided manually we load the SQLite keyStorage """ from .storage import tokenStorage if not master_password_set: from .storage import MasterPassword self.MasterPassword = MasterPassword self.tokenStorage = tokenStorage
def __init__( self, base=None, quote=None, dpay_instance=None, ): """ Init Market :param dpaycli.dpay.DPay dpay_instance: DPay instance :param dpaycli.asset.Asset base: Base asset :param dpaycli.asset.Asset quote: Quote asset """ self.dpay = dpay_instance or shared_dpay_instance() if quote is None and isinstance(base, str): quote_symbol, base_symbol = assets_from_string(base) quote = Asset(quote_symbol, dpay_instance=self.dpay) base = Asset(base_symbol, dpay_instance=self.dpay) super(Market, self).__init__({"base": base, "quote": quote}) elif base and quote: quote = Asset(quote, dpay_instance=self.dpay) base = Asset(base, dpay_instance=self.dpay) super(Market, self).__init__({"base": base, "quote": quote}) elif base is None and quote is None: quote = Asset("BBD", dpay_instance=self.dpay) base = Asset("BEX", dpay_instance=self.dpay) super(Market, self).__init__({"base": base, "quote": quote}) else: raise ValueError("Unknown Market config")
def __init__(self, from_account=None, to_account=None, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() if to_account: self.to_account = Account(to_account, dpay_instance=self.dpay) if from_account: self.from_account = Account(from_account, dpay_instance=self.dpay)
def __init__(self, data, klass=None, space_id=1, object_id=None, lazy=False, use_cache=True, id_item=None, dpay_instance=None, *args, **kwargs): self.dpay = dpay_instance or shared_dpay_instance() self.cached = False self.identifier = None # We don't read lists, sets, or tuples if isinstance(data, (list, set, tuple)): raise ValueError( "Cannot interpret lists! Please load elements individually!") if id_item and isinstance(id_item, string_types): self.id_item = id_item else: self.id_item = "id" if klass and isinstance(data, klass): self.identifier = data.get(self.id_item) super(BlockchainObject, self).__init__(data) elif isinstance(data, dict): self.identifier = data.get(self.id_item) super(BlockchainObject, self).__init__(data) elif isinstance(data, integer_types): # This is only for block number basically self.identifier = data if not lazy and not self.cached: self.refresh() # make sure to store the blocknumber for caching self[self.id_item] = (data) # Set identifier again as it is overwritten in super() in refresh() self.identifier = data elif isinstance(data, string_types): self.identifier = data if not lazy and not self.cached: self.refresh() self[self.id_item] = str(data) self.identifier = data else: self.identifier = data if self.test_valid_objectid(self.identifier): # Here we assume we deal with an id self.testid(self.identifier) if self.iscached(data): super(BlockchainObject, self).__init__(self.getcache(data)) elif not lazy and not self.cached: self.refresh() if use_cache and not lazy: self.cache() self.cached = True
def __init__(self, dpay_instance=None, *args, **kwargs): self.dpay = dpay_instance or shared_dpay_instance() self.access_token = None self.get_refresh_token = kwargs.get("get_refresh_token", False) self.hot_sign_redirect_uri = kwargs.get( "hot_sign_redirect_uri", config["hot_sign_redirect_uri"]) if self.hot_sign_redirect_uri == "": self.hot_sign_redirect_uri = None self.client_id = kwargs.get("client_id", config["dpid_client_id"]) self.scope = kwargs.get("scope", "login") self.oauth_base_url = kwargs.get("oauth_base_url", config["oauth_base_url"]) self.dpid_api_url = kwargs.get("dpid_api_url", config["dpid_api_url"])
def __init__(self, from_account="", limit=100, lazy=False, full=False, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() self.identifier = from_account self.dpay.rpc.set_next_node_on_empty_reply(False) if self.dpay.rpc.get_use_appbase(): witnessess = self.dpay.rpc.list_witnesses({'start': from_account, 'limit': limit, 'order': 'by_name'}, api="database")['witnesses'] else: witnessess = self.dpay.rpc.lookup_witness_accounts(from_account, limit) if len(witnessess) == 0: return super(ListWitnesses, self).__init__( [ Witness(x, lazy=lazy, full=full, dpay_instance=self.dpay) for x in witnessess ] )
def __init__(self, from_account="", limit=100, lazy=False, full=False, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() witnessList = [] last_limit = limit self.identifier = "" use_condenser = True self.dpay.rpc.set_next_node_on_empty_reply(False) if self.dpay.rpc.get_use_appbase() and not use_condenser: query_limit = 1000 else: query_limit = 100 if self.dpay.rpc.get_use_appbase() and not use_condenser and from_account == "": last_account = None elif self.dpay.rpc.get_use_appbase() and not use_condenser: last_account = Witness(from_account, dpay_instance=self.dpay)["votes"] else: last_account = from_account if limit > query_limit: while last_limit > query_limit: tmpList = WitnessesRankedByVote(last_account, query_limit) if (last_limit < limit): witnessList.extend(tmpList[1:]) last_limit -= query_limit - 1 else: witnessList.extend(tmpList) last_limit -= query_limit if self.dpay.rpc.get_use_appbase(): last_account = witnessList[-1]["votes"] else: last_account = witnessList[-1]["owner"] if (last_limit < limit): last_limit += 1 if self.dpay.rpc.get_use_appbase() and not use_condenser: witnessess = self.dpay.rpc.list_witnesses({'start': [last_account], 'limit': last_limit, 'order': 'by_vote_name'}, api="database")['witnesses'] elif self.dpay.rpc.get_use_appbase() and use_condenser: witnessess = self.dpay.rpc.get_witnesses_by_vote(last_account, last_limit, api="condenser") else: witnessess = self.dpay.rpc.get_witnesses_by_vote(last_account, last_limit) # self.witness_count = len(self.voted_witnessess) if (last_limit < limit): witnessess = witnessess[1:] if len(witnessess) > 0: for x in witnessess: witnessList.append(Witness(x, lazy=lazy, full=full, dpay_instance=self.dpay)) if len(witnessList) == 0: return super(WitnessesRankedByVote, self).__init__(witnessList)
def __init__(self, order, dpay_instance=None, **kwargs): self.dpay = dpay_instance or shared_dpay_instance() if isinstance(order, dict) and "current_pays" in order and "open_pays" in order: # filled orders from account history if "op" in order: order = order["op"] super(FilledOrder, self).__init__( Amount(order["open_pays"], dpay_instance=self.dpay), Amount(order["current_pays"], dpay_instance=self.dpay), ) if "date" in order: self["date"] = formatTimeString(order["date"]) else: raise ValueError("Couldn't parse 'Price'.")
def __init__( self, tx={}, use_condenser_api=True, dpay_instance=None, **kwargs ): self.dpay = dpay_instance or shared_dpay_instance() self.clear() if tx and isinstance(tx, dict): super(TransactionBuilder, self).__init__(tx) # Load operations self.ops = tx["operations"] self._require_reconstruction = False else: self._require_reconstruction = True self._use_condenser_api = use_condenser_api self.set_expiration(kwargs.get("expiration", self.dpay.expiration))
def __init__( self, owner, full=False, lazy=False, dpay_instance=None ): self.full = full self.lazy = lazy self.dpay = dpay_instance or shared_dpay_instance() if isinstance(owner, dict): owner = self._parse_json_data(owner) super(Witness, self).__init__( owner, lazy=lazy, full=full, id_item="owner", dpay_instance=dpay_instance )
def __init__( self, dpay_instance=None, mode="irreversible", max_block_wait_repetition=None, data_refresh_time_seconds=900, ): self.dpay = dpay_instance or shared_dpay_instance() if mode == "irreversible": self.mode = 'last_irreversible_block_num' elif mode == "head": self.mode = "head_block_number" else: raise ValueError("invalid value for 'mode'!") if max_block_wait_repetition: self.max_block_wait_repetition = max_block_wait_repetition else: self.max_block_wait_repetition = 3 self.block_interval = self.dpay.get_block_interval()
def test_dpay(self, node_param): if node_param == "instance": set_shared_dpay_instance(self.bts) o = DPay(node=self.urls) o.get_config() self.assertIn(o.rpc.url, self.urls) with self.assertRaises(RPCConnection): stm = DPay(node="https://abc.d", autoconnect=False, num_retries=1) stm.get_config() else: set_shared_dpay_instance( DPay(node="https://abc.d", autoconnect=False, num_retries=1)) stm = self.bts o = stm o.get_config() self.assertIn(o.rpc.url, self.urls) with self.assertRaises(RPCConnection): stm = shared_dpay_instance() stm.get_config()
def __init__(self, base, quote=None, dpay_instance=None, **kwargs): self.dpay = dpay_instance or shared_dpay_instance() if ( isinstance(base, dict) and "sell_price" in base ): super(Order, self).__init__(base["sell_price"]) self["id"] = base.get("id") elif ( isinstance(base, dict) and "min_to_receive" in base and "amount_to_sell" in base ): super(Order, self).__init__( Amount(base["min_to_receive"], dpay_instance=self.dpay), Amount(base["amount_to_sell"], dpay_instance=self.dpay), ) self["id"] = base.get("id") elif isinstance(base, Amount) and isinstance(quote, Amount): super(Order, self).__init__(None, base=base, quote=quote) else: raise ValueError("Unknown format to load Order")
def update_nodes(self, weights=None, dpay_instance=None): """ Reads metadata from fullnodeupdate and recalculates the nodes score :params list/dict weight: can be used to weight the different benchmarks .. code-block:: python from dpaycli.nodelist import NodeList nl = NodeList() weights = [0, 0.1, 0.2, 1] nl.update_nodes(weights) weights = {'block': 0.1, 'history': 0.1, 'apicall': 1, 'config': 1} nl.update_nodes(weights) """ dpay = dpay_instance or shared_dpay_instance() metadata = None account = None cnt = 0 while metadata is None and cnt < 5: cnt += 1 try: account = Account("fullnodeupdate", dpay_instance=dpay) metadata = json.loads(account["json_metadata"]) except: dpay.rpc.next() account = None metadata = None if metadata is None: return report = metadata["report"] failing_nodes = metadata["failing_nodes"] parameter = metadata["parameter"] benchmarks = parameter["benchmarks"] if weights is None: weights_dict = {} for benchmark in benchmarks: weights_dict[benchmark] = (1. / len(benchmarks)) elif isinstance(weights, list): weights_dict = {} i = 0 weight_sum = 0 for w in weights: weight_sum += w for benchmark in benchmarks: if i < len(weights): weights_dict[benchmark] = weights[i] / weight_sum else: weights_dict[benchmark] = 0. i += 1 elif isinstance(weights, dict): weights_dict = {} i = 0 weight_sum = 0 for w in weights: weight_sum += weights[w] for benchmark in benchmarks: if benchmark in weights: weights_dict[benchmark] = weights[benchmark] / weight_sum else: weights_dict[benchmark] = 0. max_score = len(report) + 1 new_nodes = [] for node in self: new_node = node.copy() for report_node in report: if node["url"] == report_node["node"]: new_node["version"] = report_node["version"] scores = [] for benchmark in benchmarks: result = report_node[benchmark] rank = result["rank"] if not result["ok"]: rank = max_score + 1 score = (max_score - rank) / (max_score - 1) * 100 weighted_score = score * weights_dict[benchmark] scores.append(weighted_score) sum_score = 0 for score in scores: sum_score += score new_node["score"] = sum_score for node_failing in failing_nodes: if node["url"] == node_failing: new_node["score"] = -1 new_nodes.append(new_node) super(NodeList, self).__init__(new_nodes)
def __init__( self, price=None, base=None, quote=None, base_asset=None, # to identify sell/buy dpay_instance=None ): self.dpay = dpay_instance or shared_dpay_instance() if price is "": price = None if (price is not None and isinstance(price, string_types) and not base and not quote): import re price, assets = price.split(" ") base_symbol, quote_symbol = assets_from_string(assets) base = Asset(base_symbol, dpay_instance=self.dpay) quote = Asset(quote_symbol, dpay_instance=self.dpay) frac = Fraction(float(price)).limit_denominator(10 ** base["precision"]) self["quote"] = Amount(amount=frac.denominator, asset=quote, dpay_instance=self.dpay) self["base"] = Amount(amount=frac.numerator, asset=base, dpay_instance=self.dpay) elif (price is not None and isinstance(price, dict) and "base" in price and "quote" in price): if "price" in price: raise AssertionError("You cannot provide a 'price' this way") # Regular 'price' objects according to dpay-core # base_id = price["base"]["asset_id"] # if price["base"]["asset_id"] == base_id: self["base"] = Amount(price["base"], dpay_instance=self.dpay) self["quote"] = Amount(price["quote"], dpay_instance=self.dpay) # else: # self["quote"] = Amount(price["base"], dpay_instance=self.dpay) # self["base"] = Amount(price["quote"], dpay_instance=self.dpay) elif (price is not None and isinstance(base, Asset) and isinstance(quote, Asset)): frac = Fraction(float(price)).limit_denominator(10 ** base["precision"]) self["quote"] = Amount(amount=frac.denominator, asset=quote, dpay_instance=self.dpay) self["base"] = Amount(amount=frac.numerator, asset=base, dpay_instance=self.dpay) elif (price is not None and isinstance(base, string_types) and isinstance(quote, string_types)): base = Asset(base, dpay_instance=self.dpay) quote = Asset(quote, dpay_instance=self.dpay) frac = Fraction(float(price)).limit_denominator(10 ** base["precision"]) self["quote"] = Amount(amount=frac.denominator, asset=quote, dpay_instance=self.dpay) self["base"] = Amount(amount=frac.numerator, asset=base, dpay_instance=self.dpay) elif (price is None and isinstance(base, string_types) and isinstance(quote, string_types)): self["quote"] = Amount(quote, dpay_instance=self.dpay) self["base"] = Amount(base, dpay_instance=self.dpay) elif (price is not None and isinstance(price, string_types) and isinstance(base, string_types)): self["quote"] = Amount(price, dpay_instance=self.dpay) self["base"] = Amount(base, dpay_instance=self.dpay) # len(args) > 1 elif isinstance(price, Amount) and isinstance(base, Amount): self["quote"], self["base"] = price, base # len(args) == 0 elif (price is None and isinstance(base, Amount) and isinstance(quote, Amount)): self["quote"] = quote self["base"] = base elif ((isinstance(price, float) or isinstance(price, integer_types)) and isinstance(base, string_types)): import re base_symbol, quote_symbol = assets_from_string(base) base = Asset(base_symbol, dpay_instance=self.dpay) quote = Asset(quote_symbol, dpay_instance=self.dpay) frac = Fraction(float(price)).limit_denominator(10 ** base["precision"]) self["quote"] = Amount(amount=frac.denominator, asset=quote, dpay_instance=self.dpay) self["base"] = Amount(amount=frac.numerator, asset=base, dpay_instance=self.dpay) else: raise ValueError("Couldn't parse 'Price'.")
def __init__(self, message, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() self.message = message
def __init__(self, lazy=False, full=True, dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() self.lazy = lazy self.full = full self.refresh()
def test_config(self): set_shared_config({"node": self.urls}) set_shared_dpay_instance(None) o = shared_dpay_instance() self.assertIn(o.rpc.url, self.urls)
def __init__(self, account, account_history=[], dpay_instance=None): self.dpay = dpay_instance or shared_dpay_instance() self.account = Account(account, dpay_instance=self.dpay) self.reset() super(AccountSnapshot, self).__init__(account_history)
def tearDownClass(cls): stm = shared_dpay_instance() stm.config.recover_with_latest_backup()
def __init__(self, amount, asset=None, new_appbase_format=True, dpay_instance=None): self["asset"] = {} self.new_appbase_format = new_appbase_format self.dpay = dpay_instance or shared_dpay_instance() if amount and asset is None and isinstance(amount, Amount): # Copy Asset object self["amount"] = amount["amount"] self["symbol"] = amount["symbol"] self["asset"] = amount["asset"] elif amount and asset is None and isinstance(amount, list) and len(amount) == 3: # Copy Asset object self["amount"] = int(amount[0]) / (10 ** amount[1]) self["asset"] = Asset(amount[2], dpay_instance=self.dpay) self["symbol"] = self["asset"]["symbol"] elif amount and asset is None and isinstance(amount, dict) and "amount" in amount and "nai" in amount and "precision" in amount: # Copy Asset object self.new_appbase_format = True self["amount"] = int(amount["amount"]) / (10 ** amount["precision"]) self["asset"] = Asset(amount["nai"], dpay_instance=self.dpay) self["symbol"] = self["asset"]["symbol"] elif amount is not None and asset is None and isinstance(amount, string_types): self["amount"], self["symbol"] = amount.split(" ") self["asset"] = Asset(self["symbol"], dpay_instance=self.dpay) elif (amount and asset is None and isinstance(amount, dict) and "amount" in amount and "asset_id" in amount): self["asset"] = Asset(amount["asset_id"], dpay_instance=self.dpay) self["symbol"] = self["asset"]["symbol"] self["amount"] = int(amount["amount"]) / 10 ** self["asset"]["precision"] elif (amount and asset is None and isinstance(amount, dict) and "amount" in amount and "asset" in amount): self["asset"] = Asset(amount["asset"], dpay_instance=self.dpay) self["symbol"] = self["asset"]["symbol"] self["amount"] = int(amount["amount"]) / 10 ** self["asset"]["precision"] elif amount and asset and isinstance(asset, Asset): self["amount"] = amount self["symbol"] = asset["symbol"] self["asset"] = asset elif amount and asset and isinstance(asset, string_types): self["amount"] = amount self["asset"] = Asset(asset, dpay_instance=self.dpay) self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (integer_types, float)) and asset and isinstance(asset, Asset): self["amount"] = amount self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (integer_types, float)) and asset and isinstance(asset, dict): self["amount"] = amount self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (integer_types, float)) and asset and isinstance(asset, string_types): self["amount"] = amount self["asset"] = Asset(asset, dpay_instance=self.dpay) self["symbol"] = asset else: raise ValueError # make sure amount is a float self["amount"] = float(self["amount"])