Ejemplo n.º 1
0
    def getWitnesses(self,
                     only_active=False,
                     lazy=False,
                     request_handler=None):
        #		from bitshares.witness import Witnesses
        #		return Witnesses(blockchain_instance=self.bts, lazy=lazy)
        rh = request_handler
        from bitshares.account import Account
        ids = self.bts.rpc.get_object("2.12.0").get(
            "current_shuffled_witnesses", [])
        witnesses = []
        seq, size = list(ids), 100
        sub_lists = [seq[i:i + size] for i in range(0, len(seq), size)]
        for ids in sub_lists:
            if rh and rh.cancelled:
                raise Cancelled()
            data = self.bts.rpc.get_objects(ids)
            for wit in data:
                witnesses.append(wit)

        from bitshares.witness import Witness
        accs = set()
        accmaps = {}
        ret = []
        for w in witnesses:
            if rh and rh.cancelled:
                raise Cancelled()
            wit = Witness(w, lazy=lazy, blockchain_instance=self.bts)
            if not wit["witness_account"] in accs:
                accs.add(wit["witness_account"])
                accmaps[wit["witness_account"]] = []
            accmaps[wit["witness_account"]].append(wit)
            ret.append(wit)
        seq, size = list(accs), 100
        sub_lists = [seq[i:i + size] for i in range(0, len(seq), size)]
        for idlist in sub_lists:
            if rh and rh.cancelled:
                raise Cancelled()
            data = self.bts.rpc.get_objects(idlist)
            for acc in data:
                for wit in accmaps[acc["id"]]:
                    wit._account = acc

        if only_active:
            account = Account("witness-account", blockchain_instance=self.bts)
            filter_by = [x[0] for x in account["active"]["account_auths"]]
            ret = list(filter(lambda x: x["witness_account"] in filter_by,
                              ret))

        return ret
Ejemplo n.º 2
0
def main():

    parser = argparse.ArgumentParser(description='', epilog='Report bugs to: ')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),
    parser.add_argument('-c',
                        '--config',
                        default='./config.yml',
                        help='specify custom path for config file')
    parser.add_argument('account')
    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.safe_load(ymlfile)

    bitshares = BitShares(node=conf['node_bts'], no_broadcast=True)
    w = Witness(args.account, bitshares_instance=bitshares)
    pprint(dict(w))
