Exemplo n.º 1
0
    def take_offer(self, data):
        bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head')
        trade_message = ''
        new_data = {}
        if data['market_or_pool'] == 'pool':
            new_data['operation_type'] = 'Pool Operation'
            if data['buy_or_sell'] == 'buy':
                amount_to_sell = Amount(data['expected_price'])
                new_data['anticipated'] = Amount('{} {}'.format(data['amount_to_buy_sell'], data['selected_asset']))
                min_to_receive = new_data['anticipated'] * .993
                trade_message = bitshares.exchange_with_liquidity_pool(
                    pool=data['pool_id'],
                    amount_to_sell=amount_to_sell,
                    min_to_receive=min_to_receive,
                    account=data['account'],
                )
            else:
                amount_to_sell = Amount('{} {}'.format(data['amount_to_buy_sell'], data['selected_asset']))
                new_data['anticipated'] = Amount(data['expected_price'])
                min_to_receive = new_data['anticipated'] * .993
                trade_message = bitshares.exchange_with_liquidity_pool(
                    pool=data['pool_id'],
                    amount_to_sell=amount_to_sell,
                    min_to_receive=min_to_receive,
                    account=data['account'],
                )
            new_data['operation_results'] = trade_message['operation_results']
            new_data['paid'] = Amount(new_data['operation_results'][0][1]['paid'][0])
            new_data['received'] = Amount(new_data['operation_results'][0][1]['received'][0])
        # still not working quite right
        else: # market trade
            pass

        pub.sendMessage('print_transaction', data=new_data)
Exemplo n.º 2
0
 def deposit_lp(self, data):
     trade_message = ''
     new_data = {}
     try:
         bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head')
         trade_message = bitshares.deposit_into_liquidity_pool(
             pool=data['poolshare_symbol'],
             amount_a=Amount(
                 data['asset_x_amount'],
                 data['asset_x_symbol'],
             ),
             amount_b=Amount(
                 data['asset_y_amount'],
                 data['asset_y_symbol'],
             ),
             account=data['account'],
         )
         new_data['operation_results'] = trade_message['operation_results']
     except Exception as err:
         print(err)
     if new_data:
         try:
             new_data['paid_x'] = Amount(new_data['operation_results'][0][1]['paid'][0])
             new_data['paid_y'] = Amount(new_data['operation_results'][0][1]['paid'][1])
             new_data['received'] = Amount(new_data['operation_results'][0][1]['received'][0])
             pub.sendMessage('print_deposit', data=new_data)
         except:
             print('error parsing deposit operation results')
     else:
         print('deposit operation failed')
Exemplo n.º 3
0
 def withdraw_lp(self, data):
     trade_message = ''
     new_data = {}
     try:
         bitshares = BitShares(nobroadcast=False, keys=data['key'], blocking='head')
         trade_message = bitshares.withdraw_from_liquidity_pool(
             pool=data['asset'],
             share_amount=Amount(
                 data['withdraw_amount'],
                 data['asset'],
             ),
             account=data['account'],
         )
         new_data['operation_results'] = trade_message['operation_results']
     except Exception as err:
         print(err)
     if new_data:
         try:
             new_data['paid'] = Amount(new_data['operation_results'][0][1]['paid'][0])
             new_data['received_x'] = Amount(new_data['operation_results'][0][1]['received'][0])
             new_data['received_y'] = Amount(new_data['operation_results'][0][1]['received'][1])
             pub.sendMessage('print_withdraw', data=new_data)
         except:
             print('error parsing withdraw operation results')
     else:
         print('withdraw operation failed')
