Exemplo n.º 1
0
def getAddress(id: str):
    # Initialise bitcoin.py
    setup('mainnet')
    wif = db.getWIF(id)

    priv = PrivateKey.from_wif(f"{wif}")

    pub = priv.get_public_key()

    address = pub.get_segwit_address().to_string()

    return address
Exemplo n.º 2
0
def tip_or_withdrawFunc(update, ctx):
    # Initialise bitcoin.py
    setup('mainnet')
    query = update.callback_query
    chID = query.message.chat.id
    msgID = query.message.message_id
    query.answer()
    data = str(query.data).split(",")
    sender = str(query.from_user.id)
    if sender == data[3]:
        if data[4] == "t":
            target = data[1]
            if data[0] == "Y":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)

                sender_wif = PrivateKey(db.getWIF(sender))
                fee = convertToSatoshis(Decimal(config.coin['minFee']))
                target_address = P2wpkhAddress(getAddress(target))
                sender_address = P2wpkhAddress(getAddress(sender))
                sender_balance = 0
                amount = convertToSatoshis(Decimal(data[2])) + fee

                unspent = requests.get(
                    f"{config.apiUrl}/unspent/{sender_address.to_string()}"
                ).json()["result"]
                txin = []
                for i in range(0, len(unspent)):
                    sender_balance += unspent[i]['value']
                    txin.append(
                        TxInput(unspent[i]['txid'], unspent[i]['index']))

                if sender_balance >= amount:

                    txout = []
                    txout.append(
                        TxOutput((amount - fee),
                                 target_address.to_script_pub_key()))

                    txchange = sender_balance - amount
                    if txchange > 0:
                        txout.append(
                            TxOutput(txchange,
                                     sender_address.to_script_pub_key()))

                    script_code = Script([
                        'OP_DUP', 'OP_HASH160',
                        sender_wif.get_public_key().to_hash160(),
                        'OP_EQUALVERIFY', 'OP_CHECKSIG'
                    ])

                    tx = Transaction(txin, txout, has_segwit=True)

                    tx.witnesses = []

                    for i in range(0, len(unspent)):
                        value = unspent[i]['value']
                        sig = sender_wif.sign_segwit_input(
                            tx, i, script_code, value)
                        tx.witnesses.append(
                            Script([sig,
                                    sender_wif.get_public_key().to_hex()]))

                    post_data = {'raw': tx.serialize()}

                    txid = requests.post(f"{config.apiUrl}/broadcast",
                                         data=post_data).json()['result']

                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"Success, sent @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}."
                    )
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"[View Transaction](https://sugar\\.wtf/esplora/tx/{str(txid)})",
                        parse_mode="MarkdownV2")
                else:
                    ctx.bot.send_message(
                        chat_id=chID,
                        text="You do not have enough funds to tip that amount")

            elif data[0] == "N":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)
                ctx.bot.send_message(
                    chat_id=chID,
                    text=
                    f"You declined sending @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}"
                )

        elif data[4] == "w":
            if data[0] == "Y":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)

                sender_wif = PrivateKey(db.getWIF(sender))
                fee = convertToSatoshis(Decimal(config.coin['minFee']))
                sender_address = P2wpkhAddress(getAddress(sender))
                sender_balance = 0
                amount = convertToSatoshis(Decimal(data[2])) + fee
                target_address = P2wpkhAddress("sugar1q" + data[1])

                unspent = requests.get(
                    f"{config.apiUrl}/unspent/{sender_address.to_string()}"
                ).json()['result']

                txin = []
                for i in range(0, len(unspent)):
                    sender_balance += unspent[i]['value']
                    txin.append(
                        TxInput(unspent[i]['txid'], unspent[i]['index']))

                if sender_balance >= amount:
                    txout = []

                    txout.append(
                        TxOutput((amount - fee),
                                 target_address.to_script_pub_key()))

                    txchange = sender_balance - amount
                    if txchange > 0:
                        txout.append(
                            TxOutput(txchange,
                                     sender_address.to_script_pub_key()))

                    script_code = Script([
                        'OP_DUP', 'OP_HASH160',
                        sender_wif.get_public_key().to_hash160(),
                        'OP_EQUALVERIFY', 'OP_CHECKSIG'
                    ])

                    tx = Transaction(txin, txout, has_segwit=True)

                    tx.witnesses = []

                    for i in range(0, len(unspent)):
                        value = unspent[i]['value']
                        sig = sender_wif.sign_segwit_input(
                            tx, i, script_code, value)
                        tx.witnesses.append(
                            Script([sig,
                                    sender_wif.get_public_key().to_hex()]))

                    post_data = {'raw': tx.serialize()}

                    txid = requests.post(f"{config.apiUrl}/broadcast",
                                         data=post_data).json()['result']

                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"Success, withdrew {data[2]} {config.coin['ticker']} to address {target_address.to_string()} "
                    )
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"[View Transaction](https://sugar\\.wtf/esplora/tx/{str(txid)})",
                        parse_mode="MarkdownV2")
                else:
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        "You do not have enough funds to withdraw the specified amount."
                    )
            elif data[0] == "N":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)
                ctx.bot.send_message(
                    chat_id=chID,
                    text=
                    f"You declined withdrawing {data[2]} {config.coin['ticker']} to address {'sugar1q' + data[1]}"
                )
