Ejemplo n.º 1
0
def getotherbalance(wallet_id):
    wallet = Wallets.query.filter_by(id=wallet_id).first()
    wallet_obj = wallet_create_or_open(name=constants.WALLET_NAME,
                                       purpose=constants.PURPOSE,
                                       account_id=constants.ACCOUNT_ID,
                                       network=constants.BITCOIN_NETWORK)
    walletkey = wallet_obj.import_key(account_id=constants.ACCOUNT_ID,
                                      key=wallet.key)
    return walletkey.balance()
Ejemplo n.º 2
0
def getbalance(profile):
    user = Users.query.filter_by(auth0_id=profile["auth0_id"]).first()
    wallet = Wallets.query.filter_by(user_id=user.id).first()
    wallet_obj = wallet_create_or_open(name=constants.WALLET_NAME,
                                       purpose=constants.PURPOSE,
                                       account_id=constants.ACCOUNT_ID,
                                       network=constants.BITCOIN_NETWORK)
    walletkey = wallet_obj.import_key(account_id=constants.ACCOUNT_ID,
                                      key=wallet.key)
    return walletkey.balance()
Ejemplo n.º 3
0
    def post(self, request):
        try:
            print('Started ' + self.__class__.__name__ + ' post method ')
            data = JSONParser().parse(request)
            username = data.get('username')
            print('Wallet creation for username='******'network') == 'bitcoin':
                    w = wallet_create_or_open(data.get('wallet_name'),
                                              network='bitcoin',
                                              username=data.get('username'),
                                              account_id=user.user_id,
                                              db_uri=db_uri)
                elif data.get('network') == 'litecoin':
                    w = wallet_create_or_open(data['wallet_name'],
                                              network='litecoin',
                                              username=data.get('username'),
                                              account_id=user.user_id,
                                              db_uri=db_uri)

                w.utxos_update()
                w.info(detail=3)
                print('wallet ', w)
                print('w.get_key()', w.get_key())
                print('w.get_key().address ', w.get_key().address)
                return JsonResponse(serializer.data, status=201)
            else:
                response_dict = {
                    'status': 'error',
                    # the format of error message determined by you base exception class
                    'msg': serializer.errors
                }
                return JsonResponse(response_dict, status=400)

        except Exception as e:
            track = traceback.format_exc()
            print(track)
            print("error" + str(e))
            raise e
Ejemplo n.º 4
0
    def post(self, request):
        try:

            data = JSONParser().parse(request)
            print('username ', data['username'])
            user = Util.get_user(data['username'])
            serializer = WalletSerializer(data=data)
            if serializer.is_valid():
                print('username ', data['username'])
                if data['type'] == 'BTC':
                    w = wallet_create_or_open(data['wallet_name'],
                                              network='bitcoin',
                                              username=data['username'],
                                              account_id=user.user_id,
                                              db_uri=db_uri)
                    w.utxos_update()
                    w.info(detail=3)
                elif data['type'] == 'LTC':
                    w = wallet_create_or_open(data['wallet_name'],
                                              network='litecoin',
                                              username=data['username'],
                                              account_id=user.user_id,
                                              db_uri=db_uri)
                    w.utxos_update()
                    w.info(detail=3)
                print('wallet ', w)
                print('w.get_key()', w.get_key())
                print('w.get_key().address ', w.get_key().address)
                return JsonResponse(serializer.data, status=201)
        except Exception as e:
            track = traceback.format_exc()
            print(track)
            print("error" + str(e))
            raise e
            return HttpResponse(status=404)
        return JsonResponse(serializer.errors, status=400)
Ejemplo n.º 5
0
def getnewaddress():
    wallet_obj = wallet_create_or_open(name=constants.WALLET_NAME,
                                       purpose=constants.PURPOSE,
                                       account_id=constants.ACCOUNT_ID,
                                       network=constants.BITCOIN_NETWORK)
    key = wallet_obj.new_key()
    re_val = {
        "account_id": constants.ACCOUNT_ID,
        "wallet_name": constants.WALLET_NAME,
        "purpose": constants.PURPOSE,
        "network": constants.BITCOIN_NETWORK,
        "key": key.wif,
        "balance": key.balance(),
        "address": key.address
    }
    return re_val
