Пример #1
0
def get_balance(pu_key):
    if not tws:
        print(
            "Start the server by calling start_wallet before checking balances."
        )
        return 0.0
    return wallet.get_balance(pu_key)
Пример #2
0
 def get_account_balance(self):
     print(self.get_unspent_tx_outs())
     return get_balance(get_public_from_wallet(), self.get_unspent_tx_outs())
Пример #3
0
async def handle_message(message):
    features = [f for f in bot_features for c in f.command_keywords if c in message.content]
    if len(features) == 1:
        feat = features[0]

        if feat.command == "HELP":
            post_response(message, feat.response_templates["success"], BOT_VERSION)

        elif feat.command == "BALANCE":
            balance = wallet.get_balance(message.author.id)
            post_response(message, feat.response_templates["success"], balance)

        elif feat.command == "DEPOSIT":
            user_deposit_address = wallet.create_or_fetch_user(message.author.id, message.author.name).wallet_address
            post_response(message, feat.response_templates["success"], user_deposit_address,
                          get_qr_url(user_deposit_address))

        elif feat.command == "WITHDRAW":
            try:
                address = find_address(message.content)
                user = wallet.create_or_fetch_user(message.author.id, message.author.name)
                amount = user.balance
                if amount < 0.01:
                    post_response(message, feat.response_templates["threshold"])
                else:
                    wallet.make_transaction_to_address(user, amount, address)
                    post_response(message, feat.response_templates["success"])
            except util.TipBotException as e:
                if e.error_type == "address_not_found":
                    post_response(message, feat.response_templates["address_not_found"])
                if e.error_type == "error":
                    post_response(message, feat.response_templates["error"])

        elif feat.command == "TIP":
            try:
                amount = find_amount(message.content)
                target_user_id = find_user_id(message.content)
                if target_user_id == message.author.id:
                    post_response(message, feat.response_templates["cant_tip_yourself"])
                elif target_user_id == os.environ.get('BOT_ID'):
                    post_response(message, feat.response_templates["cant_tip_bot"])
                else:
					target_user = await client.get_user_info(target_user_id)
					wallet.make_transaction_to_user(message.author.id, amount, target_user.id, target_user.name)
                    try:
                        asyncio.get_event_loop().create_task(post_dm(target_user_id, feat.response_templates["tip_received"], amount, message.author.id))
                    except Exception as e:
                        logger.error('could not send message')
                        logger.exception(e)
                    post_response(message, feat.response_templates["success"])
                    if 1 <= amount <= 5:
                        asyncio.get_event_loop().create_task(react_to_message(message, 1))
                    elif 5 < amount <= 10:
                        asyncio.get_event_loop().create_task(react_to_message(message, 2))
                    elif amount > 10:
                        asyncio.get_event_loop().create_task(react_to_message(message, 3))
                    asyncio.get_event_loop().create_task(react_to_message(message, 1))
            except util.TipBotException as e:
                if e.error_type == "amount_not_found":
                    post_response(message, feat.response_templates["amount_not_found"])
                if e.error_type == "user_not_found":
                    post_response(message, feat.response_templates["user_not_found"])
                if e.error_type == "insufficient_funds":
                    post_response(message, feat.response_templates["insufficient_funds"])
                if e.error_type == "error":
                    post_response(message, feat.response_templates["error"])

        elif feat.command == "TOP":
            top_users = wallet.get_top_users()
            if len(top_users) == 0:
                post_response(message, feat.response_templates["empty"])
            else:
                response = random.choice(feat.response_templates["header"]) + "\n"
                for top_user in top_users:
                    response += '\n %s %.3f XZC tipped by %s' % (util.get_numerical_emoji(top_user['index']),
                                                                 top_user['amount'], top_user['name'])
                    if top_user['index'] == 1:
                        response += ' :clap: :clap: '
                    elif top_user['index'] == 2:
                        response += ' :clap: '
                post_response(message, [response])

    else:
        post_response(message, general_responses["command_not_found"])
