예제 #1
0
def ping(n, num, arr):  # ping the blockchain and return latency

    try:
        start = time.time()
        chain = Blockchain(bitshares_instance=BitShares(n, num_retries=0),
                           mode='head')

        # print(n,chain.rpc.chain_params["chain_id"])
        ping_latency = time.time() - start
        current_block = chain.get_current_block_num()
        blocktimestamp = abs(
            chain.block_timestamp(current_block))  # + utc_offset)
        block_latency = time.time() - blocktimestamp
        # print (blocktimestamp)
        # print (time.time())
        # print (block_latency)
        # print (ping_latency)
        # print (time.ctime())
        # print (utc_offset)
        # print (chain.get_network())
        if chain.get_network()['chain_id'] != ID:
            num.value = 333333
        elif block_latency < (ping_latency + 4):
            num.value = ping_latency
        else:
            num.value = 111111
    except:
        num.value = 222222
        pass
예제 #2
0
    def recent_block_creation(self, witness_id):
        """ returns True if witness id is in the N last blocks created """
        btschain = Blockchain()
        block_created = False

        srt = None
        if self.witnesses and self.block_interval:
            srt = self.witnesses * self.block_interval
        else:
            srt = self.get_shuffle_round_time()

        currblock = btschain.get_current_block_num()
        startblock = srt * self.shuffle_rounds_alert

        c = (
            '{{"jsonrpc": "2.0", "params": ["database", "get_block_header_batch", '
            '[[{}]]], "method": "call", "id": 10}}'.format(",".join(
                str(x) for x in range(currblock - startblock, currblock))))

        r = btsconf.confs["bts"].rpc.rpcexec(loads(c))

        for bl in r:
            if bl[1] and bl[1]['witness'] == witness_id:
                block_created = True

        return block_created
예제 #3
0
def run(begin=None, end=None):

    blockchain = Blockchain(
        mode="head",
        bitshares_instance=bitshares
    )

    for op in blockchain.stream(
        opNames=["account_create"],
        start=int(begin) if begin else None,
        stop=int(end) if end else None,
    ):
        blockid = op.get("block_num")
        timestamp = op.get("timestamp")

        if not blockid % 100:
            print("Blockid: %d (%s)" % (blockid, timestamp), flush=True)

        try:
            pprint(bitshares.transfer(
                op["name"],
                config["donation_amount"], config["donation_asset"],
                account=config["registrar"]
            ))
        except Exception as e:
            log.error(str(e))
            pass
