nectar.blockchain module
- class nectar.blockchain.Blockchain(blockchain_instance: Any = None, mode: str = 'irreversible', max_block_wait_repetition: int | None = None, data_refresh_time_seconds: int = 900, **kwargs)
Bases:
objectThis class allows to access the blockchain and read data from it
- Parameters:
blockchain_instance (Blockchain) – Blockchain instance
mode (str) – (default) Irreversible block (
irreversible) or actual head block (head)max_block_wait_repetition (int) – maximum wait repetition for next block where each repetition is block_interval long (default is 3)
This class let’s you deal with blockchain related data and methods. Read blockchain related data:
Read current block and blockchain info
print(chain.get_current_block()) print(chain.blockchain.info())
Monitor for new blocks. When
stopis not set, monitoring will never stop.blocks = [] current_num = chain.get_current_block_num() for block in chain.blocks(start=current_num - 99, stop=current_num): blocks.append(block) len(blocks)
100
or each operation individually:
ops = [] current_num = chain.get_current_block_num() for operation in chain.ops(start=current_num - 99, stop=current_num): ops.append(operation)
- awaitTxConfirmation(transaction: Dict[str, Any], limit: int = 10) Dict[str, Any] | None
Returns the transaction as seen by the blockchain after being included into a block
- Parameters:
transaction (dict) – transaction to wait for
limit (int) – (optional) number of blocks to wait for the transaction (default: 10)
Note
If you want instant confirmation, you need to instantiate class:nectar.blockchain.Blockchain with
mode="head", otherwise, the call will wait until confirmed in an irreversible block.Note
This method returns once the blockchain has included a transaction with the same signature. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely.
- block_time(block_num: int) datetime
Returns a datetime of the block with the given block number.
- Parameters:
block_num (int) – Block number
- block_timestamp(block_num: int) int
Returns the timestamp of the block with the given block number as integer.
- Parameters:
block_num (int) – Block number
- blocks(start: int | None = None, stop: int | None = None, max_batch_size: int | None = None, threading: bool = False, thread_num: int = 8, only_ops: bool = False, only_virtual_ops: bool = False) Any
Yield Block objects from start up to stop (or the chain head).
This generator retrieves blocks from the connected blockchain instance and yields them as Block objects. It supports three retrieval modes: - Single-threaded sequential fetching (default). - Threaded parallel fetching across multiple blockchain instances when threading=True. - Batched RPC calls for appbase-compatible nodes when max_batch_size is set (cannot be combined with threading).
- Parameters:
start (int, optional): First block number to fetch. If omitted, defaults to the current block. stop (int, optional): Last block number to fetch. If omitted, the generator follows the chain head indefinitely. max_batch_size (int, optional): Use batched RPC calls (appbase only). Cannot be used with threading. threading (bool): If True, fetch blocks in parallel using thread_num workers. thread_num (int): Number of worker threads to use when threading=True. only_ops (bool): If True, blocks will contain only regular operations (no block metadata).
Mutually exclusive with only_virtual_ops=True.
only_virtual_ops (bool): If True, yield only virtual operations.
- Yields:
Block: A Block object for each fetched block (may contain only ops or only virtual ops depending on flags).
- Exceptions:
OfflineHasNoRPCException: Raised if batched mode is requested while offline (no RPC available). BatchedCallsNotSupported: Raised if the node does not support batched calls when max_batch_size is used.
- Notes:
For instant (non-irreversible) confirmations, initialize the Blockchain with mode=”head”; otherwise this method will wait for irreversible blocks.
max_batch_size requires appbase-compatible RPC; threaded mode creates additional blockchain instances for parallel RPC calls.
- find_change_recovery_account_requests(accounts: str | List[str]) List[Dict[str, Any]] | None
Find pending change_recovery_account requests for one or more accounts.
Accepts a single account name or a list of account names and queries the connected node for pending change_recovery_account requests. Returns the list of matching request entries, or None if the local blockchain instance is not connected or the RPC returned no data.
- Parameters:
accounts (str | list): Account name or list of account names to search for.
- Returns:
list | None: List of change_recovery_account request objects for the given account(s), or None if offline or no requests were returned.
- find_rc_accounts(name: str | List[str]) Dict[str, Any] | List[Dict[str, Any]] | None
Return resource credit (RC) parameters for one or more accounts.
If given a single account name (str), returns the RC parameters for that account as a dict. If given a list of account names, returns a list of RC-parameter dicts in the same order. Returns None when the underlying blockchain RPC is not connected or if the RPC returns no data.
- Parameters:
name (str | list): An account name or a list of account names.
- Returns:
dict | list | None: RC parameters for the account(s), or None if offline or no result.
- get_account_count() int
Returns the number of accounts
- get_account_reputations(start: str = '', stop: str = '', steps: int | float = 1000.0, limit: int = -1, **kwargs: Any) Any
Yields account reputation between start and stop.
- Parameters:
start (str) – Start at this account name
stop (str) – Stop at this account name
steps (int) – Obtain
stepsret with a single call from RPC
- get_all_accounts(start: str = '', stop: str = '', steps: int | float = 1000.0, limit: int = -1, **kwargs: Any) Any
Yields account names between start and stop.
- Parameters:
start (str) – Start at this account name
stop (str) – Stop at this account name
steps (int) – Obtain
stepsret with a single call from RPC
- get_current_block(only_ops: bool = False, only_virtual_ops: bool = False) Block
This call returns the current block
- Parameters:
only_ops (bool) – Returns block with operations only, when set to True (default: False)
only_virtual_ops (bool) – Includes only virtual operations (default: False)
Note
The block number returned depends on the
modeused when instantiating from this class.
- get_current_block_num() int
This call returns the current block number
Note
The block number returned depends on the
modeused when instantiating from this class.
- get_estimated_block_num(date: datetime | date | time | None, estimateForwards: bool = False, accurate: bool = True) int
This call estimates the block number based on a given date
- Parameters:
date (datetime) – block time for which a block number is estimated
Note
The block number returned depends on the
modeused when instantiating from this class.>>> from nectar.blockchain import Blockchain >>> from datetime import datetime >>> blockchain = Blockchain() >>> block_num = blockchain.get_estimated_block_num(datetime(2019, 6, 18, 5 ,8, 27)) >>> block_num == 33898182 True
- get_similar_account_names(name: str, limit: int = 5) List[str] | None
Return a list of accounts with names similar to the given name.
Performs an RPC call to fetch accounts starting at name. If the underlying node uses the appbase API this returns the raw accounts list from the list_accounts response (list of account objects/dicts). If using the legacy API this returns the list of account names returned by lookup_accounts. If the local blockchain connection is offline, returns None.
- Parameters:
name (str): Prefix or starting account name to search for. limit (int): Maximum number of accounts to return.
- Returns:
list or None: A list of account names or account objects (depending on RPC), or None if offline.
- get_transaction(transaction_id: str) Dict[str, Any]
Returns a transaction from the blockchain
- Parameters:
transaction_id (str) – transaction_id
- get_transaction_hex(transaction: Dict[str, Any]) str
Returns a hexdump of the serialized binary form of a transaction.
- Parameters:
transaction (dict) – transaction
- static hash_op(event: Dict[str, Any] | List[Any]) str
This method generates a hash of blockchain operation.
- is_irreversible_mode() bool
- is_transaction_existing(transaction_id: str) bool
Returns true, if the transaction_id is valid
- list_change_recovery_account_requests(start: str | List[str] = '', limit: int = 1000, order: str = 'by_account') List[Dict[str, Any]] | None
Return pending change_recovery_account requests from the blockchain.
If the local blockchain connection is offline, returns None.
- Parameters:
- start (str or list): Starting point for the listing.
For order=”by_account”: an account name (string).
For order=”by_effective_date”: a two-item list [effective_on, account_to_recover] e.g. [‘2018-12-18T01:46:24’, ‘bott’].
limit (int): Maximum number of results to return (default and max: 1000). order (str): Index to iterate: “by_account” (default) or “by_effective_date”.
- Returns:
list or None: A list of change_recovery_account request entries, or None if offline.
- ops(start: int | None = None, stop: int | None = None, only_virtual_ops: bool = False, **kwargs: Any) None
Blockchain.ops() is deprecated. Please use Blockchain.stream() instead.
- ops_statistics(start: int, stop: int | None = None, add_to_ops_stat: Dict[str, int] | None = None, with_virtual_ops: bool = True, verbose: bool = False) Dict[str, int] | None
Generates statistics for all operations (including virtual operations) starting from
start.- Parameters:
start (int) – Starting block
stop (int) – Stop at this block, if set to None, the current_block_num is taken
add_to_ops_stat (dict) – if set, the result is added to add_to_ops_stat
verbose (bool) – if True, the current block number and timestamp is printed
This call returns a dict with all possible operations and their occurrence.
- property participation_rate: float
Returns the witness participation rate in a range from 0 to 1
- stream(opNames: List[str] | None = None, raw_ops: bool = False, *args: Any, **kwargs: Any) Any
Yield blockchain operations filtered by type, normalizing several node event formats into a consistent output.
- Parameters:
opNames (list): Operation type names to filter for (e.g., [‘transfer’, ‘comment’]). If empty, all operations are yielded. raw_ops (bool): If True, yield raw operation tuples with minimal metadata; if False (default), yield a flattened dict with operation fields and metadata. *args, **kwargs: Passed through to self.blocks(…) (e.g., start, stop, max_batch_size, threading, thread_num, only_ops, only_virtual_ops).
- Yields:
- dict: When raw_ops is False, yields a dictionary with at least:
‘type’: operation name
operation fields (e.g., ‘from’, ‘to’, ‘amount’, …)
‘_id’: deterministic operation hash
‘timestamp’: block timestamp
‘block_num’: block number
‘trx_num’: transaction index within the block
‘trx_id’: transaction id
- dict: When raw_ops is True, yields a compact dictionary:
‘block_num’: block number
‘trx_num’: transaction index
‘op’: [op_type, op_payload]
‘timestamp’: block timestamp
- Notes:
The method accepts the same control parameters as blocks(…) via kwargs. The block stream determines timestamps and block-related metadata.
Operation events from different node formats (lists, legacy dicts, appbase-style dicts) are normalized by this method before yielding.
- wait_for_and_get_block(block_number: int, blocks_waiting_for: int | None = None, only_ops: bool = False, only_virtual_ops: bool = False, block_number_check_cnt: int = -1, last_current_block_num: int | None = None) Block | None
Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure.
- Parameters:
block_number (int) – desired block number
blocks_waiting_for (int) – difference between block_number and current head and defines how many blocks we are willing to wait, positive int (default: None)
only_ops (bool) – Returns blocks with operations only, when set to True (default: False)
only_virtual_ops (bool) – Includes only virtual operations (default: False)
block_number_check_cnt (int) – limit the number of retries when greater than -1
last_current_block_num (int) – can be used to reduce the number of get_current_block_num() api calls
- class nectar.blockchain.Pool(thread_count: int, batch_mode: bool = True, exception_handler: Callable = <function default_handler>)
Bases:
objectPool of threads consuming tasks from a queue
- abort(block: bool = False) None
Tell each worker that its done working
- alive() bool
Returns True if any threads are currently running
- done() bool
Returns True if not tasks are left to be completed
- enqueue(func: Callable, *args: Any, **kargs: Any) None
Add a task to the queue
- idle() bool
Returns True if all threads are waiting for work
- join() None
Wait for completion of all the tasks in the queue
- results(sleep_time: int | float = 0) List[Any]
Get the set of results that have been processed, repeatedly call until done
- run(block: bool = False) bool
Start the threads, or restart them if you’ve aborted
- class nectar.blockchain.Worker(name: str, queue: Queue, results: Queue, abort: Event, idle: Event, exception_handler: Callable)
Bases:
ThreadThread executing tasks from a given tasks queue
- run() None
Thread work loop calling the function with the params
- nectar.blockchain.default_handler(name: str, exception: Exception, *args: Any, **kwargs: Any) None