UNPKG

@btc-vision/transaction

Version:

OPNet transaction library allows you to create and sign transactions for the OPNet network.

98 lines (97 loc) 3.25 kB
import { Buffer } from 'buffer'; import { opcodes, payments, script } from '@btc-vision/bitcoin'; export class P2WDADetector { static isP2WDAUTXO(utxo) { if (!utxo.witnessScript) { return false; } const witnessScript = Buffer.isBuffer(utxo.witnessScript) ? utxo.witnessScript : Buffer.from(utxo.witnessScript, 'hex'); return this.isP2WDAWitnessScript(witnessScript); } static isP2WDAWitnessScript(witnessScript) { try { const decompiled = script.decompile(witnessScript); if (!decompiled || decompiled.length !== 7) { return false; } for (let i = 0; i < 5; i++) { if (decompiled[i] !== opcodes.OP_2DROP) { return false; } } return (Buffer.isBuffer(decompiled[5]) && decompiled[5].length === 33 && decompiled[6] === opcodes.OP_CHECKSIG); } catch { return false; } } static generateP2WDAAddress(publicKey, network) { if (publicKey.length !== 33) { throw new Error('Public key must be 33 bytes (compressed)'); } const witnessScript = script.compile([ opcodes.OP_2DROP, opcodes.OP_2DROP, opcodes.OP_2DROP, opcodes.OP_2DROP, opcodes.OP_2DROP, publicKey, opcodes.OP_CHECKSIG, ]); const p2wsh = payments.p2wsh({ redeem: { output: witnessScript }, network, }); if (!p2wsh.address || !p2wsh.output) { throw new Error('Failed to generate P2WDA address'); } return { address: p2wsh.address, witnessScript, scriptPubKey: p2wsh.output, }; } static extractPublicKeyFromP2WDA(witnessScript) { try { const decompiled = script.decompile(witnessScript); if (!decompiled || decompiled.length !== 7) { return null; } for (let i = 0; i < 5; i++) { if (decompiled[i] !== opcodes.OP_2DROP) { return null; } } if (Buffer.isBuffer(decompiled[5]) && decompiled[5].length === 33 && decompiled[6] === opcodes.OP_CHECKSIG) { return decompiled[5]; } return null; } catch { return null; } } static createSimpleP2WDAWitness(transactionSignature, witnessScript) { const witnessStack = [transactionSignature]; for (let i = 0; i < 10; i++) { witnessStack.push(Buffer.alloc(0)); } witnessStack.push(witnessScript); return witnessStack; } static validateP2WDASignature(publicKey, dataSignature, operationData) { return dataSignature.length === 64; } static estimateP2WDAWitnessSize(dataSize = 0) { return 72 + dataSize + 39 + 12; } static couldBeP2WDA(scriptPubKey) { return scriptPubKey.length === 34 && scriptPubKey[0] === 0x00 && scriptPubKey[1] === 0x20; } }