Ejemplo n.º 3
0
def find_witness(witness_name: hug.types.text, api_key: hug.types.text, request, hug_timer=5):
	"""Given a valid witness name, output witness data in JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'find_witness')

		try:
		  target_witness = Witness(witness_name)
		except:
		  # Market is not valid
		  return {'valid_witness': False,
				  'valid_key': True,
				  'took': float(hug_timer)}

		target_account = Account(target_witness['witness_account'], full=True)
		witness_account_data = extract_object(target_account)
		witness_role_data = extract_object(target_witness)

		active_witnesses = Blockchain().config()['active_witnesses']

		if witness_role_data['id'] in active_witnesses:
			witness_status = True
		else:
			witness_status = False

		return {'witness_role_data': witness_role_data,
				'witness_account_data': witness_account_data,
				'active_witness': witness_status,
				'valid_witness': True,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
Ejemplo n.º 4
0
 def _loadchaindata(self):
     for symbol in self.config.get("assets"):
         asset = Asset(symbol, full=True)
         self.data["asset"][symbol] = asset
         self.data["feed"][symbol] = asset.feeds
     for witness_name in self.witnesses:
         witness = Witness(witness_name)
         self.data["witness"][witness_name] = witness
         self.data["account"][witness_name] = witness.account
Ejemplo n.º 5
0
def check_witness():
    global currentmisses
    status = Witness(witness, bitshares_instance=bitshares)
    missed = status['total_missed']
    print(str(loopcounter) + ": Missed blocks = " + str(missed))
    if missed > currentmisses:
        # Could create the witness_update transaction and broadcast new signing key here to switch from main to backup
        # For now this script only alerts on telegram...
        alert_witness("You are missing blocks! Your current misses count = " +
                      str(missed) + ", which was " + str(currentmisses))
        currentmisses = missed
Ejemplo n.º 6
0
def check_witness():
    global currentmisses
    global startmisses
    status = Witness(witness ,bitshares_instance=bitshares)
    missed = status['total_missed']
    print(str(loopcounter)+ ": Missed blocks = " + str(missed))
    if startmisses == -1:
        startmisses = missed
    if missed > currentmisses:
    # Could create the witness_update transaction and broadcast new signing key here to switch from main to backup
    # For now this script only alerts on telegram...
        alert_witness("You are missing blocks! Your current misses count = "+str(missed)+", which was "+str(currentmisses))
        currentmisses = missed
        if (currentmisses - startmisses) == tresholdwitnessflip:
            # we have the amount of misses compared to our treshold.... lets flip witnesses to backup.
            bitshares.wallet.unlock(walletpwd)
            bitshares.update_witness(witness,url=witnessurl,key=backupsigningkey)
            alert_witness("If all went well we now switched to backupsigningkey - check https://llc.is/#/accounts/ratamahatta")
Ejemplo n.º 7
0
def updatewitness(account, reward_percent):
    GRAPHENE_1_PERCENT = 100

    witness = Witness(account)
    account = witness.account
    op = operations.Witness_update(
        **{
            "fee": {
                "amount": 0,
                "asset_id": "1.3.0"
            },
            "prefix": blockchain.prefix,
            "witness": witness["id"],
            "witness_account": account["id"],
            "block_producer_reward_pct": int(reward_percent) *
            GRAPHENE_1_PERCENT
        })
    return blockchain.finalizeOp(op, account["name"], "active")
Ejemplo n.º 8
0
def check_witness():
    global current_misses
    global start_misses
    status = Witness(witness ,bitshares_instance=bitshares)
    missed = status['total_missed']
    print(str(loop_counter) + ": Missed blocks = " + str(missed))
    if start_misses == -1:
        start_misses = missed
    if missed > current_misses:
    # Could create the witness_update transaction and broadcast new signing key here to switch from main to backup
    # For now this script only alerts on telegram...
        alert_witness("You are missing blocks! Your current misses count = " + str(missed) +", which was " + str(current_misses))
        current_misses = missed
        if (current_misses - start_misses) == threshold_witness_flip:
            # we have the amount of misses compared to our threshold.... lets flip witnesses to backup.
            # NOTICE:you must flip it back by your own
            bitshares.wallet.unlock(wallet_pwd)
            bitshares.update_witness(witness, url=witness_url, key=backup_signing_key)
            alert_witness("If all went well we now switched to backup signing key - check https://cryptofresh.com/user/roelandp")
Ejemplo n.º 9
0
def feeds(ctx, assets, pricethreshold, maxage):
    """ Price Feed Overview
    """
    import builtins
    witnesses = Witnesses(bitshares_instance=ctx.bitshares)

    def test_price(p, ref):
        if (math.fabs(float(p / ref) - 1.0) > pricethreshold / 100.0):
            return click.style(str(p), fg="red")
        elif (math.fabs(float(p / ref) - 1.0) > pricethreshold / 2.0 / 100.0):
            return click.style(str(p), fg="yellow")
        else:
            return click.style(str(p), fg="green")

    def test_date(d):
        now = datetime.utcnow()
        if now < d + timedelta(minutes=maxage):
            return click.style(str(d), fg="green")
        if now < d + timedelta(minutes=maxage / 2.0):
            return click.style(str(d), fg="yellow")
        else:
            return click.style(str(d), fg="red")

    output = ""
    for asset in tqdm(assets):
        t = PrettyTable([
            "Asset",
            "Producer",
            "Active Witness",
            "Date",
            "Settlement Price",
            "Core Exchange Price",
            "MCR",
            "SSPR"
        ])
        t.align = 'c'
        t.align["Producer"] = 'l'
        asset = Asset(asset, full=True, bitshares_instance=ctx.bitshares)
        current_feed = asset.feed
        feeds = asset.feeds
        producingwitnesses = builtins.set()
        witness_accounts = [
            x["witness_account"] for x in witnesses
        ]
        for feed in tqdm(feeds):
            producingwitnesses.add(feed["producer"]["id"])
            t.add_row([
                asset["symbol"],
                feed["producer"]["name"],
                click.style(
                    "X" if feed["producer"]["id"] in witness_accounts else "",
                    bold=True),
                test_date(feed["date"]),
                test_price(feed["settlement_price"], current_feed["settlement_price"]),
                test_price(feed["core_exchange_rate"], current_feed["core_exchange_rate"]),
                feed["maintenance_collateral_ratio"] / 10,
                feed["maximum_short_squeeze_ratio"] / 10,
            ])
        for missing in (builtins.set(witness_accounts).difference(producingwitnesses)):
            witness = Witness(missing)
            t.add_row([
                click.style(asset["symbol"], bg="red"),
                click.style(witness.account["name"], bg="red"),
                click.style(
                    "X" if feed["producer"]["id"] in witness_accounts else "",
                    bold=True),
                click.style(str(datetime(1970, 1, 1))),
                click.style("missing", bg="red"),
                click.style("missing", bg="red"),
                click.style("missing", bg="red"),
                click.style("missing", bg="red"),
            ])
        output += t.get_string(sortby="Date", reversesort=True)
        output += "\n"
    click.echo(output)
Ejemplo n.º 10
0
def main(ctx, account):
    """Show witness object."""

    witness = Witness(account, bitshares_instance=ctx.bitshares)
    pprint(dict(witness))
Ejemplo n.º 11
0
def get_hertz_value(api_key: hug.types.text, request, hug_timer=15):
	"""Retrieve reference Hertz feed price value in JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		google_analytics(request, 'get_hertz_value')

		# Getting the value of USD in BTS
		market = Market("USD:BTS") # Set reference market to USD:BTS
		price = market.ticker()["quoteSettlement_price"] # Get Settlement price of USD
		price.invert() # Switching from quantity of BTS per USD to USD price of one BTS.

		hertz_reference_timestamp = "2015-10-13T14:12:24+00:00" # Bitshares 2.0 genesis block timestamp
		hertz_current_timestamp = pendulum.now().timestamp() # Current timestamp for reference within the hertz script
		hertz_amplitude = 0.14 # 14% fluctuating the price feed $+-0.14 (1% per day)
		hertz_period_days = 28 # Aka wavelength, time for one full SIN wave cycle.
		hertz_phase_days = 0.908056 # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day.
		hertz_reference_asset_value = 1.00 # $1.00 USD, not much point changing as the ratio will be the same.

		hertz_value = get_hertz_feed(hertz_reference_timestamp, hertz_current_timestamp, hertz_period_days, hertz_phase_days, hertz_reference_asset_value, hertz_amplitude)
		hertz = Price(hertz_value, "USD/HERTZ") # Limit the hertz_usd decimal places & convert from float.

		# Calculate HERTZ price in BTS (THIS IS WHAT YOU PUBLISH!)
		hertz_bts = price.as_base("BTS") * hertz.as_quote("HERTZ")

		unofficial_data = {'hertz_price_in_usd': hertz['price'],
						   'hertz_price_in_bts': hertz_bts['price'],
						   'core_exchange_rate': hertz_bts['price']*0.80,
						   'usd_price_in_bts': 1/price['price'],
						   'bts_price_in_usd': price['price']}
		########

		try:
		  target_asset = Asset("HERTZ", full=True)
		except:
		  return {'valid_asset': False,
				  'valid_key': True,
				  'took': float(hug_timer)}

		try:
		  bitasset_data = target_asset['bitasset_data_id']
		except:
		  bitasset_data = None

		extracted_object = extract_object(target_asset)

		bitasset_data = extracted_object['bitasset_data']
		current_feeds = bitasset_data['current_feed']
		current_feed_settlement_price = current_feeds['settlement_price']
		current_feed_cer = current_feeds['core_exchange_rate']

		if (int(current_feed_settlement_price['base']['amount']) > 0 and int(current_feed_settlement_price['quote']['amount']) > 0):
			current_feed_settlement_price['api_calculated_rate'] = int(current_feed_settlement_price['quote']['amount'])/int(current_feed_settlement_price['base']['amount'])
		else:
			current_feed_settlement_price['api_calculated_rate'] = 0

		if (int(current_feed_cer['base']['amount']) > 0 and int(current_feed_cer['quote']['amount']) > 0):
			current_feed_cer['api_calculated_rate'] = int(current_feed_cer['quote']['amount'])/int(current_feed_cer['base']['amount'])
		else:
			current_feed_cer['api_calculated_rate'] = 0

		witness_feeds = bitasset_data['feeds']
		witness_feed_data = {}
		witness_iterator = 0

		for witness_feed in witness_feeds:
			# Extract that data!
			witness_id = witness_feed[0]
			witness_iterator += 1

			try:
			  target_account = Account(str(witness_id))
			except:
			  print("Witness account doesn't work?!")

			extracted_object = extract_object(target_account)

			witness_name = extracted_object['name']
			publish_timestamp = witness_feed[1][0]
			feed_data = witness_feed[1][1]
			settlement_price = feed_data['settlement_price']

			if (int(settlement_price['quote']['amount']) > 0):
				maintenance_collateral_ratio = feed_data['maintenance_collateral_ratio']
				maximum_short_squeeze_ratio = feed_data['maximum_short_squeeze_ratio']
				core_exchange_rate = feed_data['core_exchange_rate']

				settlement_price_before = int(settlement_price['quote']['amount'])/int(settlement_price['base']['amount'])
				core_exchange_rate_before = int(core_exchange_rate['quote']['amount'])/(int(core_exchange_rate['base']['amount']))

				settlement_price['api_calculated_rate'] = settlement_price_before / 10
				core_exchange_rate['api_calculated_rate'] = core_exchange_rate_before / 10

				try:
					target_witness = Witness(witness_name)
				except:
					target_witness = None

				if (target_witness is not None):
					witness_role_data = extract_object(target_witness)
					witness_identity = witness_role_data['id']
					witness_url = witness_role_data['url']
					witness_feed_data[str(witness_iterator)] = {'witness_account_id': witness_id,
											  'witness_name': witness_name,
											  'witness_id': witness_identity,
											  'witness_url': witness_url,
											  'publish_timestamp': publish_timestamp,
											  'settlement_price': settlement_price,
											  'maintenance_collateral_ratio': maintenance_collateral_ratio,
											  'maximum_short_squeeze_ratio': maximum_short_squeeze_ratio,
											  'core_exchange_rate': core_exchange_rate}
				else:
					witness_feed_data[str(witness_iterator)] = {'witness_account_id': witness_id,
											  'witness_name': witness_name,
											  'witness_id': "N/A",
											  'witness_url': "#",
											  'publish_timestamp': publish_timestamp,
											  'settlement_price': settlement_price,
											  'maintenance_collateral_ratio': maintenance_collateral_ratio,
											  'maximum_short_squeeze_ratio': maximum_short_squeeze_ratio,
											  'core_exchange_rate': core_exchange_rate}
			else:
				continue

		return {'unofficial_reference': unofficial_data,
				'witness_feeds': witness_feed_data,
				'current_feeds': current_feeds,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
def checkWitness():
    # Define and initialize the "static" variables we need to persist
    global startMisses, nextIdx, previousMisses, loopCounter, counterOnLastMiss

    status = Witness(ACNT)
    missed = status['total_missed']
    currentKey = status['signing_key']

    # Monitoring a fresh witness, so reset all "static" variables
    if startMisses == -1:
        startMisses = previousMisses = missed
        counterOnLastMiss = loopCounter = 0
        keyCount = len(WITNESS_KEYS)
        for k in range(keyCount):
            if currentKey == WITNESS_KEYS[k]:
                nextIdx = (k + 1) % keyCount

    print("\r%d samples, missed=%d(%d), key=%.16s..." %
          (loopCounter, missed, counterOnLastMiss, currentKey),
          end='')

    if missed > previousMisses:
        if previousMisses != -1:  # Switch failure?
            counterOnLastMiss = loopCounter  # No.
            delta = previousMisses - startMisses
            previousMisses = missed
            msg = "Missed another block! (delta=%d)" % delta
            print("\n", msg)
            logging.info(msg)
        else:
            msg = "Rebroadcasting switch to (%s)..." % key
            print("\n", msg)
            logging.info(msg)

        if delta >= FLIP:
            key = WITNESS_KEYS[nextIdx]
            if previousMisses != -1:
                msg = "Time to switch! (next key: %s)" % key
                print("\n", msg)
                logging.info(msg)
            # Flip witness to a backup
            API.wallet.unlock(PASS)
            API.update_witness(ACNT, url=WURL, key=key)
            time.sleep(9)  # Wait 3 block times before trying to confirm switch

            if Witness(ACNT)['signing_key'] == key:
                msg = "Witness updated. Now using " + key
                print("\n", msg)
                logging.info(msg)
                startMisses = -1  # Starting fresh, reset all counters
            else:
                msg = "Signing key did not change! Will try again in "
                msg += str(FREQ) + " seconds"
                previousMisses = -1  # This will flag a retry
                print("\n", msg)
                logging.info(msg)
    else:
        # If we haven’t missed any for awhile reset the counters
        if loopCounter - counterOnLastMiss >= RSET:
            startMisses = -1

    loopCounter += 1
Ejemplo n.º 13
0
 def get_witness_ids(self, name):
     """ returns witness id and witness account ids from a username  """
     w = Witness(name, bitshares_instance=self.bts)
     return w['id'], w.account['id']