예제 #1
0
def signup():
    if request.method == 'POST' and request.form.get(
            'email') and request.form.get('username') and request.form.get(
                'password'):
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email')
        if User.query.filter_by(username=username).first():
            flash('Username taken')
            return render_template('signup.html')

        else:
            wallet = PrivateKey()
            user = User(username=username,
                        password=password,
                        email=email,
                        address=wallet.address,
                        wallet=wallet.to_wif())
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))

    elif request.method == 'POST':
        flash('Check your input')
    else:
        return render_template('signup.html')

    return render_template('signup.html')
예제 #2
0
파일: wallet.py 프로젝트: meowyen/homework
 def create_tx(self, coin, account, to, amount):
     """
     Return prepared transaction for coin and account.
     """
     if coin is ETH:
         gasEstimate = self.w3.eth.estimateGas({
             "from": account.address,
             "to": to,
             "value": amount
         })
         return {
             "from": account.address,
             "to": to,
             "value": self.w3.toWei(amount, 'ether'),
             "gasPrice": self.w3.eth.gasPrice,
             "gas": gasEstimate,
             "nonce": self.w3.eth.getTransactionCount(account.address),
         }
     elif coin is BTCTEST:
         return PrivateKeyTestnet.prepare_transaction(
             account.address, [(to, amount, BTC)])
     elif coin is BTC:
         return PrivateKey.prepare_transaction(account.address,
                                               [(to, amount, BTC)])
     else:
         return None
예제 #3
0
def transaction():
    getbalance(current_user.wallet)

    if request.method == 'POST' and request.form.get(
            'amount') and request.form.get('address'):
        if current_user.wallet < int(amount):
            flash('not enough funds')
            return render_template('transaction.html')

        amount = request.form.get('amount')
        address = request.form.get('address')
        key = PrivateKey(current_user.wallet)
        myamount = (app.config['TRANSACTION_PERCENTAGE']) / 100 * amount
        youramount = amount - myamount
        transactionid = key.send([(address, youramount, 'usd'),
                                  (app.config['COMPANY_ADRESS'], myamount,
                                   'usd')])
        flash('transaction succeded transactionid ={transactionid}')
    return render_template('transaction.html')
예제 #4
0
파일: wallet.py 프로젝트: meowyen/homework
 def priv_key_to_account(self, coin, priv_key):
     """
     Return private key to account.
     """
     if coin is ETH:
         return Account.from_key(priv_key)
     elif coin is BTCTEST:
         return PrivateKeyTestnet(priv_key)
     elif coin is BTC:
         return PrivateKey(priv_key)
     else:
         return None
예제 #5
0
def get_bitcoin(page):
    html = requests.get(f'https://lbc.cryptoguru.org/dio/{page}').text
    soup = BeautifulSoup(html, 'lxml')
    sp = soup.find_all('span')
    sp_a = []
    for i in sp:
        sp1 = []
        try:
            sp1.append([
                i.find('span').get_text()[:-1],
                i.find_all('a')[1].get_text(),
                i.find_all('a')[2].get_text()
            ])
            sp_a.append(sp1)
        except:
            pass
    for col, i in enumerate(sp_a):
        key1 = PrivateKey(i[0][0])
        print(col)
        if key1.get_balance() != '0':
            print(i)
예제 #6
0
def priv_key_to_account(coin, priv_key):
    """
    This function return the address of a wallet
    given its corresponding private key
    """
    if coin == ETH:
        account_address = Account.privateKeyToAccount(priv_key).address
    if coin == BTCTEST:
        account_address = PrivateKeyTestnet(priv_key).address
    if coin == BTC:
        account_address = PrivateKey(priv_key).address

    return account_address
예제 #7
0
파일: btc.py 프로젝트: tirinox/ydalir
def make_keys():
    key = PrivateKey()
    code = qrcode.QRCode(version=1,
                         error_correction=qrcode.constants.ERROR_CORRECT_M,
                         box_size=10,
                         border=4)
    code.add_data(f'bitcoin:{key.address}')
    code.make(fit=True)
    img = code.make_image(fill_color="black", back_color="white")
    with io.BytesIO() as output:
        img.save(output, format="PNG")
        contents = output.getvalue()
        return contents, key
