import { ForgeConfig } from "./ForgeConfig.js"; import { ForgeState } from "./ForgeState.js"; import { Token } from "@tat-protocol/token"; import { NWPCServer, NWPCRequest, NWPCContext, NWPCResponseObject, NWPCResponse } from "@tat-protocol/nwpc"; import { StorageInterface, SpentSetStore, SupplyStore, type StoredTx, type TxOutput, type TxRecord, type CommitTransferResult, type CommitMintResult } from "@tat-protocol/storage"; import { type TxLedger } from "./BlobLedger.js"; /** * Transaction data structure */ interface TransactionData { ins?: string[]; outs?: string[]; witnessData?: string[]; [key: string]: unknown; } /** * Base class for implementing a token forge (issuer). * * ForgeBase provides the core infrastructure for creating, validating, and managing * tokens in the TAT Protocol. Subclasses must implement the abstract methods for * minting fungible tokens and TATs, as well as handling transfers and burns. * * The forge maintains state including spent tokens, authorized forgers, and supply limits. * It validates all token transactions and publishes spent token notifications. * * @example * ```typescript * class MyForge extends ForgeBase { * async forgeToken(req, context, res) { * // Implementation for minting fungible tokens * } * async transferToken(req, context, res) { * // Implementation for transferring tokens * } * async burnToken(req, context, res) { * // Implementation for burning tokens * } * } * ``` */ export declare abstract class ForgeBase extends NWPCServer { config: ForgeConfig; state: ForgeState; storage: StorageInterface; owner: string; isInitialized: boolean; private spendLock; private blobLedger?; private outboxTimer?; private outboxDraining; private lastPruneAt; /** * Creates a new ForgeBase instance. * * The constructor initializes the forge with configuration, sets up storage, * and registers default handlers for forge, transfer, and burn operations. * * @param config - Configuration object containing owner, storage, keys, and supply limits * @throws {Error} If owner is not provided in config * @throws {Error} If storage is not provided in config */ constructor(config: ForgeConfig); /** * Abstract method for minting new fungible tokens. * * Implementations should validate the request, check authorization and supply limits, * create new token(s), and return them to the requester. Fungible tokens are identical * and interchangeable, each with a specific denomination/amount. * * @param req - The NWPC request containing minting parameters * @param context - The request context with sender and recipient information * @param res - Response object for sending the result * @returns Response containing the newly minted token(s) or an error */ abstract forgeToken(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; /** * Abstract method for transferring tokens between parties. * * Implementations should validate inputs, verify signatures and locks, check that * tokens haven't been spent, update the spent token registry, and create new outputs. * This is the core method for handling token transfers in the protocol. * * @param req - The NWPC request containing the transaction with inputs and outputs * @param context - The request context with sender and recipient information * @param res - Response object for sending the result * @returns Response confirming the transfer or an error */ abstract transferToken(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; /** * Abstract method for burning (destroying) tokens. * * Implementations should verify token ownership, mark the token as spent, and * optionally update supply counters. Burning is permanent and cannot be reversed. * * @param req - The NWPC request containing the token to burn * @param context - The request context with sender information * @param res - Response object for sending the result * @returns Response confirming the burn or an error */ abstract burnToken(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; setupDefaultHandlers(): void; onlyAuthorized(_req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject, next: () => Promise): Promise; onlyOwner(_req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject, next: () => Promise): Promise; /** * Initializes the forge instance. * * This method must be called after construction and before using the forge. * It loads or generates keys, initializes storage, loads saved state, and * establishes network connections. Safe to call multiple times (idempotent). * * @throws {Error} If keys cannot be initialized or storage fails * * @example * ```typescript * const forge = new MyForge(config); * await forge.initialize(); * // Forge is now ready to handle requests * ``` */ initialize(): Promise; getPublicKey(): string | undefined; sign(data: Uint8Array): Promise; verifyToken(tokenHash: string, signature: string, publicKey: string, readerPubkey?: string, timeWindow?: number, currentTime?: number): Promise; /** * Grants authorization to mint tokens to a specific public key. * * Only the forge owner can add authorized forgers. Authorized forgers can mint * new tokens within the configured supply limits. This is useful for delegating * minting authority while maintaining control over the forge. * * @param pubkey - The public key to authorize for minting * @throws {Error} If the forge is not initialized * * @example * ```typescript * await forge.addAuthorizedForger('delegatePubkey'); * // 'delegatePubkey' can now mint tokens * ``` */ addAuthorizedForger(pubkey: string): Promise; /** * Revokes minting authorization from a public key. * * Only the forge owner can remove authorized forgers. The removed forger will * no longer be able to mint new tokens, though previously minted tokens remain valid. * * @param pubkey - The public key to remove from authorized forgers * @throws {Error} If the forge is not initialized * * @example * ```typescript * await forge.removeAuthorizedForger('delegatePubkey'); * // 'delegatePubkey' can no longer mint tokens * ``` */ removeAuthorizedForger(pubkey: string): Promise; /** * Retrieves the list of public keys authorized to mint tokens. * * @returns Array of authorized forger public keys * * @example * ```typescript * const authorizedForgers = forge.getAuthorizedForgers(); * console.log('Authorized minters:', authorizedForgers); * ``` */ getAuthorizedForgers(): string[]; _saveState(): Promise; /** * Runs a spent-set-mutating operation (transfer/burn) under a per-forge lock * so that check-then-mark sequences cannot interleave across concurrent * requests. Callbacks are chained regardless of prior success/failure, and a * failing callback never poisons the lock for the next caller. */ /** * Move any spent hashes sitting in blob state into the configured store. * * A forge that has been running accumulated its spent set in the state blob. * Pointing it at a store without carrying those across would present every * previously spent token as unspent — every one of them replayable, which is * a mint of free money rather than a migration inconvenience. So this runs on * every load, is idempotent (`tryMarkSpent` on a hash already present is a * no-op returning false), and clears the blob copy only once the store has * accepted the hashes. * * No-op when no store is configured, which is what keeps existing forges on * exactly their current behaviour. */ protected importBlobSpentSet(): Promise; /** * Adopt the cap and any already-issued supply into the configured store. * * Without this an upgrading forge would start from zero issued and hand * itself a full cap's worth of fresh headroom — an over-issue by exactly the * amount already in circulation. Runs on load, and only seeds when the store * has nothing recorded, so restarts do not double-count. */ protected adoptSupplyIntoStore(): Promise; /** Supply enforcement, when configured. See ForgeConfig.supplyStore. */ protected get supply(): SupplyStore | undefined; /** * Reserve `amount` against the cap before minting. * * @returns `true` if the reservation fit, `false` if it would exceed the cap. * * Reserve BEFORE minting: if the mint then fails the forge has under-issued, * which is the safe direction. Reserving afterwards would let a token exist * that the cap never counted. */ protected reserveSupply(amount: number): Promise; /** Remaining headroom, for error messages. */ protected remainingSupply(): Promise; /** Allocate the next sequential asset id. */ protected allocateAssetId(): Promise; /** The spent set, when one is configured. See ForgeConfig.spentSetStore. */ protected get spentSet(): SpentSetStore | undefined; protected get spentKeysetId(): string; /** * Has this token hash already been spent? * * Every read of the spent set goes through here so there is exactly one place * that knows whether the store or the legacy blob is authoritative. */ protected isTokenSpent(tokenHash: string): Promise; /** * Batch form of {@link isTokenSpent}, for the verify RPC. */ protected getTokenSpentStates(tokenHashes: string[]): Promise>; /** * Record a token hash as spent. * * @returns `true` if this call marked it, `false` if it was already spent. * * With a store this is a single atomic test-and-insert that is durable before * it resolves, and it does NOT touch blob state — which is what removes the * O(N^2) write amplification, since the blob write was the quadratic term * rather than the Set insert. * * Without a store this keeps the original behaviour exactly: add to the * in-memory Set and re-serialise the whole state blob. */ protected markTokenSpent(tokenHash: string): Promise; protected runExclusive(fn: () => Promise): Promise; _loadState(): Promise; publishSpentToken(tokenHash: string): Promise; /** * Publish the public "spent" notice for a hash already recorded as spent. * Fire-and-forget: the spend is authoritative in the spent set, this only * lets other devices reconcile early. */ protected announceSpent(tokenHash: string): void; /** * Burn a token this forge issued, authorized by its lock key. * * Params: `{ token, witness }`, where `witness` is the lock key's signature * over `burnAuthDigest(tokenHash)`. The burn digest has its own domain tag, * so a transfer witness seen on the wire cannot be replayed as a burn. * Unlocked tokens cannot be burned: no key could authorize it, so anyone who * had seen the JWT could destroy it. */ handleBurn(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; handleVerify(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; /** Header version for tokens this forge mints. See ForgeConfig.tokenHashVersion. */ protected get tokenVersion(): string; /** The commit/outbox ledger: the configured one, or the state blob. */ protected get txLedger(): TxLedger; /** * Refuse configurations that cannot commit a transfer together with its * outputs, and non-durable state in production. */ protected assertLedgerConfig(): void; /** * Refuse to persist the forge's secret key into storage that stores it in * plaintext, unless `allowPlaintextSecrets` says so. */ protected assertSecretStorage(): void; /** A committed transfer or mint, with each output's delivery state. */ getTx(txId: string): Promise; /** * Commit a transfer: every input marked spent, the record and its outbox * rows written, as one unit. Nothing is sent before this resolves. */ protected commitTransfer(record: TxRecord): Promise; /** Commit a mint: supply reserved and the record written, as one unit. */ protected commitMint(record: TxRecord, amount: number): Promise; /** * The outputs `requester` may see: all of them for the key that submitted * the tx, otherwise only those addressed to the requester. `tx_id` is * derivable from input hashes, which spent notices publish, so knowing it * proves nothing. */ protected outputsVisibleTo(tx: StoredTx, requester: string): { to: string; token: string; }[]; /** * Transfer path shared by the fungible and non-fungible forges: commit, then * announce the spends, then deliver. */ protected commitAndDeliverTransfer(params: { inputHashes: string[]; /** The request's outputs, as signed; fingerprinted to tell a retry from a double-spend. */ outs: unknown[]; outputs: TxOutput[]; submitter: string; requestId?: string; kind?: "transfer" | "burn"; }, res: NWPCResponseObject): Promise; /** * If `ins` were already consumed by a committed transfer, answer with that * transfer instead of re-validating (the inputs are spent now, so validation * would report a double-spend at a payer whose transfer succeeded). Returns * `undefined` when there is nothing to replay. */ protected replayCommittedTransfer(ins: unknown[] | undefined, outs: unknown[] | undefined, requester: string, res: NWPCResponseObject): Promise<{ replayed: true; response: unknown; } | undefined>; /** * Try each undelivered output once, then tell the requester the tx is * committed. Delivery failures never fail the request: the value has moved, * the output stays in the outbox, and a caller told otherwise would retry. */ protected deliverAndReply(tx: StoredTx, res: NWPCResponseObject, requester: string): Promise; /** One delivery attempt, recorded in the ledger either way. */ private tryDeliver; /** * Retry every due, undelivered output. Runs on a timer once initialized; * callable directly (tests, or an operator draining by hand). */ drainOutbox(now?: number): Promise; /** Drop tx records older than the retention window (never less than 30 days). */ pruneTxRecords(now?: number): Promise; protected startOutbox(): void; protected stopOutbox(): void; disconnect(): Promise; /** * `status {tx_id}`: the committed transfer or mint and the outputs the * requester may see, so a pocket that lost its replies can recover. */ handleStatus(req: NWPCRequest, context: NWPCContext, res: NWPCResponseObject): Promise; /** * Transition for pockets still signing the v1 spend digest, which binds only * to/amount/tokenID. * * Accepted only while the announced window is open and only where v1 already * covers everything that matters: no output carries a timeLock (v1 does not * bind it), every output's issuer is this forge (checked for all outputs), * and outputs spend the inputs exactly (enforced for every transfer, since * change is always explicit). After the window the pocket gets an explicit * UPGRADE_REQUIRED rather than a generic authorization failure. * * @returns `null` if the v1 witness is accepted, `undefined` if it is not a * valid v1 witness either, or `[message, code]` to reject with. */ protected checkV1SpendWitness(tokenHash: string, outs: Record[], witness: Uint8Array, lock: string): null | undefined | [string, number]; /** * Signs a token and converts it to JWT format. * * This method prepares the token for issuance by creating a signature using the * forge's private key (or signer) and encoding the result as a JWT string. The JWT * can then be sent to users or stored. * * @param token - The token to sign * @returns The signed token as a JWT string * * @example * ```typescript * const token = new Token({ token_type: TokenType.FUNGIBLE, payload: {...} }); * const jwt = await forge.signAndCreateJWT(token); * // Send jwt to the user * ``` */ signAndCreateJWT(token: Token): Promise; /** * Validates all input tokens in a transaction. * * This method performs comprehensive validation of transaction inputs including: * - Checking tokens haven't been spent (double-spend prevention) * - Verifying tokens haven't expired * - Validating P2PK lock signatures if present * - Checking time locks haven't expired * - Validating HTLC secrets if present * * @param tx - The transaction data containing input tokens * @param witnessData - Optional witness signatures for P2PK locked tokens * @param providedHTLCSecret - Optional secret for unlocking HTLC tokens * @returns Tuple of [validated transaction, error message, error code, error details] * On success: [tx, null, null, undefined] * On failure: [null, errorMessage, errorCode, errorDetails] * * @example * ```typescript * const [validTx, error, code, details] = await forge.validateTXInputs(tx, witnessData); * if (error) { * return res.error(code, error); * } * // Proceed with validated transaction * ``` */ validateTXInputs(tx: TransactionData, witnessData?: string[], providedHTLCSecret?: string, opts?: { /** Digest the P2PK witness must sign. Default: spendAuthDigest over tx.outs. */ witnessDigest?: (tokenHash: string) => Uint8Array; /** Refuse inputs with no P2PK lock (nothing could authorize them). */ requireLock?: boolean; }): Promise<[ TransactionData | null, string | null, number | null, string | undefined ]>; } export {};