BSV blockchainBSV blockchain

Write a custom script template

Write a script templateA class that builds a locking script and the unlocking script that spends it that locks testnet satoshisThe smallest unit of BitcoinSV (BSV). 100,000,000 satoshis make 1 BSV to two conditions, a private key and a secret, then lock 500 satoshis with it and spend them back. A template of your own fits when the P2PKHPay to Public Key Hash, the standard script that locks coins to an address, PushDrop and RPuzzle templates of @bsv/sdk do not cover the condition your app needs, and it plugs into Transaction the same way they do. The example builds on the folder of Build a transaction from inputs and outputs and runs standalone on testnet. This page was written against @bsv/sdk 4.0.1 and Node.js 24.

Before you begin

You need:

  • The folder of Build a transaction from inputs and outputs, with @bsv/sdk 4.0.1, the testnet key in .env and the transaction ID that send.mjs printed. That transaction pays your address, so its output funds this example and you do not need a new faucet request.
  • An understanding of how a locking scriptThe part of a transaction output that sets the condition to spend it and an unlocking scriptThe part of an input that meets the condition set by the locking script of the output it spends run together, covered in How Script works.

How it works

A script template is an object with two methods. lock returns the locking script of an output. unlock returns an object with sign, which builds the unlocking script of the input that spends that output, and estimateLength, which returns its size in bytes before the signature exists, so that Transaction can compute the fee.

The template on this page, HashKeyLock, accepts a spend only from the holder of a private key who also knows a secret. The locking script stores the SHA-256 hash of the secret and the hash of the public key, and the unlocking script pushes a signature, the public key and the secret:

ScriptContent
LockingOP_SHA256 <secret hash> OP_EQUALVERIFY OP_DUP OP_HASH160 <public key hash> OP_EQUALVERIFY OP_CHECKSIG
Unlocking<signature> <public key> <secret>

The unlocking script runs first and leaves the secret on top of the stack. OP_SHA256 <secret hash> OP_EQUALVERIFY hashes the secret and stops the spend if it does not match. The rest is the P2PKH check, which needs the signature and the public key under it. Three files run the example:

  • HashKeyLock.mjs is the template.
  • lock.mjs spends an output that pays your address and creates an output locked with HashKeyLock.
  • unlock.mjs spends that output back to your address with the key and the secret.

Write the template

Start with the template itself, in the folder of the Build a transaction example:

Create the template

Save this class as HashKeyLock.mjs. It builds both scripts from opcodesA one byte instruction in a locking or unlocking script, such as OP_DUP. Scripts run on a stack. and reuses the P2PKH template for the signature:

HashKeyLock.mjs
import { LockingScript, UnlockingScript, OP, P2PKH, Utils } from '@bsv/sdk'

export default class HashKeyLock {
  lock (address, secretHash) {
    const pubKeyHash = Utils.fromBase58Check(address).data
    return new LockingScript([
      { op: OP.OP_SHA256 },
      { op: secretHash.length, data: secretHash },
      { op: OP.OP_EQUALVERIFY },
      { op: OP.OP_DUP },
      { op: OP.OP_HASH160 },
      { op: pubKeyHash.length, data: pubKeyHash },
      { op: OP.OP_EQUALVERIFY },
      { op: OP.OP_CHECKSIG }
    ])
  }

  unlock (privateKey, secret) {
    if (secret.length < 1 || secret.length > 75) {
      throw new Error('The secret must be 1 to 75 bytes long')
    }
    const p2pkh = new P2PKH().unlock(privateKey)
    return {
      sign: async (tx, inputIndex) => {
        const signed = await p2pkh.sign(tx, inputIndex)
        return new UnlockingScript([
          ...signed.chunks,
          { op: secret.length, data: secret }
        ])
      },
      estimateLength: async () => (await p2pkh.estimateLength()) + 1 + secret.length
    }
  }
}
  • In lock, Utils.fromBase58Check(address).data is the 20 byte public key hash inside the address.
  • Each chunk is an opcode, or a push whose op is the length of its data. A push of 1 to 75 bytes needs no other opcode, which is why unlock limits the secret to 75 bytes.
  • sign lets P2PKH build the signature and the public key, then appends the secret. The signature commits to the locking script of the output being spent, so it is valid for the HashKeyLock script too.
  • estimateLength adds the push of the secret, 1 byte plus its length, to the 108 bytes that P2PKH estimates for the signature and the public key.