예제 #8
0
def priv_key_to_account(coin, priv_key):
    """
    Convert Private Key of specific coin type to wallet account
    ---
    Parameter:
    coin - coin type (defined in `constants.py`)
    priv_key - private key
    """
    if (coin == ETH):
        #print("ETH Account")
        return Account.privateKeyToAccount(priv_key)
    elif (coin == BTCTEST):
        #print("BTC-Test Account")
        return PrivateKeyTestnet(priv_key)
    elif (coin == BTC):
        return PrivateKey(priv_key)
    else:
        print(f"Unable to process {coin}")
        return ""
예제 #9
0
def create_tx(coin, account, to, amount):
    """
    Create transaction
    ---
    Parameter:
    coin - coin type (defined in `constants.py`)
    account - eth_account Account object
    to - recipient wallet address
    amount - amount to send
    """
    if (coin == ETH):
        return create_eth_tx(account, to, amount)
    elif (coin == BTCTEST):
        return PrivateKeyTestnet.prepare_transaction(account.address,
                                                     [(to, amount, BTC)])
    elif (coin == BTC):
        return PrivateKey.prepare_transaction(account.address,
                                              [(to, amount, BTC)])
    else:
        print(f"Unable to process {coin}")
        return ""
예제 #10
0
def getbalance(wallet):
    key = PrivateKey(wallet)
    newbalance = key.balance_as('usd')
    user = User.query.filter_by(wallet=wallet)
    user.amount = newbalance
    db.session.commit()
예제 #11
0
from flask import Flask, render_template, flash, request, redirect, send_file, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from werkzeug.utils import secure_filename
import os
from bit import PrivateKey

wallet = PrivateKey('')

print(wallet.address)
print(wallet.balance)
print(wallet.to_wif())

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.db'
db = SQLAlchemy(app)
app.config['SECRET_KEY'] = 'SUPERSECRETKEY'
app.config['TRANSACTION_PERCENTAGE'] = 5
app.config['COMPANY_ADRESS'] = 123456789

login_manager = LoginManager(app)


class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(1000), unique=True, nullable=False)
    wallet = db.Column(db.String(1000), nullable=False)
예제 #12
0
def ProcessSweepDeposit(message):
    username = message.author.name.lower()
    userAccount = reddit.redditor(username)
    RegisterNewUser(username, False)

    tipbitWindow.AddEventString('Attempting Sweep Deposit: {}'.format(
        message.body))
    if (tipbitUtilities.ImportPrivateKey(message.body, '', True) is False):
        print('Failed to sweep private key "{}"'.format(message.body))
        return

    legacyAddress = PrivateKeyTestnet(
        message.body).address if botSpecificData.testnet else PrivateKey(
            message.body).address
    print('legacy sweep - {}'.format(legacyAddress))
    segwitAddress = tipbitUtilities.GetUnusedAddressSegwit('', legacyAddress)
    print('segwit sweep - {}'.format(segwitAddress))

    sweepAddress = ''
    balanceList = tipbitUtilities.WalletBalancesList
    if (legacyAddress in balanceList): sweepAddress = legacyAddress
    elif (segwitAddress in balanceList): sweepAddress = segwitAddress

    if (sweepAddress == ''):
        print(
            'Attempted sweep of empty wallet. Cancelling Sweep Deposit for {}'.
            format(username))
        return

    print('Balance found at sweep address: {}'.format(sweepAddress))
    sweepBalance = tipbitUtilities.BTCToSatoshis(balanceList[sweepAddress])

    print('Sweep Balance: {} Satoshis'.format(sweepBalance))

    if (sweepBalance < botSpecificData.MINIMUM_DEPOSIT):
        MINIMUM_DEPOSIT_MBTC = tipbitUtilities.SatoshisToMBTC(
            botSpecificData.MINIMUM_DEPOSIT)
        tipbitWindow.AddEventString(
            'Failed to perform sweep deposit for user [{}] (balance under minimum deposit)'
            .format(username))
        userAccount.message(
            'Sweep Deposit failed!',
            messageTemplates.
            USER_FAILED_SWEEP_DEPOSIT_UNDER_MINIMUM_MESSAGE_TEXT.format(
                MINIMUM_DEPOSIT_MBTC,
                (' Testnet Bitcoins' if botSpecificData.testnet else '')))
        return False

    #  Attempt to prepare a transaction so we can determine the fee to take out so the user eats the cost
    depositBalance = sweepBalance
    storageTX = ''
    estimatedFee, storageTX = tipbitUtilities.SendFromAddressToAddress(
        sweepAddress, botSpecificData.PRIMARY_STORAGE_ADDRESS, depositBalance,
        botSpecificData.STORAGE_TRANSFER_FEE_PER_BYTE)
    newDepositDelta = depositBalance - estimatedFee

    depositBalanceMBTC = tipbitUtilities.SatoshisToMBTC(depositBalance)
    estimatedFeeMBTC = tipbitUtilities.SatoshisToMBTC(estimatedFee)
    newDepositDeltaMBTC = tipbitUtilities.SatoshisToMBTC(newDepositDelta)

    #  Now we should have an estimated fee, so we can subtract that from the amount we're sending, and transfer it
    addToUserBalance(username, int(newDepositDelta))
    balanceMBTC = tipbitUtilities.SatoshisToMBTC(getUserBalance(username))
    tipbitWindow.AddEventString(
        'Sweep Deposit successfully sent to storage: {} mBTC{}'.format(
            tipbitUtilities.SatoshisToMBTC(newDepositDelta),
            (' Testnet Bitcoins' if botSpecificData.testnet else '')))
    userAccount.message(
        'Your deposit was successful!',
        messageTemplates.USER_NEW_SWEEP_DEPOSIT_MESSAGE_TEXT.format(
            depositBalanceMBTC,
            (' Testnet Bitcoins' if botSpecificData.testnet else ''),
            depositBalanceMBTC, estimatedFeeMBTC, newDepositDeltaMBTC,
            balanceMBTC,
            (' Testnet Bitcoins' if botSpecificData.testnet else ''),
            storageTX))

    tipbitUtilities.SetAddressToAccount(legacyAddress, '')
    tipbitUtilities.SetAddressToAccount(segwitAddress, '')

    #  Return True so that we know to
    return True
