def __init__(self, name_list, batch_limit=100, lazy=False, full=True, hive_instance=None): self.hive = hive_instance or shared_hive_instance() if not self.hive.is_connected(): return witnesses = [] name_cnt = 0 if self.hive.rpc.get_use_appbase(): while name_cnt < len(name_list): self.hive.rpc.set_next_node_on_empty_reply(False) witnesses += self.hive.rpc.find_witnesses( {'owners': name_list[name_cnt:batch_limit + name_cnt]}, api="database")["witnesses"] name_cnt += batch_limit else: for witness in name_list: witnesses.append(self.hive.rpc.get_witness_by_account(witness)) self.identifier = "" super(GetWitnesses, self).__init__([ Witness(x, lazy=lazy, full=full, hive_instance=self.hive) for x in witnesses ])
def __init__(self, account, lazy=False, full=True, hive_instance=None): self.hive = hive_instance or shared_hive_instance() self.account = Account(account, full=True, hive_instance=self.hive) account_name = self.account["name"] self.identifier = account_name self.hive.rpc.set_next_node_on_empty_reply(False) if self.hive.rpc.get_use_appbase(): if "witnesses_voted_for" not in self.account: return limit = self.account["witnesses_voted_for"] witnessess_dict = self.hive.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, hive_instance=self.hive) for x in witnessess ])
def __init__(self, hive_instance=None, *args, **kwargs): self.hive = hive_instance or shared_hive_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, from_account="", limit=100, lazy=False, full=False, hive_instance=None): self.hive = hive_instance or shared_hive_instance() self.identifier = from_account self.hive.rpc.set_next_node_on_empty_reply(False) if self.hive.rpc.get_use_appbase(): witnessess = self.hive.rpc.list_witnesses( { 'start': from_account, 'limit': limit, 'order': 'by_name' }, api="database")['witnesses'] else: witnessess = self.hive.rpc.lookup_witness_accounts( from_account, limit) if len(witnessess) == 0: return super(ListWitnesses, self).__init__([ Witness(x, lazy=lazy, full=full, hive_instance=self.hive) for x in witnessess ])
def setUpClass(cls): hv = shared_hive_instance() hv.config.refreshBackup() nodelist = NodeList() nodelist.update_nodes(hive_instance=Hive( node=nodelist.get_nodes(exclude_limited=False), num_retries=10)) cls.hv = Hive( node=nodelist.get_nodes(exclude_limited=True), 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.hv.set_default_account("test") set_shared_hive_instance(cls.hv) # self.hv.newWallet("TestingOneTwoThree") cls.wallet = Wallet(hive_instance=cls.hv) cls.wallet.wipe(True) cls.wallet.newWallet(pwd="TestingOneTwoThree") cls.wallet.unlock(pwd="TestingOneTwoThree") cls.wallet.addPrivateKey(wif)
def __init__( self, base=None, quote=None, hive_instance=None, ): """ Init Market :param bhive.hive.Hive hive_instance: Hive instance :param bhive.asset.Asset base: Base asset :param bhive.asset.Asset quote: Quote asset """ self.hive = hive_instance or shared_hive_instance() if quote is None and isinstance(base, str): quote_symbol, base_symbol = assets_from_string(base) quote = Asset(quote_symbol, hive_instance=self.hive) base = Asset(base_symbol, hive_instance=self.hive) super(Market, self).__init__({"base": base, "quote": quote}) elif base and quote: quote = Asset(quote, hive_instance=self.hive) base = Asset(base, hive_instance=self.hive) super(Market, self).__init__({"base": base, "quote": quote}) elif base is None and quote is None: quote = Asset("HBD", hive_instance=self.hive) base = Asset("HIVE", hive_instance=self.hive) super(Market, self).__init__({"base": base, "quote": quote}) else: raise ValueError("Unknown Market config")
def __init__(self, from_account=None, to_account=None, hive_instance=None): self.hive = hive_instance or shared_hive_instance() if to_account: self.to_account = Account(to_account, hive_instance=self.hive) if from_account: self.from_account = Account(from_account, hive_instance=self.hive)
def __init__(self, data, klass=None, space_id=1, object_id=None, lazy=False, use_cache=True, id_item=None, hive_instance=None, *args, **kwargs): self.hive = hive_instance or shared_hive_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, owner, full=False, lazy=False, hive_instance=None): self.full = full self.lazy = lazy self.hive = hive_instance or shared_hive_instance() if isinstance(owner, dict): owner = self._parse_json_data(owner) super(Witness, self).__init__(owner, lazy=lazy, full=full, id_item="owner", hive_instance=hive_instance)
def __init__(self, hive_instance=None, *args, **kwargs): self.hive = hive_instance or shared_hive_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["sc2_client_id"]) self.scope = kwargs.get("scope", "login") self.oauth_base_url = kwargs.get("oauth_base_url", config["oauth_base_url"]) self.sc2_api_url = kwargs.get("sc2_api_url", config["sc2_api_url"])
def __init__(self, tx={}, use_condenser_api=True, hive_instance=None, **kwargs): self.hive = hive_instance or shared_hive_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.hive.expiration))
def __init__( self, hive_instance=None, mode="irreversible", max_block_wait_repetition=None, data_refresh_time_seconds=900, ): self.hive = hive_instance or shared_hive_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.hive.get_block_interval()
def test_hive(self, node_param): if node_param == "instance": set_shared_hive_instance(self.bts) o = Hive(node=self.urls) o.get_config() self.assertIn(o.rpc.url, self.urls) with self.assertRaises(RPCConnection): hv = Hive(node="https://abc.d", autoconnect=False, num_retries=1) hv.get_config() else: set_shared_hive_instance( Hive(node="https://abc.d", autoconnect=False, num_retries=1)) hv = self.bts o = hv o.get_config() self.assertIn(o.rpc.url, self.urls) with self.assertRaises(RPCConnection): hv = shared_hive_instance() hv.get_config()
def tearDownClass(cls): hv = shared_hive_instance() hv.config.recover_with_latest_backup()
def __init__(self, message, hive_instance=None): self.hive = hive_instance or shared_hive_instance() self.message = message
def __init__(self, amount, asset=None, fixed_point_arithmetic=False, new_appbase_format=True, hive_instance=None): self["asset"] = {} self.new_appbase_format = new_appbase_format self.fixed_point_arithmetic = fixed_point_arithmetic self.hive = hive_instance or shared_hive_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"] = Decimal(amount[0]) / Decimal(10**amount[1]) self["asset"] = Asset(amount[2], hive_instance=self.hive) 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"] = Decimal(amount["amount"]) / Decimal( 10**amount["precision"]) self["asset"] = Asset(amount["nai"], hive_instance=self.hive) 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"], hive_instance=self.hive) 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"], hive_instance=self.hive) self["symbol"] = self["asset"]["symbol"] self["amount"] = Decimal(amount["amount"]) / Decimal( 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"], hive_instance=self.hive) self["symbol"] = self["asset"]["symbol"] self["amount"] = Decimal(amount["amount"]) / Decimal( 10**self["asset"]["precision"]) elif isinstance(amount, (float)) and asset and isinstance(asset, Asset): self["amount"] = str(amount) self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (integer_types, Decimal)) and asset and isinstance( asset, Asset): self["amount"] = amount self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (float)) and asset and isinstance(asset, dict): self["amount"] = str(amount) self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (integer_types, Decimal)) and asset and isinstance( asset, dict): self["amount"] = amount self["asset"] = asset self["symbol"] = self["asset"]["symbol"] elif isinstance(amount, (float)) and asset and isinstance(asset, string_types): self["amount"] = str(amount) self["asset"] = Asset(asset, hive_instance=self.hive) self["symbol"] = asset elif isinstance(amount, (integer_types, Decimal)) and asset and isinstance( asset, string_types): self["amount"] = amount self["asset"] = Asset(asset, hive_instance=self.hive) self["symbol"] = asset 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, hive_instance=self.hive) self["symbol"] = self["asset"]["symbol"] else: raise ValueError if self.fixed_point_arithmetic: self["amount"] = quantize(self["amount"], self["asset"]["precision"]) else: self["amount"] = Decimal(self["amount"])
def __init__(self, from_account="", limit=100, lazy=False, full=False, hive_instance=None): self.hive = hive_instance or shared_hive_instance() witnessList = [] last_limit = limit self.identifier = "" use_condenser = True self.hive.rpc.set_next_node_on_empty_reply(False) if self.hive.rpc.get_use_appbase() and not use_condenser: query_limit = 1000 else: query_limit = 100 if self.hive.rpc.get_use_appbase( ) and not use_condenser and from_account == "": last_account = None elif self.hive.rpc.get_use_appbase() and not use_condenser: last_account = Witness(from_account, hive_instance=self.hive)["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.hive.rpc.get_use_appbase(): last_account = witnessList[-1]["votes"] else: last_account = witnessList[-1]["owner"] if (last_limit < limit): last_limit += 1 if self.hive.rpc.get_use_appbase() and not use_condenser: witnessess = self.hive.rpc.list_witnesses( { 'start': [last_account], 'limit': last_limit, 'order': 'by_vote_name' }, api="database")['witnesses'] elif self.hive.rpc.get_use_appbase() and use_condenser: witnessess = self.hive.rpc.get_witnesses_by_vote(last_account, last_limit, api="condenser") else: witnessess = self.hive.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, hive_instance=self.hive)) if len(witnessList) == 0: return super(WitnessesRankedByVote, self).__init__(witnessList)
def test_config(self): set_shared_config({"node": self.urls}) set_shared_hive_instance(None) o = shared_hive_instance() self.assertIn(o.rpc.url, self.urls)
def __init__(self, lazy=False, full=True, hive_instance=None): self.hive = hive_instance or shared_hive_instance() self.lazy = lazy self.full = full self.refresh()
def __init__(self, account, account_history=[], hive_instance=None): self.hive = hive_instance or shared_hive_instance() self.account = Account(account, hive_instance=self.hive) self.reset() super(AccountSnapshot, self).__init__(account_history)
from bhive import Hive from bhive.instance import shared_hive_instance from bhive.market import Market from django import template register = template.Library() shared_hive_instance() m = Market() @register.simple_tag def usd_price(): value = m.steem_usd_implied() value = float('{0:.2f}'.format(value)) return value
def update_nodes(self, weights=None, hive_instance=None): """ Reads metadata from fullnodeupdate and recalculates the nodes score :param list/dict weight: can be used to weight the different benchmarks :type weight: list, dict .. code-block:: python from bhive.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) """ hive = hive_instance or shared_hive_instance() metadata = None account = None cnt = 0 while metadata is None and cnt < 5: cnt += 1 try: account = Account("fullnodeupdate", hive_instance=hive) metadata = json.loads(account["json_metadata"]) except: hive.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)