postchain-client-py


Namepostchain-client-py JSON
Version 0.1.7 PyPI version JSON
download
home_pageNone
SummaryA Python client for Postchain
upload_time2025-03-21 12:06:52
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT License Copyright (c) 2025 Chromaway Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
keywords blockchain postchain chromaway
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Postchain Client Python

A Python client library for interacting with Postchain nodes on [Chromia](https://chromia.com/) blockchain networks. This library provides a robust interface for creating, signing, and sending transactions, as well as querying the blockchain, with full async support.

## Features

- ✨ Full asynchronous API support using `aiohttp`
- 🔒 Secure transaction creation and signing
- 🔄 GTV (Generic Type Value) encoding/decoding
- 🔍 Comprehensive blockchain querying capabilities
- ✅ Extensive test coverage
- 📝 Type hints throughout for better development experience

## Prerequisites

- Python 3.7 or higher
- A running Postchain node (for actual usage)

## Installation

```bash
# Clone the repository
git clone git@bitbucket.org:chromawallet/postchain-client-py.git
cd postchain-client-py

# Install dependencies and the package
pip install -e .

# For development (includes testing tools)
pip install -e ".[dev]"
```

### To create inside a virtual environment

## Virtual Environment Setup

### Linux/macOS

```bash
# Required system dependecies
# Install dependencies with Homebrew (setup Homebrew first if you don't have it)
brew install automake pkg-config libtool libffi gmp

# Create virtual environment
python3 -m venv .venv

# Activate virtual environment
source .venv/bin/activate

# Install the package
pip install -e . 
# Or install development dependencies
pip install -e ".[dev]"
```

# Windows Setup Guide

## Prerequisites

1. Install Chocolatey (Run in Admin PowerShell):
```powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
```

2. Install pkg-config (Run in Admin PowerShell):
```powershell
choco install pkgconfiglite
```

3. Install Visual Studio Build Tools:
   - Download from: https://visualstudio.microsoft.com/visual-cpp-build-tools/
   - During installation, select "Desktop development with C++"
   - This is required for building certain Python packages

## Project Setup

1. Create and activate virtual environment:
```bash
# Create virtual environment
python -m venv .venv

# Activate virtual environment (Command Prompt)
.venv\Scripts\activate.bat
# OR (PowerShell)
.venv\Scripts\Activate.ps1
```

2. Install the package:
```bash
# Install in development mode with all dependencies
pip install -e ".[dev]"
```


## Configuration

Create a `.env` file in your project root:

```env
POSTCHAIN_TEST_NODE=http://localhost:7740
BLOCKCHAIN_TEST_RID=your_blockchain_rid
PRIV_KEY=your_private_key
```

## Quick Start

Here's a simple example to get you started:

```python
import asyncio
from postchain_client_py import BlockchainClient
from postchain_client_py.blockchain_client.types import NetworkSettings

async def main():
    # Initialize network settings
    settings = NetworkSettings(
        node_url_pool=["http://localhost:7740"],
        blockchain_rid="YOUR_BLOCKCHAIN_RID",
    )
    
    # Create client and execute query
    client = await BlockchainClient.create(settings)
    result = await client.query("get_collections")
    print(f"Collections: {result}")
    
    # Clean up
    await client.rest_client.close()

if __name__ == "__main__":
    asyncio.run(main())
```

## Advanced Examples

### Setting Up the Environment

```python
import os
import asyncio
from dotenv import load_dotenv
from coincurve import PrivateKey
from postchain_client_py import BlockchainClient
from postchain_client_py.blockchain_client.types import NetworkSettings, Operation, Transaction
from postchain_client_py.blockchain_client.enums import FailoverStrategy

# Load environment variables
load_dotenv()
```

### Network Configuration

```python
settings = NetworkSettings(
    node_url_pool=[os.getenv("POSTCHAIN_TEST_NODE", "http://localhost:7740")],
    directory_node_url_pool=['a directory node url like system.chromaway.com:7740'],
    blockchain_rid="YOUR_BLOCKCHAIN_RID",
    # Optional parameters
    status_poll_interval=int(os.getenv("STATUS_POLL_INTERVAL", "500")), # Opitional (default: 500)
    status_poll_count=int(os.getenv("STATUS_POLL_COUNT", "5")), # Opitional (default: 5)
    verbose=True, # Opitional (default: False)
    attempt_interval=int(os.getenv("ATTEMPT_INTERVAL", "5000")), # Opitional (default: 5000)
    attempts_per_endpoint=int(os.getenv("ATTEMPTS_PER_ENDPOINT", "3")), # Opitional (default: 3)
    failover_strategy=FailoverStrategy.ABORT_ON_ERROR, # Opitional (default: FailoverStrategy.ABORT_ON_ERROR)
    unreachable_duration=int(os.getenv("UNREACHABLE_DURATION", "30000")), # Opitional (default: 30000)
    use_sticky_node=False, # Opitional (default: False)
    blockchain_iid=int(os.getenv("BLOCKCHAIN_IID", "0")) # Opitional (default: 0)
)
```

### Querying the Blockchain
Note: This example assumes you have local blockchain running as from this repo: https://bitbucket.org/chromawallet/book-course/src/39076dc778734d2a7b560846d83289b1597f4f5e/
Beware of it commit hash (39076dc778734d2a7b560846d83289b1597f4f5e) because that should be the one with right blockchain_rid that has been set in the test files as constant. You can change it to any other BRID for testing.
```python
async def query_example(client: BlockchainClient):
    # Simple query without arguments
    books = await client.query("get_all_books")
    print(f"Books: {books}")

    # Query with arguments
    reviews = await client.query(
        "get_all_reviews_for_book", 
        {"isbn": "ISBN123"}
    )
    print(f"Reviews: {reviews}")
```

### Creating and Sending Transactions

```python
async def transaction_example(client: BlockchainClient):
    # Setup keys
    private_bytes = bytes.fromhex(os.getenv("PRIV_KEY"))
    private_key = PrivateKey(private_bytes, raw=True)
    public_key = private_key.pubkey.serialize()

    # Create operation
    operation = Operation(
        op_name="create_book",
        args=["ISBN123", "Python Mastery", "Jane Doe"]
    )
    
    # Build transaction
    transaction = Transaction(
        operations=[operation],
        signers=[public_key],
        signatures=None,
        blockchain_rid=client.config.blockchain_rid
    )
    
    # Sign and send
    signed_tx = await client.sign_transaction(transaction, private_bytes)
    receipt = await client.send_transaction(signed_tx, do_status_polling=True)
    
    if receipt.status == ResponseStatus.CONFIRMED:
        print("Transaction confirmed!")
```

### Complete Working Example

For a complete working example that demonstrates creating books, adding reviews, and querying the blockchain, check out our [examples directory](examples/) or visit our [documentation](docs/).

## Development

### Running Tests

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/
```

### Code Quality

- Format code using Black: `black .`
- Follow type hints and docstring conventions
- Run tests before submitting PRs

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add: your feature description'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License:

```
MIT License

Copyright (c) 2024 Chromaway

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## Support

If you encounter any issues or have questions, please:
1. Check the existing issues on GitHub
2. Create a new issue if needed
3. Provide as much context as possible

---

Made with ❤️ for the Postchain community

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "postchain-client-py",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "blockchain, postchain, chromaway",
    "author": null,
    "author_email": "TheCosmos <mert.akayasi@chromaway.com>",
    "download_url": "https://files.pythonhosted.org/packages/3d/cc/e6a67c827f7f5576f3a57d41104e78cc3ec7be849cea2da7ebe78e919914/postchain_client_py-0.1.7.tar.gz",
    "platform": null,
    "description": "# Postchain Client Python\n\nA Python client library for interacting with Postchain nodes on [Chromia](https://chromia.com/) blockchain networks. This library provides a robust interface for creating, signing, and sending transactions, as well as querying the blockchain, with full async support.\n\n## Features\n\n- \u2728 Full asynchronous API support using `aiohttp`\n- \ud83d\udd12 Secure transaction creation and signing\n- \ud83d\udd04 GTV (Generic Type Value) encoding/decoding\n- \ud83d\udd0d Comprehensive blockchain querying capabilities\n- \u2705 Extensive test coverage\n- \ud83d\udcdd Type hints throughout for better development experience\n\n## Prerequisites\n\n- Python 3.7 or higher\n- A running Postchain node (for actual usage)\n\n## Installation\n\n```bash\n# Clone the repository\ngit clone git@bitbucket.org:chromawallet/postchain-client-py.git\ncd postchain-client-py\n\n# Install dependencies and the package\npip install -e .\n\n# For development (includes testing tools)\npip install -e \".[dev]\"\n```\n\n### To create inside a virtual environment\n\n## Virtual Environment Setup\n\n### Linux/macOS\n\n```bash\n# Required system dependecies\n# Install dependencies with Homebrew (setup Homebrew first if you don't have it)\nbrew install automake pkg-config libtool libffi gmp\n\n# Create virtual environment\npython3 -m venv .venv\n\n# Activate virtual environment\nsource .venv/bin/activate\n\n# Install the package\npip install -e . \n# Or install development dependencies\npip install -e \".[dev]\"\n```\n\n# Windows Setup Guide\n\n## Prerequisites\n\n1. Install Chocolatey (Run in Admin PowerShell):\n```powershell\nSet-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))\n```\n\n2. Install pkg-config (Run in Admin PowerShell):\n```powershell\nchoco install pkgconfiglite\n```\n\n3. Install Visual Studio Build Tools:\n   - Download from: https://visualstudio.microsoft.com/visual-cpp-build-tools/\n   - During installation, select \"Desktop development with C++\"\n   - This is required for building certain Python packages\n\n## Project Setup\n\n1. Create and activate virtual environment:\n```bash\n# Create virtual environment\npython -m venv .venv\n\n# Activate virtual environment (Command Prompt)\n.venv\\Scripts\\activate.bat\n# OR (PowerShell)\n.venv\\Scripts\\Activate.ps1\n```\n\n2. Install the package:\n```bash\n# Install in development mode with all dependencies\npip install -e \".[dev]\"\n```\n\n\n## Configuration\n\nCreate a `.env` file in your project root:\n\n```env\nPOSTCHAIN_TEST_NODE=http://localhost:7740\nBLOCKCHAIN_TEST_RID=your_blockchain_rid\nPRIV_KEY=your_private_key\n```\n\n## Quick Start\n\nHere's a simple example to get you started:\n\n```python\nimport asyncio\nfrom postchain_client_py import BlockchainClient\nfrom postchain_client_py.blockchain_client.types import NetworkSettings\n\nasync def main():\n    # Initialize network settings\n    settings = NetworkSettings(\n        node_url_pool=[\"http://localhost:7740\"],\n        blockchain_rid=\"YOUR_BLOCKCHAIN_RID\",\n    )\n    \n    # Create client and execute query\n    client = await BlockchainClient.create(settings)\n    result = await client.query(\"get_collections\")\n    print(f\"Collections: {result}\")\n    \n    # Clean up\n    await client.rest_client.close()\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## Advanced Examples\n\n### Setting Up the Environment\n\n```python\nimport os\nimport asyncio\nfrom dotenv import load_dotenv\nfrom coincurve import PrivateKey\nfrom postchain_client_py import BlockchainClient\nfrom postchain_client_py.blockchain_client.types import NetworkSettings, Operation, Transaction\nfrom postchain_client_py.blockchain_client.enums import FailoverStrategy\n\n# Load environment variables\nload_dotenv()\n```\n\n### Network Configuration\n\n```python\nsettings = NetworkSettings(\n    node_url_pool=[os.getenv(\"POSTCHAIN_TEST_NODE\", \"http://localhost:7740\")],\n    directory_node_url_pool=['a directory node url like system.chromaway.com:7740'],\n    blockchain_rid=\"YOUR_BLOCKCHAIN_RID\",\n    # Optional parameters\n    status_poll_interval=int(os.getenv(\"STATUS_POLL_INTERVAL\", \"500\")), # Opitional (default: 500)\n    status_poll_count=int(os.getenv(\"STATUS_POLL_COUNT\", \"5\")), # Opitional (default: 5)\n    verbose=True, # Opitional (default: False)\n    attempt_interval=int(os.getenv(\"ATTEMPT_INTERVAL\", \"5000\")), # Opitional (default: 5000)\n    attempts_per_endpoint=int(os.getenv(\"ATTEMPTS_PER_ENDPOINT\", \"3\")), # Opitional (default: 3)\n    failover_strategy=FailoverStrategy.ABORT_ON_ERROR, # Opitional (default: FailoverStrategy.ABORT_ON_ERROR)\n    unreachable_duration=int(os.getenv(\"UNREACHABLE_DURATION\", \"30000\")), # Opitional (default: 30000)\n    use_sticky_node=False, # Opitional (default: False)\n    blockchain_iid=int(os.getenv(\"BLOCKCHAIN_IID\", \"0\")) # Opitional (default: 0)\n)\n```\n\n### Querying the Blockchain\nNote: This example assumes you have local blockchain running as from this repo: https://bitbucket.org/chromawallet/book-course/src/39076dc778734d2a7b560846d83289b1597f4f5e/\nBeware of it commit hash (39076dc778734d2a7b560846d83289b1597f4f5e) because that should be the one with right blockchain_rid that has been set in the test files as constant. You can change it to any other BRID for testing.\n```python\nasync def query_example(client: BlockchainClient):\n    # Simple query without arguments\n    books = await client.query(\"get_all_books\")\n    print(f\"Books: {books}\")\n\n    # Query with arguments\n    reviews = await client.query(\n        \"get_all_reviews_for_book\", \n        {\"isbn\": \"ISBN123\"}\n    )\n    print(f\"Reviews: {reviews}\")\n```\n\n### Creating and Sending Transactions\n\n```python\nasync def transaction_example(client: BlockchainClient):\n    # Setup keys\n    private_bytes = bytes.fromhex(os.getenv(\"PRIV_KEY\"))\n    private_key = PrivateKey(private_bytes, raw=True)\n    public_key = private_key.pubkey.serialize()\n\n    # Create operation\n    operation = Operation(\n        op_name=\"create_book\",\n        args=[\"ISBN123\", \"Python Mastery\", \"Jane Doe\"]\n    )\n    \n    # Build transaction\n    transaction = Transaction(\n        operations=[operation],\n        signers=[public_key],\n        signatures=None,\n        blockchain_rid=client.config.blockchain_rid\n    )\n    \n    # Sign and send\n    signed_tx = await client.sign_transaction(transaction, private_bytes)\n    receipt = await client.send_transaction(signed_tx, do_status_polling=True)\n    \n    if receipt.status == ResponseStatus.CONFIRMED:\n        print(\"Transaction confirmed!\")\n```\n\n### Complete Working Example\n\nFor a complete working example that demonstrates creating books, adding reviews, and querying the blockchain, check out our [examples directory](examples/) or visit our [documentation](docs/).\n\n## Development\n\n### Running Tests\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest tests/\n```\n\n### Code Quality\n\n- Format code using Black: `black .`\n- Follow type hints and docstring conventions\n- Run tests before submitting PRs\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add: your feature description'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License:\n\n```\nMIT License\n\nCopyright (c) 2024 Chromaway\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n## Support\n\nIf you encounter any issues or have questions, please:\n1. Check the existing issues on GitHub\n2. Create a new issue if needed\n3. Provide as much context as possible\n\n---\n\nMade with \u2764\ufe0f for the Postchain community\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2025 Chromaway  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. ",
    "summary": "A Python client for Postchain",
    "version": "0.1.7",
    "project_urls": {
        "Homepage": "https://bitbucket.org/chromawallet/postchain-client-py"
    },
    "split_keywords": [
        "blockchain",
        " postchain",
        " chromaway"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "232f1b07ef23811721bfc5e4a9a964cfe8c70c693de18a2b9997613ad04b55ac",
                "md5": "72a97bae96576034c55716ce7254af03",
                "sha256": "63cdbd1d8c3a69b9b34a179bfd8880a640b0fcaa60c6e0841f610edfb74b793f"
            },
            "downloads": -1,
            "filename": "postchain_client_py-0.1.7-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "72a97bae96576034c55716ce7254af03",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 26875,
            "upload_time": "2025-03-21T12:06:50",
            "upload_time_iso_8601": "2025-03-21T12:06:50.041484Z",
            "url": "https://files.pythonhosted.org/packages/23/2f/1b07ef23811721bfc5e4a9a964cfe8c70c693de18a2b9997613ad04b55ac/postchain_client_py-0.1.7-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3dcce6a67c827f7f5576f3a57d41104e78cc3ec7be849cea2da7ebe78e919914",
                "md5": "ec891f4a4da2a7bc0b7ec071745a043a",
                "sha256": "33086a044c3bae5fab5c0cc500c2bd689fdeb27bea822cee76ceb6d151cb1fc8"
            },
            "downloads": -1,
            "filename": "postchain_client_py-0.1.7.tar.gz",
            "has_sig": false,
            "md5_digest": "ec891f4a4da2a7bc0b7ec071745a043a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 26038,
            "upload_time": "2025-03-21T12:06:52",
            "upload_time_iso_8601": "2025-03-21T12:06:52.175877Z",
            "url": "https://files.pythonhosted.org/packages/3d/cc/e6a67c827f7f5576f3a57d41104e78cc3ec7be849cea2da7ebe78e919914/postchain_client_py-0.1.7.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-03-21 12:06:52",
    "github": false,
    "gitlab": false,
    "bitbucket": true,
    "codeberg": false,
    "bitbucket_user": "chromawallet",
    "bitbucket_project": "postchain-client-py",
    "lcname": "postchain-client-py"
}
        
Elapsed time: 2.23737s