Пример #4
0
async def on_message(message):

    # make sure bot doesnt reply to himself
    if message.author == client.user:
        return

    try:
        feat = [f for f in bot_features for c in f.command_keywords if c in message.content][0]
    except IndexError:
        pass

    # $help
    if message.content.startswith('$help') or message.content.startswith('$man'):
        post_response(message, feat.response_templates["success"], BOT_VERSION)

    # $balance
    try:
        if message.content.startswith('$balance') or message.content.startswith('$wallet'):
            if isinstance(message.channel, discord.abc.PrivateChannel):
                balance = wallet.get_balance(message.author.id)

                post_response(message, feat.response_templates["success"], balance)
            else:
                post_response(message, feat.response_templates["not_private"])

    except socket_error as serr:
        if serr.errno != errno.ECONNREFUSED:
            raise serr
        logger.exception("wallet down !")
        post_response(message, general_responses["wallet_down"])

    # $deposit
    try:
        if message.content.startswith('$deposit'):
            if isinstance(message.channel, discord.abc.PrivateChannel):
                user_deposit_address = wallet.create_or_fetch_user(message.author.id, message.author.name).wallet_address

                post_response(message, feat.response_templates["success"],
                              user_deposit_address,
                              get_qr_url(user_deposit_address))
            else:
                post_response(message, feat.response_templates["not_private"])

    except socket_error as serr:
        if serr.errno != errno.ECONNREFUSED:
            raise serr
        logger.exception("wallet down !")
        post_response(message, general_responses["wallet_down"])

    # $withdraw
    try:
        if message.content.startswith('$withdraw'):
            try:
                address = find_address(message.content.split("$withdraw")[1].strip())
                user = wallet.create_or_fetch_user(message.author.id, message.author.name)
                amount = find_amount(message.content.split("$withdraw")[1].strip())
                if amount < 0.01:
                    post_response(message, feat.response_templates["threshold"])
                else:
                    txid = wallet.make_transaction_to_address(user, amount, address)
                    post_response(message, feat.response_templates["success"])
                    asyncio.get_event_loop().create_task(message.channel.send(f"Txid: {txid}"))

            except util.TipBotException as e:
                if e.error_type == "address_not_found":
                    post_response(message, feat.response_templates["address_not_found"])
                if e.error_type == "error":
                    post_response(message, feat.response_templates["error"])
    except socket_error as serr:
        if serr.errno != errno.ECONNREFUSED:
            raise serr
        logger.exception("wallet down !")
        post_response(message, general_responses["wallet_down"])

    # $tip
    if message.content.startswith('$tip') or message.content.startswith('$send'):
        try:
            amount = find_amount(message.content)
            target_user_id = find_user_id(message.content)
            if target_user_id == message.author.id:
                post_response(message, feat.response_templates["cant_tip_yourself"])
            elif target_user_id == int(BOT_ID):
                post_response(message, feat.response_templates["cant_tip_bot"])
            else:
                target_user = await client.fetch_user(target_user_id)
                wallet.make_transaction_to_user(message.author.id, amount, target_user.id, target_user.name)
                try:
                    asyncio.get_event_loop().create_task(
                        post_dm(target_user_id, feat.response_templates["tip_received"], amount, message.author.id))
                except Exception as e:
                    logger.error('could not send message')
                    logger.exception(e)
                post_response(message, feat.response_templates["success"])
                if 1 <= amount <= 5:
                    asyncio.get_event_loop().create_task(react_to_message(message, 1))
                elif 5 < amount <= 10:
                    asyncio.get_event_loop().create_task(react_to_message(message, 2))
                elif amount > 10:
                    asyncio.get_event_loop().create_task(react_to_message(message, 3))
                asyncio.get_event_loop().create_task(react_to_message(message, 1))

        except util.TipBotException as e:
            if e.error_type == "amount_not_found":
                post_response(message, feat.response_templates["amount_not_found"])
            if e.error_type == "user_not_found":
                post_response(message, feat.response_templates["user_not_found"])
            if e.error_type == "insufficient_funds":
                post_response(message, feat.response_templates["insufficient_funds"])
            if e.error_type == "error":
                post_response(message, feat.response_templates["error"])
            if e.error_type == "too_many_decimals":
                post_response(message, feat.response_templates["too_many_decimals"])

    # $top
    if message.content.startswith('$top') or message.content.startswith('$rank') or message.content.startswith('$leaderboard'):

        top_users = wallet.get_top_users()
        if len(top_users) == 0:
            post_response(message, feat.response_templates["empty"])
        else:
            response = random.choice(feat.response_templates["header"]) + "\n"
            for top_user in top_users:
                response += '\n %s %.6f PPC tipped by %s' % (util.get_numerical_emoji(top_user['index']),
                                                                top_user['amount'], top_user['name'])
                if top_user['index'] == 1:
                    response += ' :clap: :clap: '
                elif top_user['index'] == 2:
                    response += ' :clap: '
            post_response(message, [response])
Пример #5
0
def run_miner():
    """Run the main miner loop.
    """

    global blockchain
    global public
    global private

    while True:
        # Load transaction queue and blockchain from server.
        txns = load_transactions()
        blockchain = load_blockchain()

        # Loc:  Check our balance
        balance = get_balance(public)
        print "Current balance", balance

        # Loc:  Set up attack
        is_attacking = False
        if balance > 60:
            print "Setting up Finney attack"
            is_attacking = True
            t = Transaction(
                id=gen_uuid(),
                owner=public,
                receiver=
                "6f181e44edfc93de084071e590421e5b083f93da6012d441658b6b31a966ae9c",
                coins=balance,
                signature=None)
            # Sign it.
            t.signature = sign(t.comp(), private)

            # Pay myself a lot!
            for x in range(0, 3):
                txns.append(t)

        # Add reward to us yay.
        reward = Transaction(id=gen_uuid(),
                             owner="mined",
                             receiver=public,
                             coins=REWARD,
                             signature=None)
        reward.signature = sign(reward.comp(), private)
        txns.append(reward)

        # Construct a new block.
        b = Block(timestamp=datetime.datetime.now(),
                  transactions=txns,
                  previous_hash=blockchain.head.hash_block())

        # Let's mine this block.
        mine_till_found(b)

        # Is this _the_ new block?
        # or did the server swoop us :(
        new_chain = load_blockchain()

        if new_chain.head.hash_block() == blockchain.head.hash_block():
            # WE MINED THIS BLOCK YAY.
            # AND WE WIN.

            # Loc: Add in a Finney attack to double spend the coin

            resp = get_route('add', data=str(b))
            if resp['success']:
                print "Block added!"
                delete_queue(txns)
            else:
                print "Couldn't add block:", resp['message']
        else:
            print "Someone else mined the block before us :("