@btc-stamps/tx-builder
Version:
Transaction builder for Bitcoin Stamps and SRC-20 tokens with advanced UTXO selection
1,801 lines (1,775 loc) • 60.1 kB
TypeScript
export { c as EnhancedPSBTBuilder, E as EnhancedPSBTOptions, I as InputMetadata, O as OutputMetadata, a as PSBTBuilder, b as PSBTMetadata, P as PSBTOptions, S as ScriptBuilder, T as TransactionBuilder } from '../script-builder-TG8Qv8P8.js';
import { Transaction, Psbt, Network } from 'bitcoinjs-lib';
import { U as UTXO } from '../provider.interface-53Rg30ZJ.js';
import { S as SelectionOptions, a as SelectionResult, b as SelectorAlgorithm, I as IUTXOSelector, E as EnhancedSelectionResult } from '../selector.interface-vD2d-t2t.js';
import 'node:buffer';
import '../fee-normalizer-BGRDTCVR.js';
import 'ecpair';
import '../src20.interface-BFhaLcm9.js';
import '../protection.interface-DWbXoL2W.js';
/**
* RBF and CPFP Interface
* Replace-By-Fee and Child-Pays-For-Parent transaction support
*/
interface RBFConfig {
/** Original transaction to replace */
originalTxid: string;
/** Minimum fee rate increase (sat/vB) */
minFeeRateIncrease: number;
/** Maximum fee rate cap (sat/vB) */
maxFeeRate?: number;
/** Target fee rate for replacement */
targetFeeRate?: number;
/** Whether to replace all inputs (true) or just increase fee (false) */
replaceAllInputs?: boolean;
/** Additional UTXOs to use if needed */
additionalUtxos?: UTXO[];
/** Change address for fee adjustments */
changeAddress?: string;
/** Original transaction fee rate (sat/vB) - used when original UTXOs are not available */
originalFeeRate?: number;
}
interface CPFPConfig {
/** Parent transaction(s) to accelerate */
parentTxids: string[];
/** Parent transaction fee rates (sat/vB) */
parentFeeRates: number[];
/** Target effective fee rate for the package */
targetPackageFeeRate: number;
/** UTXOs from parent transactions to spend */
parentOutputs: Array<{
txid: string;
vout: number;
value: number;
scriptPubKey: string;
}>;
/** Destination for CPFP transaction */
destination: string;
/** Minimum output value */
minOutputValue?: number;
}
interface RBFTransaction {
/** Replacement PSBT */
psbt: Psbt;
/** Original transaction that's being replaced */
originalTxid: string;
/** Original transaction fee */
originalFee: number;
/** New transaction fee */
newFee: number;
/** Fee increase amount */
feeIncrease: number;
/** Original fee rate */
originalFeeRate: number;
/** New fee rate */
newFeeRate: number;
/** Whether additional inputs were needed */
addedInputs: boolean;
/** UTXOs that were added (if any) */
addedUtxos: UTXO[];
/** Validation status */
valid: boolean;
/** Validation messages */
messages: string[];
}
interface CPFPTransaction {
/** Child PSBT that pays for parent */
psbt: Psbt;
/** Parent transaction IDs being accelerated */
parentTxids: string[];
/** Combined package size (parent + child) */
packageSize: number;
/** Combined package fee */
packageFee: number;
/** Effective package fee rate */
packageFeeRate: number;
/** Individual child transaction fee */
childFee: number;
/** Child transaction size */
childSize: number;
/** Child transaction fee rate */
childFeeRate: number;
/** Validation status */
valid: boolean;
/** Validation messages */
messages: string[];
}
interface UTXOLock {
/** Transaction ID and output index */
outpoint: string;
/** Lock expiry timestamp */
expiresAt: number;
/** Lock purpose */
purpose: 'rbf' | 'cpfp' | 'pending';
/** Lock identifier */
lockId: string;
}
interface PackageInfo {
/** Transaction IDs in the package */
txids: string[];
/** Total package size */
totalSize: number;
/** Total package fee */
totalFee: number;
/** Effective fee rate */
effectiveFeeRate: number;
/** Individual transaction details */
transactions: Array<{
txid: string;
size: number;
fee: number;
feeRate: number;
inputs: string[];
outputs: Array<{
value: number;
address?: string;
}>;
}>;
/** Package dependency graph */
dependencies: Map<string, string[]>;
}
/**
* RBF Transaction Builder Interface
*/
interface IRBFBuilder {
/**
* Create RBF replacement transaction
*/
createReplacement(originalTx: Transaction, config: RBFConfig, availableUtxos: UTXO[]): Promise<RBFTransaction>;
/**
* Calculate minimum fee for RBF
*/
calculateMinimumRBFFee(originalTx: Transaction, newSize?: number): number;
/**
* Validate RBF transaction
*/
validateRBF(originalTx: Transaction, replacementPsbt: Psbt): {
valid: boolean;
errors: string[];
warnings: string[];
};
/**
* Check if transaction signals RBF
*/
signalsRBF(tx: Transaction | Psbt): boolean;
/**
* Enable RBF signaling in PSBT
*/
enableRBF(psbt: Psbt): void;
}
/**
* CPFP Transaction Builder Interface
*/
interface ICPFPBuilder {
/**
* Create CPFP child transaction
*/
createChild(parentTxs: Transaction[], config: CPFPConfig, network: Network): Promise<CPFPTransaction>;
/**
* Calculate required child fee for target package rate
*/
calculateRequiredChildFee(parentTxs: Transaction[], targetPackageFeeRate: number, childSize: number): number;
/**
* Validate CPFP package
*/
validatePackage(parentTxs: Transaction[], childPsbt: Psbt): {
valid: boolean;
errors: string[];
warnings: string[];
packageInfo: PackageInfo;
};
/**
* Optimize CPFP fee allocation
*/
optimizeFeeAllocation(parentTxs: Transaction[], availableValue: number, targetFeeRate: number): {
recommendedChildFee: number;
optimalOutputValue: number;
effectivePackageRate: number;
};
}
/**
* UTXO Lock Manager Interface
*/
interface IUTXOLockManager {
/**
* Lock UTXO for exclusive use
*/
lockUTXO(outpoint: string, purpose: 'rbf' | 'cpfp' | 'pending', durationMs?: number): Promise<string>;
/**
* Unlock UTXO
*/
unlockUTXO(lockId: string): Promise<boolean>;
/**
* Check if UTXO is locked
*/
isLocked(outpoint: string): Promise<boolean>;
/**
* Get locked UTXOs
*/
getLockedUTXOs(): Promise<UTXOLock[]>;
/**
* Clear expired locks
*/
clearExpiredLocks(): Promise<number>;
/**
* Lock multiple UTXOs atomically
*/
lockMultiple(outpoints: string[], purpose: 'rbf' | 'cpfp' | 'pending', durationMs?: number): Promise<string[]>;
}
/**
* PSBT Validation Interface
* Comprehensive PSBT validation and finalization support
*/
interface PSBTValidationResult {
/** Overall validation status */
valid: boolean;
/** Whether transaction can be finalized */
canFinalize: boolean;
/** Critical errors that prevent finalization */
criticalErrors: ValidationError[];
/** Non-critical warnings */
warnings: ValidationWarning[];
/** Successful rule checks */
passed: string[];
/** Input-specific validation results */
inputValidation: InputValidationResult[];
/** Output-specific validation results */
outputValidation: OutputValidationResult[];
/** Overall transaction analysis */
transactionAnalysis: TransactionAnalysis;
}
interface ValidationError {
/** Error rule name */
rule: string;
/** Error message */
message: string;
/** Input/output index if applicable */
index?: number;
/** Error severity */
severity: 'critical' | 'high' | 'medium' | 'low';
/** Suggested fix */
suggestion?: string;
}
interface ValidationWarning {
/** Warning rule name */
rule: string;
/** Warning message */
message: string;
/** Input/output index if applicable */
index?: number;
/** Recommended action */
recommendation?: string;
}
interface InputValidationResult {
/** Input index */
index: number;
/** Input validation status */
valid: boolean;
/** Whether input can be finalized */
canFinalize: boolean;
/** Input errors */
errors: ValidationError[];
/** Input warnings */
warnings: ValidationWarning[];
/** Input analysis */
analysis: InputAnalysis;
}
interface OutputValidationResult {
/** Output index */
index: number;
/** Output validation status */
valid: boolean;
/** Output errors */
errors: ValidationError[];
/** Output warnings */
warnings: ValidationWarning[];
/** Output analysis */
analysis: OutputAnalysis;
}
interface InputAnalysis {
/** Input type detected */
inputType: 'P2PKH' | 'P2WPKH' | 'P2SH' | 'P2WSH' | 'P2TR' | 'unknown';
/** Whether input has witness UTXO */
hasWitnessUtxo: boolean;
/** Whether input has non-witness UTXO */
hasNonWitnessUtxo: boolean;
/** Whether input has redeem script */
hasRedeemScript: boolean;
/** Whether input has witness script */
hasWitnessScript: boolean;
/** Number of signatures present */
signaturesCount: number;
/** Required signatures */
signaturesRequired: number;
/** BIP32 derivation paths count */
derivationPathsCount: number;
/** Sighash types used */
sighashTypes: number[];
/** Estimated input size */
estimatedSize: number;
}
interface OutputAnalysis {
/** Output type detected */
outputType: 'P2PKH' | 'P2WPKH' | 'P2SH' | 'P2WSH' | 'P2TR' | 'OP_RETURN' | 'unknown';
/** Output value */
value: number;
/** Whether output is change */
isChange: boolean;
/** Whether output is above dust threshold */
aboveDustThreshold: boolean;
/** BIP32 derivation paths count */
derivationPathsCount: number;
/** Output address (if extractable) */
address?: string;
}
interface TransactionAnalysis {
/** Transaction version */
version: number;
/** Transaction locktime */
locktime: number;
/** Input count */
inputCount: number;
/** Output count */
outputCount: number;
/** Total input value */
totalInputValue: number;
/** Total output value */
totalOutputValue: number;
/** Transaction fee */
fee: number;
/** Fee rate (sat/vB) */
feeRate: number;
/** Estimated transaction size */
estimatedSize: number;
/** Whether RBF is signaled */
rbfEnabled: boolean;
/** Whether transaction is segwit */
isSegwit: boolean;
/** Complexity score */
complexityScore: number;
}
interface FinalizationOptions {
/** Skip signature validation during finalization */
skipSignatureValidation?: boolean;
/** Allow partial finalization of inputs */
allowPartialFinalization?: boolean;
/** Finalize specific inputs only */
inputIndices?: number[];
/** Custom finalization handlers */
customFinalizers?: Map<string, InputFinalizer>;
/** Whether to extract transaction after finalization */
extractTransaction?: boolean;
}
interface FinalizationResult {
/** Whether finalization was successful */
success: boolean;
/** Number of inputs finalized */
finalizedInputs: number;
/** Total inputs */
totalInputs: number;
/** Inputs that failed finalization */
failedInputs: number[];
/** Finalization errors */
errors: ValidationError[];
/** Finalization warnings */
warnings: ValidationWarning[];
/** Final transaction (if successfully finalized and extracted) */
transaction?: Transaction;
/** Transaction ID (if finalized) */
transactionId?: string;
}
interface InputFinalizer {
/** Finalizer name */
name: string;
/** Whether this finalizer can handle the input */
canFinalize(psbt: Psbt, inputIndex: number): boolean;
/** Finalize the input */
finalize(psbt: Psbt, inputIndex: number): {
success: boolean;
error?: string;
};
}
interface PSBTAnalysisReport {
/** PSBT summary */
summary: {
valid: boolean;
canFinalize: boolean;
completionPercentage: number;
estimatedFee: number;
estimatedFeeRate: number;
};
/** Detailed validation results */
validation: PSBTValidationResult;
/** Finalization readiness */
finalization: {
ready: boolean;
readyInputs: number[];
blockedInputs: Array<{
index: number;
reason: string;
missingComponents: string[];
}>;
};
/** Security analysis */
security: {
riskLevel: 'low' | 'medium' | 'high' | 'critical';
risks: string[];
recommendations: string[];
};
/** Compatibility analysis */
compatibility: {
bitcoinjsLib: boolean;
bip174: boolean;
};
}
/**
* PSBT Validator Interface
*/
interface IPSBTValidator {
/**
* Validate PSBT comprehensively
*/
validate(psbt: Psbt, network?: Network): Promise<PSBTValidationResult>;
/**
* Validate specific input
*/
validateInput(psbt: Psbt, inputIndex: number): Promise<InputValidationResult>;
/**
* Validate specific output
*/
validateOutput(psbt: Psbt, outputIndex: number): Promise<OutputValidationResult>;
/**
* Check if PSBT can be finalized
*/
canFinalize(psbt: Psbt): Promise<boolean>;
/**
* Get missing components for finalization
*/
getMissingComponents(psbt: Psbt): Promise<Array<{
inputIndex: number;
missing: string[];
}>>;
/**
* Analyze PSBT structure and completeness
*/
analyze(psbt: Psbt): Promise<PSBTAnalysisReport>;
}
/**
* PSBT Finalizer Interface
*/
interface IPSBTFinalizer {
/**
* Finalize PSBT
*/
finalize(psbt: Psbt, options?: FinalizationOptions): Promise<FinalizationResult>;
/**
* Finalize specific inputs
*/
finalizeInputs(psbt: Psbt, inputIndices: number[]): Promise<FinalizationResult>;
/**
* Check finalization readiness
*/
checkFinalizationReadiness(psbt: Psbt): Promise<{
ready: boolean;
readyInputs: number[];
blockedInputs: Array<{
index: number;
reason: string;
}>;
}>;
/**
* Extract final transaction
*/
extractTransaction(psbt: Psbt): Transaction;
/**
* Register custom input finalizer
*/
registerFinalizer(finalizer: InputFinalizer): void;
/**
* Simulate transaction execution
*/
simulateExecution(psbt: Psbt): Promise<{
success: boolean;
errors: string[];
gasUsed?: number;
}>;
}
/**
* RBF (Replace-By-Fee) Builder
* Implementation for creating replacement transactions
*/
/**
* RBF Builder Implementation
*/
declare class RBFBuilder implements IRBFBuilder {
private network;
private defaultMinFeeIncrease;
constructor(network?: Network);
/**
* Create RBF replacement transaction
*/
createReplacement(originalTx: Transaction, config: RBFConfig, availableUtxos: UTXO[]): Promise<RBFTransaction>;
/**
* Calculate minimum fee for RBF
*/
calculateMinimumRBFFee(originalTx: Transaction, newSize?: number): number;
/**
* Validate RBF transaction
*/
validateRBF(originalTx: Transaction, replacementPsbt: Psbt): {
valid: boolean;
errors: string[];
warnings: string[];
};
/**
* Check if transaction signals RBF
*/
signalsRBF(tx: Transaction | Psbt): boolean;
/**
* Enable RBF signaling in PSBT
*/
enableRBF(psbt: Psbt): void;
private calculateTransactionFee;
private calculateTotalOutputValue;
private extractOriginalInputs;
private selectUtxosForReplacement;
private selectAdditionalUtxos;
private addInputToPsbt;
private addOutputsToPsbt;
private estimateReplacementSize;
private estimateInputOutputSize;
private estimateTransactionSize;
private getTotalOutputValue;
private calculatePsbtFee;
private estimateOriginalFee;
private hasChangeOutput;
}
/**
* CPFP (Child-Pays-For-Parent) Builder
* Implementation for creating child transactions that accelerate parent transactions
*/
/**
* CPFP Builder Implementation
*/
declare class CPFPBuilder implements ICPFPBuilder {
private dustThreshold;
constructor(_network?: Network);
/**
* Create CPFP child transaction
*/
createChild(parentTxs: Transaction[], config: CPFPConfig, network: Network): Promise<CPFPTransaction>;
/**
* Calculate required child fee for target package rate
*/
calculateRequiredChildFee(parentTxs: Transaction[], targetPackageFeeRate: number, childSize: number): number;
/**
* Validate CPFP package
*/
validatePackage(parentTxs: Transaction[], childPsbt: Psbt): {
valid: boolean;
errors: string[];
warnings: string[];
packageInfo: PackageInfo;
};
/**
* Optimize CPFP fee allocation
*/
optimizeFeeAllocation(parentTxs: Transaction[], availableValue: number, targetFeeRate: number): {
recommendedChildFee: number;
optimalOutputValue: number;
effectivePackageRate: number;
};
private validateCPFPConfig;
private calculateParentPackageFee;
private estimateChildSize;
private estimateTransactionSize;
private estimateTransactionFee;
private buildPackageInfo;
private calculateChildFee;
private detectCircularDependencies;
/**
* Generate a temporary transaction ID for a PSBT
* This is a placeholder ID that represents the transaction before it's finalized
*/
private generateTemporaryTxid;
}
/**
* UTXO Lock Manager
* Manages exclusive locks on UTXOs to prevent double-spending during RBF/CPFP operations
*/
/**
* UTXO Lock Manager Implementation
*/
declare class UTXOLockManager implements IUTXOLockManager {
private locks;
private lockIdToOutpoint;
private defaultLockDuration;
/**
* Lock UTXO for exclusive use
*/
lockUTXO(outpoint: string, purpose: 'rbf' | 'cpfp' | 'pending', durationMs?: number): Promise<string>;
/**
* Unlock UTXO
*/
unlockUTXO(lockId: string): Promise<boolean>;
/**
* Check if UTXO is locked
*/
isLocked(outpoint: string): Promise<boolean>;
/**
* Get locked UTXOs
*/
getLockedUTXOs(): Promise<UTXOLock[]>;
/**
* Clear expired locks
*/
clearExpiredLocks(): Promise<number>;
/**
* Lock multiple UTXOs atomically
*/
lockMultiple(outpoints: string[], purpose: 'rbf' | 'cpfp' | 'pending', durationMs?: number): Promise<string[]>;
/**
* Extend lock duration
*/
extendLock(lockId: string, additionalDurationMs: number): boolean;
/**
* Get lock information
*/
getLockInfo(outpoint: string): UTXOLock | null;
/**
* Get locks by purpose
*/
getLocksByPurpose(purpose: 'rbf' | 'cpfp' | 'pending'): Promise<UTXOLock[]>;
/**
* Force unlock UTXO (admin function)
*/
forceUnlock(outpoint: string): boolean;
/**
* Check lock health and cleanup
*/
performMaintenance(): Promise<{
totalLocks: number;
expiredLocks: number;
activeLocks: number;
locksByPurpose: Record<string, number>;
}>;
/**
* Get lock statistics
*/
getStatistics(): Promise<{
totalLocks: number;
locksByPurpose: Record<string, number>;
averageRemainingTime: number;
upcomingExpirations: Array<{
outpoint: string;
expiresAt: number;
purpose: string;
}>;
}>;
private generateLockId;
/**
* Check if UTXOs are available for locking (not locked by others)
*/
checkAvailability(outpoints: string[]): Promise<{
available: string[];
locked: Array<{
outpoint: string;
lock: UTXOLock;
}>;
}>;
/**
* Batch unlock multiple locks
*/
unlockMultiple(lockIds: string[]): Promise<{
successful: string[];
failed: string[];
}>;
}
/**
* PSBT Validator
* Comprehensive PSBT validation implementation
*/
/**
* PSBT Validator Implementation
*/
declare class PSBTValidator implements IPSBTValidator {
private network;
private _validationRules;
constructor(network?: Network);
/**
* Validate PSBT comprehensively
*/
validate(psbt: Psbt, network?: Network): Promise<PSBTValidationResult>;
/**
* Validate specific input
*/
validateInput(psbt: Psbt, inputIndex: number): Promise<InputValidationResult>;
/**
* Validate specific output
*/
validateOutput(psbt: Psbt, outputIndex: number): Promise<OutputValidationResult>;
/**
* Check if PSBT can be finalized
*/
canFinalize(psbt: Psbt): Promise<boolean>;
/**
* Get missing components for finalization
*/
getMissingComponents(psbt: Psbt): Promise<Array<{
inputIndex: number;
missing: string[];
}>>;
/**
* Analyze PSBT structure and completeness
*/
analyze(psbt: Psbt): Promise<PSBTAnalysisReport>;
private initializeValidationRules;
private validatePSBTStructure;
private validateTransactionLevel_func;
private validateInputSignatures;
private validateInputScripts;
private validateSequenceNumber;
private validateOutputValue;
private validateOutputScript;
private validateBIP32Derivation;
private canFinalizeInput;
private getMissingInputComponents;
private analyzeInput;
private analyzeOutput;
private analyzeTransaction;
private getFinalizationReadiness;
private analyzeSecurityRisks;
private analyzeCompatibility;
private calculateFee;
private calculateTotalInputValue;
private calculateTotalOutputValue;
private estimateTransactionSize;
private calculateCompletionPercentage;
private detectInputType;
private detectOutputType;
private getRequiredSignatures;
private extractSighashTypes;
private estimateInputSize;
private isChangeOutput;
private extractAddress;
private isP2SH;
private isP2WSH;
private isRBFEnabled;
private isSegwitTransaction;
private calculateComplexityScore;
private calculateRiskLevel;
private checkBIP174Compliance;
private _hasComplexScripts;
private getEmptyInputAnalysis;
private getEmptyOutputAnalysis;
private getEmptyTransactionAnalysis;
}
/**
* PSBT Finalizer
* Comprehensive PSBT finalization implementation
*/
/**
* PSBT Finalizer Implementation
*/
declare class PSBTFinalizer implements IPSBTFinalizer {
private customFinalizers;
constructor();
/**
* Finalize PSBT
*/
finalize(psbt: Psbt, options?: FinalizationOptions): Promise<FinalizationResult>;
/**
* Finalize specific inputs
*/
finalizeInputs(psbt: Psbt, inputIndices: number[]): Promise<FinalizationResult>;
/**
* Check finalization readiness
*/
checkFinalizationReadiness(psbt: Psbt): Promise<{
ready: boolean;
readyInputs: number[];
blockedInputs: Array<{
index: number;
reason: string;
}>;
}>;
/**
* Extract final transaction
*/
extractTransaction(psbt: Psbt): Transaction;
/**
* Register custom input finalizer
*/
registerFinalizer(finalizer: InputFinalizer): void;
/**
* Simulate transaction execution
*/
simulateExecution(psbt: Psbt): Promise<{
success: boolean;
errors: string[];
gasUsed?: number;
}>;
private registerDefaultFinalizers;
private finalizeInput;
private canFinalizeInput;
private getFinalizationBlockReason;
private getRequiredSignatures;
private isP2WPKH;
private isP2SH;
private isP2WSH;
}
/**
* Performance Monitoring System
* Comprehensive monitoring for UTXO selection algorithms and transaction building
*/
interface AlgorithmMetrics {
name: string;
executionTime: number;
success: boolean;
inputCount?: number;
totalValue?: number;
fee?: number;
change?: number;
wasteMetric?: number;
memoryUsage?: number;
timestamp: number;
utxoSetSize: number;
targetValue: number;
feeRate: number;
}
interface PerformanceBenchmark {
utxoSetSize: number;
targetPercentage: number;
feeRate: number;
expectedTimeMs: number;
}
interface BenchmarkResult$1 {
benchmark: PerformanceBenchmark;
algorithmResults: Array<{
algorithm: string;
metrics: AlgorithmMetrics;
meetsTarget: boolean;
performanceRatio: number;
}>;
winner: string | null;
timestamp: number;
}
interface MemoryProfile {
heapUsed: number;
heapTotal: number;
external: number;
arrayBuffers: number;
peak: number;
timestamp: number;
}
interface PerformanceReport {
timeRange: {
start: number;
end: number;
};
totalSelections: number;
successRate: number;
averageExecutionTime: number;
p95ExecutionTime: number;
p99ExecutionTime: number;
algorithmComparison: Record<string, {
selectionCount: number;
successRate: number;
averageTime: number;
averageWaste: number;
preferredScenarios: string[];
}>;
memoryUsage: {
peak: number;
average: number;
growth: number;
};
recommendations: string[];
}
/**
* Performance monitoring and benchmarking system
*/
declare class PerformanceMonitor {
private metrics;
private benchmarkHistory;
private memoryProfiles;
private startTime;
private maxHistorySize;
private performanceTargets;
/**
* Start performance measurement for an algorithm
*/
startMeasurement(): {
recordSelection: (algorithmName: string, utxos: UTXO[], options: SelectionOptions, result: SelectionResult | null, startTime: number) => void;
};
/**
* Record algorithm performance metrics
*/
recordMetrics(metrics: AlgorithmMetrics): void;
/**
* Run comprehensive benchmark suite
*/
runBenchmarkSuite(algorithms: Array<{
name: string;
selector: any;
}>, testScenarios?: PerformanceBenchmark[]): Promise<BenchmarkResult$1[]>;
/**
* Generate performance report
*/
generateReport(timeRangeMs?: number): PerformanceReport;
/**
* Get algorithm performance comparison
*/
compareAlgorithms(timeRangeMs?: number): Array<{
algorithm: string;
metrics: {
averageTime: number;
successRate: number;
wasteScore: number;
memoryEfficiency: number;
consistencyScore: number;
};
rank: number;
bestUseCase: string;
}>;
/**
* Capture memory snapshot
*/
private captureMemorySnapshot;
/**
* Check if metrics meet performance targets
*/
private checkPerformanceTargets;
/**
* Get performance target for UTXO set size
*/
private getPerformanceTarget;
/**
* Generate test UTXOs for benchmarking
*/
private generateTestUTXOs;
/**
* Get default benchmark scenarios
*/
private getDefaultBenchmarks;
/**
* Get preferred scenarios for algorithm
*/
private getPreferredScenarios;
/**
* Calculate waste score (lower is better)
*/
private calculateWasteScore;
/**
* Calculate memory efficiency score (higher is better)
*/
private calculateMemoryEfficiency;
/**
* Calculate consistency score (lower variance = higher score)
*/
private calculateConsistencyScore;
/**
* Calculate overall score for ranking
*/
private calculateOverallScore;
/**
* Determine best use case for algorithm
*/
private determineBestUseCase;
/**
* Calculate memory growth rate
*/
private calculateMemoryGrowth;
/**
* Generate recommendations based on performance data
*/
private generateRecommendations;
/**
* Get empty report structure
*/
private getEmptyReport;
/**
* Export performance data
*/
export(): {
metrics: AlgorithmMetrics[];
benchmarkHistory: BenchmarkResult$1[];
memoryProfiles: MemoryProfile[];
config: any;
};
/**
* Reset all performance data
*/
reset(): void;
/**
* Update performance targets
*/
updateTargets(targets: Partial<typeof this.performanceTargets>): void;
/**
* Initialize the performance monitor
*/
initialize(): Promise<void>;
/**
* Start monitoring
*/
startMonitoring(): void;
/**
* Set performance targets
*/
setPerformanceTargets(targets: any): void;
/**
* Log selection request
*/
logRequest(requestId: string, request: any): void;
/**
* Log selection response
*/
logResponse(requestId: string, _result: any, metadata: any): void;
/**
* Log error
*/
logError(requestId: string, error: Error, executionTime: number): void;
/**
* Get aggregated metrics for performance monitoring
*/
getAggregatedMetrics(): any;
/**
* Get algorithm performance data
*/
getAlgorithmPerformance(): Map<string, any>;
/**
* Shutdown the performance monitor
*/
shutdown(): Promise<void>;
}
/**
* Create performance monitor instance
*/
declare function createPerformanceMonitor(): PerformanceMonitor;
/**
* Global performance monitor instance
*/
declare const _globalPerformanceMonitor: PerformanceMonitor;
/**
* UTXO Cache Manager
* Advanced caching layer with TTL management and performance optimization
*/
interface UTXOCacheEntry {
utxos: UTXO[];
timestamp: number;
ttl: number;
accessCount: number;
lastAccessed: number;
blockHeight?: number;
totalValue: number;
hash: string;
}
interface IndexedUTXOData {
byValue: Map<number, UTXO[]>;
byConfirmations: Map<number, UTXO[]>;
sortedByValue: UTXO[];
sortedByConfirmations: UTXO[];
totalValue: number;
count: number;
lastUpdated: number;
}
interface CacheConfig {
maxCacheSize: number;
defaultTTL: number;
blockHeightTTL: number;
memoryLimit: number;
enableIndexing: boolean;
compressionThreshold: number;
}
interface CacheStats {
totalEntries: number;
hitRate: number;
missRate: number;
memoryUsage: number;
indexHitRate: number;
averageUTXOSetSize: number;
evictionCount: number;
compressionRatio: number;
}
/**
* Advanced UTXO caching system with indexing and performance optimization
*/
declare class UTXOCacheManager {
private cache;
private indexCache;
private accessOrder;
private stats;
private config;
private memoryUsage;
constructor(config?: Partial<CacheConfig>);
/**
* Get cached UTXOs for an address
*/
getUTXOs(address: string, blockHeight?: number): UTXO[] | null;
/**
* Cache UTXOs for an address
*/
setUTXOs(address: string, utxos: UTXO[], blockHeight?: number, customTTL?: number): void;
/**
* Get UTXOs optimized for specific selection criteria
*/
getOptimizedUTXOs(address: string, options: SelectionOptions, blockHeight?: number): UTXO[] | null;
/**
* Pre-filter UTXOs by value range for faster selection
*/
getUTXOsByValueRange(address: string, minValue: number, maxValue: number, blockHeight?: number): UTXO[] | null;
/**
* Get UTXOs suitable for specific confirmation requirements
*/
getUTXOsByConfirmations(address: string, minConfirmations: number, blockHeight?: number): UTXO[] | null;
/**
* Invalidate cache entries for an address
*/
invalidateAddress(address: string): number;
/**
* Invalidate cache entries older than specified block height
*/
invalidateByBlockHeight(blockHeight: number): number;
/**
* Batch update multiple addresses
*/
batchUpdate(updates: Array<{
address: string;
utxos: UTXO[];
blockHeight?: number;
ttl?: number;
}>): void;
/**
* Get cache statistics
*/
getStats(): CacheStats;
/**
* Clear all cached data
*/
clear(): void;
/**
* Export cache data for analysis
*/
export(): {
config: CacheConfig;
stats: CacheStats;
entries: Array<{
key: string;
utxoCount: number;
totalValue: number;
age: number;
accessCount: number;
ttl: number;
blockHeight?: number;
}>;
};
/**
* Generate cache key
*/
private generateKey;
/**
* Check if cache entry is expired
*/
private isExpired;
/**
* Check if indexed data is expired
*/
private isIndexExpired;
/**
* Calculate TTL based on UTXO characteristics
*/
private calculateTTL;
/**
* Update access tracking
*/
private updateAccess;
/**
* Update access order for LRU
*/
private updateAccessOrder;
/**
* Evict cache entry
*/
private evictEntry;
/**
* Compress UTXOs if needed
*/
private compressUTXOs;
/**
* Decompress UTXOs
*/
private decompressUTXOs;
/**
* Generate hash for UTXO set integrity
*/
private generateUTXOHash;
/**
* Create indexed data structures
*/
private createIndexedData;
/**
* Select UTXOs from indexed data based on selection options
*/
private selectFromIndexedData;
/**
* Update memory usage tracking
*/
private updateMemoryUsage;
/**
* Enforce cache size and memory limits
*/
private enforceLimits;
/**
* Initialize the cache manager
*/
initialize(): Promise<void>;
/**
* Shutdown the cache manager
*/
shutdown(): Promise<void>;
/**
* Generic set method for caching selection results
*/
set(key: string, _value: any, ttl?: number): void;
/**
* Generic get method for cached selection results
*/
get(key: string): any;
}
/**
* Create UTXO cache manager
*/
declare function createUTXOCacheManager(config?: Partial<CacheConfig>): UTXOCacheManager;
/**
* Create memory-optimized cache
*/
declare function createMemoryOptimizedUTXOCache(): UTXOCacheManager;
/**
* Create performance-optimized cache
*/
declare function createPerformanceOptimizedUTXOCache(): UTXOCacheManager;
/**
* Performance-Aware Selector Factory
* Enhanced selector factory with performance monitoring and caching integration
*/
interface PerformanceConfig {
enableMonitoring: boolean;
enableCaching: boolean;
cacheTTL: number;
performanceTargets: {
smallSet: {
utxos: number;
timeMs: number;
};
mediumSet: {
utxos: number;
timeMs: number;
};
largeSet: {
utxos: number;
timeMs: number;
};
};
algorithmTimeouts: Record<SelectorAlgorithm, number>;
adaptiveSelection: boolean;
}
interface SelectorMetrics {
algorithm: string;
executionTime: number;
success: boolean;
cacheHit: boolean;
utxoSetSize: number;
targetValue: number;
performance: 'excellent' | 'good' | 'poor' | 'timeout';
}
/**
* Performance-aware selector with monitoring and caching
*/
declare class PerformanceAwareSelector implements IUTXOSelector {
private algorithm;
private baseSelector;
private performanceMonitor;
private _cacheManager;
private config;
constructor(algorithm: SelectorAlgorithm, performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<PerformanceConfig>);
getName(): string;
/**
* Main selection method with performance monitoring and caching
*/
select(utxos: UTXO[], options: SelectionOptions): EnhancedSelectionResult;
estimateFee(inputCount: number, outputCount: number, feeRate: number): number;
/**
* Perform the actual selection with timeout protection
*/
private performSelection;
/**
* Get cached selection result
*/
private getCachedResult;
/**
* Cache selection result
*/
private cacheResult;
/**
* Generate cache key for selection parameters
*/
private generateCacheKey;
/**
* Generate hash for UTXO set
*/
private hashUTXOs;
/**
* Generate hash for selection options
*/
private hashOptions;
}
/**
* Enhanced selector factory with performance awareness
*/
declare class PerformanceAwareSelectorFactory {
private performanceMonitor;
private cacheManager;
private selectorCache;
private config;
constructor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<PerformanceConfig>);
/**
* Create performance-aware selector
*/
create(algorithm: SelectorAlgorithm): PerformanceAwareSelector;
/**
* Get recommended algorithm based on performance data and scenario
*/
getRecommendedAlgorithm(scenario: {
utxoCount: number;
targetValue: number;
feeRate: number;
dustThreshold?: number | undefined;
}): SelectorAlgorithm;
/**
* Get multiple selectors for parallel execution
*/
getParallelSelectors(scenario: {
utxoCount: number;
targetValue: number;
feeRate: number;
}, maxSelectors?: number): PerformanceAwareSelector[];
/**
* Run benchmark on all algorithms
*/
runBenchmark(scenarios?: Array<{
utxoSetSize: number;
targetPercentage: number;
feeRate: number;
expectedTimeMs: number;
}>): Promise<void>;
/**
* Get performance report
*/
getPerformanceReport(timeRangeMs?: number): PerformanceReport;
/**
* Get cache statistics
*/
getCacheStats(): CacheStats;
/**
* Clear all caches
*/
clearCaches(): void;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<PerformanceConfig>): void;
/**
* Get all suitable algorithms for a scenario
*/
private getAllSuitableAlgorithms;
/**
* Estimate execution time based on UTXO count and historical performance
*/
private estimateExecutionTime;
/**
* Get performance target for UTXO set size
*/
private getPerformanceTarget;
}
/**
* Create performance-aware selector factory
*/
declare function createPerformanceAwareSelectorFactory(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<PerformanceConfig>): PerformanceAwareSelectorFactory;
/**
* Create optimized selector factory with default configuration
*/
declare function createOptimizedSelectorFactory(): PerformanceAwareSelectorFactory;
/**
* Parallel Algorithm Execution System
* Runs multiple UTXO selection algorithms in parallel for optimal results
*/
interface ParallelSelectionConfig {
maxConcurrency: number;
timeoutMs: number;
returnFirst: boolean;
enableRacing: boolean;
qualityThreshold: number;
enableFallback: boolean;
}
interface ParallelSelectionResult {
result: SelectionResult;
algorithm: SelectorAlgorithm;
executionTime: number;
allResults: Array<{
algorithm: SelectorAlgorithm;
result: SelectionResult | null;
executionTime: number;
error?: string;
}>;
totalExecutionTime: number;
winnerMetrics: {
wasteScore: number;
efficiencyScore: number;
qualityScore: number;
};
}
interface AlgorithmResult {
algorithm: SelectorAlgorithm;
result: SelectionResult | null;
executionTime: number;
error?: string;
metrics: {
wasteScore: number;
efficiencyScore: number;
qualityScore: number;
};
}
/**
* Parallel UTXO selection system
*/
declare class ParallelSelector {
private selectorFactory;
private performanceMonitor;
private config;
private workerPool;
private activeJobs;
constructor(selectorFactory: PerformanceAwareSelectorFactory, performanceMonitor: PerformanceMonitor, config?: Partial<ParallelSelectionConfig>);
/**
* Select UTXOs using parallel algorithm execution
*/
selectParallel(utxos: UTXO[], options: SelectionOptions, algorithms?: SelectorAlgorithm[]): Promise<ParallelSelectionResult | null>;
/**
* Select UTXOs using racing mode (first successful result wins)
*/
selectRacing(utxos: UTXO[], options: SelectionOptions, algorithms?: SelectorAlgorithm[]): Promise<ParallelSelectionResult | null>;
/**
* Run multiple algorithms and compare results
*/
benchmarkAlgorithms(utxos: UTXO[], options: SelectionOptions, algorithms?: SelectorAlgorithm[]): Promise<Array<AlgorithmResult>>;
/**
* Select optimal algorithms for the given scenario
*/
private selectOptimalAlgorithms;
/**
* Run algorithms in parallel
*/
private runAlgorithmsParallel;
/**
* Run single algorithm with timeout
*/
private runAlgorithmWithTimeout;
/**
* Select best result from multiple successful results
*/
private selectBestResult;
/**
* Calculate quality metrics for a result
*/
private calculateMetrics;
/**
* Calculate waste metric if not provided
*/
private calculateWaste;
/**
* Fallback to sequential execution
*/
private fallbackToSequential;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<ParallelSelectionConfig>): void;
/**
* Get performance statistics
*/
getStats(): {
config: Required<ParallelSelectionConfig>;
activeJobs: number;
workerPoolSize: number;
};
/**
* Cleanup resources
*/
cleanup(): void;
}
/**
* Create parallel selector with default configuration
*/
declare function createParallelSelector(selectorFactory: PerformanceAwareSelectorFactory, performanceMonitor: PerformanceMonitor, config?: Partial<ParallelSelectionConfig>): ParallelSelector;
/**
* Create high-performance parallel selector
*/
declare function createHighPerformanceParallelSelector(selectorFactory: PerformanceAwareSelectorFactory, performanceMonitor: PerformanceMonitor): ParallelSelector;
/**
* Create racing-optimized parallel selector (speed over quality)
*/
declare function createRacingParallelSelector(selectorFactory: PerformanceAwareSelectorFactory, performanceMonitor: PerformanceMonitor): ParallelSelector;
/**
* Streaming UTXO Processor
* Handles large UTXO sets efficiently using streaming and chunking
*/
interface StreamingConfig {
chunkSize: number;
maxMemoryMB: number;
enableCompression: boolean;
sortStrategy: 'value' | 'confirmations' | 'age' | 'none';
filterStrategy: 'aggressive' | 'moderate' | 'conservative';
enablePrefetch: boolean;
concurrentChunks: number;
}
interface UTXOChunk {
id: string;
utxos: UTXO[];
totalValue: number;
averageValue: number;
count: number;
memorySize: number;
processed: boolean;
}
interface StreamingStats {
totalUTXOs: number;
chunksProcessed: number;
memoryUsage: number;
filterEfficiency: number;
processingSpeed: number;
cacheHitRate: number;
}
/**
* Streaming UTXO processor for handling large datasets
*/
declare class StreamingUTXOProcessor {
private config;
private _performanceMonitor;
private cacheManager;
private processedChunks;
private memoryUsage;
private stats;
constructor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<StreamingConfig>);
/**
* Process large UTXO set using streaming approach
*/
processLargeUTXOSet(utxoSource: AsyncIterable<UTXO> | UTXO[], options: SelectionOptions, onProgress?: (progress: {
processed: number;
total?: number;
found?: boolean;
}) => void): Promise<SelectionResult | null>;
/**
* Stream UTXOs by value range for efficient filtering
*/
streamUTXOsByValueRange(utxoSource: AsyncIterable<UTXO> | UTXO[], minValue: number, maxValue: number): AsyncGenerator<UTXO>;
/**
* Prefetch and cache UTXOs based on selection patterns
*/
prefetchOptimalUTXOs(address: string, options: SelectionOptions, provider: any): Promise<UTXO[]>;
/**
* Create indexed UTXO structure for faster searching
*/
createUTXOIndex(utxos: UTXO[]): {
byValue: Map<number, UTXO[]>;
byConfirmations: Map<number, UTXO[]>;
sortedByValue: UTXO[];
valueRanges: Array<{
min: number;
max: number;
utxos: UTXO[];
}>;
};
/**
* Get statistics about streaming processing
*/
getStats(): StreamingStats;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<StreamingConfig>): void;
/**
* Clear processed chunks and reset memory
*/
cleanup(): void;
/**
* Convert array to async iterable
*/
private arrayToAsyncIterable;
/**
* Create chunks from UTXO stream
*/
private chunkStream;
/**
* Create chunk object
*/
private createChunk;
/**
* Process individual chunk
*/
private processChunk;
/**
* Simple accumulative selection for chunk processing
*/
private attemptSelection;
/**
* Estimate transaction fee
*/
private estimateFee;
/**
* Estimate transaction size in vBytes
*/
private estimateTransactionSize;
/**
* Pre-filter UTXOs based on selection options
*/
private prefilterUTXOs;
/**
* Sort UTXOs based on configured strategy
*/
private sortUTXOs;
/**
* Check if result is better than current best
*/
private isResultBetter;
/**
* Check if result is good enough to stop searching
*/
private isResultGoodEnough;
/**
* Estimate memory size of UTXO array
*/
private estimateMemorySize;
/**
* Manage memory usage by cleaning up old chunks
*/
private manageMemory;
/**
* Create value ranges for efficient range queries
*/
private createValueRanges;
/**
* Reset statistics
*/
private resetStats;
}
/**
* Create streaming UTXO processor
*/
declare function createStreamingUTXOProcessor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<StreamingConfig>): StreamingUTXOProcessor;
/**
* Create memory-optimized streaming processor
*/
declare function createMemoryOptimizedStreamingProcessor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager): StreamingUTXOProcessor;
/**
* Create high-performance streaming processor
*/
declare function createHighPerformanceStreamingProcessor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager): StreamingUTXOProcessor;
/**
* Real-time Performance Monitoring Dashboard
* Comprehensive monitoring system with alerts and real-time metrics
*/
interface DashboardConfig {
updateIntervalMs: number;
retentionPeriodMs: number;
enableRealTimeUpdates: boolean;
enableAlerts: boolean;
alertThresholds: {
errorRate: number;
responseTime: number;
memoryUsage: number;
cacheHitRate: number;
};
enableWebSocket: boolean;
enableLogging: boolean;
}
interface RealTimeMetrics {
timestamp: number;
selectionMetrics: {
successRate: number;
averageTime: number;
p95Time: number;
requestsPerSecond: number;
algorithmDistribution: Record<string, number>;
};
cacheMetrics: {
hitRate: number;
memoryUsage: number;
totalEntries: number;
evictionRate: number;
};
systemMetrics: {
heapUsed: number;
heapTotal: number;
cpuUsage: number;
activeConnections: number;
};
alerts: Alert[];
}
interface Alert {
id: string;
type: 'error' | 'warning' | 'info';
severity: 'critical' | 'high' | 'medium' | 'low';
title: string;
message: string;
timestamp: number;
resolved: boolean;
data?: any;
}
interface DashboardStats {
uptime: number;
totalSelections: number;
totalAlerts: number;
systemHealth: 'healthy' | 'degraded' | 'critical';
performanceScore: number;
recommendations: string[];
}
/**
* Real-time monitoring dashboard
*/
declare class MonitoringDashboard {
private config;
private performanceMonitor;
private cacheManager;
private alerts;
private metrics;
private updateTimer;
private startTime;
private subscribers;
constructor(performanceMonitor: PerformanceMonitor, cacheManager: UTXOCacheManager, config?: Partial<DashboardConfig>);
/**
* Get current real-time metrics
*/
getCurrentMetrics(): RealTimeMetrics;
/**
* Get dashboard statistics
*/
getDashboardStats(): DashboardStats;
/**
* Get performance trends over time
*/
getPerformanceTrends(timeRangeMs?: number): {
timestamps: number[];
successRate: number[];
averageTime: number[];
memoryUsage: number[];
cacheHitRate: number[];
};
/**
* Create custom alert
*/
createAlert(type: Alert['type'], severity: Alert['severity'], title: string, message: string, data?: any): string;
/**
* Resolve alert
*/
resolveAlert(alertId: string): boolean;
/**
* Subscribe to real-ti