Add the secret to .env

.env holds your private key. Keep it private, never print it and never commit it.

Open .env, the file that holds your key, and add a line with the secret under the key, with a value of your own in place of open sesame:

.env
TESTNET_WIF=YOUR_TESTNET_WIF
SECRET=open sesame

Keep the TESTNET_WIF line as create-key.mjs wrote it. Both scripts read the secret from there. lock.mjs stores only its hash on chain, and unlock.mjs reveals it.

The secret becomes public in the transaction that spends the output. Anyone can then read it on the explorer, so never reuse a secret, and do not use a password you keep elsewhere. The key is still needed to spend, so the secret alone cannot move the coins.

Lock satoshis with the template

With the template ready, write lock.mjs in the same folder. It follows send.mjs of the Build a transaction example, except that its first output uses HashKeyLock instead of P2PKH:

Write the lock script

Save this script as lock.mjs. It reads the key and the secret, fetches the funding transaction and locks 500 satoshis in its output 0:

lock.mjs
import { PrivateKey, P2PKH, Transaction, SatoshisPerKilobyte, Teranode, Hash, Utils } from '@bsv/sdk'
import HashKeyLock from './HashKeyLock.mjs'

process.loadEnvFile('.env')
const { TESTNET_WIF, SECRET } = process.env
if (TESTNET_WIF === undefined || SECRET === undefined) {
  throw new Error('.env needs TESTNET_WIF and SECRET')
}
const key = PrivateKey.fromWif(TESTNET_WIF)
const address = key.toAddress('testnet')
const secret = Utils.toArray(SECRET, 'utf8')
if (secret.length < 1 || secret.length > 75) {
  throw new Error('SECRET must be 1 to 75 bytes long')
}
const secretHash = Hash.sha256(secret)

const fundingTxid = process.argv[2]
if (fundingTxid === undefined) {
  throw new Error('Pass the ID of a transaction that pays your address: node lock.mjs FUNDING_TXID')
}
const response = await fetch(`https://api.whatsonchain.com/v1/bsv/test/tx/${fundingTxid}/hex`)
if (!response.ok) {
  throw new Error(`WhatsOnChain answered ${response.status} for ${fundingTxid}`)
}
const sourceTransaction = Transaction.fromHex((await response.text()).trim())
const ownLockingScript = new P2PKH().lock(address).toHex()
const sourceOutputIndex = sourceTransaction.outputs.findIndex(
  (output) => output.lockingScript.toHex() === ownLockingScript
)
if (sourceOutputIndex === -1) {
  throw new Error(`No output of ${fundingTxid} pays ${address}`)
}

const tx = new Transaction()
tx.addInput({
  sourceTransaction,
  sourceOutputIndex,
  unlockingScriptTemplate: new P2PKH().unlock(key)
})
tx.addOutput({
  lockingScript: new HashKeyLock().lock(address, secretHash),
  satoshis: 500
})
tx.addOutput({
  lockingScript: new P2PKH().lock(address),
  change: true
})

await tx.fee(new SatoshisPerKilobyte(1))
await tx.sign()

const result = await tx.broadcast(new Teranode('https://arcade-v2-testnet-us-1.bsvblockchain.tech/tx'))
if (result.status === 'error') {
  throw new Error(`Broadcast failed: ${result.code} ${result.description}`)
}
console.log(`Locked 500 satoshis in output 0 of ${result.txid}`)
console.log(`Explorer: https://test.whatsonchain.com/tx/${result.txid}`)
  • The script checks that the secret is 1 to 75 bytes, the same limit as unlock, so it never locks an output that unlock.mjs cannot spend. Only the SHA-256 hash of the secret goes into the locking script of output 0, which new HashKeyLock().lock(address, secretHash) builds.
  • The input spends the first output of the funding transaction that pays your address, with the P2PKH template, as in send.mjs, and the change goes back to your address.

Run the lock script

Pass the transaction ID that send.mjs printed, in place of FUNDING_TXID:

node lock.mjs FUNDING_TXID

The script prints the ID of the new transaction and its explorer link. Your ID differs:

Locked 500 satoshis in output 0 of 009acb3121f8305039b609e549d7085bc5fde0a1ca1e9dc5d89383f1adef0c8d
Explorer: https://test.whatsonchain.com/tx/009acb3121f8305039b609e549d7085bc5fde0a1ca1e9dc5d89383f1adef0c8d

