Skip to content

About

Python implementation of the Knish.IO client SDK

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

Knish.IO: Post-Blockchain Platform
info@wishknish.com | https://wishknish.com

Knish.IO Python Client SDK

This is the official Python implementation of the Knish.IO client SDK. Its purpose is to expose class libraries for building and signing Knish.IO Molecules, composing Atoms, generating Wallets, and much more.

Installation

The SDK can be installed via pip:

pip install knishioclient

Requirements:

  • Python 3.11 or higher
  • Node.js 20.19 or higher on the PATH (required for ML-KEM quantum-resistant cryptography). The wheel bundles the ML-KEM bridge and its pinned @noble/post-quantum modules, so a pip install needs no npm step.
  • The libsodium shared library, which libnacl loads when knishioclient is imported: Debian/Ubuntu apt-get install libsodium23, Alpine apk add libsodium, macOS brew install libsodium. On Apple silicon, Homebrew's library directory is not on the default search path, so also export DYLD_FALLBACK_LIBRARY_PATH="$(brew --prefix libsodium)/lib".
  • Virtual environment (recommended)
  • Required packages: numpy, cryptography, libnacl, base58, aiohttp

Setup with virtual environment:

# Create and activate virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install the SDK
pip install knishioclient

# Or, in a source checkout, install runtime + dev/test tooling for development
pip install -r requirements.txt -r requirements-dev.txt

# A source checkout also needs the ML-KEM bridge's pinned Node modules (building a wheel
# refuses to run without them)
cd bin
npm ci
cd ..

Dependency security & reproducible installs

requirements.txt declares runtime dependencies with lower-bound (>=) floors so the library composes with a consumer's own dependency graph, and requirements-dev.txt adds the lint/test/audit/build tooling (ruff, pytest, pip-audit, build). For a fully pinned, reproducible install we also commit requirements.lock — a universal, hash-verified resolution of the runtime closure generated with uv pip compile requirements.txt --universal --generate-hashes -o requirements.lock --exclude-newer <cutoff>, where <cutoff> is an RFC 3339 instant at least seven days in the past; regenerate it whenever requirements.txt changes and install it with pip install -r requirements.lock in environments that need byte-for-byte reproducibility (the floors in requirements.txt remain the source of truth for supported versions). CI and the publish workflow install the development tools from requirements-dev.lock, generated at the same cutoff and constrained to the runtime lock with uv pip compile requirements-dev.txt -c requirements.lock --universal --generate-hashes --exclude-newer <cutoff> -o requirements-dev.lock; regenerate it after requirements-dev.txt or requirements.lock changes. The dependency set is scanned for known CVEs with pip-audit -r requirements.txt (and pip-audit -r requirements.lock, pip-audit -r requirements-dev.lock); the current closure reports no known vulnerabilities.

After installation, import the SDK in your project:

from knishioclient.client.KnishIOClient import KnishIOClient
from knishioclient.models import Wallet, Molecule, Atom
from knishioclient.libraries import crypto

Basic Usage

The purpose of the Knish.IO SDK is to expose various ledger functions to new or existing applications.

There are two ways to take advantage of these functions:

  1. The easy way: use the KnishIOClient wrapper class

  2. The granular way: build Atom and Molecule instances and broadcast GraphQL messages yourself

This document will explain both ways.

The Easy Way: KnishIOClient Wrapper

  1. Include the wrapper class in your application code:

    from knishioclient.client.KnishIOClient import KnishIOClient
  2. Instantiate the class with your node URI:

    client = KnishIOClient("http://localhost:8000/graphql")
    client.set_cell_slug("my-cell-slug")
  3. Request authorization token from the node:

    response = client.request_auth_token(secret)
    
    if response.success():
        # Authentication successful
        print("Authenticated successfully!")
    else:
        raise Exception(f"Authentication failed: {response.reason()}")

    (Note: The secret parameter can be a salted combination of username + password, a biometric hash, an existing user identifier from an external authentication process, for example)

  4. Begin using client to trigger commands described below...