Ejemplo n.º 6
0
def store_data(network):  # pragma: no cover
    srv = SmurferService(network)
    form = StoreDataForm()
    tx_fee = srv.estimatefee(10) // 10
    if form.validate_on_submit():
        w = wallet_create_or_open('BS_embed_data_wallet',
                                  witness_type='p2sh-segwit',
                                  network=srv.network.name)
        w.scan(scan_gap_limit=1)
        if w.balance():
            lock_script = b'\x6a' + varstr(form.data.data)
            t = w.send([Output(0, lock_script=lock_script)],
                       fee=form.transaction_fee.data)
            return render_template(
                'explorer/store_data_send.html',
                title=_('Push Transaction'),
                subtitle=_('Embed the data on the %s network' %
                           srv.network.name),
                transaction=t,
                t=t)
        else:
            k = w.get_key()
            message = "Store%20Data%20-%20Blocksmurfer"
            paymentlink = '%s:%s?amount=%.8f&message=%s' % \
                          (srv.network.name, k.address, form.transaction_fee.data * srv.network.denominator, message)
            return render_template(
                'explorer/store_data_fund.html',
                title=_('Fund Transaction'),
                subtitle=_(
                    'Fund the %s transaction and store data on the blockchain'
                    % srv.network.name),
                address=k.address,
                tx_fee=form.transaction_fee.data,
                data=form.data.data,
                paymentlink=paymentlink)

    return render_template('explorer/store_data.html',
                           title=_('Store data'),
                           subtitle=_('Embed data on the %s blockchain' %
                                      srv.network.name),
                           form=form,
                           tx_fee=tx_fee)
Ejemplo n.º 7
0
    def get(self, request):
        try:

            srv = Service(providers=['blockchair'])
            print(srv.estimatefee(5))
            print('fee created')

            print('wallet starts')
            srv = LitecoindClient()
            print(srv.estimatefee(5))
            print('litecoin fee created')

            print('new adress', srv.getnewaddress())

            # tx = srv.getutxos('LbLCMRq2oiNgxxesrg7SoCBAMsAAMTqmB9')

            print('wallet starts')
            srv = BitcoindClient()
            print(srv.estimatefee(5))
            print('bitcoin fee created')

            print('bitcoin new adress', srv.getnewaddress())

            print('wallet created in local')
            db_uri = 'postgresql://*****:*****@localhost:5432/altcoin'
            w = wallet_create_or_open('wallet_mysql3', db_uri=db_uri)
            print('wallet created in remote')
            # w = HDWallet.create('Walletmsql1',)
            print('wallet created')
        except Exception:
            track = traceback.format_exc()
            print('-------track start--------')
            print(track)
            print('-------track end--------')

            return HttpResponse(status=404)
        return JsonResponse('', status=400, safe=False)
