def __init__(self, testing=False, unittest_prkey=''):
     if testing == True:
         self.testing = testing
         self.private_key = read_drive(testing)
         self.key = PrivateKeyTestnet(self.private_key)
     elif unittest_prkey != '':
         self.testing = testing
         self.private_key = unittest_prkey
         self.key = Key(self.private_key)
     else:
         self.testing = testing
         self.private_key = read_drive(testing)
         self.key = Key(self.private_key)
Esempio n. 2
0
 def to_key_pairs(cls, mnemonic):
     w = wallet.create_wallet(network="bch", seed=mnemonic, children=1)
     wif = w['wif']
     key = Key(wif)
     address = key.address
     keypair = {"private_key_WIF": wif, "address": address}
     return keypair
Esempio n. 3
0
def balance(bot, update):
    """ Fetches and returns the balance (in USD) """
    if not checks.check_username(update):
        return
    create_user(update.message.from_user.username)
    key = Key(get_wif(update.message.from_user.username))
    balance = key.get_balance("usd")
    return update.message.reply_text("You have: $" + str(balance))
Esempio n. 4
0
def create_user(username):
    """Checks if a Telegram user is present in the database.
    Returns True if a user is created, False otherwise.
    """
    db.connect(reuse_if_open=True)
    key = Key()
    try:
        User.create(username=username, bch_address=key.address, wif=key.to_wif())
        db.close()
        return True
    except IntegrityError:
        db.close()
        return False
Esempio n. 5
0
def index():
    if 'user' not in session:
        session['user'] = secrets.token_hex()
        key = Key()
        wif = key.to_wif()
        # Stores the keys in the cookies
        session['wif'] = wif
        session['address'] = key.address

    return render_template(
        'index.html',
        eb_link=EVENT_BRIBE_LINK,
        address=session['address'],
        wif=session['wif'],
    )
Esempio n. 6
0
def withdraw(bot, update, args):
    """ Withdraws BCH to user's wallet """
    if not checks.check_username(update):
        return

    if update.message.chat.type != "private":  # check if in DM
        return bot.send_message(
            chat_id=update.effective_chat.id,
            text="Private message me to withdraw your money",
        )

    if len(args) != 2:
        message = ("Usage: /withdraw [amount] [address]\n\n"
                   "You may also withdraw everything at once using:"
                   " /withdraw all [address]")
        return update.message.reply_text(message)

    address = checks.check_address(update, args[1])
    if not address:  # does not send anything if address is False
        return

    wif = get_wif(update.message.from_user.username)
    key = Key(wif)

    if args[0] == "all":
        sent_amount = 1000
        currency = "satoshi"
    else:
        amount = args[0].replace("$", "")
        if not checks.amount_is_valid(amount):
            return update.message.reply_text(amount + " is not a valid amount")
        currency = "usd"
        sent_amount = float(amount) - 0.01  # after 1 cent fee

    outputs = [
        (address, sent_amount, currency),
    ]
    key.get_unspents()
    try:
        if args[0] == "all":
            tx_id = key.send(outputs, fee=1, leftover=address)
        else:
            tx_id = key.send(outputs, fee=1)
    except Exception:
        return update.message.reply_text("Transaction failed!")

    return update.message.reply_text("Sent! Transaction ID: " + tx_id)
Esempio n. 7
0
def withdraw(bot, update, args):
    """ Withdraws BCH to user's wallet """
    if not checks.check_username(update):
        return

    if update.message.chat.type != 'private':  # check if in DM
        return bot.send_message(
            chat_id=update.effective_chat.id,
            text='Private message me to withdraw your money')

    if len(args) != 2:
        message = 'Usage: /withdraw [amount] [address]\n\n'\
            'You may also withdraw everything at once using:'\
            ' /withdraw all [address]'
        return update.message.reply_text(message)

    address = checks.check_address(update, args[1])
    if not address:  # does not send anything if address is False
        return

    wif = get_wif(update.message.from_user.username)
    key = Key(wif)

    if args[0] == 'all':
        sent_amount = 1000
        currency = 'satoshi'
    else:
        amount = args[0].replace('$', '')
        if not checks.amount_is_valid(amount):
            return update.message.reply_text(amount + ' is not a valid amount')
        currency = 'usd'
        sent_amount = float(amount) - 0.01  # after 1 cent fee

    outputs = [
        (address, sent_amount, currency),
    ]
    key.get_unspents()
    try:
        if args[0] == 'all':
            tx_id = key.send(outputs, fee=1, leftover=address)
        else:
            tx_id = key.send(outputs, fee=1)
    except Exception:
        return update.message.reply_text('Transaction failed!')

    return update.message.reply_text('Sent! Transaction ID: ' + tx_id)
