cashscript_py package

Public API for CashScript-Py.

Exports the most commonly used classes and helpers: - Contract - Output, Utxo - ElectrumNetworkProvider, NetworkProvider - SignatureTemplate - TransactionBuilder

class Contract(artifact: dict[str, Any], constructor_args: list[bool | int | str | bytes], provider: NetworkProvider, address_type: LockingBytecodeType = LockingBytecodeType.P2SH32)[source]

Bases: object

High-level interface to a CashScript contract.

A Contract is constructed from a compiled cashc JSON artifact and constructor arguments. It exposes ABI functions via the unlock mapping and provides helper methods for querying UTXOs and balances.

name

The contract name from the artifact.

address

The contract address (token-unaware).

token_address

The contract address (token-aware).

bytecode

Contract redeem script bytecode (hex).

bytesize

Size of the redeem script in bytes.

opcount

Count of non-push opcodes in the redeem script.

provider

Network provider used for blockchain operations.

address_type

Locking bytecode type (e.g., P2SH32).

unlock

Mapping of function name to unlocker factory.

async get_balance() int[source]

Return the total balance (sum of UTXO satoshis) at the contract address.

Returns:

The sum of satoshis across all UTXOs at the contract address.

async get_utxos() list[Utxo][source]

Fetch all UTXOs (confirmed/unconfirmed) for the contract address.

Returns:

A list of UTXOs spendable by this contract.

class ElectrumNetworkProvider(network: Network = Network.MAINNET)[source]

Bases: NetworkProvider

NetworkProvider backed by bitcash FulcrumProtocolAPI.

Connects to specific servers per network and provides UTXO queries, block height, raw transaction fetching, and broadcasting.

async get_block_height() int[source]

Return the current block height.

Raises:
async get_raw_transaction(txid: str) str[source]

Retrieve the raw transaction hex for a txid.

Parameters:

txid – Transaction ID (hex).

Returns:

Raw transaction hex.

Raises:
async get_utxos(address: str) list[Utxo][source]

Fetch UTXOs for a CashAddress.

Parameters:

address – CashAddress string.

Returns:

List of Utxo objects.

Raises:
property network: Network

Return the configured network.

async send_raw_transaction(tx_hex: str) str[source]

Broadcast a raw transaction to the network.

Parameters:

tx_hex – Hex-encoded transaction.

Returns:

Transaction ID computed for the broadcast transaction.

Raises:

BroadcastFailed – If the transaction was not accepted by the network.

class HashType(*values)[source]

Bases: Flag

Supported SIGHASH flags.

SIGHASH_ALL = 1
SIGHASH_ANYONECANPAY = 128
SIGHASH_FORKID = 64
SIGHASH_NONE = 2
SIGHASH_SINGLE = 3
SIGHASH_UTXOS = 32
class LockingBytecodeType(*values)[source]

Bases: StrEnum

Supported locking bytecode templates (address types).

P2PK = 'p2pk'
P2PKH = 'p2pkh'
P2SH20 = 'p2sh20'
P2SH32 = 'p2sh32'
class Network(*values)[source]

Bases: StrEnum

Supported Bitcoin Cash networks (network and address prefixes).

CHIPNET = 'chipnet'
MAINNET = 'mainnet'
MOCKNET = 'mocknet'
REGTEST = 'regtest'
TESTNET3 = 'testnet3'
TESTNET4 = 'testnet4'
class NetworkProvider[source]

Bases: ABC

Abstract base class for providers connecting to BCH networks.

Implementations must support querying UTXOs, block height, raw transactions, and broadcasting.

abstractmethod async get_block_height() int[source]

Return the current block height.

Raises:
abstractmethod async get_raw_transaction(txid: str) str[source]

Retrieve the raw transaction hex for a txid.

Parameters:

txid – Transaction ID (hex).

Returns:

Raw transaction hex.

Raises:
abstractmethod async get_utxos(address: str) list[Utxo][source]

Retrieve UTXOs for a given CashAddress.

Parameters:

address – The CashAddress for which UTXOs are requested.

Returns:

A list of spendable UTXOs.

abstract property network: Network

Return the network this provider connects to.

abstractmethod async send_raw_transaction(tx_hex: str) str[source]

Broadcast a raw transaction to the network.

Parameters:

tx_hex – Hex-encoded transaction.

Returns:

Transaction ID computed for the broadcast transaction.

Raises:

BroadcastFailed – If the transaction was not accepted by the network.

class NftCapability(*values)[source]

Bases: StrEnum

NFT CashTokens capabilities.

MINTING = 'minting'
MUTABLE = 'mutable'
NONE = 'none'
class Output(to: bytes | str, amount: int, token: TokenDetails | None = None)[source]

Bases: object

Transaction output description.

to

Recipient locking bytecode (bytes) or CashAddress (str).

amount

BCH amount in satoshis.

token

Optional CashToken details.

class SignatureAlgorithm(*values)[source]

Bases: Flag

Supported signature algorithms.

ECDSA = 0
SCHNORR = 1
class SignatureTemplate(signer: bytes | str, hashtype: HashType = <HashType.SIGHASH_ALL|SIGHASH_UTXOS: 33>, signature_algorithm: SignatureAlgorithm = <SignatureAlgorithm.SCHNORR: 1>, deterministic_schnorr: bool = False)[source]

Bases: object

Encapsulates private-key signing for Bitcoin Cash transactions/messages.