Ejemplo n.º 8
0
def func_walletupdate():
    connection = pymysql.connect(host=db_host,
                                 user=db_user,
                                 password=db_pass,
                                 db=db_name,
                                 unix_socket=db_sock)

    cursor = connection.cursor(pymysql.cursors.DictCursor)
    # Current ACCOUNT_ID: 4, PURPOSE: 44
    sql = "SELECT * FROM `wallet_infos` WHERE `account_id`=%s AND `wallet_name`=%s AND `network`=%s AND `purpose`=%s AND `status`=%s"
    cursor.execute(sql,
                   (constants.ACCOUNT_ID, constants.WALLET_NAME,
                    constants.BITCOIN_NETWORK, constants.PURPOSE, "pending"))
    walletinfos = cursor.fetchall()

    # Get wallet
    wallet = wallet_create_or_open(name=constants.WALLET_NAME,
                                   purpose=constants.PURPOSE,
                                   account_id=constants.ACCOUNT_ID,
                                   network=constants.BITCOIN_NETWORK)
    wallet._balance_update(account_id=constants.ACCOUNT_ID,
                           network=constants.BITCOIN_NETWORK)
    wallet.utxos_update(account_id=constants.ACCOUNT_ID, update_balance=True)

    sql = "SELECT * FROM `games` ORDER BY id DESC LIMIT 1"
    cursor.execute(sql)
    currentgame = cursor.fetchone()

    if currentgame:
        # Check wallet info
        for walletinfo in walletinfos:
            walletkey = wallet.import_key(account_id=constants.ACCOUNT_ID,
                                          key=walletinfo["key"])

            delay = 0
            if len(walletinfo["addrGenDate"]) <= 15:
                epoch_time = int(time.time())
                wallet_date = int(walletinfo["addrGenDate"][1:][:10])
                wallet_date = datetime.fromtimestamp(wallet_date /
                                                     1000).strftime("%d")
                current_date = datetime.fromtimestamp(epoch_time /
                                                      1000).strftime("%d")
                delay = int(current_date) - int(wallet_date)
                print("======", delay)

            if walletkey.balance(
            ) > 0 and delay > 1 and walletinfo["status"] is "pending":
                sql = "DELETE FROM `pixel_infos` WHERE `id`=%s"
                cursor.execute(sql, walletinfo["pixelinfo_id"])
                connection.commit()
                sql = "DELETE FROM `wallet_infos` WHERE `id`=%s"
                cursor.execute(sql, walletinfo["id"])
                connection.commit()

            # addresslst = []
            # addresslst.append(walletkey.address)
            # srv = Service(network=constants.BITCOIN_NETWORK, providers=['blockexplorer', 'blockchaininfo'])
            # srv.getbalance(addresslst)
            # srv.gettransactions(addresslst)
            # srv.getutxos(addresslst)

            print("=== HDWalletKey ===", walletkey.address,
                  walletkey.balance())
            if walletkey.balance() != 0:
                pixelinfo_id = walletinfo["pixelinfo_id"]
                sql = "SELECT * FROM `pixel_infos` WHERE `id`=%s"
                cursor.execute(sql, pixelinfo_id)
                pixelinfo = cursor.fetchone()
                pixel_price = currentgame["pixel_price"]
                agreedbtc = (pixelinfo["widthv"] * pixelinfo["heightv"] * constants.BITCOIN_CONVERT) * pixel_price\
                    * (1 - constants.BITCOIN_FEE)
                # print("=== Agreed Bitcoin Amount ===", agreedbtc)
                if walletkey.balance() >= agreedbtc:
                    sql = "UPDATE `wallet_infos` SET `balance`=%s, `status`='accepted' WHERE `id`=" + str(
                        walletinfo["id"])
                    cursor.execute(sql, (walletkey.balance()))
                    connection.commit()
                else:
                    sql = "UPDATE `wallet_infos` SET `balance`=%s WHERE `id`=" + str(
                        walletinfo["id"])
                    cursor.execute(sql, (walletkey.balance()))
                    connection.commit()

    connection.close()
Ejemplo n.º 9
0
from bitcoinlib.wallets import Wallet, wallet_delete, wallet_create_or_open
from bitcoinlib.transactions import *

# Create or open Wallets (Wallet1, Wallet2)
w3 = wallet_create_or_open('Wallet3', network='testnet', witness_type='segwit')
w4 = wallet_create_or_open('Wallet4', network='testnet', witness_type='segwit')

# Get the keys and addresses:
key3 = w3.get_key()
address3 = key3.address
key4 = w4.get_key()
address4 = key4.address
print("**** Wallet3 Address ****")
print(address3)
print(key3)
print("**** Wallet4 Address ****")
print(address4)
print(key4)
print("********")

# Scan Wallet1 for transactions and UTXOs:
w3.scan()
w4.scan()
print("**** Wallet Info ****")
print(w3.info())
print(w4.info())
print("**** UTXOS updating... ****")
w3.utxos_update()
w4.utxos_update()
print("**** UTXOS ****")
print(w3.utxos())
from bitcoinlib.wallets import wallet_create_or_open, wallet_create_or_open_multisig
from bitcoinlib.keys import HDKey
from time import sleep

wif = 'tprv8ZgxMBicQKsPdpenF8SX1WMsr6eaS3rZgqhqVu1LJ3wkAp1NhREnFrsvzK4A7ERrHhxqjzZpoESRjwpgrrhjC1cWALzZRxoycCNz8jBNWre'
wif2 = 'tprv8ZgxMBicQKsPdktmSG4hGs6kq3dmTMmiDtLZwaipsCYxqbhtqWH69kNGZvNufnemLTCP3gbypLf1koKfAEujo5cnWPKBg3YbpZa63J9Cqtj'
cowif2 = HDKey(wif2).account_multisig_key()