예제 #4
0
def get_latest_block(api_key: hug.types.text, request, hug_timer=5):
	"""Retrieve the latest block's details (date & time) & output in JSON!"""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'get_latest_block')

		chain = Blockchain()
		current_block_number = chain.get_current_block_num()
		block_date = chain.block_time(current_block_number)

		target_block = Block(current_block_number)

		return {'previous': target_block['previous'],
				'timestamp': target_block['timestamp'],
				'witness': target_block['witness'],
				'transaction_merkle_root': target_block['transaction_merkle_root'],
				'extensions': target_block['extensions'],
				'witness_signature': target_block['witness_signature'],
				'transactions': target_block['transactions'],
				'id': target_block['id'],
				'block_date': block_date,
				'block_number': current_block_number,
				'valid_block_number': True,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
예제 #5
0
def reconnect(BitPAIR, USERNAME, PASS_PHRASE):

    # create fresh websocket connection
    connected = 0
    while not connected:
        # fetch fresh nodes list from subprocess and shuffle it
        nds = race_read('nodes.txt')
        if isinstance(nds, list):
            nodes = nds
        shuffle(nodes)
        node = nodes[0]
        try:
            account = Account(USERNAME,
                              bitshares_instance=BitShares(node,
                                                           num_retries=0))
            market = Market(BitPAIR,
                            bitshares_instance=BitShares(node,
                                                         num_retries=0),
                            mode='head')
            chain = Blockchain(
                bitshares_instance=BitShares(node, num_retries=0), mode='head')
            if chain.get_network()['chain_id'] != ID:
                raise ValueError('Not Mainnet Chain')
            connected = 1
        except:
            pass
    try:
        market.bitshares.wallet.unlock(PASS_PHRASE)
    except:
        pass
    return account, market, nodes, chain
예제 #6
0
파일: info.py 프로젝트: kjmeta1/uptick
def fees(ctx, currency):
    """ List fees
    """
    from bitsharesbase.operationids import getOperationNameForId
    from bitshares.market import Market

    market = Market("%s:%s" % (currency, "BTS"))
    ticker = market.ticker()
    if "quoteSettlement_price" in ticker:
        price = ticker.get("quoteSettlement_price")
    else:
        price = ticker.get("latest", 0)
    price.invert()

    chain = Blockchain(bitshares_instance=ctx.bitshares)
    feesObj = chain.chainParameters().get("current_fees")
    fees = feesObj["parameters"]

    t = [["Operation", "Type", "Fee", currency]]

    for fee in fees:
        for f in fee[1]:
            data = [
                highlight(getOperationNameForId(fee[0])),
                detail(f),
                detail(Amount({"amount": fee[1].get(f, 0), "asset_id": "1.3.0"})),
                detail(
                    price * Amount({"amount": fee[1].get(f, 0), "asset_id": "1.3.0"})
                ),
            ]
            t.append(data)
    print_table(t)
예제 #7
0
def blockchain_listener():
    """
	Execute forever listening blockchain operations
	:return:
	"""
    from bitshares.blockchain import Blockchain
    chain = Blockchain()
    for block in chain.blocks():
        #print("listenet:", block)
        Redisdb.rpush("bitshares_op", pickle.dumps(block))
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
        )
        self.bts.set_default_account("init0")
        set_shared_bitshares_instance(self.bts)
        self.chain = Blockchain(mode="head")
    def __init__(self):
        """ Initializes the History object. This method will be executed whenever
        we call an instance of the class."""
        self.chain = Blockchain(mode='head')
        current_block_num = self.chain.get_current_block_num()

        # The upper bound block number
        self.upper = current_block_num

        # The lower bound block number
        self.lower = 1
예제 #10
0
def reconnect():

    global account, market, nodes, chain, pings
    try:
        history_text.delete("1.0", "end")
        history_text.insert(END, '\n\n CONNECTING...')
        master.update()
    except:
        pass
    print(cyan(time.ctime() + ' CONNECTING...'))
    start = time.time()

    # create fresh websocket connection
    connected = 0
    while not connected:
        # fetch fresh nodes list from subprocess and shuffle it
        metaNODE = Bitshares_Trustless_Client()
        nds = metaNODE['whitelist']
        del metaNODE
        if isinstance(nds, list):
            nodes = nds
        shuffle(nodes)
        node = nodes[0]
        print(green(node))
        pings = [0]
        try:
            account = Account(USERNAME,
                              bitshares_instance=BitShares(nodes,
                                                           num_retries=2))
            market = Market(BitPAIR,
                            bitshares_instance=BitShares(nodes, num_retries=2),
                            mode='head')
            chain = Blockchain(bitshares_instance=BitShares(nodes,
                                                            num_retries=2),
                               mode='head')
            if chain.get_network()['chain_id'] != ID:
                raise ValueError('Not Mainnet Chain')
            connected = 1
        except Exception as e:
            try:
                history_text.insert(END, '\n\n RECONNECTING...')
                master.update()
            except:
                pass
            msg = (time.ctime() + str(type(e).__name__) + str(e.args))
            print('RECONNECTING ' + msg)
            pass
    try:
        market.bitshares.wallet.unlock(PASS_PHRASE)
    except:
        # print('YOUR WALLET IS LOCKED')
        pass
    print('CONNECTION ELAPSED: ', ('%.1f' % (time.time() - start)))