Esempio n. 8
0
def send_bitcash_message(message):
    if len(message.encode('utf-8')) > 213:
        raise ValueError(message + "超长,长度是:" + len(message.encode('utf-8')))
    else:
        config = get_systemconfigs()
        key = Key(config.private_key)
        upspents = key.get_unspents()
        logger.info(upspents)
        logger.info(key.address)
        outputs = [
            (config.outaddress, 10056, 'satoshi'),
        ]
        try:
            txhash, txid = key.send(outputs,
                                    message=message,
                                    fee=config.default_fee)
            logging.info('{m}交易成功,txid:{txid}'.format(m=message, txid=txid))
            return (txhash, txid)
        except Exception as e:
            logging.error('{m}交易失败,异常:{e}'.format(m=message, e=str(e)))
            raise e
Esempio n. 9
0
 def __init__(self, prkey):
     self.prkey = Key(prkey)
Esempio n. 10
0
def tip(bot, update, args):
    """ Sends Bitcoin Cash on-chain """
    if not checks.check_username(update):
        return

    if len(args) != 2 and not update.message.reply_to_message:
        return update.message.reply_text("Usage: /tip [amount] [username]")

    if "@" in args[0]:
        # this swaps args[0] and args[1] in case user input username before
        # amount (e.g. /tip @merc1er $1) - the latter will still work
        tmp = args[1]
        args[1] = args[0]
        args[0] = tmp

    amount = args[0].replace("$", "")
    if not checks.amount_is_valid(amount):
        return update.message.reply_text(amount + " is not a valid amount.")

    if update.message.reply_to_message:
        recipient_username = update.message.reply_to_message.from_user.username
        if not recipient_username:
            return update.message.reply_text(
                "You cannot tip someone who has not set a username.")
    else:
        recipient_username = args[1]
        if not checks.username_is_valid(recipient_username):
            return update.message.reply_text(recipient_username +
                                             " is not a valid username.")

    recipient_username = recipient_username.replace("@", "")
    sender_username = update.message.from_user.username

    if recipient_username == sender_username:
        return update.message.reply_text("You cannot send money to yourself.")

    create_user(recipient_username)  # IMPROVE
    recipient_address = get_address(recipient_username)
    sender_wif = get_wif(sender_username)

    key = Key(sender_wif)
    balance = key.get_balance("usd")
    # checks the balance
    if float(amount) > float(balance):
        return update.message.reply_text("You don't have enough funds! " +
                                         "Type /deposit to add funds!!")

    fee = float(amount) * FEE_PERCENTAGE
    sent_amount = float(amount) - 0.01

    if fee < 0.01:
        outputs = [
            (recipient_address, sent_amount, "usd"),
        ]
    else:
        sent_amount -= fee  # deducts fee
        outputs = [
            (recipient_address, sent_amount, "usd"),
            (FEE_ADDRESS, fee, "usd"),
        ]

    try:
        key.send(outputs, fee=1)
    except Exception:
        return bot.send_message(
            chat_id=update.effective_chat.id,
            text="Transaction failed!",
            parse_mode=ParseMode.MARKDOWN,
        )

    return bot.send_message(
        chat_id=update.effective_chat.id,
        text="You sent $" + amount + " to " + recipient_username,
    )
Esempio n. 11
0
def bch_network(net=CRYPTO_NETWORK, prkey=None):
    if net == 'mainnet':
        key = Key(prkey)
    elif net == 'testnet':
        key = PrivateKeyTestnet(prkey)
    return key
Esempio n. 12
0
    return satoshi_to_currency_cached(satoshi, 'bch')


def is_address_valid(address):
    return convert.is_valid(address)


def send(address, amount):
    outputs = [
        (address, amount, 'bch'),
    ]
    try:
        return key.send(outputs)
    except:
        return false


if key_exists():
    print('Debug: key exists')
    priv_key = open(PRIVATE_KEY, 'r')
    key = Key(priv_key.read())
else:
    print('Debug: key does not exists')
    key = Key()
    create_path(PRIVATE_KEY)
    priv_key = open(PRIVATE_KEY, 'w')
    priv_key.write(key.to_wif())
    priv_key.close()
    img = pyqrcode.create(key.address)
    img.svg(QR)