예제 #13
0
async def main_logic(message: types.Message):

    # Логика для пользователя
    # Получаем данные пользователя
    data = reg_and_data_main(message)

    if data is not None:
        if data[6] == 0:
            if message.text == '💳 Получить BTC':
                img = qrcode.make(data[3])
                img.save('qr.jpg')

                await bot.send_message(message.chat.id,
                                       f'''💳 Ваш адрес биткойн кошелька:
    
*{data[3]}*''',
                                       parse_mode="Markdown")
                await bot.send_photo(message.chat.id,
                                     photo=open('qr.jpg', 'rb'))

            if message.text == '🌐 Ваш баланс':
                url = f'https://blockchain.info/rawaddr/{data[3]}'
                x = requests.get(url)
                wallet = x.json()

                await bot.send_message(
                    message.chat.id,
                    f'''💰 *Итоговый баланс:* {format(wallet['final_balance'] / 100000000, '.9f')} BTC
    
*Всего получено:* {format(wallet['total_received'] / 100000000, '.9f')} BTC
*Всего отправлено:* {format(wallet['total_sent'] / 100000000, '.9f')} BTC

https://www.blockchain.com/ru/btc/address/{data[3]}''',
                    parse_mode="Markdown")

            if message.text == '📤 Отправить BTC':
                sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                    1, message.chat.id)
                cursor.execute(sql)
                conn.commit()
                button = KeyboardButton('⬇️ Назад')
                kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button)
                # Отправляем сообщение с кнопкой
                await bot.send_message(
                    message.chat.id,
                    '📤 Отправьте *адрес биткойн кошелька*, куда хотите перевести BTC (Например: 12rAUoBgNgCqBpKTHwKksrAwkHBFdq1yvr)',
                    reply_markup=kb,
                    parse_mode="Markdown")

        if data[6] == 1:
            if message.text == '⬇️ Назад':
                sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                    0, message.chat.id)
                cursor.execute(sql)
                conn.commit()
                button = KeyboardButton('🌐 Ваш баланс')
                button2 = KeyboardButton('💳 Получить BTC')
                button3 = KeyboardButton('📤 Отправить BTC')
                kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button).add(
                    button2, button3)
                await bot.send_message(message.chat.id,
                                       'Вы вернулись в меню',
                                       reply_markup=kb)

            if message.text != '⬇️ Назад':
                result = re.match(
                    r'^(?=.*[0-9])(?=.*[a-zA-Z])[\da-zA-Z]{27,34}$',
                    message.text)

                if result is None:
                    mes = '''❗️*Ошибка*
Check that BTC wallet is entered correctly!'''
                    await bot.send_message(message.chat.id,
                                           mes,
                                           parse_mode="Markdown")
                else:
                    sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                        2, message.chat.id)
                    cursor.execute(sql)
                    conn.commit()
                    sql = "UPDATE users SET btc_sent = '{}' WHERE chatid = {}".format(
                        result.group(0), message.chat.id)
                    cursor.execute(sql)
                    conn.commit()
                    button = KeyboardButton('⬇️ Назад')
                    kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button)
                    # Отправляем сообщение с кнопкой
                    await bot.send_message(
                        message.chat.id,
                        f'💰 Отправьте сумму, которую хотите перевести по адресу *{result.group(0)}* в BTC (Например: 0.0001). *Комиссия перевода 0.0001 BTC*',
                        reply_markup=kb,
                        parse_mode="Markdown")
        if data[6] == 2:
            if message.text == '⬇️ Назад':
                sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                    0, message.chat.id)
                cursor.execute(sql)
                conn.commit()
                button = KeyboardButton('🌐 Ваш баланс')
                button2 = KeyboardButton('💳 Получить BTC')
                button3 = KeyboardButton('📤 Отправить BTC')
                kb = ReplyKeyboardMarkup(resize_keyboard=True).add(button).add(
                    button2, button3)
                await bot.send_message(message.chat.id,
                                       'Вы вернулись в меню',
                                       reply_markup=kb)

            if message.text != '⬇️ Назад':
                try:
                    sum = float(message.text)
                    url = f'https://blockchain.info/rawaddr/{data[3]}'
                    x = requests.get(url)
                    wallet = x.json()
                    if sum + 10000 <= wallet['final_balance'] / 100000000:
                        try:
                            my_key = PrivateKey(wif=data[4])
                            # Коммисия перевода, если поставить слишком маленькую, то транзакцию не примут
                            # И чем больше коммисия, тем быстрее пройдет перевод
                            fee = 10000
                            # Генерация транзакции
                            tx_hash = my_key.create_transaction(
                                [(data[5], sum, 'btc')],
                                fee=fee,
                                absolute_fee=True)
                            print(tx_hash)
                            url = 'https://blockchain.info/pushtx'
                            x = requests.post(url, data={'tx': tx_hash})
                            result = x.text
                            sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                                0, message.chat.id)
                            cursor.execute(sql)
                            conn.commit()
                            button = KeyboardButton('🌐 Ваш баланс')
                            button2 = KeyboardButton('💳 Получить BTC')
                            button3 = KeyboardButton('📤 Отправить BTC')
                            kb = ReplyKeyboardMarkup(
                                resize_keyboard=True).add(button).add(
                                    button2, button3)
                            await bot.send_message(message.chat.id,
                                                   result,
                                                   reply_markup=kb)
                        except Exception:
                            sql = "UPDATE users SET state = {} WHERE chatid = {}".format(
                                0, message.chat.id)
                            cursor.execute(sql)
                            conn.commit()
                            button = KeyboardButton('🌐 Ваш баланс')
                            button2 = KeyboardButton('💳 Получить BTC')
                            button3 = KeyboardButton('📤 Отправить BTC')
                            kb = ReplyKeyboardMarkup(
                                resize_keyboard=True).add(button).add(
                                    button2, button3)
                            await bot.send_message(
                                message.chat.id,
                                "⚠ Ошибка при выолнении транзакции",
                                reply_markup=kb)
                    else:
                        await bot.send_message(
                            message.chat.id,
                            '⚠️  На вашем балансе недостаточно средств.')
                except ValueError:
                    await bot.send_message(
                        message.chat.id,
                        '⚠️Неправильно введена сумма отправления, попробуйте еще раз'
                    )

    else:
        await bot.send_message(message.chat.id, 'Нажмите /start')