KnishIOClient Methods

  • Query metadata for a Wallet Bundle. Omit the bundle_hash parameter to query your own Wallet Bundle:

    response = client.query_bundle(
        bundle_hash='c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d'
    )
    
    if response.success():
        bundle_data = response.data()
        print(bundle_data)  # Raw Metadata
  • Query metadata for a Meta Asset:

    result = client.query_meta(
        meta_type='Vehicle',
        meta_id=None,  # Meta ID
        key='LicensePlate',
        value='1H17P',
        latest=True,  # Limit meta values to latest per key
        through_atom=True  # Optional, query through Atom (default: True)
    )
    
    print(result)  # Raw Metadata
  • Writing new metadata for a Meta Asset:

    response = client.create_meta(
        meta_type='Pokemon',
        meta_id='Charizard',
        metadata={
            'type': 'fire',
            'weaknesses': [
                'rock',
                'water',
                'electric'
            ],
            'immunities': [
                'ground',
            ],
            'hp': 78,
            'attack': 84,
        }
    )
    
    if response.success():
        # Do things!
        print("Metadata created successfully!")
    
    print(response.data())  # Raw response
  • Query Wallets associated with a Wallet Bundle:

    wallets = client.query_wallets(
        bundle_hash='c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d',
        unspent=True  # Optional, limit results to unspent wallets
    )
    
    print(wallets)  # Raw response
  • Declaring new Wallets:

    (Note: If Tokens are sent to undeclared Wallets, Shadow Wallets will be used (placeholder Wallets that can receive, but cannot send) to store tokens until they are claimed.)

    response = client.create_wallet('FOO')  # Token Slug for the wallet we are declaring
    
    if response.success():
        # Do things!
        print("Wallet created successfully!")
    
    print(response.data())  # Raw response
  • Issuing new Tokens:

    response = client.create_token(
        token_slug='CRZY',  # Token slug (ticker symbol)
        initial_amount=100000000,  # Initial amount to issue
        meta={
            'name': 'CrazyCoin',  # Public name for the token
            'fungibility': 'fungible',  # Fungibility style (fungible / nonfungible / stackable)
            'supply': 'limited',  # Supply style (limited / replenishable)
            'decimals': 2  # Decimal places
        },
        units=[],  # Optional, for stackable tokens
        batch_id=None  # Optional, for stackable tokens
    )
    
    if response.success():
        # Do things!
        print("Token created successfully!")
    
    print(response.data())  # Raw response
  • Transferring Tokens to other users:

    response = client.transfer_token(
        wallet_object_or_bundle_hash='7bf38257401eb3b0f20cabf5e6cf3f14c76760386473b220d95fa1c38642b61d',  # Recipient's bundle hash
        token_slug='CRZY',  # Token slug
        amount=100,
        units=[],  # Optional, for stackable tokens
        batch_id=None  # Optional, for stackable tokens
    )
    
    if response.success():
        # Do things!
        print("Token transferred successfully!")
    
    print(response.data())  # Raw response
  • Creating a new Rule:

    response = client.create_rule(
        meta_type='MyMetaType',
        meta_id='MyMetaId',
        rule=[{
            'condition': [{'key': 'role', 'value': 'admin', 'comparison': '=='}],
            'callback': [{'action': 'allow'}]
        }],
        policy={}  # Optional policy object
    )
    
    if response.success():
        # Do things!
        print("Rule created successfully!")
    
    print(response.data())  # Raw response
  • Querying Atoms:

    response = client.query_atom(
        molecular_hash='hash',
        bundle_hash='bundle',
        isotope='V',
        token_slug='CRZY',
        latest=True,
        limit=15,
        offset=1
    )
    
    print(response.data())  # Raw response
  • Working with Buffer Tokens:

    # Deposit to buffer
    deposit_response = client.deposit_buffer_token(
        token_slug='CRZY',
        amount=100,
        trade_rates={
            'OTHER_TOKEN': 0.5
        }
    )
    
    # Withdraw from buffer
    withdraw_response = client.withdraw_buffer_token(
        token_slug='CRZY',
        amount=50
    )
    
    print([deposit_response.data(), withdraw_response.data()])  # Raw responses
  • Getting client information:

    # Note: Fingerprint methods may not be available in the Python SDK
    # Check client configuration and bundle information
    if client.has_secret():
        bundle = client.bundle()
        print(f"Client bundle: {bundle}")