Exemplo n.º 4
0
    def test_gateway_handler(self):
        bitshares = BitShares(settings.BITSHARES_NODE_URL,
                              nobroadcast=settings.BLOCKCHAIN_NOBROADCAST,
                              keys=[settings.BITSHARES_GATEWAY_WIF])
        bitshares.set_default_account(settings.BITSHARES_GATEWAY_ACCOUNT)

        transnet = Transnet(settings.TRANSNET_NODE_URL,
                            nobroadcast=settings.BLOCKCHAIN_NOBROADCAST,
                            keys={
                                'active': settings.TRANSNET_GATEWAY_WIF,
                                'memo': settings.TRANSNET_GATEWAY_WIF_MEMO
                            })
        transnet.set_default_account(settings.TRANSNET_GATEWAY_ACCOUNT)

        transaction = BitsharesTransnetTransaction.objects.create(
            trx_id='test',
            trx_in_block=3,
            op_in_trx=3,
            asset='UTECH.UTCORE',
            amount=pow(10, 5),
            account_external='superpchelka23',
            account_internal='superpchelka23')

        handler = BitsharesGatewayHandler(bitshares,
                                          settings.BITSHARES_GATEWAY_ACCOUNT,
                                          transnet,
                                          settings.TRANSNET_GATEWAY_ACCOUNT,
                                          settings.TRANSNET_GATEWAY_WIF_MEMO,
                                          {'UTECH.UTCORE': 'UTECH.UTCORE'})

        handler.handle([transaction], lambda: True)

        self.assertTrue(transaction.closed,
                        'Transaction must be properly processed')
Exemplo n.º 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
Exemplo n.º 6
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares("wss://node.testnet.bitshares.eu",
                             nobroadcast=True,
                             keys={"active": wif})
        set_shared_bitshares_instance(self.bts)
        self.bts.set_default_account("init0")
Exemplo n.º 7
0
class Testcases(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
            # We want to bundle many operations into a single transaction
            bundle=True,
            # Overwrite wallet to use this list of wifs only
            wif={"active": wif}
        )
        self.bts.set_default_account("init0")
        set_shared_bitshares_instance(self.bts)

    def test_account(self):
        Account("witness-account")
        Account("1.2.3")
        asset = Asset("1.3.0")
        symbol = asset["symbol"]
        account = Account("witness-account", full=True)
        self.assertEqual(account.name, "witness-account")
        self.assertEqual(account["name"], account.name)
        self.assertEqual(account["id"], "1.2.1")
        self.assertIsInstance(account.balance("1.3.0"), Amount)
        # self.assertIsInstance(account.balance({"symbol": symbol}), Amount)
        self.assertIsInstance(account.balances, list)
        for h in account.history(limit=1):
            pass

        # BlockchainObjects method
        account.cached = False
        self.assertTrue(account.items())
        account.cached = False
        self.assertIn("id", account)
        account.cached = False
        self.assertEqual(account["id"], "1.2.1")
        self.assertEqual(str(account), "<Account 1.2.1>")
        self.assertIsInstance(Account(account), Account)

    def test_account_upgrade(self):
        account = Account("witness-account")
        tx = account.upgrade()
        ops = tx["operations"]
        op = ops[0][1]
        self.assertEqual(len(ops), 1)
        self.assertEqual(
            getOperationNameForId(ops[0][0]),
            "account_upgrade"
        )
        self.assertTrue(
            op["upgrade_to_lifetime_member"]
        )
        self.assertEqual(
            op["account_to_upgrade"],
            "1.2.1",
        )
