bsvlib


Namebsvlib JSON
Version 0.10.0 PyPI version JSON
download
home_pagehttps://github.com/gitzhou/bsvlib
SummaryBitcoin SV (BSV) Python Library
upload_time2023-06-25 16:20:25
maintainer
docs_urlNone
authoraaron67
requires_python>=3.7
license
keywords bsv bitcoin-sv bitcoin sv bitcoinsv cryptocurrency payments tools wallet
VCS
bugtrack_url
requirements requests typing-extensions pycryptodomex coincurve pytest ecdsa pytest-codecov build twine
Travis-CI No Travis.
coveralls test coverage
            # bsvlib

[![build](https://github.com/gitzhou/bsvlib/actions/workflows/build.yml/badge.svg)](https://github.com/gitzhou/bsvlib/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/gitzhou/bsvlib/branch/master/graph/badge.svg?token=ZD1AS8JG9W)](https://codecov.io/gh/gitzhou/bsvlib)
[![PyPI version](https://img.shields.io/pypi/v/bsvlib)](https://pypi.org/project/bsvlib)
[![Python versions](https://img.shields.io/pypi/pyversions/bsvlib)](https://pypi.org/project/bsvlib)
[![MIT license](https://img.shields.io/badge/license-MIT-blue)](https://en.wikipedia.org/wiki/MIT_License)

A Bitcoin SV (BSV) Python Library that is extremely simple to use but more.

- MAINNET and TESTNET supported
- P2PKH, P2PK, and bare-multisig supported
- All the SIGHASH flags supported
- Additional script types can be customized
- [WhatsOnChain](https://developers.whatsonchain.com/) API integrated
- Ability to adapt to different service providers
- Fully ECDSA implementation
- ECDH and Electrum ECIES (aka BIE1) implementation
- HD implementation (BIP-32, BIP-39, BIP-44)

## Installation

```
$ pip install bsvlib
```

## Examples

1. Send BSV in one line

```python
from bsvlib import Wallet

# Donate to aaron67!
outputs = [('1HYeFCE2KG4CW4Jwz5NmDqAZK9Q626ChmN', 724996)]
print(Wallet(['YOUR_WIF']).create_transaction(outputs=outputs).broadcast())
```

2. Send unspent locked by different keys in one transaction, support OP_RETURN output as well

```python
from bsvlib import Wallet
from bsvlib.constants import Chain

w = Wallet(chain=Chain.TEST)

w.add_key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')
w.add_key('93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me')
print(w.get_balance(refresh=True))

outputs = [('mqBuyzdHfD87VfgxaYeM9pex3sJn4ihYHY', 724), ('mr1FHq6GwWzmD1y8Jxq6rNDGsiiQ9caF7r', 996)]
pushdatas = ['hello', b'world']
print(w.create_transaction(outputs=outputs, pushdatas=pushdatas, combine=True).broadcast())
```

3. Operate P2PK

```python
import time

from bsvlib import Wallet, TxOutput, Transaction
from bsvlib.constants import Chain
from bsvlib.keys import Key
from bsvlib.script import P2pkScriptType

chain = Chain.TEST

k = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')
p2pk_output = TxOutput(P2pkScriptType.locking(k.public_key().serialize()), 996, P2pkScriptType())

unspents = Wallet(chain=chain).add_keys([k, '93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me']).get_unspents(refresh=True)
t = Transaction(chain=chain).add_inputs(unspents).add_output(p2pk_output).add_change(k.address()).sign()
print('create p2pk:', t.broadcast())

time.sleep(2)
unspents = t.to_unspents(args=[{'private_keys': [k]}] * 2)
t = Transaction(chain=chain).add_inputs(unspents).add_change(k.address()).sign()
print('sepnd p2pk:', t.broadcast())
```

4. Operate bare-multisig

```python
import time
from typing import List, Union

from bsvlib import Key, Unspent, Transaction, TxOutput
from bsvlib.constants import Chain
from bsvlib.script import BareMultisigScriptType, Script
from bsvlib.service import WhatsOnChain

k1 = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')
k2 = Key('93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me')
provider = WhatsOnChain(Chain.TEST)
unspents = Unspent.get_unspents(provider=provider, private_keys=[k1])

# a 2-of-3 multi-sig output
public_keys: List[Union[str, bytes]] = [k1.public_key().hex(), Key().public_key().hex(), k2.public_key().serialize()]
multisig_script: Script = BareMultisigScriptType.locking(public_keys, 2)
output = TxOutput(out=multisig_script, satoshi=1000, script_type=BareMultisigScriptType())

# create a multi-sig output
t = Transaction(provider=provider).add_inputs(unspents).add_output(output).add_change().sign()
r = t.broadcast()
print(f'create multisig - {r}')
assert r.propagated
time.sleep(2)

# send the multi-sig unspent we just created
unspent = t.to_unspent(0, private_keys=[k1, k2])
r = Transaction(provider=provider).add_input(unspent).add_change(k1.address()).sign().broadcast()
print(f'spend multisig - {r}')
```

5. Sign with different SIGHASH flags, [more examples](https://github.com/gitzhou/bsvlib/tree/master/examples)

```python
from bsvlib import Key, Wallet, Transaction, TxInput, TxOutput
from bsvlib.constants import SIGHASH, Chain
from bsvlib.service import WhatsOnChain

provider = WhatsOnChain(Chain.TEST)
private_key = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')
unspents = Wallet([private_key]).get_unspents(refresh=True, provider=provider)

t = Transaction(provider=provider)
t.add_input(TxInput(unspents[0], sighash=SIGHASH.SINGLE_FORKID))
t.add_output(TxOutput(private_key.address(), 135))
t.sign()

# it's good to append any outputs AFTER the first output, no need to sign, can broadcast directly
print(t.add_change().broadcast())
```

6. Sign arbitrary text with private key

```python
from bsvlib import Key, verify_signed_text

private_key = Key('L5agPjZKceSTkhqZF2dmFptT5LFrbr6ZGPvP7u4A6dvhTrr71WZ9')
text = 'hello world'

# sign arbitrary text with bitcoin private key
address, signature = private_key.sign_text(text)

# verify https://reinproject.org/bitcoin-signature-tool/
print(address, signature)

# verify
print(verify_signed_text(text, address, signature))
```

7. Encrypt message with public key, decrypt with the corresponding private key

```python
from bsvlib import Key

private_key = Key('L5agPjZKceSTkhqZF2dmFptT5LFrbr6ZGPvP7u4A6dvhTrr71WZ9')
public_key = private_key.public_key()

plain = 'hello world'

# use public key to encrypt
encrypted = public_key.encrypt_text(plain)
print(encrypted)

# decrypt with the corresponding private key
print(private_key.decrypt_text(encrypted))
```

8. Process HD wallet derivation

![image](https://user-images.githubusercontent.com/1585505/150875831-2663e158-b00d-4089-8276-1ad72e335d28.png)

```python
from typing import List

from bsvlib.hd import mnemonic_from_entropy, Xprv, derive_xprvs_from_mnemonic

#
# HD derivation
#
entropy = 'cd9b819d9c62f0027116c1849e7d497f'

# snow swing guess decide congress abuse session subway loyal view false zebra
mnemonic: str = mnemonic_from_entropy(entropy)
print(mnemonic)

keys: List[Xprv] = derive_xprvs_from_mnemonic(mnemonic, path="m/44'/0'/0'", change=1, index_start=0, index_end=5)
for key in keys:
    print(key.address(), key.private_key().wif())

#
# random mnemonic
#
print()
print(mnemonic_from_entropy())
print(mnemonic_from_entropy(lang='en'))
print(mnemonic_from_entropy(lang='zh-cn'))
```

## Credits

- [AustEcon / bitsv](https://github.com/AustEcon/bitsv)
- [ofek / coincurve](https://github.com/ofek/coincurve/)
- [btclib-org / btclib](https://github.com/btclib-org/btclib)
- [@xiangpengm](https://github.com/xiangpengm)

## Donation

If you like my work or have found this library useful, feel free to donate me a cup of coffee.

Every little satoshi helps. 👏

```
1HYeFCE2KG4CW4Jwz5NmDqAZK9Q626ChmN
```

![](https://aaron67-public.oss-cn-beijing.aliyuncs.com/202201200232249.png?x-oss-process=image/resize,p_50)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/gitzhou/bsvlib",
    "name": "bsvlib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "bsv,bitcoin-sv,bitcoin sv,bitcoinsv,cryptocurrency,payments,tools,wallet",
    "author": "aaron67",
    "author_email": "aaron67@aaron67.cc",
    "download_url": "https://files.pythonhosted.org/packages/ef/27/211f37ceded1906b3de105c1fe52c89e40c327b99b089f3d61a869d94aec/bsvlib-0.10.0.tar.gz",
    "platform": null,
    "description": "# bsvlib\n\n[![build](https://github.com/gitzhou/bsvlib/actions/workflows/build.yml/badge.svg)](https://github.com/gitzhou/bsvlib/actions/workflows/build.yml)\n[![codecov](https://codecov.io/gh/gitzhou/bsvlib/branch/master/graph/badge.svg?token=ZD1AS8JG9W)](https://codecov.io/gh/gitzhou/bsvlib)\n[![PyPI version](https://img.shields.io/pypi/v/bsvlib)](https://pypi.org/project/bsvlib)\n[![Python versions](https://img.shields.io/pypi/pyversions/bsvlib)](https://pypi.org/project/bsvlib)\n[![MIT license](https://img.shields.io/badge/license-MIT-blue)](https://en.wikipedia.org/wiki/MIT_License)\n\nA Bitcoin SV (BSV) Python Library that is extremely simple to use but more.\n\n- MAINNET and TESTNET supported\n- P2PKH, P2PK, and bare-multisig supported\n- All the SIGHASH flags supported\n- Additional script types can be customized\n- [WhatsOnChain](https://developers.whatsonchain.com/) API integrated\n- Ability to adapt to different service providers\n- Fully ECDSA implementation\n- ECDH and Electrum ECIES (aka BIE1) implementation\n- HD implementation (BIP-32, BIP-39, BIP-44)\n\n## Installation\n\n```\n$ pip install bsvlib\n```\n\n## Examples\n\n1. Send BSV in one line\n\n```python\nfrom bsvlib import Wallet\n\n# Donate to aaron67!\noutputs = [('1HYeFCE2KG4CW4Jwz5NmDqAZK9Q626ChmN', 724996)]\nprint(Wallet(['YOUR_WIF']).create_transaction(outputs=outputs).broadcast())\n```\n\n2. Send unspent locked by different keys in one transaction, support OP_RETURN output as well\n\n```python\nfrom bsvlib import Wallet\nfrom bsvlib.constants import Chain\n\nw = Wallet(chain=Chain.TEST)\n\nw.add_key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')\nw.add_key('93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me')\nprint(w.get_balance(refresh=True))\n\noutputs = [('mqBuyzdHfD87VfgxaYeM9pex3sJn4ihYHY', 724), ('mr1FHq6GwWzmD1y8Jxq6rNDGsiiQ9caF7r', 996)]\npushdatas = ['hello', b'world']\nprint(w.create_transaction(outputs=outputs, pushdatas=pushdatas, combine=True).broadcast())\n```\n\n3. Operate P2PK\n\n```python\nimport time\n\nfrom bsvlib import Wallet, TxOutput, Transaction\nfrom bsvlib.constants import Chain\nfrom bsvlib.keys import Key\nfrom bsvlib.script import P2pkScriptType\n\nchain = Chain.TEST\n\nk = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')\np2pk_output = TxOutput(P2pkScriptType.locking(k.public_key().serialize()), 996, P2pkScriptType())\n\nunspents = Wallet(chain=chain).add_keys([k, '93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me']).get_unspents(refresh=True)\nt = Transaction(chain=chain).add_inputs(unspents).add_output(p2pk_output).add_change(k.address()).sign()\nprint('create p2pk:', t.broadcast())\n\ntime.sleep(2)\nunspents = t.to_unspents(args=[{'private_keys': [k]}] * 2)\nt = Transaction(chain=chain).add_inputs(unspents).add_change(k.address()).sign()\nprint('sepnd p2pk:', t.broadcast())\n```\n\n4. Operate bare-multisig\n\n```python\nimport time\nfrom typing import List, Union\n\nfrom bsvlib import Key, Unspent, Transaction, TxOutput\nfrom bsvlib.constants import Chain\nfrom bsvlib.script import BareMultisigScriptType, Script\nfrom bsvlib.service import WhatsOnChain\n\nk1 = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')\nk2 = Key('93UnxexmsTYCmDJdctz4zacuwxQd5prDmH6rfpEyKkQViAVA3me')\nprovider = WhatsOnChain(Chain.TEST)\nunspents = Unspent.get_unspents(provider=provider, private_keys=[k1])\n\n# a 2-of-3 multi-sig output\npublic_keys: List[Union[str, bytes]] = [k1.public_key().hex(), Key().public_key().hex(), k2.public_key().serialize()]\nmultisig_script: Script = BareMultisigScriptType.locking(public_keys, 2)\noutput = TxOutput(out=multisig_script, satoshi=1000, script_type=BareMultisigScriptType())\n\n# create a multi-sig output\nt = Transaction(provider=provider).add_inputs(unspents).add_output(output).add_change().sign()\nr = t.broadcast()\nprint(f'create multisig - {r}')\nassert r.propagated\ntime.sleep(2)\n\n# send the multi-sig unspent we just created\nunspent = t.to_unspent(0, private_keys=[k1, k2])\nr = Transaction(provider=provider).add_input(unspent).add_change(k1.address()).sign().broadcast()\nprint(f'spend multisig - {r}')\n```\n\n5. Sign with different SIGHASH flags, [more examples](https://github.com/gitzhou/bsvlib/tree/master/examples)\n\n```python\nfrom bsvlib import Key, Wallet, Transaction, TxInput, TxOutput\nfrom bsvlib.constants import SIGHASH, Chain\nfrom bsvlib.service import WhatsOnChain\n\nprovider = WhatsOnChain(Chain.TEST)\nprivate_key = Key('cVwfreZB3i8iv9JpdSStd9PWhZZGGJCFLS4rEKWfbkahibwhticA')\nunspents = Wallet([private_key]).get_unspents(refresh=True, provider=provider)\n\nt = Transaction(provider=provider)\nt.add_input(TxInput(unspents[0], sighash=SIGHASH.SINGLE_FORKID))\nt.add_output(TxOutput(private_key.address(), 135))\nt.sign()\n\n# it's good to append any outputs AFTER the first output, no need to sign, can broadcast directly\nprint(t.add_change().broadcast())\n```\n\n6. Sign arbitrary text with private key\n\n```python\nfrom bsvlib import Key, verify_signed_text\n\nprivate_key = Key('L5agPjZKceSTkhqZF2dmFptT5LFrbr6ZGPvP7u4A6dvhTrr71WZ9')\ntext = 'hello world'\n\n# sign arbitrary text with bitcoin private key\naddress, signature = private_key.sign_text(text)\n\n# verify https://reinproject.org/bitcoin-signature-tool/\nprint(address, signature)\n\n# verify\nprint(verify_signed_text(text, address, signature))\n```\n\n7. Encrypt message with public key, decrypt with the corresponding private key\n\n```python\nfrom bsvlib import Key\n\nprivate_key = Key('L5agPjZKceSTkhqZF2dmFptT5LFrbr6ZGPvP7u4A6dvhTrr71WZ9')\npublic_key = private_key.public_key()\n\nplain = 'hello world'\n\n# use public key to encrypt\nencrypted = public_key.encrypt_text(plain)\nprint(encrypted)\n\n# decrypt with the corresponding private key\nprint(private_key.decrypt_text(encrypted))\n```\n\n8. Process HD wallet derivation\n\n![image](https://user-images.githubusercontent.com/1585505/150875831-2663e158-b00d-4089-8276-1ad72e335d28.png)\n\n```python\nfrom typing import List\n\nfrom bsvlib.hd import mnemonic_from_entropy, Xprv, derive_xprvs_from_mnemonic\n\n#\n# HD derivation\n#\nentropy = 'cd9b819d9c62f0027116c1849e7d497f'\n\n# snow swing guess decide congress abuse session subway loyal view false zebra\nmnemonic: str = mnemonic_from_entropy(entropy)\nprint(mnemonic)\n\nkeys: List[Xprv] = derive_xprvs_from_mnemonic(mnemonic, path=\"m/44'/0'/0'\", change=1, index_start=0, index_end=5)\nfor key in keys:\n    print(key.address(), key.private_key().wif())\n\n#\n# random mnemonic\n#\nprint()\nprint(mnemonic_from_entropy())\nprint(mnemonic_from_entropy(lang='en'))\nprint(mnemonic_from_entropy(lang='zh-cn'))\n```\n\n## Credits\n\n- [AustEcon / bitsv](https://github.com/AustEcon/bitsv)\n- [ofek / coincurve](https://github.com/ofek/coincurve/)\n- [btclib-org / btclib](https://github.com/btclib-org/btclib)\n- [@xiangpengm](https://github.com/xiangpengm)\n\n## Donation\n\nIf you like my work or have found this library useful, feel free to donate me a cup of coffee.\n\nEvery little satoshi helps. \ud83d\udc4f\n\n```\n1HYeFCE2KG4CW4Jwz5NmDqAZK9Q626ChmN\n```\n\n![](https://aaron67-public.oss-cn-beijing.aliyuncs.com/202201200232249.png?x-oss-process=image/resize,p_50)\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Bitcoin SV (BSV) Python Library",
    "version": "0.10.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/gitzhou/bsvlib/issues",
        "Homepage": "https://github.com/gitzhou/bsvlib"
    },
    "split_keywords": [
        "bsv",
        "bitcoin-sv",
        "bitcoin sv",
        "bitcoinsv",
        "cryptocurrency",
        "payments",
        "tools",
        "wallet"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "db0036eca7df32656913545d6f09e280a02f116188e70519819282782246baba",
                "md5": "1bbf97db3634b03280d73b1e7222a74d",
                "sha256": "ce22f04d9c5121216ded20662d94dae117a985150568bf9cbb355608524e8133"
            },
            "downloads": -1,
            "filename": "bsvlib-0.10.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1bbf97db3634b03280d73b1e7222a74d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 45225,
            "upload_time": "2023-06-25T16:20:23",
            "upload_time_iso_8601": "2023-06-25T16:20:23.598818Z",
            "url": "https://files.pythonhosted.org/packages/db/00/36eca7df32656913545d6f09e280a02f116188e70519819282782246baba/bsvlib-0.10.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ef27211f37ceded1906b3de105c1fe52c89e40c327b99b089f3d61a869d94aec",
                "md5": "cb08d73d71d8390d55a053a66556d216",
                "sha256": "eb360c7b4cc6598634677b035a13fe55db2a1b16228354ddc8d5165241b3b4cc"
            },
            "downloads": -1,
            "filename": "bsvlib-0.10.0.tar.gz",
            "has_sig": false,
            "md5_digest": "cb08d73d71d8390d55a053a66556d216",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 58136,
            "upload_time": "2023-06-25T16:20:25",
            "upload_time_iso_8601": "2023-06-25T16:20:25.670179Z",
            "url": "https://files.pythonhosted.org/packages/ef/27/211f37ceded1906b3de105c1fe52c89e40c327b99b089f3d61a869d94aec/bsvlib-0.10.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-25 16:20:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "gitzhou",
    "github_project": "bsvlib",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "requests",
            "specs": [
                [
                    "==",
                    "2.28.1"
                ]
            ]
        },
        {
            "name": "typing-extensions",
            "specs": [
                [
                    "==",
                    "4.4.0"
                ]
            ]
        },
        {
            "name": "pycryptodomex",
            "specs": [
                [
                    "==",
                    "3.15.0"
                ]
            ]
        },
        {
            "name": "coincurve",
            "specs": [
                [
                    "==",
                    "18.0.0"
                ]
            ]
        },
        {
            "name": "pytest",
            "specs": [
                [
                    "==",
                    "7.1.3"
                ]
            ]
        },
        {
            "name": "ecdsa",
            "specs": [
                [
                    "==",
                    "0.18.0"
                ]
            ]
        },
        {
            "name": "pytest-codecov",
            "specs": [
                [
                    "==",
                    "0.5.0"
                ]
            ]
        },
        {
            "name": "build",
            "specs": [
                [
                    "==",
                    "0.9.0"
                ]
            ]
        },
        {
            "name": "twine",
            "specs": [
                [
                    "==",
                    "4.0.1"
                ]
            ]
        }
    ],
    "lcname": "bsvlib"
}
        
Elapsed time: 0.12906s