예제 #1
0
파일: view_.py 프로젝트: snaik7/altcoin
    def post(self, request):
        print("enter wallet send")
        try:
            data = JSONParser().parse(request)
            wallet_id = data.get('wallet_id')
            address = data.get('address')
            amount = data.get('amount')
            print('wallet_id ' + str(wallet_id))
            print('address ' + str(address))
            '''
            print('wallet starts')
            srv = BitcoindClient()
            print(srv.getutxos('1CRkjhJgWC6tPNdfqnXRgYDPniSScHenuP'))
            print('bitcoin fee created')
            '''

            wallet = HDWallet(wallet_id, db_uri=db_uri)
            print(' wallet.username ',
                  wallet.key_for_path('m/44\'/0\'/1\'/0/0'))

            user = User.objects.filter(username=wallet.username)
            print('user', user)
            if user.count() > 0:
                user = user[0]
                print('wallets  ', wallet, ' user_id ', user.user_id)

                from_wallet_key = wallet.key(wallet.name)
                print('from wallet key', from_wallet_key.key_id)
                print('to wallet key as same ', wallet.key(address))

                # print('performing txn update  update db')
                # wallet.transactions_update(account_id=user.user_id,key_id=from_wallet.key_id)

                utx = wallet.utxos_update(account_id=user.user_id)
                wallet.info()
                wallet.get_key()
                print('key change', wallet.get_key_change())
                utxos = wallet.utxos(account_id=user.user_id)
                res = wallet.send_to(address, amount)
                print("Send transaction result:")
                if res.hash:
                    print("Successfully send, tx id:", res.hash)
                else:
                    print("TX not send, result:", res.errors)

                return JsonResponse(res.as_dict(), safe=False)

        except Exception as e:
            track = traceback.format_exc()
            logger.exception(track)
            raise e
