UNPKG

tiny-crypto-suite

Version:

Tiny tools, big crypto — seamless encryption and certificate handling for modern web and Node apps.

943 lines 42.5 kB
export default TinyChainInstance; /** * A mapping of addresses to their balances. * * Each key in this object represents an address (usually a string), * and the corresponding value is a `bigint` representing the starting balance * for that address in the blockchain. */ export type Balances = { [x: string]: bigint; }; /** * Represents the configuration for gas usage and fee settings in a blockchain block. * This config is used to define the gas-related parameters when creating or processing a block. * These values are essential for controlling the transaction cost and prioritization of block inclusion. */ export type GasConfig = { /** * - The maximum allowed gas usage for the block (defaults to 50,000). */ gasLimit?: bigint | undefined; /** * - The maximum fee per gas unit for the block (defaults to 200). */ maxFeePerGas?: bigint | undefined; /** * - The priority fee per gas unit (defaults to the default value). */ maxPriorityFeePerGas?: bigint | undefined; }; /** * Represents the content payload to be inserted into a blockchain block. * This object contains the transaction data and its corresponding cryptographic signature. */ export type BlockContent = { /** * - The transaction data that describes the operation or transfer. */ data: import("./TinyChainBlock.mjs").TransactionData; /** * - A cryptographic signature verifying the authenticity of the transaction. */ sig: Buffer | string; }; /** * A mapping of addresses to their balances. * * Each key in this object represents an address (usually a string), * and the corresponding value is a `bigint` representing the starting balance * for that address in the blockchain. * * @example * { * alice: 1000000000n, * bob: 1000000000n, * charlie: 1000000000n, * adminUser: 1000000000n * } * * @typedef {Object.<string, bigint>} Balances */ /** * Represents the configuration for gas usage and fee settings in a blockchain block. * This config is used to define the gas-related parameters when creating or processing a block. * These values are essential for controlling the transaction cost and prioritization of block inclusion. * * @typedef {Object} GasConfig * @property {bigint} [gasLimit=50000n] - The maximum allowed gas usage for the block (defaults to 50,000). * @property {bigint} [maxFeePerGas=200n] - The maximum fee per gas unit for the block (defaults to 200). * @property {bigint} [maxPriorityFeePerGas=this.getDefaultPriorityFee()] - The priority fee per gas unit (defaults to the default value). */ /** * Represents the content payload to be inserted into a blockchain block. * This object contains the transaction data and its corresponding cryptographic signature. * * @typedef {Object} BlockContent * @property {TransactionData} data - The transaction data that describes the operation or transfer. * @property {Buffer|string} sig - A cryptographic signature verifying the authenticity of the transaction. */ /** * Represents a complete blockchain instance, managing block creation, mining, * validation, and balance tracking in optional currency and payload modes. * * This class handles a dynamic and extensible blockchain environment with gas fee mechanics, * custom payloads, transfer restrictions, admin controls, halving logic, and export/import capabilities. * * @class * @beta */ declare class TinyChainInstance { /** * Constructs a new blockchain instance with optional configuration parameters. * * This constructor initializes core parameters of the blockchain, including gas costs, * difficulty, reward system, and modes (currency/payload). It also sets up the initial * balances and admin list. If `currencyMode` is enabled, initial balances will be * registered immediately. * * @param {Object} [options] - Configuration options for the blockchain instance. * @param {TinySecp256k1} [options.signer] - Signer instance for cryptographic operations. * @param {string|number|bigint} [options.chainId=0] - The chain ID. * @param {string|number|bigint} [options.transferGas=15000] - Fixed gas cost per transfer operation (symbolic). * @param {string|number|bigint} [options.baseFeePerGas=21000] - Base gas fee per unit (in gwei). * @param {string|number|bigint} [options.priorityFeeDefault=2] - Default priority tip per gas unit (in gwei). * @param {string|number|bigint} [options.diff=1] - Difficulty for proof-of-work or validation cost. * @param {boolean} [options.payloadString=true] - If true, treats payloads as strings. * @param {boolean} [options.currencyMode=false] - Enables balance tracking and gas economics. * @param {boolean} [options.payloadMode=false] - Enables payload execution mode for blocks. * @param {string|number|bigint} [options.initialReward=15000000000000000000n] - Reward for the genesis block or first mining. * @param {string|number|bigint} [options.halvingInterval=100] - Block interval for reward halving logic. * @param {string|number|bigint} [options.lastBlockReward=1000] - Reward for the last mined block. * @param {Balances} [options.initialBalances={}] - Optional mapping of initial addresses to balances. * @param {string[]} [options.admins=[]] - List of admin public keys granted elevated permissions. * * @param {number} [options.blockContentSizeLimit=-1] - Defines the maximum size (in bytes) allowed inside a single block's content. * A value of -1 disables the limit entirely. * * @param {number} [options.blockSizeLimit=-1] - Defines the total maximum size (in bytes) for an entire block. * A value of -1 disables the limit entirely. * * @param {number} [options.payloadSizeLimit=-1] - Sets the maximum allowed size (in bytes) for a transaction payload. * A value of -1 disables the limit entirely. * * @throws {Error} Throws an error if any parameter has an invalid type or value. */ constructor({ signer, chainId, transferGas, baseFeePerGas, priorityFeeDefault, diff, payloadString, currencyMode, payloadMode, initialReward, halvingInterval, lastBlockReward, initialBalances, blockSizeLimit, blockContentSizeLimit, payloadSizeLimit, admins, }?: { signer?: TinySecp256k1 | undefined; chainId?: string | number | bigint | undefined; transferGas?: string | number | bigint | undefined; baseFeePerGas?: string | number | bigint | undefined; priorityFeeDefault?: string | number | bigint | undefined; diff?: string | number | bigint | undefined; payloadString?: boolean | undefined; currencyMode?: boolean | undefined; payloadMode?: boolean | undefined; initialReward?: string | number | bigint | undefined; halvingInterval?: string | number | bigint | undefined; lastBlockReward?: string | number | bigint | undefined; initialBalances?: { [x: string]: bigint; } | undefined; admins?: string[] | undefined; blockContentSizeLimit?: number | undefined; blockSizeLimit?: number | undefined; payloadSizeLimit?: number | undefined; }); /** * Provides access to a secure internal EventEmitter for subclass use only. * * This method exposes a dedicated EventEmitter instance intended specifically for subclasses * that extend the main class. It prevents subclasses from accidentally or intentionally using * the primary class's public event system (`emit`), which could lead to unpredictable behavior * or interference in the base class's event flow. * * For security and consistency, this method is designed to be accessed only once. * Multiple accesses are blocked to avoid leaks or misuse of the internal event bus. * * @returns {EventEmitter} A special internal EventEmitter instance for subclass use. * @throws {Error} If the method is called more than once. */ getSysEvents(): EventEmitter; /** * @typedef {(...args: any[]) => void} ListenerCallback * A generic callback function used for event listeners. */ /** * Sets the maximum number of listeners for the internal event emitter. * * @param {number} max - The maximum number of listeners allowed. */ setMaxListeners(max: number): void; /** * Emits an event with optional arguments. * @param {string | symbol} event - The name of the event to emit. * @param {...any} args - Arguments passed to event listeners. * @returns {boolean} `true` if the event had listeners, `false` otherwise. */ emit(event: string | symbol, ...args: any[]): boolean; /** * Registers a listener for the specified event. * @param {string | symbol} event - The name of the event to listen for. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ on(event: string | symbol, listener: (...args: any[]) => void): this; /** * Registers a one-time listener for the specified event. * @param {string | symbol} event - The name of the event to listen for once. * @param {ListenerCallback} listener - The callback function to invoke. * @returns {this} The current class instance (for chaining). */ once(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes a listener from the specified event. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ off(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `on`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The callback to register. * @returns {this} The current class instance (for chaining). */ addListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Alias for `off`. * @param {string | symbol} event - The name of the event. * @param {ListenerCallback} listener - The listener to remove. * @returns {this} The current class instance (for chaining). */ removeListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * Removes all listeners for a specific event, or all events if no event is specified. * @param {string | symbol} [event] - The name of the event. If omitted, all listeners from all events will be removed. * @returns {this} The current class instance (for chaining). */ removeAllListeners(event?: string | symbol): this; /** * Returns the number of times the given `listener` is registered for the specified `event`. * If no `listener` is passed, returns how many listeners are registered for the `event`. * @param {string | symbol} eventName - The name of the event. * @param {Function} [listener] - Optional listener function to count. * @returns {number} Number of matching listeners. */ listenerCount(eventName: string | symbol, listener?: Function): number; /** * Adds a listener function to the **beginning** of the listeners array for the specified event. * The listener is called every time the event is emitted. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Adds a **one-time** listener function to the **beginning** of the listeners array. * The next time the event is triggered, this listener is removed and then invoked. * @param {string | symbol} eventName - The event name. * @param {ListenerCallback} listener - The callback function. * @returns {this} The current class instance (for chaining). */ prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; /** * Returns an array of event names for which listeners are currently registered. * @returns {(string | symbol)[]} Array of event names. */ eventNames(): (string | symbol)[]; /** * Gets the current maximum number of listeners allowed for any single event. * @returns {number} The max listener count. */ getMaxListeners(): number; /** * Returns a copy of the listeners array for the specified event. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of listener functions. */ listeners(eventName: string | symbol): Function[]; /** * Returns a copy of the internal listeners array for the specified event, * including wrapper functions like those used by `.once()`. * @param {string | symbol} eventName - The event name. * @returns {Function[]} An array of raw listener functions. */ rawListeners(eventName: string | symbol): Function[]; /** * Add a new value type and its converter function. * @param {string} typeName * @param {(data: any) => any} getFunction * @param {(data: any) => { __type: string, value?: any }} convertFunction */ addValueType(typeName: string, getFunction: (data: any) => any, convertFunction: (data: any) => { __type: string; value?: any; }): void; /** * Checks whether the blockchain has a valid genesis block. * * A genesis block is identified by having: * - index equal to 0n * - prevHash equal to `'0'` * - at least one data entry * - the first data entry's `address` equal to `'0'` * * @returns {boolean} `true` if a valid genesis block is present, otherwise `false`. */ hasGenesisBlock(): boolean; /** * The tiny blockchain. * * @type {TinyChainBlock[]} */ chain: TinyChainBlock[]; /** * The initial balances of accounts, only used if `currencyMode` is enabled. * * @type {Balances} */ initialBalances: Balances; /** * A set of administrator public keys with elevated privileges. * * @type {Set<string>} */ admins: Set<string>; /** * Enables or disables currency mode, where balances are tracked. * * @type {boolean} */ currencyMode: boolean; /** * Enables or disables payload mode, which allows block data to carry payloads. * * @type {boolean} */ payloadMode: boolean; /** * The symbolic gas cost applied per transfer operation. * * @type {bigint} */ transferGas: bigint; /** * The chain id applied per transfer operation. * * @type {bigint} */ chainId: bigint; /** * The base fee per unit of gas, similar to Ethereum's `baseFeePerGas`. * * @type {bigint} */ baseFeePerGas: bigint; /** * The default priority fee (tip) per gas unit offered by transactions. * * @type {bigint} */ priorityFeeDefault: bigint; /** * The mining difficulty, used to simulate block validation complexity. * * @type {bigint} */ diff: bigint; /** * The initial block reward. * * @type {bigint} */ initialReward: bigint; /** * The number of blocks after which the mining reward is halved. * * @type {bigint} */ halvingInterval: bigint; /** * The reward of the last mined block, used for tracking reward evolution. * * @type {bigint} */ lastBlockReward: bigint; /** * The `balances` object, where the key is the address (string) * and the value is the balance (bigint) of that address. * * @type {Balances} */ balances: Balances; /** * Sets the initial balances for the system. * * This method updates the `initialBalances` with a new set of address-balance pairs. * It validates the input to ensure that each address is a valid string and each balance is a positive `bigint`. * * @emits InitialBalancesUpdated - Emitted when the initial balances are updated. * * @param {Balances} initialBalances - An object mapping addresses to their corresponding balances. * @throws {Error} Throws an error if any address is invalid or any balance is not a positive `bigint`. * * @returns {void} */ setInitialBalances(initialBalances: Balances): void; /** * Gets the current initial balances configured in the system. * * This method returns the mapping of addresses to their initial balances as last set * by `setInitialBalances`. It ensures the returned data is a valid object. * * @returns {Balances} An object mapping addresses to their corresponding initial balances. * @throws {Error} Throws an error if the internal initialBalances is not a valid object. */ getInitialBalances(): Balances; /** * Asynchronously initializes the blockchain instance by creating the genesis block. * * This method wraps the internal initialization logic in a queue to ensure * exclusive access during the setup phase. It emits an `Initialized` event * once the genesis block has been created and added to the chain. * * @param {TinySecp256k1} [signer=this.#signer] - The address that is executing the block, typically the transaction sender. * * @returns {Promise<void>} A promise that resolves once initialization is complete. * * @emits Initialized - When the genesis block is successfully created and added. */ init(signer?: TinySecp256k1): Promise<void>; /** * Simulates gas estimation for an Ethereum-like transaction. * Considers base cost, data size, and per-transfer cost. * @param {Transaction[]|NewTransaction[]} transfers - List of transfers (e.g., token or balance movements). * @param {any} payload - Data to be included in the transaction (e.g., contract call). * @returns {bigint} */ estimateGasUsed(transfers: import("./TinyChainBlock.mjs").Transaction[] | import("./TinyChainBlock.mjs").NewTransaction[], payload: any): bigint; /** * Validates the blockchain from a starting to an ending index. * * It checks whether each block has a valid hash and that each block correctly references the previous one. * Skips the genesis block by default and starts from index 1 unless a different start is provided. * * @param {number} [startIndex=0] - The starting index to validate from (inclusive). * @param {number|null} [endIndex=null] - The ending index to validate up to (inclusive). Defaults to the last block. * @returns {boolean|null} Returns `true` if the chain is valid, `false` or `null` otherwise. */ isValid(startIndex?: number, endIndex?: number | null): boolean | null; /** * Checks if a new block is valid in relation to the latest block in the chain. * * This is typically used before appending a new block to ensure integrity. * * @param {TinyChainBlock} newBlock - The new block to validate. * @param {TinyChainBlock} [prevBlock=this.getLatestBlock()] - The prev block to validate. * @returns {boolean|null} Returns `true` if the new block is valid, otherwise `false` or `null`. */ isValidNewBlock(newBlock: TinyChainBlock, prevBlock?: TinyChainBlock): boolean | null; /** * Checks whether the new block has a valid previous hash. * * This ensures the block references a previous block and is not the genesis block. * * @param {TinyChainBlock} newBlock - The block to check. * @returns {boolean} Returns `true` if the previous hash is valid, otherwise `false`. */ existsPrevBlock(newBlock: TinyChainBlock): boolean; /** * Calculates the current block reward based on the chain height and halving intervals. * * The reward starts at `initialReward` and is halved every `halvingInterval` blocks. * If the chain height exceeds the reward threshold, the reward becomes zero. * * @returns {bigint} The current block reward in the smallest unit of currency (e.g., wei, satoshis). * Returns `0n` if the reward has been exhausted. */ getCurrentReward(): bigint; /** @type {Object<string, string>} */ invalidAddress: { [x: string]: string; }; /** * Validates the transaction content before inclusion in a block. * This method checks payload format, transfer structure, gas-related constraints, * and address validity. Throws detailed errors if any validation fails. * * @param {Object} [options={}] - Content data to be validated. * @param {string} [options.payload] - Raw payload data in string format. Required. * @param {Transaction[]|NewTransaction[]} [options.transfers] - List of transfers to be validated. Must be an array. * @param {bigint} [options.gasLimit] - Maximum allowed gas usage for the transaction. * @param {bigint} [options.maxFeePerGas] - The maximum total fee per unit of gas the sender is willing to pay. * @param {bigint} [options.maxPriorityFeePerGas] - The tip paid to miners per unit of gas. * @param {string} [options.address] - Sender address of the transaction. * @param {string} [options.addressType] - Type of address (e.g., 'user', 'contract'). Must be a non-empty string. * * @throws {Error} If payload is not a string when required. * @throws {Error} If transfers is not an array. * @throws {Error} If any gas parameter is not a BigInt. * @throws {Error} If address is not a string. * @throws {Error} If addressType is invalid. * @throws {Error} If gas used exceeds the provided gas limit. * @throws {Error} If block content size exceeds the defined block content size limit. * @throws {Error} If payload size exceeds the defined payload size limit. * * @returns {bigint} Returns the estimated gas used for the transaction. */ validateContent({ payload, transfers, gasLimit, maxFeePerGas, maxPriorityFeePerGas, address, addressType, }?: { payload?: string | undefined; transfers?: import("./TinyChainBlock.mjs").NewTransaction[] | import("./TinyChainBlock.mjs").Transaction[] | undefined; gasLimit?: bigint | undefined; maxFeePerGas?: bigint | undefined; maxPriorityFeePerGas?: bigint | undefined; address?: string | undefined; addressType?: string | undefined; }): bigint; /** * Creates a new block content for the blockchain with the provided transaction data and gas options. * * The method will validate the address, estimate the gas used for the transactions, and ensure that the gas * limit is not exceeded before creating the block. It also includes reward information if `currencyMode` is enabled. * * @param {Object} [options={}] - Block options. * @param {TinySecp256k1} [options.signer=this.#signer] - The address that is executing the block, typically the transaction sender. * @param {string} [options.payload=''] - The data to be included in the block's payload. Default is an empty string. * @param {Array<Transaction>} [options.transfers=[]] - The list of transfers (transactions) to be included in the block. * @param {GasConfig} [options.gasOptions={}] - Optional gas-related configuration. * * @return {BlockContent} * @throws {Error} Throws an error if the `execAddress` is invalid or if the gas limit is exceeded. */ createBlockContent({ signer, payload, transfers, gasOptions, }?: { signer?: TinySecp256k1 | undefined; payload?: string | undefined; transfers?: import("./TinyChainBlock.mjs").Transaction[] | undefined; gasOptions?: GasConfig | undefined; }): BlockContent; /** * Creates a new blockchain block using the provided signed content payloads. * * This method aggregates multiple `BlockContent` entries—each containing transaction data and a corresponding signature—into a single block. * It includes optional reward data when the chain is operating in `currencyMode`, and computes the current difficulty setting (`diff`) at creation time. * * The block is finalized by calling an internal method that handles structural assembly and final consistency. * * @param {BlockContent[]} content - An array of signed block content objects, each containing transaction data and its signature. * @param {TinySecp256k1} [signer=this.#signer] - The address that is executing the block, typically the transaction sender. * @returns {TinyChainBlock} The newly created block instance with all aggregated data, ready to be appended to the chain. * @throws {Error} */ createBlock(content: BlockContent[], signer?: TinySecp256k1): TinyChainBlock; /** * Mines a new block and adds it to the blockchain after validating and updating balances. * * This method will: * - Validate the block by checking its correctness using the `isValidNewBlock()` method. * - Update balances if `currencyMode` or `payloadMode` is enabled. * - Add the mined block to the blockchain and emit an event for the new block. * * @param {string|null} minerAddress - The address of the miner who is mining the block. * @param {TinyChainBlock} newBlock - The new block instance to be mined. * * @emits NewBlock - When the new block is added. * * @returns {Promise<TinyChainBlock>} A promise that resolves to the mined block once it has been added to the blockchain. * * @throws {Error} Throws an error if the mining process fails, or if the block is invalid. */ mineBlock(minerAddress: string | null, newBlock: TinyChainBlock): Promise<TinyChainBlock>; /** * Adds a pre-mined block to the blockchain after validating it and updating balances. * * This method will: * - Validate the block by checking its hash, linkage and structure via `isValidNewBlock()`. * - Update account balances if `currencyMode` or `payloadMode` is enabled. * - Append the validated block to the blockchain and emit the `NewBlock` event. * * @param {TinyChainBlock} minedBlock - The already mined block to be added to the blockchain. * * @emits NewBlock - When the new block is added. * * @returns {Promise<TinyChainBlock>} A promise that resolves to the block once it has been added. * * @throws {Error} Throws an error if the block is invalid or balance update fails. */ addMinedBlock(minedBlock: TinyChainBlock): Promise<TinyChainBlock>; /** * Gets the first block in the blockchain. * * This method retrieves the first block from the blockchain by calling `getChainBlock(0)`. * * @returns {TinyChainBlock} The first block in the blockchain. */ getFirstBlock(): TinyChainBlock; /** * Gets the latest block in the blockchain. * * This method retrieves the most recent block added to the blockchain by calling `getChainBlock(chain.length - 1)`. * * @returns {TinyChainBlock} The latest block in the blockchain. */ getLatestBlock(): TinyChainBlock; /** * Checks the latest block in the blockchain. * * This method checks existence the most recent block added to the blockchain. * * @returns {boolean} The latest block in the blockchain exists. */ existsLatestBlock(): boolean; /** * Initializes the `balances` object and emits events related to balance setup. * * This method resets the internal `balances` object to an empty state and emits * a `BalancesInitialized` event. If `currencyMode` is active, it will populate * the `balances` from the `initialBalances` mapping, converting all balances to BigInt, * and emit a `BalanceStarted` event for each initialized address. * * @emits BalancesInitialized - When the balances object is reset. * @emits BalanceStarted - For each address initialized when in currency mode. */ startBalances(): void; /** * Validates a list of transfers for a transaction. * Ensures that each transfer has valid 'from' and 'to' addresses, * the sender has enough balance, and non-admins can only transfer their own funds. * * @param {string} pubKey - The hex public key executing the transaction. * @param {string} addressType - The address type executing the transaction. * @param {NewTransaction[]} transfers - The list of transfers to validate. * @param {Balances} [balances] - A mapping of addresses to their balances. * @throws {Error} If the list is not an array, if any transfer is malformed, * or if the sender is unauthorized or lacks balance. */ validateTransfers(pubKey: string, addressType: string, transfers: import("./TinyChainBlock.mjs").NewTransaction[], balances?: Balances): void; /** * Updates the balances of addresses involved in the block, including gas fees and transfers. * * This method handles updating the balances for the addresses involved in the block's transactions. * It checks for sufficient balance, validates transactions, and applies the gas fees. * If the block includes a miner address, it adds the block reward and the gas collected to the miner's balance. * * @param {TinyChainBlock} block - The block whose balances need to be updated. * @param {Balances} [balances] - A mapping of addresses to their balances. * @param {boolean} [emitEvents=true] - If you need to send events. * * @emits BalanceStarted - For each address initialized when in currency mode. * @emits BalanceUpdated - For each address updated when in currency mode. * @emits Payload - For each payload executed when in payload mode. * @emits MinerBalanceUpdated - For each miner address updated when in currency mode. * * @throws {Error} Throws an error if: * - The reward is not a valid `BigInt`. * - The miner address is not a valid string or null. * - Any address in the transfers is invalid or has insufficient balance. * - The gas limit is exceeded. * - A transfer is made by a non-admin without being their own balance. * - Any other invalid operation occurs during balance updates. * * @returns {void} This method does not return any value. */ updateBalance(block: TinyChainBlock, balances?: Balances, emitEvents?: boolean): void; /** * Retrieves a copy of all balances in the system. * * This method returns an object mapping each address to its balance. * Only works when `currencyMode` is enabled. * * @returns {Balances} An object where each key is an address and the value is a `bigint` representing its balance. * * @throws {Error} Throws if `currencyMode` is disabled . */ getBalances(): Balances; /** * Retrieves a snapshot of all balances as they were at a specific block index. * * This method reprocesses the blockchain from the genesis block up to (and including) * the specified index, recalculating all balances based on transfers and gas usage. * * Only works when `currencyMode` is enabled. Throws if the index is out of bounds. * * @param {number} [startIndex=0] - The starting index of the block range. * @param {number|null} [endIndex=null] - The ending index (inclusive); defaults to the last block. * * @returns {Balances} An object mapping each address to its `bigint` balance at the specified block. * * @throws {Error} Throws if `currencyMode` is disabled or if the index is invalid. */ getBalancesAt(startIndex?: number, endIndex?: number | null): Balances; /** * Returns the total amount of burned currency in the system. * * This value represents the sum of rewards and gas fees that were not claimed by any miner (i.e., blocks without a miner address). * * @returns {bigint} The total burned balance as a `bigint`. * * @throws {Error} Throws if `currencyMode` is disabled . */ getBurnedBalance(): bigint; /** * Returns the current balance of a specific address. * * If the address does not exist in the balance record, it returns 0n. * * @param {string} address - The address whose balance should be retrieved. * @returns {bigint} The balance of the given address, or 0n if not found. * * @throws {Error} Throws if `currencyMode` is disabled. */ getBalance(address: string): bigint; /** * Recalculates all balances based on the current blockchain state. * * This method resets the `balances` using `startBalances()` and, if either * `currencyMode` or `payloadMode` is enabled, iterates through the entire * blockchain (`this.chain`) applying `updateBalance()` to each block to * recompute the balances. Finally, it emits a `BalanceRecalculated` event * with the updated balances. * * @emits BalanceRecalculated - When the balance recalculation process is complete. */ recalculateBalances(): void; /** * Returns the current length of the chain based on the latest block index. * * @returns {bigint} The index of the latest block, representing the chain length. */ getChainLength(): bigint; /** * Checks if a block with the specified chain index exists. * * This method searches the chain for a block whose internal index (retrieved via `.getIndex()`) * matches the given `bigint` value. * * @param {bigint} index - The unique internal index of the block to check. * @returns {boolean} Returns true if a block with that index exists, otherwise false. */ chainBlockIndexExists(index: bigint): boolean; /** * Retrieves a block from the chain at a specific block index. * * @param {bigint} index - The index of the block to retrieve. * @param {string} [hash] - The index of the block to retrieve. * @returns {TinyChainBlock} The block instance at the specified index. * @throws {Error} If the block at the given block index does not exist. */ getChainBlockByIndex(index: bigint, hash?: string): TinyChainBlock; /** * Checks if a block exists at the specified array index. * * This method verifies whether there is a chain block at the given zero-based position in the array. * * @param {number} index - The array index of the block to check. * @returns {boolean} Returns true if a block exists at that index, otherwise false. */ chainBlockExists(index: number): boolean; /** * Retrieves a block from the chain at a specific array index. * * @param {number} index - The index of the block to retrieve. * @returns {TinyChainBlock} The block instance at the specified index. * @throws {Error} If the block at the given array index does not exist. */ getChainBlock(index: number): TinyChainBlock; /** * Retrieves a specific transaction from a block at a given index. * * @param {number} index - The index of the block. * @param {string} tx - The index of the transaction within the block. * @returns {TransactionData} The transaction object. */ getChainBlockTx(index: number, tx: string): import("./TinyChainBlock.mjs").TransactionData; /** * Returns all the data from the entire blockchain. * * Each block's raw data is returned as structured by its `get()` method. * * @returns {GetTransactionData[]} An array containing all blocks' data. */ getAllChainData(): import("./TinyChainBlock.mjs").GetTransactionData[]; /** * Clears the entire blockchain. * * This method removes all blocks from the chain, effectively resetting the blockchain to an empty state. * It also resets any other associated data, like balances and burned balances. * * @emits ChainCleared - Emitted when the blockchain is cleared. * * @returns {void} */ cleanChain(): void; /** * Ignores a specific chain block by its index, preventing it from affecting calculations. * * @param {bigint} index - The index of the chain block to ignore. * @param {string} hash - The hash of the chain block to ignore. * @throws {Error} If the block does not exist. */ ignoreChainBlock(index: bigint, hash: string): void; /** * Reverts the ignore status of a specific chain block by its index. * * @param {bigint} index - The index of the chain block to unignore. * @param {string} hash - The hash of the chain block to unignore. * @returns {boolean} Returns true if the block was previously ignored and has now been unignored. */ unignoreChainBlock(index: bigint, hash: string): boolean; /** * Checks if a chain block is currently being ignored. * * @param {bigint} index - The index of the chain block to check. * @param {string} hash - The hash of the chain block to check. * @returns {boolean} Returns true if the block is ignored. */ isChainBlockIgnored(index: bigint, hash: string): boolean; /** * Checks if a chain block hash is currently being ignored. * * @param {string} hash - The hash of the chain block to check. * @returns {boolean} Returns true if the block is ignored. */ isChainBlockHashIgnored(hash: string): boolean; /** * Returns a shallow clone of the set containing all ignored chain block indices. * * @returns {Set<string>} A new Set instance with all currently ignored block indices. */ getIgnoredBlocks(): Set<string>; /** * Exports a slice of the blockchain for serialization or transfer. * * This method safely extracts and serializes blocks between two indices, * excluding any blocks currently marked as ignored. * * @param {number} [startIndex=0] - The starting index of the block range (inclusive). * @param {number|null} [endIndex=null] - The ending index (inclusive); defaults to the last block. * @returns {string[]} An array of exported block data, excluding ignored blocks. * @throws {Error} If indices are out of bounds or invalid. */ exportChain(startIndex?: number, endIndex?: number | null): string[]; /** * Imports and rebuilds a blockchain from serialized block data. * * After import, balances are recalculated and the new chain is validated. * * @emits ImportChain - When the new chain is imported. * * @param {string[]} chain - The array of serialized blocks to import. * @param {Set<string>} [ignoredBlocks] - Ignored blocks list. * @throws {Error} If the imported chain is null, invalid, or corrupted. */ importChain(chain: string[], ignoredBlocks?: Set<string>): void; /** * Sets the default base fee per gas (in gwei). * @param {bigint} value */ setBaseFeePerGas(value: bigint): void; /** * Sets the default max priority fee per gas (in gwei). * @param {bigint} value */ setDefaultPriorityFee(value: bigint): void; /** * Sets the transfer gas cost per transaction. * @param {bigint} value */ setTransferGas(value: bigint): void; /** * Sets the chain difficulty. * @param {bigint} value */ setDiff(value: bigint): void; /** * Returns the base fee per gas (in gwei). * @returns {bigint} */ getBaseFeePerGas(): bigint; /** * Returns the default priority fee (in gwei). * @returns {bigint} */ getDefaultPriorityFee(): bigint; /** * Returns the current transfer gas cost per transaction. * @returns {bigint} */ getTransferGas(): bigint; /** * Returns the chain difficulty. * @returns {bigint} */ getDiff(): bigint; /** * Returns the initial reward per block. * @returns {bigint} */ getInitialReward(): bigint; /** * Returns the halving interval. * @returns {bigint} */ getHalvingInterval(): bigint; /** * Returns the last block reward index. * @returns {bigint} */ getLastBlockReward(): bigint; /** * Returns the chain ID. * @returns {bigint} */ getChainId(): bigint; /** * Returns true if the blockchain is in currency mode. * @returns {boolean} */ isCurrencyMode(): boolean; /** * Returns true if the blockchain is in payload mode. * @returns {boolean} */ isPayloadMode(): boolean; /** * Returns a list of all admin addresses. * @returns {Set<string>} */ getAdmins(): Set<string>; /** * Returns true if payloads are stored as string. * @returns {boolean} */ isPayloadString(): boolean; /** * Gets the maximum allowed size (in bytes) in a block's content. * @returns {number} */ getBlockContentSizeLimit(): number; /** * Gets the maximum payload size allowed per transaction (in bytes). * @returns {number} */ getPayloadSizeLimit(): number; /** * Gets the maximum total size allowed for a block (in bytes). * @returns {number} */ getBlockSizeLimit(): number; /** * Destroys the current instance by resetting all internal state. * * This method clears the chain data, resets all balances, * and removes all attached listeners from both internal and system event emitters. * It should be called when the instance is no longer needed to free up memory and avoid leaks. */ destroy(): void; #private; } import { Buffer } from 'buffer'; import { EventEmitter } from 'events'; import TinyChainBlock from './TinyChainBlock.mjs'; import TinySecp256k1 from './Secp256k1/index.mjs'; //# sourceMappingURL=TinyChainInstance.d.mts.map