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")],
    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.

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 (blockchain_rid automatically set from client.config)
    transaction = Transaction(
        operations=[operation],
        signers=[public_key],
        signatures=None
        # blockchain_rid automatically set from client.config
    )
    
    # 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!")

Alternative: Using Transaction.create() with explicit config

# You can also explicitly pass the client config when creating transactions
transaction = Transaction.create(
    operations=[operation],
    signers=[public_key],
    client_config=client.config  # Explicitly set blockchain_rid from config
)

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.2.3.tar.gz (31.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.2.3-py3-none-any.whl (31.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: postchain_client_py-0.2.3.tar.gz
  • Upload date:
  • Size: 31.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.22

File hashes

Hashes for postchain_client_py-0.2.3.tar.gz
Algorithm Hash digest
SHA256 d83d529bbedfb680fa043d36859e2a98cab79dfa626ab164f0c48be7fd72a680
MD5 745c1c130ac9733cdc6d7369ccc2bcae
BLAKE2b-256 7c44bed2226bed9a2118dd275b17ab6fc96447d99ff37c12662dc04cf9b0800a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for postchain_client_py-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 29df8ee2b57a416b880f5375048047cec29ec8fc42af1c60018f2c8c0d8b3059
MD5 c760b5b13cd5dcec2ac3b4ace6a7b12e
BLAKE2b-256 8b46dee10aa6aaa8a9d48a46a7393eba357cbd944efc58706f38ebc6d1700b06

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