def play_game(account, amountBet, userRoll):

    memo = Memo('bts-dice-game', account)

    nodeForConnections = 'wss://api.bitsharesdex.com'

    blockchain = Blockchain(node=nodeForConnections, mode='head')

    bitshares = BitShares(
        node=nodeForConnections,
        nobroadcast=False,
    )

    blockNum = blockchain.get_current_block_num()

    userGuess = userRoll
    seed(blockNum * (userGuess + 1))

    diceRatios = btsDiceRatios
    winRatio = diceRatios.get_ratio(userGuess)

    value = randint(1, 100)
    correctGuess = value < int(userGuess)

    bitshares.wallet.unlock('superSecretPassword')

    if winRatio is None:
        print('You submitted something not correct to this contract.')
    elif correctGuess:
        winningAmount = winRatio * amountBet
        winningString = "Correct! You guessed {0} and rolled {1}. You won {2:.5f} BTS.".format(
            userRoll, value, winningAmount)
        bitshares.transfer(account,
                           winningAmount,
                           'BTS',
                           winningString,
                           account='bts-dice-game')
        print(winningString)
    else:
        losingString = "Incorrect. You guessed {0} and rolled {1}.".format(
            userRoll, value)
        bitshares.transfer(account,
                           0.00001,
                           'BTS',
                           losingString,
                           account='bts-dice-game')
        print(
            'You guessed incorrectly. Your guess was {a} and you rolled {b}.'.
            format(a=userRoll, b=value))