Exemplo n.º 3
0
def tip_or_withdrawFunc(update, ctx):
    # Initialise bitcoin.py
    setup('mainnet')
    query = update.callback_query
    chID = query.message.chat.id
    msgID = query.message.message_id
    query.answer()
    data = str(query.data).split(",")
    sender = str(query.from_user.id)
    chatid = query.message.chat_id
    if sender == data[3]:
        if data[4] == "t":
            target = data[1]
            if data[0] == "Y":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)

                sender_wif = PrivateKey(db.getWIF(sender))
                fee = convertToSatoshis(Decimal(config.coin['minFee']))
                #target_address = P2wpkhAddress(getAddress(target))
                target_address = P2pkhAddress(getAddress(target))
                #sender_address = P2wpkhAddress(getAddress(sender))
                sender_address = P2pkhAddress(getAddress(sender))
                sender_balance = 0
                amount = convertToSatoshis(Decimal(data[2])) + fee

                unspent = requests.get(
                    f"{config.apiUrl}/unspent/{sender_address.to_string()}"
                ).json()["result"]
                txin = []
                for i in range(0, len(unspent)):
                    sender_balance += unspent[i]['value']
                    txin.append(
                        TxInput(unspent[i]['txid'], unspent[i]['index']))

                if sender_balance >= amount:
                    txout = []
                    txout = (TxOutput((amount - fee),
                                      Script([
                                          'OP_DUP', 'OP_HASH160',
                                          target_address.to_hash160(),
                                          'OP_EQUALVERIFY', 'OP_CHECKSIG'
                                      ])))

                    txchange = sender_balance - amount
                    if txchange > 0:
                        change_txout = (TxOutput(
                            txchange, sender_address.to_script_pub_key()))

                    script_code = Script([
                        'OP_DUP', 'OP_HASH160',
                        sender_wif.get_public_key().to_hash160(),
                        'OP_EQUALVERIFY', 'OP_CHECKSIG'
                    ])

                    tx = Transaction(txin, [txout, change_txout])

                    # get public key as hex
                    pk = sender_wif.get_public_key().to_hex()

                    sigpk = []

                    for i in range(0, len(unspent)):
                        value = unspent[i]['value']
                        sig = sender_wif.sign_input(
                            tx, i,
                            Script([
                                'OP_DUP', 'OP_HASH160',
                                sender_address.to_hash160(), 'OP_EQUALVERIFY',
                                'OP_CHECKSIG'
                            ]))
                        sigpk.append(Script([sig, pk]))
                        txin[i].script_sig = sigpk[i]

                    #signed_tx = tx.serialize()
                    #print("\nRaw signed transaction:\n" + signed_tx)
                    #exit(0)

                    post_data = {'raw': tx.serialize()}

                    txid = requests.post(f"{config.apiUrl}/broadcast",
                                         data=post_data).json()['result']

                    if checkRus(chatid):
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"Успешно, отправлено @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}."
                        )
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"[Детали транзакции](https://ytn.ccore.online/transaction/{str(txid)})",
                            parse_mode="MarkdownV2")
                    else:
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"Success, sent @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}."
                        )
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"[View Transaction](https://ytn.ccore.online/transaction/{str(txid)})",
                            parse_mode="MarkdownV2")
                else:
                    if checkRus(chatid):
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            "У вас недостаточно средств, чтобы дать эту сумму чаевых"
                        )
                    else:
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            "You do not have enough funds to tip that amount")

            elif data[0] == "N":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)
                if checkRus(chatid):
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"Вы отказались от отправки @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}"
                    )
                else:
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"You declined sending @{db.getUserName(data[1])} {data[2]} {config.coin['ticker']}"
                    )

        elif data[4] == "w":
            if data[0] == "Y":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)

                sender_wif = PrivateKey(db.getWIF(sender))
                fee = convertToSatoshis(Decimal(config.coin['minFee']))
                #sender_address = P2wpkhAddress(getAddress(sender))
                sender_address = P2pkhAddress(getAddress(sender))
                sender_balance = 0
                amount = convertToSatoshis(Decimal(data[2])) + fee
                #target_address = P2wpkhAddress("ytn1q" + data[1])
                #target = data[1]
                target_address = P2pkhAddress("Y" + data[1])

                unspent = requests.get(
                    f"{config.apiUrl}/unspent/{sender_address.to_string()}"
                ).json()['result']

                txin = []
                for i in range(0, len(unspent)):
                    sender_balance += unspent[i]['value']
                    txin.append(
                        TxInput(unspent[i]['txid'], unspent[i]['index']))

                if sender_balance >= amount:
                    txout = []

                    txout = (TxOutput((amount - fee),
                                      Script([
                                          'OP_DUP', 'OP_HASH160',
                                          target_address.to_hash160(),
                                          'OP_EQUALVERIFY', 'OP_CHECKSIG'
                                      ])))

                    txchange = sender_balance - amount
                    if txchange > 0:
                        change_txout = (TxOutput(
                            txchange, sender_address.to_script_pub_key()))

                    script_code = Script([
                        'OP_DUP', 'OP_HASH160',
                        sender_wif.get_public_key().to_hash160(),
                        'OP_EQUALVERIFY', 'OP_CHECKSIG'
                    ])

                    tx = Transaction(txin, [txout, change_txout])

                    # get public key as hex
                    pk = sender_wif.get_public_key().to_hex()

                    sigpk = []

                    for i in range(0, len(unspent)):
                        value = unspent[i]['value']
                        sig = sender_wif.sign_input(
                            tx, i,
                            Script([
                                'OP_DUP', 'OP_HASH160',
                                sender_address.to_hash160(), 'OP_EQUALVERIFY',
                                'OP_CHECKSIG'
                            ]))
                        sigpk.append(Script([sig, pk]))
                        txin[i].script_sig = sigpk[i]

                    #signed_tx = tx.serialize()
                    #print("\nRaw signed transaction:\n" + signed_tx)
                    #exit(0)

                    post_data = {'raw': tx.serialize()}

                    txid = requests.post(f"{config.apiUrl}/broadcast",
                                         data=post_data).json()['result']

                    if checkRus(chatid):
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"Успех, сняли {data[2]} {config.coin['ticker']} to address {target_address.to_string()} "
                        )
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"[Детали транзакции](https://ytn.ccore.online/transaction/{str(txid)})",
                            parse_mode="MarkdownV2")
                    else:
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"Success, withdrew {data[2]} {config.coin['ticker']} to address {target_address.to_string()} "
                        )
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            f"[View Transaction](https://ytn.ccore.online/transaction/{str(txid)})",
                            parse_mode="MarkdownV2")
                else:
                    if checkRus(chatid):
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            "У вас недостаточно средств для вывода указанной суммы."
                        )
                    else:
                        ctx.bot.send_message(
                            chat_id=chID,
                            text=
                            "You do not have enough funds to withdraw the specified amount."
                        )
            elif data[0] == "N":
                ctx.bot.delete_message(chat_id=chID, message_id=msgID)
                if checkRus(chatid):
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"Вы отказались снимать {data[2]} {config.coin['ticker']} to address {'Y' + data[1]}"
                    )
                else:
                    ctx.bot.send_message(
                        chat_id=chID,
                        text=
                        f"You declined withdrawing {data[2]} {config.coin['ticker']} to address {'Y' + data[1]}"
                    )