Advanced Usage: Working with Molecules

For more granular control, you can work directly with Molecules:

  • Create a new Molecule:

    from knishioclient.models import Molecule
    
    molecule = Molecule(
        secret=secret,
        source_wallet=source_wallet,
        remainder_wallet=remainder_wallet,
        cell_slug=cell_slug
    )
  • Create a custom Mutation:

    from knishioclient.mutation.MutationProposeMolecule import MutationProposeMolecule
    
    mutation = MutationProposeMolecule(client, molecule)
  • Sign and check a Molecule:

    molecule.sign()
    try:
        if molecule.check():
            print("Molecule validation passed!")
        else:
            print("Molecule validation failed!")
    except Exception as e:
        print(f"Molecule validation error: {e}")
  • Execute a custom Query or Mutation:

    response = client.execute_query(mutation)
    
    if response.success():
        print("Molecule executed successfully!")

The Hard Way: DIY Everything

This method involves individually building Atoms and Molecules, triggering the signature and validation processes, and communicating the resulting signed Molecule mutation or Query to a Knish.IO node via GraphQL.

  1. Include the relevant classes in your application code:

    from knishioclient.models import Molecule, Wallet, Atom
    from knishioclient.libraries import crypto
  2. Generate a 2048-symbol hexadecimal secret, either randomly, or via hashing login + password + salt, OAuth secret ID, biometric ID, or any other static value.

  3. (optional) Initialize a signing wallet with:

    wallet = Wallet(
        secret=secret,
        token=token_slug,
        position=custom_position,  # (optional) instantiate specific wallet instance vs. random
        characters=character_set  # (optional) override the character set used by the wallet
    )

    WARNING 1: If ContinuID is enabled on the node, you will need to use a specific wallet, and therefore will first need to query the node to retrieve the position for that wallet.

    WARNING 2: The Knish.IO protocol mandates that all C and M transactions be signed with a USER token wallet.

  4. Build your molecule with:

    molecule = Molecule(
        secret=secret,
        source_wallet=source_wallet,  # (optional) wallet for signing
        remainder_wallet=remainder_wallet,  # (optional) wallet to receive remainder tokens
        cell_slug=cell_slug  # (optional) used to point a transaction to a specific branch of the ledger
    )
  5. Either use one of the shortcut methods provided by the Molecule class (which will build Atom instances for you), or create Atom instances yourself.

    DIY example:

    # This example records a new Wallet on the ledger
    
    # Define metadata for our new wallet
    new_wallet_meta = {
        'address': new_wallet.address,
        'token': new_wallet.token,
        'bundle': new_wallet.bundle,
        'position': new_wallet.position,
        'batchId': new_wallet.batchId,
    }
    
    # Build the C isotope atom
    wallet_creation_atom = Atom(
        position=source_wallet.position,
        wallet_address=source_wallet.address,
        isotope='C',
        token=source_wallet.token,
        meta_type='wallet',
        meta_id=new_wallet.address,
        meta=new_wallet_meta,
        index=molecule.generate_index()
    )
    
    # Add the atom to our molecule
    molecule.add_atom(wallet_creation_atom)
    
    # Adding a ContinuID / remainder atom
    molecule.add_continue_id_atom()

    Molecule shortcut method example:

    # This example commits metadata to some Meta Asset
    
    # Defining our metadata
    metadata = {
        'foo': 'Foo',
        'bar': 'Bar'
    }
    
    molecule.init_meta(
        meta=metadata,
        meta_type='MyMetaType',
        meta_id='MetaId123'
    )
  6. Sign the molecule with the stored user secret:

    molecule.sign()
  7. Make sure everything checks out by verifying the molecule:

    try:
        if molecule.check():
            # If we're validating a V isotope transaction,
            # add the source wallet as a parameter
            print("Molecule validation passed!")
        else:
            print("Molecule validation failed!")
    except Exception as e:
        print(f"Molecule check failed: {e}")
        # Handle the error
  8. Broadcast the molecule to a Knish.IO node:

    from knishioclient.mutation.MutationProposeMolecule import MutationProposeMolecule
    
    # Build our mutation object using the KnishIOClient wrapper
    mutation = MutationProposeMolecule(client, molecule)
    
    # Send the mutation to the node and get a response
    response = client.execute_query(mutation)
  9. Inspect the response...

    # For basic queries, we look at the data property:
    print(response.data())
    
    # For mutations, check if the molecule was accepted by the ledger:
    print("Success" if response.success() else "Failed")
    
    # We can also check the reason for rejection
    print(response.reason())
    
    # Some queries may also produce a payload, with additional data:
    print(response.payload())

    Payloads are provided by responses to the following queries:

    1. QueryBalance and QueryContinuId -> returns a Wallet instance
    2. QueryWalletList -> returns a list of Wallet instances
    3. MutationProposeMolecule, MutationRequestAuthorization, MutationCreateIdentifier, MutationLinkIdentifier, MutationClaimShadowWallet, MutationCreateToken, MutationRequestTokens, and MutationTransferTokens -> returns molecule metadata