예제 #12
0
def get_info(api_key: hug.types.text, hug_timer=5):
    """Bitshares current chain info!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        chain = Blockchain()
        chain_info = chain.info()

        return {
            'chain_info': chain_info,
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
예제 #13
0
def get_network(api_key: hug.types.text, request, hug_timer=5):
	"""Bitshares current chain network!"""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'get_network')
		chain = Blockchain()
		chain_get_network = chain.get_network()

		return {'get_network': chain_get_network,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
예제 #14
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)}
예제 #15
0
def list_of_witnesses(api_key: hug.types.text, request, hug_timer=5):
	"""Output the list of active witnesses in JSON."""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'list_of_witnesses')

		list_of_witnesses = Witnesses()

		witness_data = []
		for witness in list_of_witnesses:
			target_account = Account(witness['witness_account'])
			witness_account_data = extract_object(target_account)
			witness_role_data = extract_object(witness)

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

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

			witness_data.append({'witness_role_data': witness_role_data,
								 'witness_account_data': witness_account_data,
								 'witness_status': witness_status})

		return {'witnesses': witness_data,
				'witness_count': len(list_of_witnesses),
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
 def ping(n, num, arr):
     try:
         start = time.time()
         chain = Blockchain(bitshares_instance=BitShares(n, num_retries=0),
                            mode='head')
         ping_latency = time.time() - start
         current_block = chain.get_current_block_num()
         blocktimestamp = abs(
             chain.block_timestamp(current_block) + utc_offset)
         block_latency = time.time() - blocktimestamp
         if block_latency < (ping_latency + 4):
             num.value = ping_latency
         else:
             num.value = 111111
     except:
         num.value = 222222
         pass
예제 #17
0
def chain_info(api_key: hug.types.text, request, hug_timer=5):
	"""Bitshares current chain information!"""
	if (check_api_token(api_key) == True): # Check the api key
		# API KEY VALID
		google_analytics(request, 'chain_info')
		chain = Blockchain()
		chain_info = chain.info()

		extracted_object = extract_object(chain_info)

		return {'chain_info': extracted_object,
				'valid_key': True,
				'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
예제 #18
0
def get_committee_member(committee_id: hug.types.text,
                         api_key: hug.types.text,
                         hug_timer=15):
    """Retrieve information about a single committee member (inc full account details)!"""
    if (check_api_token(api_key) == True):  # Check the api key
        if ("1.5." not in committee_id):
            return {
                'valid_committee_id': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        try:
            target_committee_member = bitshares_api_node.rpc.get_objects(
                [committee_id])[0]
        except:
            return {
                'valid_committee_id': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        if target_committee_member is None:
            return {
                'valid_committee_id': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        target_account = Account(
            target_committee_member['committee_member_account'],
            full=True)  # Full info!
        target_account_data = extract_object(target_account)

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

        if committee_id in active_committee_members:
            target_account_data['status'] = True
        else:
            target_account_data['status'] = False

        target_committee_member[
            'committee_member_details'] = target_account_data

        return {
            'get_committee_member': target_committee_member,
            'valid_committee_id': True,
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
def get_all_accounts(api_key: hug.types.text, hug_timer=5):
    """Retrieve all Bitshares account names. Takes a while!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        chain = Blockchain()
        chain_get_all_accounts = chain.get_all_accounts()

        list_of_accounts = []

        for account in chain_get_all_accounts:
            list_of_accounts.append(account)

        return {
            'accounts': list_of_accounts,
            'num_accounts': len(list_of_accounts),
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
예제 #20
0
def get_all_account_balances(api_key: hug.types.text, hug_timer=60):
    """Retrieve all Bitshares account names & balances.
       WARNING: This may take hours to complete! """
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        chain = Blockchain()
        chain_get_all_accounts = chain.get_all_accounts()

        list_of_accounts = []

        for account in chain_get_all_accounts:
            target_account_balances = Account(account).balances
            if (len(target_account_balances) > 0):
                balance_json_list = []
                for balance in target_account_balances:
                    current_balance_target = Amount(balance)
                    balance_json_list.append({
                        current_balance_target.symbol:
                        current_balance_target.amount
                    })

                list_of_accounts.append({
                    'account_name': account,
                    'balances': balance_json_list
                })
            else:
                list_of_accounts.append({
                    'account_name': account,
                    'balances': []
                })

        return {
            'accounts': list_of_accounts,
            'num_accounts': len(list_of_accounts),
            'valid_key': True,
            'took': float(hug_timer)
        }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
예제 #21
0
def run():
    socketio = SocketIO(message_queue='redis://')
    bitshares = BitShares(node="wss://this.uptick.rocks/")
    chain = Blockchain(mode="head", bitshares_instance=bitshares)
    print(chain.bitshares.rpc.url)
    for block in chain.blocks():
        timestamp = int(datetime.strptime(block["timestamp"], '%Y-%m-%dT%H:%M:%S').timestamp())
        num_ops = sum([len(tx["operations"]) for tx in block["transactions"]])
        num_txs = len(block["transactions"])
        BTSBlock(timestamp, block.get("block_num", None), num_txs, num_ops)
        notice = {
            "block": block.get("block_num", 0),
            "timestamp": timestamp,
            "num_transactions": num_txs,
            "num_operations": num_ops,
        }
        print(notice)
        socketio.emit(
            'notice',
            notice,
            namespace=namespace,
            room=room,
            broadcast=True)
def run():
    socketio = SocketIO(message_queue='redis://')
    testnet = BitShares(node="wss://node.testnet.bitshares.eu")
    chain = Blockchain(mode="head", bitshares_instance=testnet)
    print(chain.bitshares.rpc.url, flush=True)
    for block in chain.blocks():
        timestamp = int(datetime.strptime(block["timestamp"], '%Y-%m-%dT%H:%M:%S').timestamp())
        num_ops = sum([len(tx["operations"]) for tx in block["transactions"]])
        num_txs = len(block["transactions"])
        TestBlock(timestamp, block.get("block_num", None), num_txs, num_ops)
        notice = {
            "block": block.get("block_num", 0),
            "timestamp": timestamp,
            "num_transactions": num_txs,
            "num_operations": num_ops,
        }
        print(notice, flush=True)
        socketio.emit(
            'notice',
            notice,
            namespace=namespace,
            room=room,
            broadcast=True)
예제 #23
0
파일: info.py 프로젝트: pluswave/uptick
def fees(ctx, currency):
    """ List fees
    """
    from bitsharesbase.operationids import getOperationNameForId
    from bitshares.market import Market

    market = Market("%s:%s" % (currency, "BTS"))
    ticker = market.ticker()
    if "quoteSettlement_price" in ticker:
        price = ticker.get("quoteSettlement_price")
    else:
        price = ticker.get("latest", 0)

    chain = Blockchain(bitshares_instance=ctx.bitshares)
    feesObj = chain.chainParameters().get("current_fees")
    scale = feesObj["scale"]
    fees = feesObj["parameters"]

    t = PrettyTable(["Operation", "Type", "Fee", currency])
    t.align = "l"
    t.align["Fee"] = "r"
    t.align[currency] = "r"

    for fee in fees:
        for f in fee[1]:
            t.add_row([
                getOperationNameForId(fee[0]), f,
                str(Amount({
                    "amount": fee[1].get(f, 0),
                    "asset_id": "1.3.0"
                })),
                str(price * Amount({
                    "amount": fee[1].get(f, 0),
                    "asset_id": "1.3.0"
                }))
            ])
    click.echo(t)
예제 #24
0
def get_block_details(block_number: hug.types.number,
                      api_key: hug.types.text,
                      hug_timer=5):
    """Retrieve a specific block's details (date & time) & output in JSON!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        try:
            target_block = Block(block_number)
        except:
            return {
                'valid_block_number': False,
                'valid_key': True,
                'took': float(hug_timer)
            }

        chain = Blockchain()
        block_date = chain.block_time(block_number)

        return {
            'previous': target_block['previous'],
            'timestamp': target_block['timestamp'],
            'witness': target_block['witness'],
            'transaction_merkle_root': target_block['transaction_merkle_root'],
            'extensions': target_block['extensions'],
            'witness_signature': target_block['witness_signature'],
            'transactions': target_block['transactions'],
            'id': target_block['id'],
            'date': block_date,
            'block_number': block_number,
            'valid_block_number': True,
            'valid_key': True,
            'took': float(hug_timer)
        }

    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
예제 #25
0
def run(begin=None, end=None):

    blockchain = Blockchain(mode="head", bitshares_instance=bitshares)

    for op in blockchain.stream(
            opNames=["account_create"],
            start=int(begin) if begin else None,
            stop=int(end) if end else None,
    ):
        blockid = op.get("block_num")
        timestamp = op.get("timestamp")

        if not blockid % 100:
            print("Blockid: %d (%s)" % (blockid, timestamp), flush=True)

        try:
            pprint(
                bitshares.transfer(op["name"],
                                   config["donation_amount"],
                                   config["donation_asset"],
                                   account=config["registrar"]))
        except Exception as e:
            log.error(str(e))
            pass
예제 #26
0
    def handle(self, *args, **options):
        for op in Blockchain().stream(['transfer'], start=START_BLOCK):
            block_num = op['block_num']
            cache.set('START_BLOCK', block_num + 1)

            if op['to'] != GATEWAY_ACCOUNT_ID:
                continue

            transfer = parse_transfer(op)

            if transfer.is_valid_memo:
                try:
                    eos_issue(transfer)
                except Exception:
                    logger.exception('Error emit tokens')
                    client.captureException()

            transfer.save()
예제 #27
0
def get_committee_members(api_key: hug.types.text, hug_timer=15):
    """Get a list of all committee members!"""
    if (check_api_token(api_key) == True):  # Check the api key
        # API KEY VALID
        num_committee_members_request = request_json(
            '{"jsonrpc": "2.0", "method": "get_committee_count", "params": [], "id": 1}'
        )

        if num_committee_members_request.status_code is not 200:
            # We want to catch any failed GET requests!
            return {
                'request_status_code_error': True,
                'valid_key': True,
                'took': float(hug_timer)
            }
        else:
            # Request was successful
            active_committee_members = Blockchain().config(
            )['active_committee_members']

            num_committee_members = num_committee_members_request.json(
            )['result']

            committee_member_list = []
            for member in range(num_committee_members):
                committee_id = "1.5." + str(member)
                current_committee_member = bitshares_api_node.rpc.get_objects(
                    [committee_id])[0]

                if committee_id in active_committee_members:
                    current_committee_member['status'] = True
                else:
                    current_committee_member['status'] = False

                committee_member_list.append(current_committee_member)

            return {
                'committee_members': committee_member_list,
                'valid_key': True,
                'took': float(hug_timer)
            }
    else:
        # API KEY INVALID!
        return {'valid_key': False, 'took': float(hug_timer)}
예제 #28
0
def get_committee_members(api_key: hug.types.text, request, hug_timer=15):
	"""Get a list of all committee members!"""
	if (check_api_token(api_key) == True): # Check the api key
		google_analytics(request, 'get_committee_members')
		# API KEY VALID
		num_committee_members_request = request_json('{"jsonrpc": "2.0", "method": "get_committee_count", "params": [], "id": 1}')

		if num_committee_members_request.status_code is not 200:
			# We want to catch any failed GET requests!
			return {'request_status_code_error': True,
				  'valid_key': True,
				  'took': float(hug_timer)}
		else:
			# Request was successful
			active_committee_members = Blockchain().config()['active_committee_members']

			num_committee_members = num_committee_members_request.json()['result']

			committee_member_list = []
			for member in range(num_committee_members):
				committee_id = "1.5." + str(member)
				current_committee_member = bitshares_api_node.rpc.get_objects([committee_id])[0]

				if committee_id in active_committee_members:
					current_committee_member['status'] = True
					# The following needs to be cached, it takes far too long to query even just 11 account names..
					#target_account = Account(current_committee_member['committee_member_account'])
					#target_account_data = extract_object(target_account)
					#current_committee_member['name'] = target_account_data['name']
				else:
					current_committee_member['status'] = False

				committee_member_list.append(current_committee_member)

			return {'committee_members': committee_member_list,
					'valid_key': True,
					'took': float(hug_timer)}
	else:
	# API KEY INVALID!
		return {'valid_key': False,
				'took': float(hug_timer)}
예제 #29
0
 def generate_history(self, pool):
     return_data = {}
     op_list = {}
     payload = {
         "id":
         1,
         "method":
         "call",
         "params": [
             "history", "get_liquidity_pool_history",
             [pool, formatTimeFromNow(0), None, 100, 63]
         ]
     }
     self._set_ws_connection()
     self.ws.send(json.dumps(payload))
     result = self.ws.recv()
     r = json.loads(result)
     if r['result']:
         for i in r['result']:
             if not i['sequence'] in op_list.keys():
                 op_list[i['sequence']] = i
     sort_order = sorted(op_list, reverse=True)
     return_data['history'] = []
     _prev_price = None
     for index, op in enumerate(sort_order):
         # the dictionary keys are always asset_a, icon, asset_b, price, price_color
         # this determines what is for sale, and puts the correct arrow and asset order
         if op_list[op]['op']['op'][1]['amount_to_sell'][
                 'asset_id'] == self.asset_a_id:
             icon = 'arrow-right'
             asset_a = str(Amount(
                 op_list[op]['op']['result'][1]['paid'][0]))
             asset_b = str(
                 Amount(op_list[op]['op']['result'][1]['received'][0]))
         else:
             icon = 'arrow-left'
             asset_a = str(
                 Amount(op_list[op]['op']['result'][1]['received'][0]))
             asset_b = str(Amount(
                 op_list[op]['op']['result'][1]['paid'][0]))
         try:
             if op_list[sort_order[index + 1]]['op']['op'][1][
                     'amount_to_sell']['asset_id'] == self.asset_a_id:
                 _asset_a = str(
                     Amount(op_list[sort_order[index + 1]]['op']['result']
                            [1]['paid'][0]))
                 _asset_b = str(
                     Amount(op_list[sort_order[index + 1]]['op']['result']
                            [1]['received'][0]))
             else:
                 _asset_a = str(
                     Amount(op_list[sort_order[index + 1]]['op']['result']
                            [1]['received'][0]))
                 _asset_b = str(
                     Amount(op_list[sort_order[index + 1]]['op']['result']
                            [1]['paid'][0]))
         except:
             pass
         _price_ab = float(asset_a.split(' ')[0].replace(',', '')) / float(
             asset_b.split(' ')[0].replace(',', ''))
         _price_ba = float(asset_b.split(' ')[0].replace(',', '')) / float(
             asset_a.split(' ')[0].replace(',', ''))
         # check previous y/x price, change color depending on result
         price_ab_color = '#808080'
         price_ba_color = '#808080'
         if index != 99:
             _prev_price_ab = float(
                 _asset_a.split(' ')[0].replace(',', '')) / float(
                     _asset_b.split(' ')[0].replace(',', ''))
             _prev_price_ba = float(
                 _asset_b.split(' ')[0].replace(',', '')) / float(
                     _asset_a.split(' ')[0].replace(',', ''))
             if _price_ab > _prev_price_ab:
                 price_ab_color = '#669f38'
                 price_ba_color = '#e9002c'
             elif _price_ab < _prev_price_ab:
                 price_ab_color = '#e9002c'
                 price_ba_color = '#669f38'
         self.history.append({
             'asset_a': asset_a,
             'icon': icon,
             'asset_b': asset_b,
             'price_ab': f'{_price_ab:.3f}',
             'price_ab_color': price_ab_color,
             'price_ba': f'{_price_ba:.3f}',
             'price_ba_color': price_ba_color,
         })
     # Generate activity from history for stats panel
     _last_confirmed_block = Blockchain(
         mode='irreversible').get_current_block_num()
     swap_count = 0
     for op in sort_order:
         if op_list[op]['op']['block_num'] > _last_confirmed_block - (
                 self.BLOCK_HOUR * 24):
             swap_count += 1
     return_data['swap_count'] = swap_count
     for op in self.history:
         if self.price_switch == 'b/a':
             return_data['history'].append({
                 'asset_a':
                 op['asset_a'],
                 'icon':
                 op['icon'],
                 'asset_b':
                 op['asset_b'],
                 'price':
                 op['price_ba'],
                 'price_color':
                 op['price_ba_color'],
             })
         else:
             return_data['history'].append({
                 'asset_a':
                 op['asset_a'],
                 'icon':
                 op['icon'],
                 'asset_b':
                 op['asset_b'],
                 'price':
                 op['price_ab'],
                 'price_color':
                 op['price_ab_color'],
             })
     return return_data
예제 #30
0
from bitshares import BitShares
from bitshares.blockchain import  Blockchain
from pprint import pprint

print("####Begins####")

# creates a connection to a bitshares node.
testnet = BitShares( "ws://0.0.0.0:11011", nobroadcast=True, bundle=True,)
blockchain = Blockchain(testnet)

# wallet creation
# testnet.wallet.create("akhil")
# testnet.wallet.addPrivateKey("5JtyazjyGeFScWH3614tWpGe3xzkxmCrsb4Q2y3WJn883EyW9qT")

# testnet.wallet.unlock("akhil")
for op in blockchain.ops():
    print(op)

# pprint(testnet.wallet.getAccounts())


# bitshares.transfer("<to>", "<amount>", "<asset>", "[<memo>]", account="<from>")
예제 #31
0
    def listen(self):
        """ Listen to the blockchain and send blocks to
            :func:`BlockchainMonitor.process_block`

            .. note:: Depending on the setting of ``watch_mode`` in the
                configuration, the listen method has slightly different
                behavior. Namely, we here have the choice between "head" (the
                last block) and "irreversible" (the block that is confirmed by
                2/3 of all block producers and is thus irreversible)
        """
        last_block = self.storage.get_last_head_block_num()

        logging.getLogger(__name__).debug("Start listen with start=" + str(self.start_block) + " stop=" + str(self.stop_block) + " last=" + str(last_block))

        # if set to true, block numbers may not be consecutively
        self.allow_block_jump = False

        if not self.start_block:
            if last_block > 0:
                self.start_block = last_block + 1
        else:
            if not self.start_block == self.storage.get_last_head_block_num() + 1:
                # allow first block to jump
                self.allow_block_jump = True
                logging.getLogger(__name__).warning("Force listen with different block than last in storage (storage=" + str(last_block) + ", given=" + str(self.start_block) + ")")

        retry = True
        while (retry):
            retry = False

            block_listener = Blockchain(
                mode=self.watch_mode,
                max_block_wait_repetition=12,
                bitshares_instance=self.bitshares
            )

            if not block_listener.mode == "last_irreversible_block_num":
                block_listener.mode = "last_irreversible_block_num"

            try:
                for block in block_listener.blocks(
                    start=self.start_block,
                    stop=self.stop_block
                ):
                    logging.getLogger(__name__).debug("Processing block " + str(block["block_num"]))

                    last_head_block = self.storage.get_last_head_block_num()

                    if last_head_block == 0 or\
                            block["block_num"] == last_head_block + 1 or\
                            (self.allow_block_jump and last_head_block < block["block_num"]):
                        self.allow_block_jump = False
                        # no blocks missed
                        self.process_block(block)
                        self.storage.set_last_head_block_num(block["block_num"])
                    elif block["block_num"] == last_head_block:
                        # possible on connection error, skip block
                        continue
                    else:
                        self.start_block = last_head_block + 1
                        if self.stop_block is not None and self.start_block > self.stop_block:
                            logging.getLogger(__name__).error("Block was missed, or trying to march backwards. Stop block already reached, shutting down ...")
                            return
                        else:
                            logging.getLogger(__name__).error("Block was missed, or trying to march backwards. Retry with next block " + str(last_head_block + 1))
                            raise BlockchainMonitorRetryException()
            except BlockchainMonitorRetryException:
                retry = True
예제 #32
0
 def setUp(self):
     fixture_data()
     self.chain = Blockchain(mode="head")