예제 #2
0
def main():
    print("Command Line Wallet for BitcoinLib\n")
    # --- Parse commandline arguments ---
    args = parse_args()

    databasefile = DEFAULT_DATABASE
    if args.database:
        databasefile = os.path.join(BCL_DATABASE_DIR, args.database)

    if args.generate_key:
        passphrase = get_passphrase(args)
        passphrase = ' '.join(passphrase)
        seed = binascii.hexlify(Mnemonic().to_seed(passphrase))
        hdkey = HDKey.from_seed(seed, network=args.network)
        print(
            "Private master key, to create multisig wallet on this machine: %s"
            % hdkey.wif())
        print(
            "Public account key, to share with other cosigner multisig wallets: %s"
            %
            hdkey.public_master(witness_type=args.witness_type, multisig=True))
        print("Network: %s" % hdkey.network.name)
        clw_exit()

    # List wallets, then exit
    if args.list_wallets:
        print("BitcoinLib wallets:")
        for w in wallets_list(databasefile=databasefile):
            if 'parent_id' in w and w['parent_id']:
                continue
            print("[%d] %s (%s) %s" %
                  (w['id'], w['name'], w['network'], w['owner']))
        clw_exit()

    # Delete specified wallet, then exit
    if args.wallet_remove:
        if not wallet_exists(args.wallet_name, databasefile=databasefile):
            clw_exit("Wallet '%s' not found" % args.wallet_name)
        inp = input(
            "\nWallet '%s' with all keys and will be removed, without private key it cannot be restored."
            "\nPlease retype exact name of wallet to proceed: " %
            args.wallet_name)
        if inp == args.wallet_name:
            if wallet_delete(args.wallet_name,
                             force=True,
                             databasefile=databasefile):
                clw_exit("\nWallet %s has been removed" % args.wallet_name)
            else:
                clw_exit("\nError when deleting wallet")
        else:
            clw_exit("\nSpecified wallet name incorrect")

    wlt = None
    if args.wallet_name and not args.wallet_name.isdigit(
    ) and not wallet_exists(args.wallet_name, databasefile=databasefile):
        if not args.create_from_key and input(
                "Wallet %s does not exist, create new wallet [yN]? " %
                args.wallet_name).lower() != 'y':
            clw_exit('Aborted')
        wlt = create_wallet(args.wallet_name, args, databasefile)
        args.wallet_info = True
    else:
        try:
            wlt = HDWallet(args.wallet_name, databasefile=databasefile)
            if args.passphrase is not None:
                print(
                    "WARNING: Using passphrase option for existing wallet ignored"
                )
            if args.create_from_key is not None:
                print(
                    "WARNING: Using create_from_key option for existing wallet ignored"
                )
        except WalletError as e:
            clw_exit("Error: %s" % e.msg)

    if wlt is None:
        clw_exit("Could not open wallet %s" % args.wallet_name)

    if args.import_private:
        if wlt.import_key(args.import_private):
            clw_exit("Private key imported")
        else:
            clw_exit("Failed to import key")

    if args.wallet_recreate:
        wallet_empty(args.wallet_name)
        print("Removed transactions and generated keys from this wallet")
    if args.update_utxos:
        wlt.utxos_update()
    if args.update_transactions:
        wlt.scan(scan_gap_limit=5)

    if args.export_private:
        if wlt.scheme == 'multisig':
            for w in wlt.cosigner:
                if w.main_key and w.main_key.is_private:
                    print(w.main_key.wif)
        elif not wlt.main_key or not wlt.main_key.is_private:
            print("No private key available for this wallet")
        else:
            print(wlt.main_key.wif)
        clw_exit()

    if args.network is None:
        args.network = wlt.network.name

    tx_import = None
    if args.import_tx_file:
        try:
            fn = args.import_tx_file
            f = open(fn, "r")
        except FileNotFoundError:
            clw_exit("File %s not found" % args.import_tx_file)
        try:
            tx_import = ast.literal_eval(f.read())
        except (ValueError, SyntaxError):
            tx_import = f.read()
    if args.import_tx:
        try:
            tx_import = ast.literal_eval(args.import_tx)
        except (ValueError, SyntaxError):
            tx_import = args.import_tx
    if tx_import:
        if isinstance(tx_import, dict):
            wt = wlt.transaction_import(tx_import)
        else:
            wt = wlt.transaction_import_raw(tx_import, network=args.network)
        wt.sign()
        if args.push:
            res = wt.send()
            if res:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.hash)
            else:
                print("Error creating transaction: %s" % wt.error)
        wt.info()
        print("Signed transaction:")
        print_transaction(wt)
        clw_exit()

    if args.receive:
        keys = wlt.get_key(network=args.network, number_of_keys=args.receive)
        if args.receive != 1:
            keys += wlt.get_key_change(network=args.network,
                                       number_of_keys=args.receive)
        keys = [keys] if not isinstance(keys, list) else keys
        print("Receive address(es):")
        for key in keys:
            addr = key.address
            print(addr)
            if QRCODES_AVAILABLE and args.receive == 1:
                qrcode = pyqrcode.create(addr)
                print(qrcode.terminal())
        if not QRCODES_AVAILABLE and args.receive == 1:
            print(
                "Install qr code module to show QR codes: pip install pyqrcode"
            )
        clw_exit()
    if args.create_transaction == []:
        clw_exit("Missing arguments for --create-transaction/-t option")
    if args.create_transaction:
        if args.fee_per_kb:
            clw_exit("Fee-per-kb option not allowed with --create-transaction")
        try:
            wt = create_transaction(wlt, args.create_transaction, args)
        except WalletError as e:
            clw_exit("Cannot create transaction: %s" % e.msg)
        wt.sign()
        print("Transaction created")
        wt.info()
        if args.push:
            wt.send()
            if wt.pushed:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.hash)
            else:
                print("Error creating transaction: %s" % wt.error)
        else:
            print(
                "\nTransaction created but not send yet. Transaction dictionary for export: "
            )
            print_transaction(wt)
        clw_exit()
    if args.sweep:
        if args.fee:
            clw_exit("Fee option not allowed with --sweep")
        offline = True
        print("Sweep wallet. Send all funds to %s" % args.sweep)
        if args.push:
            offline = False
        wt = wlt.sweep(args.sweep,
                       offline=offline,
                       network=args.network,
                       fee_per_kb=args.fee_per_kb)
        if not wt:
            clw_exit(
                "Error occurred when sweeping wallet: %s. Are UTXO's available and updated?"
                % wt)
        wt.info()
        if args.push:
            if wt.pushed:
                print("Transaction pushed to network. Transaction ID: %s" %
                      wt.hash)
            elif not wt:
                print("Cannot sweep wallet, are UTXO's updated and available?")
            else:
                print("Error sweeping wallet: %s" % wt.error)
        else:
            print(
                "\nTransaction created but not send yet. Transaction dictionary for export: "
            )
            print_transaction(wt)
        clw_exit()

    # print("Updating wallet")
    if args.network == 'bitcoinlib_test':
        wlt.utxos_update()
    print("Wallet info for %s" % wlt.name)
    wlt.info()
utxos = wallet3o5.utxos()
wallet3o5.info()

# Creating transactions just like in a normal wallet, then send raw transaction to other cosigners. They
# can sign the transaction with there on key and pass it on to the next signer or broadcast it to the network.
# You can use bitcoinlib/tools/sign_raw.py to import and sign a raw transaction.

t = None
if utxos:
    print("\nNew unspent outputs found!")
    print(
        "Now a new transaction will be created to sweep this wallet and send bitcoins to a testnet faucet"
    )
    send_to_address = '2NGZrVvZG92qGYqzTLjCAewvPZ7JE8S8VxE'
    t = wallet3o5.sweep(send_to_address, min_confirms=0, offline=True)
    print(
        "Now send the raw transaction hex to one of the other cosigners to sign using sign_raw.py"
    )
    print("Raw transaction: %s" % t.raw_hex())
else:
    print("Please send funds to %s, so we can create a transaction" %
          wallet3o5.get_key().address)
    print("Restart this program when funds are send...")

# Sign the transaction with 2 other cosigner keys and push the transaction
if t:
    t.sign(cosigners[0]['key'])
    t.sign(cosigners[4]['key'])
    t.send()
    t.info()
예제 #4
0
            wlt = create_wallet(args.wallet_name, args, databasefile)
            args.wallet_info = True
    else:
        try:
            wlt = HDWallet(args.wallet_name, databasefile=databasefile)
            if args.passphrase is not None or args.passphrase_strength is not None:
                print(
                    "WARNING: Using passphrase options for existing wallet ignored"
                )
        except WalletError as e:
            clw_exit("Error: %s" % e.msg)
    if wlt is None:
        clw_exit("Could not open wallet %s" % args.wallet_name)

    if args.receive:
        addr = wlt.get_key().address
        print("Receive address is %s" % addr)
        if QRCODES_AVAILABLE:
            qrcode = pyqrcode.create(addr)
            print(qrcode.terminal())
        else:
            print(
                "Install qr code module to show QR codes: pip install pyqrcode"
            )
        clw_exit()
    if args.scan:
        print("Scanning wallet: updating addresses, transactions and balances")
        print("Can take a while")
        wlt.scan()
        print("Scanning complete, show wallet info")
        wlt.info()
예제 #5
0
    utxos = online_wallet.utxos()
    if utxos:
        print("\nNew unspent outputs found!")
        print(
            "Now a new transaction will be created to sweep this wallet and send bitcoins to a testnet faucet"
        )
        send_to_address = 'n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi'
        t = online_wallet.sweep(send_to_address, min_confirms=0)
        print(t.raw_hex())
        print(
            "Now copy-and-paste the raw transaction hex to your Offline PC and sign it there with a second signature:"
        )
        print("\nfrom bitcoinlib.wallets import HDWallet")
        print("")
        print("wlt = HDWallet('%s')" % WALLET_NAME)
        print("utxos = ", end='')
        pprint(utxos)
        print("")
        print("wlt.utxos_update(utxos=utxos)")
        print("t = wlt.transaction_import_raw('%s')" % t.raw_hex())
        print("t.sign()")
        print("")
        print(
            "# Push the following raw transaction to the blockchain network on any online PC:"
        )
        print("print(t.raw_hex())")
    else:
        print("\nPlease send funds to %s, so we can create a transaction" %
              online_wallet.get_key().address)
        print("\nRestart this program when funds are send...")