Exemplo n.º 8
0
def balances_bit_shares(config, secrets_json, source, scopeTickers):
    printSource = '' # this is cleaner than passing printSource as a param.
    if not config.VERBOSE: printSource = source+"\n  " # VERBOSE already printed it.

    from bitshares import BitShares
    amounts = BitShares(config, secrets_json['account'])
    for key, value in amounts.items():
        if not scopeTickers or key in scopeTickers:
            printBalance(printSource, key, value)
            printSource = '  '

    try: # bitshares.account will work under Python3, but throw exception if Python2
        from bitshares.account import Account
        account = Account(secrets_json['account'])
        print (account.json())
        # We add the balances and open-orders amounts, since we still own unfilled open-orders
        amounts = { }
        for balance in account.balances:
            ticker = balance.symbol.replace('BRIDGE.','')
            if ticker not in amounts: amounts[ticker] = 0
            amounts[ticker] += balance.amount
        for openorder in account.openorders:
            order = openorder['base']
            ticker = order.symbol.replace('BRIDGE.','')
            if ticker not in amounts: amounts[ticker] = 0
            amounts[ticker] += order.amount
        for key, value in amounts.items():
            if not scopeTickers or key in scopeTickers:
                printBalance(printSource, key, value)
                printSource = '  '
        return ''
    except KeyboardInterrupt as ex:
        raise KeyboardInterrupt()
    except:
        ex = sys.exc_info()[0]
        if config.VERBOSE: print( "Exception in balances.balances_bit_shares(): "+str(ex), file=sys.stderr )

    proc = subprocess.Popen(['/opt/mining/mining/balances/bit-shares.py', source], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    out, err = proc.communicate(None)
    if err:
        print(err,file=sys.stderr)
        return
    out = out.decode('utf-8')

    lines = out.splitlines()
    # "[0.00001017 BRIDGE.BTC, 162.1362 BRIDGE.RVN]"
    line = lines[0].replace('[','').replace(']','')
    vals = line.split(", ")
    for val in vals:
        val_coin = val.split(' ')
        value = val_coin[0]
        ticker = val_coin[1].replace('BRIDGE.','')
        if not scopeTickers or ticker in scopeTickers:
            #print('  '+ticker + " " + value)
            printBalance(printSource, ticker, float(value.replace(',','')))
            printSource = '  '
    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")
Exemplo n.º 10
0
def dex_withdraw():

    # undeveloped definition for withdrawals
    from bitshares import BitShares
    bitshares = BitShares()
    bitshares.wallet.unlock("wallet-passphrase")
    bitshares.transfer(to=send_to,
                       amount=send_amount,
                       asset=BTS,
                       memo=None,
                       account=account)
Exemplo n.º 11
0
    def test_default_connection2(self):
        b1 = BitShares("wss://node.testnet.bitshares.eu", nobroadcast=True)
        test = Asset("1.3.0", blockchain_instance=b1)
        test.refresh()

        b2 = BitShares("wss://node.bitshares.eu", nobroadcast=True)
        bts = Asset("1.3.0", blockchain_instance=b2)
        bts.refresh()

        self.assertEqual(test["symbol"], "TEST")
        self.assertEqual(bts["symbol"], "X4T")
Exemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            nobroadcast=True,
            # We want to bundle many operations into a single transaction
            bundle=True,
            # Overwrite wallet to use this list of wifs only
            wif=[wif])
        self.bts.set_default_account("init0")
        set_shared_bitshares_instance(self.bts)
Exemplo n.º 13
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
            keys={"active": wif},
        )
        # from getpass import getpass
        # self.bts.wallet.unlock(getpass())
        set_shared_bitshares_instance(self.bts)
        self.bts.set_default_account("init0")
Exemplo n.º 14
0
    def test_bts1bts2(self):
        b1 = BitShares(
            "wss://node.testnet.bitshares.eu",
            nobroadcast=True,
        )

        b2 = BitShares(
            "wss://node.bitshares.eu",
            nobroadcast=True,
        )

        self.assertNotEqual(b1.rpc.url, b2.rpc.url)
Exemplo n.º 15
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)))
Exemplo n.º 16
0
    def __init__(self):
        self.site_settings = SettingsModel.load()
        self.bitshares = BitShares(
            self.site_settings.bitshares_transnet_node_url,
            nobroadcast=settings.BLOCKCHAIN_NOBROADCAST,
            keys={
                'active': self.site_settings.bitshares_transnet_active_wif,
            },
        )
        self.bitshares.set_default_account(
            self.site_settings.bitshares_transnet_gateway_address)

        super(BitsharesBasedGateway, self).__init__()
