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:
objectHigh-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.
- class ElectrumNetworkProvider(network: Network = Network.MAINNET)[source]
Bases:
NetworkProviderNetworkProvider 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:
RequestFailed – If the provider returns an error.
UnexpectedResponse – If the provider returns a malformed response.
- 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:
RequestFailed – If the provider returns an error.
UnexpectedResponse – If the provider returns a malformed response.
- async get_utxos(address: str) list[Utxo][source]
Fetch UTXOs for a CashAddress.
- Parameters:
address – CashAddress string.
- Returns:
List of Utxo objects.
- Raises:
RequestFailed – If the provider returns an error.
UnexpectedResponse – If the provider returns a malformed response.
- 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:
FlagSupported 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:
StrEnumSupported locking bytecode templates (address types).
- P2PK = 'p2pk'
- P2PKH = 'p2pkh'
- P2SH20 = 'p2sh20'
- P2SH32 = 'p2sh32'
- class Network(*values)[source]
Bases:
StrEnumSupported Bitcoin Cash networks (network and address prefixes).
- CHIPNET = 'chipnet'
- MAINNET = 'mainnet'
- MOCKNET = 'mocknet'
- REGTEST = 'regtest'
- TESTNET3 = 'testnet3'
- TESTNET4 = 'testnet4'
- class NetworkProvider[source]
Bases:
ABCAbstract 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:
RequestFailed – If the provider returns an error.
UnexpectedResponse – If the provider returns a malformed response.
- 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:
RequestFailed – If the provider returns an error.
UnexpectedResponse – If the provider returns a malformed response.
- 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.
- 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:
StrEnumNFT CashTokens capabilities.
- MINTING = 'minting'
- MUTABLE = 'mutable'
- NONE = 'none'
- class Output(to: bytes | str, amount: int, token: TokenDetails | None = None)[source]
Bases:
objectTransaction output description.
- to
Recipient locking bytecode (bytes) or CashAddress (str).
- amount
BCH amount in satoshis.
- token
Optional CashToken details.
- class SignatureAlgorithm(*values)[source]
Bases:
FlagSupported 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:
objectEncapsulates 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_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
- class TokenDetails(amount: int | None, category: str, nft: Nft | None)[source]
Bases:
objectCashToken details: fungible amount and optional NFT.
- class Nft(capability: NftCapability, commitment: str | None)[source]
Bases:
objectNested 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:
objectBuild, 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:
OutputAddressInvalid – If a provided address cannot be parsed.
OutputSatoshisNonPositiveError – If amount <= 0.
OutputSatoshisTooSmallError – If amount is below dust minimum.
TokensToNonTokenAddressError – If sending tokens to a non-token address.
OutputTokenAmountTooSmallError – If token amount is negative.
- 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:
objectSpendable output reference with optional CashToken details.
Subpackages
- cashscript_py.helpers package
- Submodules
- cashscript_py.helpers.address module
- cashscript_py.helpers.argument_encoding module
- cashscript_py.helpers.bch_opcodes module
- cashscript_py.helpers.bech32 module
- cashscript_py.helpers.cashaddress module
LockingBytecodeTypeaddress_contents_to_locking_bytecode()address_string_to_locking_bytecode()cash_address_checksum_to_uint5_array()cash_address_polynomial_modulo()decode_cash_address_format()encode_cash_address()encode_cash_address_format()encode_cash_address_version_byte()encode_locking_bytecode_p2pk()encode_locking_bytecode_p2pkh()encode_locking_bytecode_p2sh20()encode_locking_bytecode_p2sh32()get_network_prefix()is_valid_bit_length()locking_bytecode_to_address_contents()locking_bytecode_to_cash_address()mask_cash_address_prefix()payload_to_cash_address()split_version_byte()
- cashscript_py.helpers.cashtoken module
- cashscript_py.helpers.crypto module
- cashscript_py.helpers.data_encoding module
- cashscript_py.helpers.schnorr module
- cashscript_py.helpers.script module
- cashscript_py.helpers.transaction module
- Submodules
- cashscript_py.network package
Submodules
- cashscript_py.contract module
- cashscript_py.interfaces module
- cashscript_py.signature_template module
- cashscript_py.transaction_builder module