Provides methods to sign 32-byte hashes with Schnorr or ECDSA, generate signatures including the hashtype byte for CHECKSIG, and assemble a P2PKH unlocker for standard inputs.

generate_signature(payload: bytes, bch_fork_id: bool = True) bytes[source]

Sign a 32-byte hash and append the hashtype byte for CHECKSIG.

Parameters:
  • payload – 32-byte sighash.

  • bch_fork_id – If True, include SIGHASH_FORKID in the hashtype.

Returns:

raw sig + 1-byte hashtype.

Return type:

Signature bytes suitable for CHECKSIG

get_hash_type(bch_fork_id: bool = True) HashType[source]

Return the configured SIGHASH flags (optionally OR-ed with ForkID).

get_public_key() bytes[source]

Return the compressed public key (33 bytes).

get_signature_algorithm() SignatureAlgorithm[source]

Return the signature algorithm (Schnorr or ECDSA).

sign_message_hash(payload: bytes) bytes[source]

Sign a 32-byte message hash (no hashtype byte).

Parameters:

payload – A 32-byte message digest.

Returns:

  • 64-byte Schnorr signature, or

  • DER-encoded ECDSA signature (variable length).

Return type:

Raw signature bytes

unlock_p2pkh() Unlocker[source]

Create a standard P2PKH Unlocker using this template.

Returns:

An Unlocker that can sign and unlock P2PKH inputs for this key.

verify_signature(signature: bytes, payload: bytes) bool[source]

Verify a raw signature against a 32-byte message hash.

Parameters:
  • signature – Raw signature (64-byte Schnorr or DER ECDSA).

  • payload – 32-byte message digest.

Returns:

True if the signature is valid for this template’s public key.

class TokenDetails(amount: int | None, category: str, nft: Nft | None)[source]

Bases: object

CashToken details: fungible amount and optional NFT.

class Nft(capability: NftCapability, commitment: str | None)[source]

Bases: object

Nested NFT metadata.

class TransactionBuilder(provider: NetworkProvider, *, maximum_fee_satoshis: int | None = None, maximum_fee_sats_per_byte: float | None = None, allow_implicit_fungible_token_burn: bool = False)[source]

Bases: object

Build, sign, and send BCH transactions via unlockers.

Supports multiple inputs/outputs, OP_RETURN, fee caps, and token burn checks.

add_input(utxo: Utxo, unlocker: Unlocker, sequence: int | None = None) TransactionBuilder[source]

Add a single input.

Parameters:
  • utxo – UTXO to spend.

  • unlocker – Unlocker capable of generating scripts/signatures.

  • sequence – Optional sequence number for this input.

Returns:

This builder (for chaining).

add_inputs(utxos: list[Utxo] | list[UnlockableUtxo], unlocker: Unlocker | None = None, sequence: int | None = None) TransactionBuilder[source]

Add multiple inputs either with a shared unlocker or individually attached unlockers.

Parameters:
  • utxos – List of UTXOs (or UnlockableUtxo instances).

  • unlocker – Shared unlocker if utxos are plain UTXOs.

  • sequence – Optional sequence number for all added inputs (when using a shared unlocker).

Returns:

This builder (for chaining).

Raises:

ValueError – If both or neither forms of unlockers are provided.

add_op_return_output(chunks: list[str]) TransactionBuilder[source]

Add an OP_RETURN output.

Parameters:

chunks – List of strings (UTF-8 or hex with 0x prefix) to push.

add_output(output: Output) TransactionBuilder[source]

Add a single output.

Parameters:

output – Recipient and amount, optionally with token details.

Returns:

This builder (for chaining).

add_outputs(outputs: list[Output]) TransactionBuilder[source]

Add multiple outputs (validated for dust, tokens, etc.).

Parameters:

outputs – Outputs to append.

Returns:

This builder (for chaining).

Raises:
build() str[source]

Build the transaction, generate unlocking scripts, and return serialized hex.

Returns:

Hex-encoded transaction.

Raises:

ValueError – If fee caps are exceeded or implicit token burns are disallowed.

async get_tx_details(txid: str, raw: bool = False) dict[str, str][source]

Poll for transaction details until available or timeout.

Parameters:
  • txid – Transaction ID to fetch.

  • raw – If True, return only hex (no decoded details).

Returns:

…} when raw=True or {‘txid’: …, ‘hex’: …}.

Return type:

A dict containing either {‘hex’

Raises:

Exception – If details cannot be retrieved in time.

async send(raw: bool = False) dict[str, str][source]

Build and broadcast the transaction, retrying for details.

Parameters:

raw – If True, return only the raw hex when details are fetched.

Returns:

…} when raw=True or {‘txid’: …, ‘hex’: …}.

Return type:

A dict containing either {‘hex’

Raises:

Exception – If broadcasting fails.

set_locktime(locktime: int) TransactionBuilder[source]

Set the transaction locktime.

Parameters:

locktime – Block height or timestamp (per network rules).

Returns:

This builder (for chaining).

class Utxo(txid: str, vout: int, satoshis: int, token: TokenDetails | None = None)[source]

Bases: object

Spendable output reference with optional CashToken details.

classmethod from_unspent(unspent: Unspent) Utxo[source]

Convert a bitcash Unspent to a Utxo, mapping CashToken/NFT details.

Parameters:

unspent – bitcash Unspent instance.

Returns:

Converted UTXO.

Return type:

Utxo

Subpackages

Submodules