#
# CREATE WALLETS
#

# Segwit P2SH-P2WPKH Wallet
w1 = wallet_create_or_open('segwit_testnet_p2sh_p2wpkh',
                           key=wif,
                           witness_type='p2sh-segwit',
                           network='testnet')
w1_key = w1.get_key()

# Segwit Native P2WPKH Wallet
w2 = wallet_create_or_open('segwit_testnet_p2wpkh',
                           key=wif,
                           witness_type='segwit',
                           network='testnet')
w2_key = w2.get_key()

# Segwit Native P2WSH Wallet
w3 = wallet_create_or_open_multisig('segwit_testnet_p2wsh',
                                    key_list=[wif, cowif2.public()],
                                    witness_type='segwit',
                                    network='testnet')
Ejemplo n.º 11
0
from bitcoinlib.keys import HDKey
from bitcoinlib.wallets import wallet_create_or_open

tx_fee = 500
tx_amount = 1000
wif = 'tprv8ZgxMBicQKsPdd7kWYnxC5BTucY6fESWSA9tWwtKiSpasvL1WDbtHNEU8sZDTWcoxG2qYzBA5HFWzR2NoxgG2MTyR8PeCry266DbmjF8pT4'
wif2 = 'tprv8ZgxMBicQKsPe2Fpzm7zK6WsUqcYGZsZe3vwvQGLEqe8eunrxJXXxaw3pF283uQ9J7EhTVazDhKVquwk8a5K1rSx3T9qZJiNHkzJz3sRrWd'

#
# CREATE WALLETS
#

# Segwit P2SH-P2WPKH Wallet
w1 = wallet_create_or_open('segwit_testnet_p2sh_p2wpkh',
                           keys=wif,
                           witness_type='p2sh-segwit',
                           network='testnet')
w1_key = w1.get_key()

# Segwit Native P2WPKH Wallet
w2 = wallet_create_or_open('segwit_testnet_p2wpkh',
                           keys=wif,
                           witness_type='segwit',
                           network='testnet')
w2_key = w2.get_key()

# Segwit Native P2WSH Wallet
w3 = wallet_create_or_open(
    'segwit_testnet_p2wsh',
    keys=[
        wif,
Ejemplo n.º 12
0
        }
    }
})

#Code used to initialize wallets, which are now used in each running of the script
NETWORK = 'testnet'
#k1 = HDKey('tprv8ZgxMBicQKsPd1Q44tfDiZC98iYouKRC2CzjT3HGt1yYw2zuX2awTotzGAZQEAU9bi2M5MCj8iedP9MREPjUgpDEBwBgGi2C8eK'
#           '5zNYeiX8', network=NETWORK)
#k2 = HDKey('tprv8ZgxMBicQKsPeUbMS6kswJc11zgVEXUnUZuGo3bF6bBrAg1ieFfUdPc9UHqbD5HcXizThrcKike1c4z6xHrz6MWGwy8L6YKVbgJ'
#           'MeQHdWDp', network=NETWORK)

#w1 = HDWallet.create('multisig_2of2_cosigner1', sigs_required=2, keys=[k1, k2.public_master(multisig=True)], network=NETWORK)
#w2 = HDWallet.create('multisig_2of2_cosigner2',  sigs_required=2, keys=[k1.public_master(multisig=True), k2], network=NETWORK)

#open multisig wallet M
w1 = wallet_create_or_open('multisig_2of2_cosigner1')
w2 = wallet_create_or_open('multisig_2of2_cosigner2')
wal3 = wallet_create_or_open('rcvr', network=NETWORK)
wal4 = wallet_create_or_open('sndr', network=NETWORK)
print((wal3.addresslist()))
#print(w2.address)

#initialize trasaction on wallet 1
w1.utxos_update()
tswap = w1.send_to(wal3.addresslist()[0], 2, network=NETWORK)
treturn = w1.send_to(wal4.addresslist()[0], 2, network=NETWORK)

tswap.info()
treturn.info()

#sign and sent transaction on wallet 2