The explorer shows one input and two outputs: 500 satoshis in output 0 and the change. Copy the transaction ID, since unlock.mjs needs it.

Spend the locked output

The output now waits for a spend that brings both the key and the secret. Write unlock.mjs in the same folder:

Write the unlock script

Save this script as unlock.mjs. It fetches the lock transaction and spends its output 0 back to your address with the HashKeyLock unlock:

unlock.mjs
import { PrivateKey, P2PKH, Transaction, SatoshisPerKilobyte, Teranode, Utils } from '@bsv/sdk'
import HashKeyLock from './HashKeyLock.mjs'

process.loadEnvFile('.env')
const { TESTNET_WIF, SECRET } = process.env
if (TESTNET_WIF === undefined || SECRET === undefined) {
  throw new Error('.env needs TESTNET_WIF and SECRET')
}
const key = PrivateKey.fromWif(TESTNET_WIF)
const address = key.toAddress('testnet')
const secret = Utils.toArray(SECRET, 'utf8')

const lockTxid = process.argv[2]
if (lockTxid === undefined) {
  throw new Error('Pass the transaction ID that lock.mjs printed: node unlock.mjs LOCK_TXID')
}
const response = await fetch(`https://api.whatsonchain.com/v1/bsv/test/tx/${lockTxid}/hex`)
if (!response.ok) {
  throw new Error(`WhatsOnChain answered ${response.status} for ${lockTxid}`)
}
const sourceTransaction = Transaction.fromHex((await response.text()).trim())

const tx = new Transaction()
tx.addInput({
  sourceTransaction,
  sourceOutputIndex: 0,
  unlockingScriptTemplate: new HashKeyLock().unlock(key, secret)
})
tx.addOutput({
  lockingScript: new P2PKH().lock(address),
  change: true
})

await tx.fee(new SatoshisPerKilobyte(1))
await tx.sign()

const result = await tx.broadcast(new Teranode('https://arcade-v2-testnet-us-1.bsvblockchain.tech/tx'))
if (result.status === 'error') {
  throw new Error(`Broadcast failed: ${result.code} ${result.description}`)
}
console.log(`Unlocked output 0 of ${lockTxid}, fee ${tx.getFee()} satoshis`)
console.log(`Explorer: https://test.whatsonchain.com/tx/${result.txid}`)

The only template call is new HashKeyLock().unlock(key, secret). tx.fee asks it for estimateLength, and tx.sign calls its sign. The single output is change, so the 500 satoshis minus the fee return to your address.

Run the unlock script

Pass the transaction ID that lock.mjs printed, in place of LOCK_TXID:

node unlock.mjs LOCK_TXID

The script prints the output it spent, the fee and the explorer link of the spend. Your IDs differ:

Unlocked output 0 of 009acb3121f8305039b609e549d7085bc5fde0a1ca1e9dc5d89383f1adef0c8d, fee 1 satoshis
Explorer: https://test.whatsonchain.com/tx/90bf674e248cce9f55bec40027185707aca67b93806aca0053ad44dc171d53aa

WhatsOnChain can take a few seconds to list a new transaction. If unlock.mjs stops with WhatsOnChain answered 404, wait a moment and run it again.

The explorer shows one input and one output to your address, with the 500 satoshis minus the fee. A transaction on Mainnet cannot be reversed once it is broadcast, so a new template stays on testnet until both scripts work.

Troubleshooting

Broadcast fails with "Script failed an OP_EQUALVERIFY operation" #

BSV Broadcaster rejects the spend, and unlock.mjs stops with Broadcast failed: 400 and a description that contains TX_INVALID (31): Script failed an OP_EQUALVERIFY operation. The secret in .env does not hash to the value in the locking script, or the key is not the one the output was locked to. Put back the SECRET and the TESTNET_WIF that lock.mjs used, then run unlock.mjs again. The output stays locked until a valid spend arrives.

Lock script fails with "Transaction inputs are insufficient" #

The full message is RangeError: Transaction inputs are insufficient for the requested outputs and fee.. The output that lock.mjs spends holds fewer than 500 satoshis plus the fee, for example the change of a previous lock. Pass the ID of a transaction whose first output to your address is unspent and holds more, such as a new faucet payment.

Next steps

With a custom condition working, look up other opcodes for your own scripts or go back to how a spend is checked: