Exemple #1
0
    def getutxos(self, address, after_txid='', limit=MAX_TRANSACTIONS):
        # First get all transactions for this address from the blockchain
        from bitcoinlib.services.services import Service
        srv = Service(network=self.network.name, providers=['bcoin'])
        txs = srv.gettransactions(address, limit=25)

        # Fail if large number of transactions are found
        if not srv.complete:
            raise ClientError("If not all transactions known, we cannot determine utxo's. "
                              "Increase limit or use other provider")

        utxos = []
        for tx in txs:
            for unspent in tx.outputs:
                if unspent.address != address:
                    continue
                if not srv.isspent(tx.txid, unspent.output_n):
                    utxos.append(
                        {
                            'address': unspent.address,
                            'txid': tx.txid,
                            'confirmations': tx.confirmations,
                            'output_n': unspent.output_n,
                            'input_n': 0,
                            'block_height': tx.block_height,
                            'fee': tx.fee,
                            'size': tx.size,
                            'value': unspent.value,
                            'script': unspent.lock_script.hex(),
                            'date': tx.date,
                         }
                    )
                    if tx.txid == after_txid:
                        utxos = []
        return utxos[:limit]
 def __init__(self, network_code='btc', timeout=5, *args, **kwargs):
     if network_code in network_code_translation:
         network = network_code_translation[network_code]
         Service.__init__(self,
                          network=network,
                          timeout=timeout,
                          *args,
                          **kwargs)
     else:
         abort(422, "Error opening network with specified code")
Exemple #3
0
 def __init__(self, network_code='btc', timeout=5, *args, **kwargs):
     nw_enabled = network_code_translation.keys(
     ) if not current_app else current_app.config['NETWORKS_ENABLED']
     # TODO: Enable other networks
     # if not network_code and current_app:
     #     network_code = session.get('network_code', current_app.config['NETWORK_DEFAULT'])
     #     session['network_code'] = network_code
     if network_code in network_code_translation and network_code in nw_enabled:
         network = network_code_translation[network_code]
         Service.__init__(self,
                          network=network,
                          timeout=timeout,
                          *args,
                          **kwargs)
     else:
         abort(422, "Error opening network with specified code")
 def test_database_cache_create_drop(self):
     dbtmp = DbCache(DATABASEFILE_CACHE_TMP)
     srv = Service(cache_uri=DATABASEFILE_CACHE_TMP,
                   exclude_providers=['bitaps', 'bitgo'])
     t = srv.gettransaction(
         '68104dbd6819375e7bdf96562f89290b41598df7b002089ecdd3c8d999025b13')
     if t:
         self.assertGreaterEqual(srv.results_cache_n, 0)
         srv.gettransaction(
             '68104dbd6819375e7bdf96562f89290b41598df7b002089ecdd3c8d999025b13'
         )
         self.assertGreaterEqual(srv.results_cache_n, 1)
         dbtmp.drop_db()
         self.assertRaisesRegex(
             OperationalError, "", srv.gettransaction,
             '68104dbd6819375e7bdf96562f89290b41598df7b002089ecdd3c8d999025b13'
         )
Exemple #5
0
    def getbalance(self, addresslist):
        balance = 0.0
        from bitcoinlib.services.services import Service
        for address in addresslist:
            # First get all transactions for this address from the blockchain
            srv = Service(network=self.network.name, providers=['bcoin'])
            txs = srv.gettransactions(address, limit=25)

            # Fail if large number of transactions are found
            if not srv.complete:
                raise ClientError("If not all transactions known, we cannot determine utxo's. "
                                  "Increase limit or use other provider")

            for a in [output for outputs in [t.outputs for t in txs] for output in outputs]:
                if a.address == address:
                    balance += a.value
            for a in [i for inputs in [t.inputs for t in txs] for i in inputs]:
                if a.address == address:
                    balance -= a.value
        return int(balance)
Exemple #6
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)
Exemple #7
0
def hello():
    max_blocks = 50
    byte_per_tx = 250
    aud_per_btc = 1 / float(
        requests.get(
            'https://blockchain.info/tobtc?currency=AUD&value=1').text)
    sec_per_block = float(
        requests.get('https://blockchain.info/q/interval').text)
    btc_per_byte = Service().estimatefee(max_blocks) / 10**8
    bitcoin_quote = """
        {0!s} BTC / kb
        {0!s} BTC for 1 input and 2 outputs
        {0!s} $AUD
        {0!s} minutes
    """.format(btc_per_byte, btc_per_byte * byte_per_tx / 1000,
               aud_per_btc * btc_per_byte * byte_per_tx / 1000,
               max_blocks * sec_per_block / 60)[1:].replace('\n', '<br>')
    return bitcoin_quote
Exemple #8
0
def service():
	serv = Service()
	return serv
Exemple #9
0
            outputs += output_list

    outputs_arr = []
    output_keys = []
    total_amount = 0
    denominator = float(network_obj.denominator)
    for o in outputs:
        nk = wallet.new_key(account_id=OUTPUT_ACCOUNT_ID,
                            name=o['name'].lstrip())
        output_keys.append(nk)
        amount = int(o['amount'] * (1 / denominator))
        outputs_arr.append((nk.address, amount))
        total_amount += amount

    # --- Estimate transaction fees ---
    srv = Service(network=network)
    if args.fee_per_kb:
        fee_per_kb = args.fee_per_kb
    else:
        fee_per_kb = srv.estimatefee()
        if not srv.results:
            raise IOError(
                "No response from services, could not determine estimated transaction fees. "
                "You can use --fee-per-kb option to determine fee manually and avoid this error."
            )
    tr_size = 100 + (1 * 150) + (len(outputs_arr) * 50)
    estimated_fee = int((tr_size / 1024) * fee_per_kb)
    if estimated_fee < 0:
        raise IOError(
            "No valid response from any service provider, could not determine estimated transaction fees. "
            "You can use --fee-per-kb option to determine fee manually and avoid this error."
Exemple #10
0
# -*- coding: utf-8 -*-
#
#    BitcoinLib - Python Cryptocurrency Library
#
#    EXAMPLES - Creating and Using Cryptocurrency Wallets
#
#    © 2017 November - 1200 Web Development <http://1200wd.com/>
#

from pprint import pprint

from bitcoinlib.services.services import Service

# Tests for specific provider
srv = Service(network='bitcoin', providers=['coinfees'])
print("Estimated bitcoin transaction fee:", srv.estimatefee(3))

# Get Balance and UTXO's for given bitcoin testnet3 addresses
address = 'mqR6Dndmez8WMpb1hBJbGbrQ2mpAU73hQC'
srv = Service(network='testnet', min_providers=5)
print("Balance of address %s: %s" % (address, srv.getbalance(address)))
print("\nAll results as dict:")
pprint(srv.results)
print("\nUTXOs list:")
pprint(srv.getutxos(address))

# GET Raw Transaction data for given Transaction ID
t = 'd3c7fbd3a4ca1cca789560348a86facb3bb21dcd75ed38e85235fb6a32802955'
print("\nGET Raw Transaction:")
pprint(Service(network='testnet', min_providers=2).getrawtransaction(t))
Exemple #11
0
        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()
        clw_exit()
    if args.create_transaction:
        fee = args.fee
        if not fee:
            srv = Service(network=args.network)
            fee = srv.estimatefee()
        wt = create_transaction(wlt, args.create_transaction, fee)
        wt.sign()
        print("Transaction created")
        wt.info()
        if args.push:
            wt = wt.send()
            print("Send transaction result: %s" % wt)
        else:
            print(
                "Transaction not send yet. Raw transaction to analyse or send online: ",
                wt.raw_hex())
        clw_exit()

    print("Updating wallet")
Exemple #12
0
# -*- coding: utf-8 -*-
#
#    BitcoinLib - Python Cryptocurrency Library
#
#    EXAMPLES - Deserialize and Verify all transactions from the specified blocks using Bcoin provider
#
#    Just use for testing and experimenting, this library is not optimized for blockchain parsing!
#
#    © 2020 April - 1200 Web Development <http://1200wd.com/>
#

from time import sleep
from bitcoinlib.services.services import Service
from pprint import pprint

srv = Service(providers=['bcoin'])

# Get latest block
# blocks = [srv.blockcount()]

# Get first block
# blocks = [1]

# Check first 100000 blocks
# blocks = range(1, 100000)

# Check some more recent blocks
blocks = range(625010, 629060)

for block in blocks:
    print("Getting block %s" % block)
Exemple #13
0
# w.info()
# t = w.sweep(w.new_key().address, 10000, fee=1000)
# raw_tx = t.raw_hex()
# t.info()

# Raw partially signed transaction transaction
raw_tx = ''
if not raw_tx:
    raw_tx = input("Paste raw transaction hex: ")

t = Transaction.import_raw(raw_tx)

key_str = input("Enter private key or mnemonic passphrase: ")
if len(key_str.split(" ")) < 2:
    hdkey = HDKey(key_str)
else:
    password = input("Enter password []:")
    seed = Mnemonic().to_seed(key_str, password)
    hdkey = HDKey.from_seed(seed, network=network)

t.sign(hdkey)
t.info()

print("Raw signed transaction: ")
print(t.raw_hex())

if input("Try to send transaction [y/n] ") in ['y', 'Y']:
    srv = Service(network=network)
    res = srv.sendrawtransaction(t.raw())
    pprint(res)
from bitcoinlib.services.bitcoind import BitcoindClient
from bitcoinlib.services.services import Service

bdc = BitcoindClient()

# Check bitcoind connection
pprint(bdc.proxy.getnetworkinfo())

# Get latest block
latest_block_hash = bdc.proxy.getbestblockhash()
print("Getting latest block with hash %s" % latest_block_hash)
latest_block = bdc.proxy.getblock(latest_block_hash)
transactions = latest_block['tx']
print("Found %d transactions" % len(transactions))

srv = Service(network='bitcoin')

MAX_TRANSACTIONS = 100
count = 0
count_segwit = 0
for txid in transactions[:MAX_TRANSACTIONS]:
    print("\n=== Deserialize transaction #%d (segwit %d) ===" %
          (count, count_segwit))
    count += 1
    t = srv.gettransaction(txid)
    t.verify()
    t.info()
    if t.witness_type != 'legacy':
        count_segwit += 1
    if not t.verified:
        input("Transaction could not be verified, press any key to continue")