Exemplo n.º 17
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.bts = BitShares(nobroadcast=True, wif=[wif])
        set_shared_bitshares_instance(self.bts)
        self.bts.set_default_account("init0")

        cache = ObjectCache(default_expiration=5, no_overwrite=True)
        init0 = {
            'active': {
                'account_auths': [],
                'address_auths': [],
                'key_auths': [[str(PrivateKey(wif).pubkey), 1]],
                'weight_threshold': 1
            },
            'active_special_authority': [0, {}],
            'blacklisted_accounts': [],
            'blacklisting_accounts': [],
            'cashback_vb': '1.13.102',
            'id': '1.2.90742',
            'lifetime_referrer': '1.2.90742',
            'lifetime_referrer_fee_percentage': 8000,
            'membership_expiration_date': '1969-12-31T23:59:59',
            'name': 'init0',
            'network_fee_percentage': 2000,
            'options': {
                'extensions': [],
                'memo_key': str(PrivateKey(wif).pubkey),
                'num_committee': 0,
                'num_witness': 0,
                'votes': [],
                'voting_account': '1.2.5'
            },
            'owner': {
                'account_auths': [],
                'address_auths': [],
                'key_auths': [[str(PrivateKey(wif).pubkey), 1]],
                'weight_threshold': 1
            },
            'owner_special_authority': [0, {}],
            'referrer': '1.2.90742',
            'referrer_rewards_percentage': 0,
            'registrar': '1.2.90742',
            'statistics': '2.6.90742',
            'top_n_control_flags': 0,
            'whitelisted_accounts': [],
            'whitelisting_accounts': []
        }
        cache[init0["id"]] = init0
        cache[init0["name"]] = init0
        BlockchainObject._cache = cache
Exemplo n.º 18
0
def publish_price(account, price):
    btsNode = 'wss://node.testnet.bitshares.eu'
    bitshares = BitShares(btsNode, account.name, account.pwd)

    price = float(price)
    stlprice = Price(price,
                     "TEST/" + account.asset,
                     bitshares_instance=bitshares)

    btsAccount = Account(account.name, bitshares_instance=bitshares)

    bitshares.wallet.unlock(wallet_pwd)
    bitshares.publish_price_feed(account.asset, stlprice, account=btsAccount)
    bitshares.wallet.lock()
Exemplo n.º 19
0
    def test_default_connection(self):
        b1 = BitShares("wss://node.testnet.bitshares.eu", nobroadcast=True)
        set_shared_bitshares_instance(b1)
        test = Asset("1.3.0", blockchain_instance=b1)
        # Needed to clear cache
        test.refresh()

        b2 = BitShares("wss://node.bitshares.eu", nobroadcast=True)
        set_shared_bitshares_instance(b2)
        bts = Asset("1.3.0", blockchain_instance=b2)
        # Needed to clear cache
        bts.refresh()

        self.assertEqual(test["symbol"], "TEST")
        self.assertEqual(bts["symbol"], "BTS")
Exemplo n.º 20
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))
Exemplo n.º 21
0
 def new_func(ctx, *args, **kwargs):
     ctx.bitshares = BitShares(ctx.config["node"],
                               num_retries=-1,
                               expiration=60,
                               **ctx.obj)
     set_shared_bitshares_instance(ctx.bitshares)
     return ctx.invoke(f, *args, **kwargs)
Exemplo n.º 22
0
def run():

#    testnet = BitShares("wss://node.testnet.bitshares.eu")
    testnet = BitShares("ws://this.uptick.rocks:18090")
    
    account = Account("committee-account", full=True, bitshares_instance=testnet)
    proposals = account["proposals"]
    client = GrapheneAPI("localhost", 8092, "", "")

    for proposal in proposals:
        pprint(proposal)
        if click.confirm("Approve proposal %s" % proposal["id"]):
            # Get current fees
            core_asset = client.get_asset("1.3.0")
            committee_account = client.get_account("committee-account")
            proposal = client.get_object(proposal["id"])[0]
            prop_op = proposal["proposed_transaction"]["operations"]

            tx = client.approve_proposal(
                "faucet",
                proposal["id"],
                {"active_approvals_to_add": [
                    "committee-member-1",
                    "committee-member-2",
                    "committee-member-3",
                    "committee-member-4",
                    "committee-member-5",
                    "committee-member-6",
                    "committee-member-7",
                    "committee-member-8",
                    "committee-member-9",
                    "committee-member-10"]
                },
                True)
            pprint(tx)
Exemplo n.º 23
0
 def new_func(ctx, *args, **kwargs):
     ctx.bitshares = BitShares(
         ctx.config["node"],
         **ctx.obj
     )
     set_shared_bitshares_instance(ctx.bitshares)
     return ctx.invoke(f, *args, **kwargs)
Exemplo n.º 24
0
 def __init__(self, *args, **kwargs):
     super(Testcases, self).__init__(*args, **kwargs)
     bitshares = BitShares(
         "wss://node.bitshares.eu",
         nobroadcast=True,
     )
     set_shared_bitshares_instance(bitshares)
