Skip to main content

A Python client for Postchain

Project description

Postchain Client Python

A Python client library for interacting with Postchain nodes on Chromia 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

# 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

# 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):
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'))
  1. Install pkg-config (Run in Admin PowerShell):
choco install pkgconfiglite
  1. Install Visual Studio Build Tools:

Project Setup

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

# Activate virtual environment (Command Prompt)
.venv\Scripts\activate.bat
# OR (PowerShell)
.venv\Scripts\Activate.ps1
  1. Install the package:
# Install in development mode with all dependencies
pip install -e ".[dev]"

Configuration

Create a .env file in your project root:

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:

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

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

settings = NetworkSettings(
    node_url_pool=[os.getenv("POSTCHAIN_TEST_NODE", "http://localhost: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.

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

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 or visit our documentation.

Development

Running Tests

# 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

postchain_client_py-0.1.5.tar.gz (25.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

postchain_client_py-0.1.5-py3-none-any.whl (26.4 kB view details)

Uploaded Python 3

File details

Details for the file postchain_client_py-0.1.5.tar.gz.

File metadata

  • Download URL: postchain_client_py-0.1.5.tar.gz
  • Upload date:
  • Size: 25.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.1

File hashes

Hashes for postchain_client_py-0.1.5.tar.gz
Algorithm Hash digest
SHA256 2036ac5a5c4250dfed905877b8a717e7efbd528bcf681db739394a4bc73e1882
MD5 6dd33e0c5ed409b554d6cc063311834d
BLAKE2b-256 bad50d21a73a1b98dd26394db1c493052cb8c98c382a2cfc9f401eb2b11c243a

See more details on using hashes here.

File details

Details for the file postchain_client_py-0.1.5-py3-none-any.whl.

File metadata

File hashes

Hashes for postchain_client_py-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 f3a35e7d69f4a54d14875a51ca9aa1cb1b6e4956240e3373660faafb2f101e37
MD5 cce8df9b44ddf136ae3a55903b8ab9da
BLAKE2b-256 2e88d73d7cb91b7cff6f6144a5d74c1c4a095accf109d87b8cb91543325f932a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page