Network Freshness

The GraphQL transport (aiohttp) issues a fresh network request per query — there is no response caching — so a long-lived client never serves a stale read of ledger state. No fresh-read knob (e.g. a request policy) is required.

Secret storage

Master secrets are stored at rest in the cross-SDK AES-256-GCM envelope (PBKDF2-HMAC-SHA256 ×100000, camelCase metadata; frozen in sdks/shared-test-results/cross-platform-test-vectors.json). Every SDK decrypts every other SDK's envelope.

Provider providerType Custody (hardwareBacked) Where the key lives Recovery passphrase
MemorySecretStorageProvider memory Software (false) Process memory Optional
AesGcmSecretStorageProvider aes-gcm Software (false) Any StorageBackend (MemoryStorageBackend, FileStorageBackend [0o600]) Optional

hardwareBacked is derived by the provider from the platform, never accepted from the caller; software providers always report false. A hardware provider refuses to store without a recovery passphrase unless allow_unrecoverable is set — the recovery envelope (knishio:recovery:<bundleHash>, providerType: "aes-gcm") is software custody whose strength is bounded by that passphrase: enforce passphrase entropy or keep it on a second device.

Client integration: KnishIOClient(secret_storage=...) and client.set_secret_storage(provider, bundle_hash=...) attaches a provider and persists the secret there; the client still holds the cleartext in memory.

Thread safety

Platform wheels bundle libkcore (KnishIO-Crypto-Core), which the SDK uses for WOTS+ and ML-KEM when it loads (KNISHIO_KCORE=auto|off|require, KNISHIO_KCORE_LIB to override the library path). The library is loaded once, on first use, even when many threads make that first call together; after that, kcore calls are safe from any number of threads. The surrounding SDK code runs under the GIL, so for CPU-bound parallelism (signing or verifying many molecules) use processes, e.g. concurrent.futures.ProcessPoolExecutor, rather than threads.

Getting Help

Knish.IO is under active development, and our team is ready to assist with integration questions. The best way to seek help is to stop by our Telegram Support Channel. You can also send us a contact request via our website.

About

Python implementation of the Knish.IO client SDK

Topics

Resources

Security policy

Stars

1 star

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages