Code Monkey home page Code Monkey logo

1200wd / bitcoinlib Goto Github PK

View Code? Open in Web Editor NEW
571.0 18.0 192.0 11.51 MB

Bitcoin and other Cryptocurrencies Library for Python. Includes a fully functional wallet, Mnemonic key generation and management and connection with various service providers to receive and send blockchain and transaction information.

Home Page: http://bitcoinlib.readthedocs.io/

License: GNU General Public License v3.0

Python 99.81% Dockerfile 0.19%
bitcoin library python litecoin dash

bitcoinlib's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bitcoinlib's Issues

Can't access sqlite in different thread

I'm accessing some data in a wallet thru a thread that is not the same as the one that created that wallet. Thus i get this error:

'(sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140736073909120 and this is thread id 123145438023680'

Is it possible to create the db with check_same_thread=False?

conn = sqlite3.connect('your.db', check_same_thread=False)

I know you use SQLAlchemy and there it should be set a mentioned here

Any chance you could add that as an option? BTW: Your lib is awesome! Like it very much :-) It's even a bit over the top for my usecase but still absolutely great.

unable to run after upgrade

I am getting a KeyError: 'prefix_bech32'
Whenever I do anything other than --list-wallets

Command Line Wallet for BitcoinLib

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/bitcoinlib/tools/cli_wallet.py", line 413, in
main()
File "/usr/local/lib/python3.7/site-packages/bitcoinlib/tools/cli_wallet.py", line 273, in main
wlt = HDWallet(args.wallet_name, databasefile=databasefile)
File "/usr/local/lib/python3.7/site-packages/bitcoinlib/wallets.py", line 1233, in init
self.network = Network(db_wlt.network_name)
File "/usr/local/lib/python3.7/site-packages/bitcoinlib/networks.py", line 227, in init
self.prefix_bech32 = NETWORK_DEFINITIONS[network_name]['prefix_bech32']
KeyError: 'prefix_bech32'

Pushing Transactions stopped working

Hi,
we are using this package for a few weeks already and we encountered an issue last week. We cannot push transactions anymore. It seems that the transactions are prepared correctly but when pushig we get this error msg:

Error creating transaction: Cannot send transaction. {'blockexplorer': 'Error connecting to blockexplorer on url https://bitcoinlegacy.blockexplorer.com/api/tx/send/, response [400] 64: dust. Code:-26', 'bitcoind': 'Please install bitcoin client and specify a path to config file if path is not default. Or place a config file in .bitcoinlib/config/bitcoin.conf to reference to an external server.', 'blocktrail': ValueError('API key is needed to connect to BlockTrail',), 'blockcypher': 'Error connecting to blockcypher on url https://api.blockcypher.com/v1/btc/main/txs/push, response [400] {"error": "Error sending transaction: Transaction 6fd3a0a19b5769fbb249475f2f47f157209803ae5e3793a7f6aa5fc908de2635 non standard: dust."}', 'chainso': 'Error connecting to chainso on url https://chain.so/api/v2/send_tx/BTC, response [404] {\n "status" : "fail",\n "data" : {\n "network" : "Network is required (DOGE, DOGETEST, ...)",\n "tx_hex" : "A valid signed transaction hexadecimal string is required. Please check if all inputs in the given transactions are still available to spend. See the \"Is Tx Output Spent?\" API call for reference."\n }\n}'}

We updated all necessary packages to the most recent version but unfortunately the issue persists. Did you already encounter such an issue?

WARNING _provider_execute(169) No successfull response from any serviceprovider: ['bitcoind.testnet']

This is my provider config in provider.json file

  "bitcoind.testnet": {
    "provider": "bitcoind",
    "network": "testnet",
    "client_class": "BitcoindClient",
    "provider_coin_id": "",
    "url": "http://root:xxxxxxxx@localhost:18332",
    "api_key": "",
    "priority": 11,
    "denominator": 100000000,
    "network_overrides": null
  }

But service provider don't work. and don't show the balance of address

srv = Service(network="testnet", providers="bitcoind")
print(srv.getbalance("n3UKaXBRDhTVpkvgRH7eARZFsYE989bHjw"))

bitcoinlib.wallets.WalletError: Fee of 773 is lower then minimal network fee of 1000

Hi,

while using 'litecoind' service provider, wallet.transaction_create() proposed transaction with fee bellow "fee_min" defined in networks.json and sending of transaction failed.

Code triggering the error (as you see, I don't touch fee estimation in any way):

lock_script = b'\x6a' + varstr(data)
t_output = Output(0, lock_script=lock_script)
tx = wallet.send([t_output])

Could not parse rfc1738 URL from string

from bitcoinlib.wallets import HDWallet
w = HDWallet.create('Wallet1')

I am receiving:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
bitcoinlib\wallets.py", line 1170, in create
    hdpm = cls._create(name, key, owner=owner, network=network, account_id=accou
nt_id, purpose=purpose,
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
bitcoinlib\wallets.py", line 945, in _create
    session = DbInit(db_uri=db_uri).session
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
bitcoinlib\db.py", line 55, in __init__
    self.engine = create_engine(db_uri, isolation_level='READ UNCOMMITTED')
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
sqlalchemy\engine\__init__.py", line 479, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
sqlalchemy\engine\strategies.py", line 54, in create
    u = url.make_url(name_or_url)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
sqlalchemy\engine\url.py", line 229, in make_url
    return _parse_rfc1738_args(name_or_url)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\
sqlalchemy\engine\url.py", line 290, in _parse_rfc1738_args
    raise exc.ArgumentError(
sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'C:\Users\
User\.bitcoinlib/database\bitcoinlib.sqlite'

can somebody help me?
Thank you

v0.13 support for dash

Hey @mccwdev, not sure if you're aware but dash is undergoing a planned upgrade soon via hardfork. I say not sure if you're aware because this seems to be flying under most people's radar and as we use your library, I figured you should be aware and if need be I can lend some assistance in implementing this PR.

Looks like the changes are going to be implementing DIP002 Special Transactions

These are the highlights of the new transaction format

  1. Splitting the 32 bit version field into two 16 bit fields (version and type)
  2. Adding support for a generic extra payload following the lock_time field. The maximum allowed size for a transaction version 3 extra payload is 10000 bytes (MAX_TX_EXTRA_PAYLOAD).

Does your library implement these changes already?

Retrieving the UTXO's from bitcoind Full Node

I have a Bitcoin Core full node up and running (bitcoind daemon).
I have connected bitcoinlib via RPC to this bitcoin node. The communication works fine, however, when I want to update the UTXO's from the node with these 2 lines:

wallet = wallet_create_or_open(myWallet)
wallet.utxos_update()

...bitcoinlib gives a WARNING as follows:

2019/06/03 16:41:55 WARNING _provider_execute(155) bitcoind.getutxos((['1N4r1uDSAHpeM1sTEx6AvMB43q1guh1GuW'],)) Error 'ismine'

Is it not possible to retrieve the UTXO's from bitcoind for the bitcoinlib wallet?

logging problem

When bitcoin.keys is imported, bitcoinlib/main.py is imported as a side-effect and your logging handlers overwrite whatever logging configuration currently exists.

If this is demo.py

import logging

# Without bitcoinlib my logging statements show up
logging.basicConfig(level=logging.DEBUG)
logging.debug('debug before import')
logging.info('info before import')
logging.warning('warning before import')

# After importing bitcoinlib.keys.HDKey
from bitcoinlib.keys import HDKey
logging.debug('debug after import')
logging.info('info after import')
logging.warning('warning after import')

This is what happens when you run it:

$ python demo.py
DEBUG:root:debug before import
INFO:root:info before import
WARNING:root:warning before import
WARNING:root:warning after import
2019/07/16 00:34:06 WARNING <module>(13) warning after import

With import, the logging level chages to "warning" and format also changes.

Wrapping the lines where you configure logging in main.py in a if __name__ == '__main__' fixes this.

Transaction hash is not calulated correctly

funding_tx.as_dict() gives
{'hash': 'd21633ba23f70118185227be58a63527675641ad37967e2aa461559f577aec43', 'date': None, 'network': 'testnet', 'coinbase': False, 'flag': None, 'confirmations': None, 'block_height': None, 'block_hash': None, 'fee': 500, 'fee_per_kb': 1765, 'inputs': [{'index_n': 0, 'prev_hash': 'a927d1cba28c55f11bd50f78468467df6ccd647d6610f3100552532bc23041e3', 'output_n': 1, 'script_type': 'sig_pubkey', 'address': 'muS6eoWGB8Spau89MFairAD9whFmmiPR1H', 'value': 14715532, 'public_keys': '04eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9e', 'compressed': False, 'encoding': 'base58', 'double_spend': False, 'script': '473044022004d3960f9a6bd1b6b54ce431197f4d8f74d0e3fc1b82ab7c8f3142521c7304b3022019bdbb56fe8e6700099d875e42278e216e1c86a1538e12607ccf38eeed708740014104eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9e', 'redeemscript': '', 'sequence': 13, 'signatures': ['04d3960f9a6bd1b6b54ce431197f4d8f74d0e3fc1b82ab7c8f3142521c7304b319bdbb56fe8e6700099d875e42278e216e1c86a1538e12607ccf38eeed708740'], 'sigs_required': 1, 'locktime_cltv': None, 'locktime_csv': None, 'public_hash': '98a6a868cfee80c890eab4fac98cd502c0e1fcc7', 'script_code': '76a91498a6a868cfee80c890eab4fac98cd502c0e1fcc788ac', 'unlocking_script': '473044022004d3960f9a6bd1b6b54ce431197f4d8f74d0e3fc1b82ab7c8f3142521c7304b3022019bdbb56fe8e6700099d875e42278e216e1c86a1538e12607ccf38eeed708740014104eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9e', 'unlocking_script_unsigned': '76a91498a6a868cfee80c890eab4fac98cd502c0e1fcc788ac', 'witness_type': 'legacy', 'witness': '3044022004d3960f9a6bd1b6b54ce431197f4d8f74d0e3fc1b82ab7c8f3142521c7304b3022019bdbb56fe8e6700099d875e42278e216e1c86a1538e12607ccf38eeed7087400104eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9e', 'sort': True, 'valid': True}], 'outputs': [{'value': 10000, 'script': 'a9141a6fe71cb937e2690dd678603b886471aa97291387', 'script_type': 'p2sh', 'public_key': '', 'public_hash': '1a6fe71cb937e2690dd678603b886471aa972913', 'address': '2Muf1cQv5VXn94mCyb9N6d6KUT4Z92m5eFk', 'output_n': 0, 'spent': False}, {'value': 14705032, 'script': '76a91498a6a868cfee80c890eab4fac98cd502c0e1fcc788ac', 'script_type': 'p2pkh', 'public_key': '', 'public_hash': '98a6a868cfee80c890eab4fac98cd502c0e1fcc7', 'address': 'muS6eoWGB8Spau89MFairAD9whFmmiPR1H', 'output_n': 1, 'spent': False}], 'input_total': 14715532, 'output_total': 14715032, 'version': 2, 'locktime': 0, 'raw': '0200000001e34130c22b53520510f310667d64cd6cdf678446780fd51bf1558ca2cbd127a9010000008a473044022004d3960f9a6bd1b6b54ce431197f4d8f74d0e3fc1b82ab7c8f3142521c7304b3022019bdbb56fe8e6700099d875e42278e216e1c86a1538e12607ccf38eeed708740014104eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9e0d00000002102700000000000017a9141a6fe71cb937e2690dd678603b886471aa972913878861e000000000001976a91498a6a868cfee80c890eab4fac98cd502c0e1fcc788ac00000000', 'size': 255, 'verified': True, 'status': 'new'}

However the ID of the transaction is "14367de4ff7285eb26905eabc711cca1cb44268d38b07114cb74bd74f59579fe"
see here: https://tbtc.bitaps.com/raw/transaction/14367de4ff7285eb26905eabc711cca1cb44268d38b07114cb74bd74f59579fe

How can this id be calculated from
funding_tx.as_dict()['hash'] = 'd21633ba23f70118185227be58a63527675641ad37967e2aa461559f577aec43',

multithreading not working with sqlite3

Hello im try to make multithreading with your library, but im get every time error, so im have read that sqlite don't working with multithreading, so maybe do you have any solution ?

Possible to create as many addresses as i want?

I should be able to basically generate as many addresses for a deterministic wallet as i want but since your account_id is an integer, doesn't that restrict my possibilities to only 65535 addresses?

I could use account name without specifying the account_id i suppose but then by using wallet.get_key() i can only use an account_id. Also for scanning a specific address i can only use the account_id - or do i get it wrong?

Transaction with several utxos

Hi everyone!

I'm trying to make a Transaction from an address that has several utxos. If I build an array of Inputs, and then make the Transaction it fails:

############# Balance=1BTC / utxo1[value]=0.5BTC / utxo2[value]=0.5BTC #############
inp1 = Input(prev_hash='xxxxx',output_index=0,keys=pubkey.public(), network='testnet') #from utxo1
inp2 = Input(prev_hash='yyyy',output_index=0,keys=pubkey.public(), network='testnet') #from utxo2
out = Output(100000000, address=addr_to, network='testnet')

t = Transaction(inputs=[inp1,inp2],outputs=[out], network='testnet')
t.sign(private)
t.verify() # False

But if I try to make a Transaction only using the information from one utxo, it's completed ok:

############# Balance=1BTC / utxo1[value]=0.5BTC / utxo2[value]=0.5BTC #############
inp1 = Input(prev_hash='xxxxx',output_index=0,keys=pubkey.public(), network='testnet') #from utxo1
out = Output(50000000, address=addr_to, network='testnet')

t = Transaction(inputs=[inp1],outputs=[out], network='testnet')
t.sign(private)
t.verify() # True

Is there any way to build a Transaction from several utxo's?

Transaction: one input, several outputs

Hey guys,

I was trying to make a transaction from a specific input into several (in this case two) outputs on testnet. I based my procedure on: https://github.com/1200wd/bitcoinlib/blob/abc53591c60f675ec5cc83d9cd62b3ed8cbdd8ef/examples/transactions.py from line 48 to 58.

My code is as follows:

inp = Input(prev_hash=i['tx_hash'],output_n=i['output_n'],keys=pubkey.public(), network='testnet')
outputs = []
outputs.append(Output(int(satoshi_amount), address=addr_to, network=network_id))
outputs.append(Output(int(satoshi_amount_2), address=addr_remainder, network=network_id))
t = Transaction(inputs=[inp],outputs=outputs, network=network_id)
t.sign(pubkey.private_byte)

And it pops up the following error:

ERROR: EXCEPTION [<class 'ValueError'>].
ERROR: [{'bitcoind.testnet': 'Please install bitcoin client and specify a path to config file if path is not default. Or place a config file in .bitcoinlib/config/bitcoin.conf to reference to an external server.'}]

And the second time:

ERROR: EXCEPTION [<class 'ValueError'>].
ERROR: [{'chainso.testnet': 'Maximum number of requests reached for chainso with url https://chain.so/api/v2/get_tx_unspent/BTCTEST/n4NwqjtPk54gQUiATsxJ7iyGVxSc99tK6c, response [429] Too many requests. Please try again later, or contact [email protected] for more info.', 'bitcoind.testnet': 'Please install bitcoin client and specify a path to config file if path is not default. Or place a config file in .bitcoinlib/config/bitcoin.conf to reference to an external server.'}]

Do you have any idea why this is? I have no problem executing the transaction to a single address, but I'm having a hard time splitting it into two.

Thank you for your time,

Menetar

WARNING from gettransactions(txid)

I'm getting a lot of warnings like this:

2019/10/02 17:07:24 WARNING script_deserialize(402) Could not parse script, unrecognized script

When accessing transactions that are relatively new in the bitcoin main blockchain.
For example when I try to deserialize this transaction:

Blockchain.info link to transaction

I get the WARNING 4 times ( I guess once for each input , as it has 4 )

Ideas?

locktime_csv results in an error during broadcasting

Adding a "locktime_csv = 610" to an input of a transaction (bitcoin testnet) results in an invalid transaction.

Example: the raw transaction with locktime_csv is (can be decoded here: https://live.blockcypher.com/btc-testnet/decodetx/):
010000000101b1bf4508b0e12e750bde77eda6f569b890017eb0e91d90991d30755548bcc6010000008f62020000b275463043021f3eb1d6a06c71e55781b3f45cabbab9ade6f6c8480bdfaae9571dfc481358300220539575333c62574e2e2883168085af571e0319a5c3209ce8187f1e319373d118014104eb2c10309cf363bacef1d791c136e258dfda6a60c8cbbad0443622e7479b135ab198807e9728901f1d1da3bf46c4f2bfefd74c4ab6074baece8bc196ffc75f9effffffff02102700000000000017a9141a6fe71cb937e2690dd678603b886471aa972913875cdde000000000001976a91498a6a868cfee80c890eab4fac98cd502c0e1fcc788ac00000000

and gives the error

mandatory-script-verify-flag-failed (Opcode missing or not understood) (code 16)

when broadcasting it over https://tbtc.bitaps.com/broadcast . Removing the "locktime_csv = 610" optional argument from the transaction input results in a valid transaction (tested here: https://live.blockcypher.com/btc-testnet/tx/c6bc485575301d99901de9b07e0190b869f5a6ed77de0b752ee1b00845bfb101/ )

PS: By varying the locktime_csv I can get the following error messages:
locktime_csv = 1: (input transaction has 3 confirmations)

mandatory-script-verify-flag-failed (Locktime requirement not satisfied) (code 16)

locktime_csv = 5:

mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation) (code 16)

locktime_csv = 10:

mandatory-script-verify-flag-failed (NOPx reserved for soft-fork upgrades) (code 16)

locktime_csv = 100:

mandatory-script-verify-flag-failed (Invalid OP_IF construction) (code 16)

ImportError: No module named encoding

So far the only thing that seems to work upon installing this library is the cli-wallet functions. However, when attempting to use other functions of the wallet in the python environment I get nothing but module errors. For instance with from bitcoinlib.wallets import bitcoinlib the following error message comes up:
File "/user/home/.local/python2.7/site-packages/bitcoinlib/bitcoinlib/init.py" line 20,
import bitcoinlib.encoding
ImportError: No module named encoding

Please advise as to how to rectify this module error.

How to use other RDBMS instead of sqllite?

When I create a session and pass it on, many pieces of code takes in databasefile as default entry and processes it considering it is a local sqllite.
Instead I would like to use postgres.

Is the code already ready to be handled this way? or is it an implementation pending?

Raise exceptions rather than returning False

When interacting with the library I realized that if there are not enough funds the send_to method returns False rather than raising an exception (WalletError?) with a proper explanation of the error. In order to find the cause I have to either debug the code or inspect the logs. I think it should never return anything other than a HDWalletTransaction object, as it actually states in the documentation of all methods. Also, as developers we could inform the user of what happened using the exception message, rather than guessing if it's because there are not enough UTXOs or some other reason.

Still, if it's considered OK to return False, at least the documentation should be updated accordingly.

What is the public_hex, why is it needed when adding inputs?

Hey there!

Confused as to why I need to include ki.public_hex when I'm adding an input? I've gone digging through the code and I see keys is optional, but I'm unable to sign and get an error posted below. I'd like to know why this is and if there's a way for me to construct the transaction fully first and then sign it.

>>> t = Transaction(network='dash_testnet')
>>> prev_tx = "5b5903a9e5f5a1fee68fbd597085969a36789dc5b5e397dad76a57c3fb7c232a"
>>> ki = Key('cTuDU2P6AhB72ZrhHRnFTcZRoHdnoWkp7sSMPCBnrMG23nRNnjUX', network='dash_testnet', compressed=False)
>>> t.add_input(prev_hash=prev_tx, output_n=0, keys=ki.public_hex, compressed=False)
0
>>> t.add_output(99900000, 'yUV8W2RmEbKZD8oD7YMeBNiydHWmormCDj')
0
>>> t.sign(ki.private_byte)

Error thrown if ki.public_hex is not provided

bitcoinlib.transactions.TransactionError: This key does not sign any known key: b'\x04\xc6\xee8\xb8\xd2\x89\xda;\x02\x08!\xc1\x89\x80&X\x85@\x89\xbd[\xed\xcd\xe9,\xae\x06f&\x80\xc1\x86\xd2\xd44\x9e0//- \xaa\xa7\x83p5"1\x8bB\xdc\xaaJ\xc9eS\xc1\xa0\xbb\'D\xe0\xd0_'

Failed installation on Manjaro with Python3.7 virtualenv

Collecting bitcoinlib
Using cached https://files.pythonhosted.org/packages/6b/34/8761684d6a146c4ce1a979383456de42e2c511f185e61655beba20c304ee/bitcoinlib-0.4.8.tar.gz
ERROR: Complete output from command python setup.py egg_info:
ERROR: Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-vlblzvx6/bitcoinlib/setup.py", line 27, in
version_file = open(os.path.join(here, 'bitcoinlib/config/VERSION'))
File "/usr/lib/python3.7/codecs.py", line 898, in open
file = builtins.open(filename, mode, buffering)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-install-vlblzvx6/bitcoinlib/bitcoinlib/config/VERSION'
----------------------------------------
ERROR: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-vlblzvx6/bitcoinlib/

I've looked for solutions for the problem, but it seems like there is some files missing? Or wrong acess to files in

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-install-vlblzvx6/bitcoinlib/bitcoinlib/config/VERSION'

As it should be '/tmp/pip-install-vlblzvx6/bitcoinlib/config/VERSION' maybe
Thanks

Getting getutxos confirmations and balance of an address

Hi guys,

I'm currently reading the utxo of an address to check if I can consider a transaction to have the 6 recommended confirmations. But I have noticed that several times the amount of confirmations tend to go back, even as much as 3 confirmations. I was wondering if there have been an issue found or it might be regarding the provider.
Same thing happens, it seems, with getting the balance.
The methods are .getbalance and .getutxos.
(using version 0.3.33a2)
Thanks!

Parcial update of an HDWallet

My use case is the following:

I am working for an exchange, and I am going to process in a backend service lots of orders per minute in bitcoin.

My original idea was to create a wallet per user ID so that users can send funds to their own "wallets". However I saw all methods to send/update require an account_id parameter, which seems to imply I cannot mix inputs from several accounts into a fat output whenever we have to collect the received money once every 1-2-3 hours. Am I correct? If so, is there something that could be done to fix it?

My second idea was to use a sole wallet (account 0) and create several addresses whenever a customer creates an order. It works fine, but when calling the utxos_update method it takes a very long time to update, until the point that the caller gets a request timeout with more than ~1000 generated addresses. After inspecting the code I realized this occurs because all addresses, including old ones, are again and again refreshed. I understand that my use case is pretty special and not valid for the vast majority of users, but wouldn't be a good idea to update the balances based on some criteria? Concretely, couldn't I just filter the addresses (keys) I'm interested in and update only those utxos? I know I can do that manually, but that implies SQL updates are made one by one and address queries to bitcoind are made one by one as well instead of five by five, which is pretty inefficient and slow. Could this be improved?

Can't pip install bitcoinlib on Windows 10 with Python 3.7

It seems to be a problem finding headers for OpenSSL. It can't build scrypt. and so I can't install.

crypto_aes.c
scrypt-1.2.1/libcperciva/crypto/crypto_aes.c(6): fatal error C1083: Cannot open include file: 'openssl/aes.h': No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x86\cl.exe' failed with exit status 2

----------------------------------------

Command "d:\python37\python.exe -u -c "import setuptools, tokenize;file='C:\Users\james\AppData\Local\Temp\pip-install-tynzm0l6\scrypt\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\james\AppData\Local\Temp\pip-record-jgitvogd\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\james\AppData\Local\Temp\pip-install-tynzm0l6\scrypt
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

Does anyone know how to resolve the scrypt package failed to build issue to get bitcoinlib installed?

16: mandatory-script-verify-flag-failed

Hi all,
i get this error when im trying to push a raw tx to network:
"16: mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element). Code:-26 "
the tx1 is created in a 2of3 multisig wallet and signed, then imported to another cosigners 2of3 wallet and signed (tx2), tx2.verify() is also true but when i try to push tx2.raw_hex() to network i get this error.
i'm using a bitcoin full-node with insight-api to push the transaction(all other commands work fine)
i'd be really appreciated if you could help me

Multisig Transactions not validating unless all signatures done at once

I am not using bitcoinlib's multisignature wallets, I am generating a multisig address with bitcoin core cli using 3 public keys which I generated using bitcoinlib. I then send satoshis to the multisig address, and create a tx, sign it with key1, save to db, take it back out of db, sign it with key2 and attempt to push it to network, but I get erros 'not enough signatures provided. However, when I sign with both keys at one time, don't save to db, and just push it to network, it works fine. Here is my example code:

# 3 keypairs for new 2/3 multisig addr
with HDWallet(1) as w, HDWallet(2) as w2, HDWallet(3) as w3:
    
    pubkey1 = w.key(6).key_public
    privkey1 = w.key(6).key_private

    pubkey2 = w2.key(12).key_public
    privkey2 = w2.key(12).key_private

    pubkey3 = w3.key(18).key_public
    privkey3 = w3.key(18).key_private
    
    # Create 2/3 multisig addr
    res = Bitcoind().createmultisig(2, [pubkey1, pubkey2, pubkey3])
    multisig_addr = res['address']

###################### ... Load multisig addr with satoshis ... ######################


# Create Transaction to spend satoshis from multisig addr
t = Transaction(network='testnet')

t.add_input(prev_hash=txid_multisig_loading_tx, output_n=output_n,
            keys=[pubkey1, pubkey2, pubkey3],
            script_type='p2sh_multisig', sigs_required=2,
            value=value)


t.add_output(value=value1, address=multisig_addr)

t.sign(privkey1)

partially_signed_tx = t.raw_hex()

# Now I want to save this partially signed tx to database so I can sign it with my other key elsewhere
save_to_database(partially_signed_tx)


###################### ... Some time later ... ######################

partially_signed_tx = retrieve_from_database(partially_signed_tx)

t = Transaction.import_raw(partially_signed_tx, network='testnet')

# Sign with second private key
t.sign(privkey2)

t.verify()
t.info()

# Send tx to daemon
txid = Bitcoind().sendrawtransaction(t.raw_hex())

Here's the log error that I receive when trying to send the tx:

2019/01/07 20:22:06 DEBUG _get_response(194) <-- {"result":null,"error":{"code":-26,"message":"mandatory-script-verify-flag-failed 
(Signature must be zero for failed CHECK(MULTI)SIG operation) (code 16)"},"id":1}

And here is the Transaction.info() data from right before I send to daemon:


Not enough signatures provided. Found 1 signatures but 2 needed
Transaction 62b0a935ce01363d537ca74de76b05198a8e2731f31e4f9597852c607d00f867
Date: None
Network: testnet
Version: 1
Witness type: legacy
Status: new
Verified: False
Inputs
- 2NBCtWCgUatLRXjfqZbAxtpaad34aX1L9QZ 36700 e4a9fcda7cd0526d75867fc1617352e54388312d346ce5f3ee82f66ce16c8905 0
  Script type: p2sh_multisig (legacy), signatures: 2 (2-of-3), invalid
Outputs
- n3tt6jiP4yzmfLzQ8XwJ4hgvmvPA1Aw1da 35000
- mffEUj8cbTrWfsuu4mzv9o7HxWpDi4t3Y8 1250
Size: 375
Vsize: 300
Fee: 450
Confirmations: None

As you can see, in the body 'Script type: ...' it shows 2 signatures. But it shows invalid and does not verify. In the log it also said this:

2019/01/07 20:22:06 INFO verify(1620) Not enough valid signatures provided for input 0. Found 1 signatures but 2 needed

Anyway, not sure where to turn. Like I said, if I simply create the Transaction, and sign it with both private keys in a row, it verifies and gets broadcast by daemon..it's just when I save to db and attempt to import again and sign with key 2, I get the error.

Configuring litecoind from litecoin.conf doesn't work as expected

I'm unable to get done loading configuration from litecoin.conf (I didn't tried bitcoin.conf yet, but I expect it will be similar as the code is more or less the same).

It seems there's few things broken in parsing variables from litecoin.conf. It expects variables like 'externalip' or 'bind', but following valid config (works with litecoin-cli and remote litecoind) didn't work in bitcoinlib:

rpcconnect=myhost
rpcport=9332
rpcuser=user
rpcpassword=myunguessablepassword

You can reproduce second issue by configuring remote litecoind in litecoin.conf and run cd bitcoinlib/services && python3 litecoind.py

Edit: I rewrote this issue as I was previously mixing more things together. Seems that in the end, the problem is only about parsing wrong variables from the config.

Obtain transaction hash when generating raw transaction with several utxo inputs and outputs

Hi!
I was wondering, when I sign a transaction with just one input, I receive the transaction has without problems. Yet, when i send an array of inputs and outputs, the answer from the :

  • t = Transaction(inputs=inputs,outputs=outputs, network=network_id)
  • t.sign(pubkey.private_byte)
  • sendrawtransaction(t.raw_hex())
    It returns a 'FALSE' rather than the tx hash itself.
    bitcoinlib version: 0.3.33a2

Thank you for yout time!

Version 0.3.33a0 with python3

Hey there guys!

I was working with python 2.7.12 and decided to change all my work to python 3.5.2. I managedd to use python 3 without trouble with bitcoinlib 0.3.29 but as I upgraded to 0.33.a0, I've been having trouble using Key(network=network_id,passphrase=passphrase_msg) for creating a new address.

It returns an error: [ KeyError: 'dust_amount' ]

The traceback is:
var = Key(network=network_id,passphrase=passphrase_msg)
File "/usr/local/lib/python3.5/dist-packages/bitcoinlib/keys.py", line 304, in init
self.network = Network(network)
File "/usr/local/lib/python3.5/dist-packages/bitcoinlib/networks.py", line 166, in init
self.dust_amount = NETWORK_DEFINITIONS[network_name]['dust_amount']

This does work on python 2.7. Did I miss anything about using the latest version with python 3?

Thanks!

Bitcoind forces to register an address in order to be checked

When using bitcoinilb's HDWallet implementation with bitcoind, I've realized that I was forced to firstly register the addresses I was interested in, otherwise it'd return an error.

For the sake of completeness, here's the code:

def update() -> None:
        addresses = wallet.addresslist(account_id=0)
        registered_addresses = set(map(lambda a: a['address'],
                                       bitcoind_execute('listreceivedbyaddress', params=[0, True, True])))
        addresses_to_update = filter(lambda a: a not in registered_addresses, addresses)
        for address in addresses_to_update:
            bitcoind_execute('importaddress', params=[address, '', False])
       wallet.utxos_update(account_id=0, networks=[wallet.network.name])

As you can see, if I wouldn't call the importaddress bitcoind method it wouldn't work. Furthermore, if I wouldn't call the listreceivedbyaddress method I'd be calling more times than needed to my bitcoind node. Is this the expected behaviour, or am I missing something?

TypeError: initial_value must be unicode or None, not str

When running a very basic test, like this:

from bitcoinlib.services.services import *
from bitcoinlib.services.bitcoind import *
from pprint import pprint


from bitcoinlib.services.bitcoind import BitcoindClient
bdc = BitcoindClient.from_config('/home/user00/.bitcoin/bitcoin.conf')

# 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))

I get the error:

python blockchain_parse.py
Traceback (most recent call last):
  File "blockchain_parse.py", line 7, in <module>
    bdc = BitcoindClient.from_config('/home/chile00/.bitcoin/bitcoin.conf')
  File "/home/chile00/.local/lib/python2.7/site-packages/bitcoinlib/services/bitcoind.py", line 92, in from_config
    config.read_string(config_string)
  File "/usr/lib/python2.7/dist-packages/backports/configparser/__init__.py", line 722, in read_string
    sfile = io.StringIO(string)
TypeError: initial_value must be unicode or None, not str

Python is 3.7 . Running on Ubuntu kernel version 4.18.0.25

Possibility to generate addresses that all link back to one private key?

I know that this works of course but is it possible with you're library? And if yes, how would i go about that if i wanted to implement it?

Again, the idea is, that i generate a new address everytime i want to receive coins but still have the initial mnemonic 12 words to access the funds.

Library uses 'ANSI_X3.4-1968' -- Django/Apache

Hello,

I recently downloaded your library, but can't use it in my Django project. When I tried to import from bitcoind module in my class, I got following error.

Locale is currently set to 'ANSI_X3.4-1968'. This library needs the locale set to UTF-8 to function properly

It traces back somewhere into config.py file:

 File "/lib/python3.6/site-packages/bitcoinlib/config/config.py" in <module>
  107.                            locale.getpreferredencoding())

I have all locales set to cs.UTF-8 on my linux system.

Please help, I can't imagine where error lies especially when other external libraries work just fine with Django.

Thank you

and

Best Regards

Several errors linked to HDWallet while using bitcoind-testnet

  1. I created several HDWallet and tried to use the scan() method, but it gives errors saying that the gettransactions method does not exist in BitcoindClient.

  2. I don't know how to link the bitcoinlib wallet to bitcoind wallet. As I used the address from HDWallet and made a call getaddressinfo, but found that attributes in the response ( like ismine and iswatchonly) are false. It is located in getutxos line 183.

  3. How do I make the HDWallet address in the bitcoind wallet? Or how do I load HDWallet created from bitcoinlib to bitcoind network?

  4. When I send bitcoin through HDWallet.send_to(), it always fails and said that it could not get utxos.

  5. When I run utxos_update, it always failed and the reason is that the wallet I used is not linked to bitcoind wallet.

Could anybody help with this? Much appreciated.

Automatically choosing small feeds

Ignore. Found that the issues were coming from failed transactions being stored in the database. Once removed, everything worked again. Still don't know why transactions failed but looking into it.

Failing to open existing wallet with 0.4.2

Hi,

I just updated bitcoinlib to latest 0.4.2, but the code which worked with prior bitcoinlib version suddenly throws "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: wallets.multisig" after calling HDWallet() constructor.

Note that I'm not using multisig wallet.

Is there any backward incompatibility and do I need to upgrade my database or is this a bug? I was unable to find anything related in README.

Transaction.create() fails for non-bitcoin transactions?

inp_keys = HDKey(key.wif, compressed=key.compressed).key
fetches/recreates a HDKey instance but fails to pass the network type to it. Not sure if the current version of the library still has a problem with that, but at least the current pip version complained with WalletError: Created input address is different from address of used key. Possibly wrong key order in multisig? after that because addresses of the keys wouldn't match later.

Fix:

inp_keys = HDKey(key.wif, compressed=key.compressed, network=key.network_name).key

How to access already created HDWallet in database?

Sorry for the stupid question but i don't seem to understand how to access a wallet if i don't want to recreate the database file all the time. Right now i'm doing something like this:

wallet_delete_if_exists(wallet_name, databasefile=db_file, force=True)
wallet = HDWallet.create(wallet_name, key=passphrase, network=network, databasefile=db_file)

But if the database already exists and i just want to access a wallet that i previously created, how to do that? I saw in the code that the only two methods that return me a HDWallet object are create() and create_multisig()?

Incorrectly decodes input value

Expected behavior:

>>> rawtx = '0200000001fe1c51924a318e53e20bf09ef2bb1ec917bb655dc8c48520ce7c34bf09
... c11bd6010000006b483045022100add4b0cee1e84582b2a6cff41c7ccfaa999a494bd5af4c8
... d09a64ba79ad2f0cb02202a70a4605cb5ca81bc6171be9bab1119b68c936e7c81fc25fd31be
... b4124020a1012103d650ddba2dfdaea48d094d593931c86075bd2d4c4e7837f6234f0f3a6c8
... f3f5ffeffffff02a0860100000000001976a91475f95337f1cf59a0d6427d1f35df927e89ce
... b34088ac3c16f053020000001976a914bb527bb7e34eb809bccb568def635d9155fde2d488a
... cef750000'

>>> tx = Transaction.import_raw(rawtx, network='dash_testnet')

>>> tx
<Transaction(input_count=1, output_count=2, status=new, network=dash_testnet)>

>>> tx.inputs[0].value
9998279434

Actual behavior:

>>> tx = Transaction.import_raw(rawtx, network='dash_testnet')

>>> tx
<Transaction(input_count=1, output_count=2, status=new, network=dash_testnet)>

>>> tx.inputs[0].value
0

Here is the transaction for reference.

HD wallet legacy address

Is there a way to get legacy address starting with 1SDAxc something, from HD wallet generation? I tried listed examples, but getting probably segwit adress starting with letter 'm' instead of '1'.

My code is:

passphrase = Mnemonic().generate() self.w = HDWallet.create("Wallet", keys=passphrase, network='testnet' ) key = self.w.get_key() addr = key.address

Thank you.

Can`t using seed

from bitcoinlib.wallets import HDWallet, wallet_delete, \
                               HDKey
from bitcoinlib.mnemonic import Mnemonic

passphrase = Mnemonic().generate()
print(passphrase)

hdkey = HDKey().from_seed(passphrase)
w = HDWallet.create("Wallet2", network='bitcoin', key=hdkey)

I am receiving:

Exception has occurred: TypeError
create() got an unexpected keyword argument 'key'

How to create OP_RETURN transaction

I read the code, there is 'nulldata' script type defined in transactions.py, but could not find how to use it to create a OP_RETURN transaction. Please advise.

Connection to local bitcoind instance

Hi everyone!

Just a simple question: is there any way to connect to a local instance of bitcoind daemon via bitcoinlib and use it to send raw transactions?

If it's possible, do you have an example to perform that connection and transaction?

Thanks a lot!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.