예제 #6
0
        print("\nNew unspent outputs found!")
        print(
            "Now a new transaction will be created to sweep this wallet and send bitcoins to a testnet faucet"
        )
        send_to_address = 'n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi'
        res = thispc_wallet.sweep(send_to_address, min_confirms=0)

        assert 'transaction' in res
        print(
            "Now copy-and-paste the raw transaction hex to your Other PC and sign it there with a second signature:"
        )
        print("\nfrom bitcoinlib.wallets import HDWallet")
        print("")
        print("wlt = HDWallet('%s')" % WALLET_NAME)
        print("utxos = ", end='')
        pprint(utxos)
        print("")
        print("wlt.utxos_update(utxos=utxos)")
        print("t = wlt.transaction_import('%s')" %
              res['transaction'].raw_hex())
        print("t_signed = wlt.transaction_sign(t)")
        print("")
        print(
            "# Push the following raw transaction to the blockchain network on any online PC:"
        )
        print("print(t_signed.raw_hex())")
    else:
        print("\nPlease send funds to %s, so we can create a transaction" %
              thispc_wallet.get_key().address)
        print("\nRestart this program when funds are send...")
예제 #7
0
from bitcoinlib.wallets import HDWallet, wallet_delete
import bitcoinlib.transactions
import bitcoinlib.encoding
import hashlib
from bitcoinlib.mnemonic import Mnemonic
import codecs
import base58check

passphrase = "space cricket train sell disagree assume onion soap journey style camera false"
wallet_name = "trial"

#w = HDWallet.create(wallet_name, keys=passphrase, network='testnet', db_uri='./trial.db')
w = HDWallet(wallet_name, db_uri='./trial.db')
#w.utxos_update()
key = w.get_key()

address = key.address
print("address:", address)
# TODO: hash160 not working
# print("hash", bitcoinlib.encoding.hash160(address))
print(w.balance())

tx_hash = w.utxos()[-1]['tx_hash']

t = w.transaction(tx_hash)
script = t.outputs[0].lock_script
print(t.outputs[0].script_type)
# print(codecs.decode(t.outputs[0].lock_script, 'base58'))
print(script)

print(bitcoinlib.transactions.script_to_string(script))
예제 #8
0
    print("wlt.new_key()")
    print("wlt.info()")
else:
    thispc_wallet = HDWallet(WALLET_NAME)
    thispc_wallet.utxos_update()
    thispc_wallet.info()
    utxos = thispc_wallet.utxos()
    if utxos:
        print("\nNew unspent outputs found!")
        print("Now a new transaction will be created to sweep this wallet and send bitcoins to a testnet faucet")
        send_to_address = 'n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi'
        res = thispc_wallet.sweep(send_to_address, min_confirms=0)

        assert 'transaction' in res
        print("Now copy-and-paste the raw transaction hex to your Other PC and sign it there with a second signature:")
        print("\nfrom bitcoinlib.wallets import HDWallet")
        print("")
        print("wlt = HDWallet('%s')" % WALLET_NAME)
        print("utxos = ", end='')
        pprint(utxos)
        print("")
        print("wlt.utxos_update(utxos=utxos)")
        print("t = wlt.transaction_import('%s')" % res['transaction'].raw_hex())
        print("t_signed = wlt.transaction_sign(t)")
        print("")
        print("# Push the following raw transaction to the blockchain network on any online PC:")
        print("print(t_signed.raw_hex())")
    else:
        print("\nPlease send funds to %s, so we can create a transaction" % thispc_wallet.get_key().address)
        print("\nRestart this program when funds are send...")
예제 #9
0
            wlt = HDWallet(args.wallet_name, databasefile=databasefile)
            if args.passphrase is not None:
                print(
                    "WARNING: Using passphrase options for existing wallet ignored"
                )
        except WalletError as e:
            clw_exit("Error: %s" % e.msg)

    if wlt is None:
        clw_exit("Could not open wallet %s" % args.wallet_name)

    if args.network is None:
        args.network = wlt.network.network_name

    if args.receive:
        keys = wlt.get_key(network=args.network, number_of_keys=args.receive)
        keys = [keys] if not isinstance(keys, list) else keys
        print("Receive address(es):")
        for key in keys:
            addr = key.address
            print(addr)
            if QRCODES_AVAILABLE:
                qrcode = pyqrcode.create(addr)
                print(qrcode.terminal())
        if not QRCODES_AVAILABLE:
            print(
                "Install qr code module to show QR codes: pip install pyqrcode"
            )
        clw_exit()
    if args.scan:
        print("Scanning wallet: updating addresses, transactions and balances")