All files / src/utility ScriptTemplateSABPPP.ts

95.45% Statements 21/22
75% Branches 3/4
100% Functions 5/5
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 5557x 57x 57x               57x   57x     12x 12x   12x 12x     12x     12x 12x 12x   12x       6x 6x 6x                 6x 6x 6x           12x    
import { HexString, KeyDeriver, KeyDeriverApi, WalletProtocol } from '@bsv/sdk'
import { asBsvSdkPrivateKey, verifyTruthy } from "./index.client";
import { LockingScript, P2PKH, PrivateKey, Script, ScriptTemplate, Transaction, UnlockingScript } from "@bsv/sdk";
 
export interface ScriptTemplateParamsSABPPP {
   derivationPrefix?: string
   derivationSuffix?: string
   keyDeriver: KeyDeriverApi
}
 
export const brc29ProtocolID: WalletProtocol = [2, '3241645161d8']
 
export class ScriptTemplateSABPPP implements ScriptTemplate {
    p2pkh: P2PKH
 
    constructor(public params: ScriptTemplateParamsSABPPP) {
        this.p2pkh = new P2PKH()
 
        verifyTruthy(params.derivationPrefix)
        verifyTruthy(params.derivationSuffix)
    }
 
    getKeyID() { return `${this.params.derivationPrefix} ${this.params.derivationSuffix}` }
 
    getKeyDeriver(privKey: PrivateKey | HexString) : KeyDeriverApi {
        if (typeof privKey === 'string')
            privKey = PrivateKey.fromHex(privKey)
        Iif (!this.params.keyDeriver || this.params.keyDeriver.rootKey.toHex() !== privKey.toHex())
            return new KeyDeriver(privKey)
        return this.params.keyDeriver
    }
 
    lock(lockerPrivKey: string, unlockerPubKey: string) : LockingScript {
        const address = this.getKeyDeriver(lockerPrivKey).derivePublicKey(brc29ProtocolID, this.getKeyID(), unlockerPubKey, false).toAddress()
        const r = this.p2pkh.lock(address)
        return r
    } 
 
    unlock(unlockerPrivKey: string, lockerPubKey: string, sourceSatoshis?: number, lockingScript?: Script)
    : {
        sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>;
        estimateLength: (tx?: Transaction, inputIndex?: number) => Promise<number>;
    }
    {
        const derivedPrivateKey = this.getKeyDeriver(unlockerPrivKey).derivePrivateKey(brc29ProtocolID, this.getKeyID(), lockerPubKey).toHex()
        const r = this.p2pkh.unlock(asBsvSdkPrivateKey(derivedPrivateKey), "all", false, sourceSatoshis, lockingScript)
        return r
    }
 
    /**
     * P2PKH unlock estimateLength is a constant 
     */
    unlockLength = 108
 
}