Exemplo n.º 25
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
Exemplo n.º 26
0
 def new_func(ctx, *args, **kwargs):
     newoptions = ctx.obj
     newoptions.update(kwargsChain)
     ctx.bitshares = BitShares(**newoptions)
     ctx.blockchain = ctx.bitshares
     set_shared_bitshares_instance(ctx.bitshares)
     return ctx.invoke(f, *args, **kwargs)
Exemplo n.º 27
0
 def bitshares(self) -> BitShares:
     """Returns an instance of BitShares and caches it in the attribute _bitshares after creation"""
     if not self._bitshares:
         self._bitshares = BitShares(settings.BITSHARES_RPC_NODE,
                                     bundle=True,
                                     keys=[])
     return self._bitshares
Exemplo n.º 28
0
 def remove_offline_worker(config, worker_name):
     # Initialize the base strategy to get control over the data
     bitshares_instance = BitShares(config['node'])
     strategy = BaseStrategy(worker_name,
                             config,
                             bitshares_instance=bitshares_instance)
     strategy.purge()
Exemplo n.º 29
0
 def test_default_connection(self):
     b1 = BitShares("wss://eu.nodes.bitshares.ws", nobroadcast=True)
     set_shared_bitshares_instance(b1)
     test = Asset("1.3.0", blockchain_instance=b1)
     # Needed to clear cache
     test.refresh()
     """
Exemplo n.º 30
0
def order_and_cancel():
    cybex_config(node_rpc_endpoint=NODE_WS_ENDPOINT, chain_id=CHAIN_ID)

    net = BitShares(node=NODE_WS_ENDPOINT, **{'prefix': 'CYB'})

    unlock(net)

    try:
        net.wallet.addPrivateKey('your active private key')
    except Exception as e:
        pass

    net.wallet.unlock('your wallet unlock password')

    account = Account('account name', bitshares_instance=net)

    market = Market(base=Asset('CYB'),
                    quote=Asset('JADE.ETH'),
                    bitshares_instance=net)

    # buy 0.001 JADE.ETH at price JADE.ETH:CYB 1000, expire in 60 seconds
    # market.sell will do the sell operation
    market.buy(1000, 0.001, 60, False, 'account name', 'Head')

    # query open orders
    for order in account.openorders:
        base_amount = order['base'].amount
        base_symbol = order['base'].symbol
        quote_amount = order['quote'].amount
        quote_symbol = order['quote'].symbol
        order_number = order['id']
        print('{}:{}--{}/{}'.format(quote_symbol, base_symbol, quote_amount,
                                    base_amount))
        # cancel order
        market.cancel(order_number, 'account name')
Exemplo n.º 31
0
Arquivo: views.py Projeto: xeroc/tapin
def tapbasic(referrer):
    # test is request has 'account' key
    if not request.json or 'account' not in request.json:
        abort(400)
    account = request.json.get('account', {})

    # make sure all keys are present
    required_files = set(
        (config.get("require_fields", []) or []) +
        ["active_key", "memo_key", "owner_key", "name"]
    )
    for required in required_files:
        if str(required) not in account:
            return api_error("Please provide '{}'".format(required))

    # prevent massive account registration
    if request.headers.get('X-Real-IP'):
        ip = request.headers.get('X-Real-IP')
    else:
        ip = request.remote_addr
    if (
        config.get("restrict_ip", True) and
        ip != "127.0.0.1" and
        models.Accounts.exists(ip)
    ):
        return api_error("Only one account per IP")

    # Check if account name is cheap name
    if (
        config.get("disable_premium_names", True) and
        is_premiumname(account["name"])
    ):
        return api_error("Only cheap names allowed!")

    # This is not really needed but added to keep API-compatibility with Rails Faucet
    account.update({"id": None})

    bitshares = BitShares(
        config.witness_url,
        nobroadcast=config.nobroadcast,
        keys=[config.wif]
    )

    # See if the account to register already exists
    if not is_test_account(account["name"]):
        try:
            Account(account["name"], bitshares_instance=bitshares)
            return api_error("Account exists")
        except:
            pass

    # Registrar
    registrar = account.get("registrar", config.registrar) or config.registrar
    try:
        registrar = Account(registrar, bitshares_instance=bitshares)
    except:
        return api_error("Unknown registrar: %s" % registrar)

    # Referrer
    referrer = account.get("referrer", config.default_referrer) or config.default_referrer
    try:
        referrer = Account(referrer, bitshares_instance=bitshares)
    except:
        return api_error("Unknown referrer: %s" % referrer)
    referrer_percent = account.get("referrer_percent", config.referrer_percent)

    # Make sure to not broadcast this testing account
    if not bitshares.nobroadcast:
        if is_test_account(account["name"]):
            bitshares.nobroadcast = True
        else:
            bitshares.nobroadcast = False

    if "email" in account and account["email"]:
        try:
            models.Accounts.validate_email(account["email"])
        except Exception as e:
            return api_error(str(e))

    # Create new account
    try:
        tx = bitshares.create_account(
            account["name"],
            registrar=registrar["id"],
            referrer=referrer["id"],
            referrer_percent=referrer_percent,
            owner_key=account["owner_key"],
            active_key=account["active_key"],
            memo_key=account["memo_key"],
            proxy_account=config.get("proxy", None),
            additional_owner_accounts=config.get("additional_owner_accounts", []),
            additional_active_accounts=config.get("additional_active_accounts", []),
            additional_owner_keys=config.get("additional_owner_keys", []),
            additional_active_keys=config.get("additional_active_keys", []),
        )
    except Exception as e:
        log.error(traceback.format_exc())
        return api_error(str(e))

    if not is_test_account(account["name"]):
        models.Accounts(
            account=account["name"],
            full_name=account.get("real_name", None),
            email=account.get("email", None),
            ip=ip
        )

    reply = {"account": {
        "name": account["name"],
        "owner_key": account["owner_key"],
        "active_key": account["active_key"],
        "memo_key": account["memo_key"],
        "referrer": referrer["name"]
    }}

    if is_test_account(account["name"]):
        tx.pop("signatures", None)
        reply.update({"tx": tx})

    return jsonify(reply)
Exemplo n.º 32
0
def tapv2(name, owner, active, memo, referrer):
    # prevent massive account registration
    if request.remote_addr != "127.0.0.1" and \
            models.Accounts.exists(request.remote_addr):
        return api_error("Only one account per IP")

    # Check if account name is cheap name
    if (not re.search(r"[0-9-]", name) and
            re.search(r"[aeiouy]", name)):
        return api_error("Only cheap names allowed!")

    bitshares = BitShares(
        config.witness_url,
        nobroadcast=config.nobroadcast,
        keys=[config.wif]
    )

    try:
        Account(name, bitshares_instance=bitshares)
        return api_error("Account exists")
    except:
        pass

    # Registrar
    registrar = config.registrar
    try:
        registrar = Account(registrar, bitshares_instance=bitshares)
    except:
        return api_error("Unknown registrar: %s" % registrar)

    # Referrer
    if not referrer:
        referrer = config.default_referrer
    try:
        referrer = Account(referrer, bitshares_instance=bitshares)
    except:
        return api_error("Unknown referrer: %s" % referrer)
    referrer_percent = config.referrer_percent

    # Create new account
    try:
        bitshares.create_account(
            name,
            registrar=registrar["id"],
            referrer=referrer["id"],
            referrer_percent=referrer_percent,
            owner_key=owner,
            active_key=active,
            memo_key=memo,
            proxy_account=config.get("proxy", None),
            additional_owner_accounts=config.get(
                "additional_owner_accounts", []),
            additional_active_accounts=config.get(
                "additional_active_accounts", []),
            additional_owner_keys=config.get(
                "additional_owner_keys", []),
            additional_active_keys=config.get(
                "additional_active_keys", []),
        )
    except Exception as e:
        log.error(traceback.format_exc())
        return api_error(str(e))

    models.Accounts(name, request.remote_addr)

    return jsonify({
        "status": "Account created",
        "account": {
            "name": name,
            "owner_key": owner,
            "active_key": active,
            "memo_key": memo,
        }})