BSV blockchainBSV blockchain

How Script works

Every output on the BSV blockchain carries a locking scriptThe part of a transaction output that sets the condition to spend it that sets the condition to spend it, and every input carries an unlocking scriptThe part of an input that meets the condition set by the locking script of the output it spends that meets that condition. Both are written in Script, a small stack based language. A wallet builds these scripts for you, so you meet Script when you lock an output to a custom condition, read what an output says, or find out why a spend was rejected.

Step through the most common script, P2PKHPay to Public Key Hash, an output that only the key behind one address can spend, to see how the two work together, and check a spend in code with @bsv/sdk, which has the classes that build and check scripts. How transactions and fees work covers the transaction around them. This page was written against @bsv/sdk 4.0.1.

A locking and an unlocking script

A script is a list of chunks read from left to right. A chunk is either data, which is pushed on a stack, or an opcode, which takes items off the stack and puts a result back. The examples on this page run with Node.js after npm install @bsv/sdk.

Each example generates a new random private key on every run, only to try the scripts. Never put a private key that holds value in code, and never commit one to version control.

lock.mjs
import { PrivateKey, P2PKH } from '@bsv/sdk'

const key = PrivateKey.fromRandom()
const lockingScript = new P2PKH().lock(key.toPublicKey().toAddress('testnet'))

console.log(lockingScript.toASM())
console.log(lockingScript.toHex())

The hash differs on every run, because the key is new:

OP_DUP OP_HASH160 ad8dc0311ea55f42110c2e2c4034e2588e099088 OP_EQUALVERIFY OP_CHECKSIG
76a914ad8dc0311ea55f42110c2e2c4034e2588e09908888ac

The locking script holds only the hash of a public key, so it works the same on testnet and on Mainnet. The unlocking script that meets it is two pushes, a signature and the public key.

How a spend is checked

The network checks every input the same way. It runs the unlocking script first, then the locking script on the same stack. The two scripts run in turn and are not joined into one. In @bsv/sdk, a spend is valid when the unlocking script only pushes data and the stack ends with exactly one item that is nonzero.

The stack step by step

Press Step to walk through the P2PKH pair one chunk at a time, then switch to Another key and run it again to watch the spend fail.

The unlocking script was made with

Unlocking script

signaturepublic key

Locking script

OP_DUPOP_HASH160hash from the addressOP_EQUALVERIFYOP_CHECKSIG

Stack

empty
0 of 7

Both scripts are ready and the stack is empty. The unlocking script runs first.

Step 0 of 7. Both scripts are ready and the stack is empty. The unlocking script runs first.

OP_HASH160 is a SHA-256 followed by a RIPEMD-160, the same hash an address holds.

Check a spend in code

Spend in @bsv/sdk is the interpreter that runs these steps in your own code. It needs the output being spent and the input that spends it. This example spends the same output twice, once with the key that owns it and once with a different key:

spend.mjs
import { PrivateKey, P2PKH, Transaction, Spend } from '@bsv/sdk'

const owner = PrivateKey.fromRandom()
const stranger = PrivateKey.fromRandom()
const lockingScript = new P2PKH().lock(owner.toPublicKey().toAddress('testnet'))
const source = new Transaction(1, [], [{ lockingScript, satoshis: 1000 }])

async function check (signer) {
  const tx = new Transaction(1, [{
    sourceTransaction: source,
    sourceOutputIndex: 0,
    unlockingScriptTemplate: new P2PKH().unlock(signer),
    sequence: 0xffffffff
  }], [{ lockingScript, satoshis: 900 }])
  await tx.sign()

  const spend = new Spend({
    sourceTXID: source.id('hex'),
    sourceOutputIndex: 0,
    sourceSatoshis: 1000,
    lockingScript,
    transactionVersion: tx.version,
    otherInputs: [],
    outputs: tx.outputs,
    unlockingScript: tx.inputs[0].unlockingScript,
    inputSequence: tx.inputs[0].sequence,
    inputIndex: 0,
    lockTime: tx.lockTime
  })

  try {
    console.log('valid:', spend.validate())
  } catch (error) {
    console.log('rejected:', error.message.split('\n')[0])
  }
}

await check(owner)
await check(stranger)

source stands in for the earlier transaction, with one output of 1,000 satoshisThe smallest unit of BitcoinSV (BSV). 100,000,000 satoshis make 1 BSV locked to the owner. The input sets a sequence because the P2PKH template cannot sign an input without one. Running the file prints:

valid: true
rejected: Script evaluation error: OP_EQUALVERIFY requires the top two stack items to be equal.

validate() returns true or throws an error that says why the spend failed, and for a failed opcode it names the opcode and its position. It never returns false, so wrap it in try and catch. To watch the stack change, call spend.step() in a loop. Each call runs one chunk and returns false once both scripts are done, and spend.stack holds the stack after each step.

A passing check means the two scripts are satisfied. The network also validates the rest of the transaction.

Script templates

A script template packages one kind of script. Its lock method builds a locking script, and its unlock method returns an object with sign, which builds the unlocking script for one input, and estimateLength, which returns the size that script is expected to have.

Templates in @bsv/sdk

Switch between P2PKH, PushDropA template that locks data fields to a public key, so an output can carry data and still be spent and RPuzzleA template that locks an output with an R puzzle, which the spender unlocks with the matching K value to compare what lock and unlock take and return.

new P2PKH().lock(address)

  • address a P2PKH address, such as the one from toAddress()

returns a locking script

Locking script

OP_DUPOP_HASH16020 byte hashOP_EQUALVERIFYOP_CHECKSIG

new P2PKH().unlock(privateKey)

returns an object

sign builds the unlocking script for one input, once the transaction exists

Unlocking script from sign

signaturepublic key

estimateLength returns the expected size in bytes, before any signature exists

Estimated size108 bytes

P2PKH: lock takes address. unlock takes privateKey and returns sign and estimateLength, which estimates 108 bytes.

A fee depends on the size of the transaction, and a signature does not exist until the transaction is signed. The SDK therefore takes the size of each unlocking script from estimateLength when it computes the fee. You pass a template as the unlockingScriptTemplate of an input, as spend.mjs does.

Lock data with PushDrop

PushDrop locks data fields to a public key, so an output can carry data and still be spent. Overlay protocols use it. It takes its keys from a wallet, so its lock needs a wallet object as well as the data. This example uses ProtoWallet, a class in @bsv/sdk that signs and derives keys on its own and needs no network:

pushdrop.mjs
import { PrivateKey, PushDrop, ProtoWallet, Utils } from '@bsv/sdk'

const wallet = new ProtoWallet(PrivateKey.fromRandom())
const fields = [Utils.toArray('hello', 'utf8'), Utils.toArray('world', 'utf8')]

const lockingScript = await new PushDrop(wallet).lock(fields, [0, 'demo token'], '1', 'self')

console.log(lockingScript.toASM())

The key, the signature and the hex of the fields differ on every run. The script has this shape:

03919c18...(33 byte public key) OP_CHECKSIG 68656c6c6f 776f726c64 30450221...(71 byte signature) OP_2DROP OP_DROP

Utils.toArray turns text into the bytes of a field, and 68656c6c6f and 776f726c64 are hello and world in hex. The public key and OP_CHECKSIG come first, so only the holder of that key can spend the output. OP_2DROP and OP_DROP remove the two fields and the signature from the stack again, so the data does not change what the script has to prove.

The security level in protocolID sets how much approval a wallet asks for: none at 0, approval for each application at 1, and approval for each counterparty and application at 2. The name must be 5 to 400 bytes, so 'demo token' works where 'demo' does not. ProtoWallet rejects a shorter name with the message The protocolID[1] parameter must be at least 5 length.

Scripts that carry data

An output can store data in its script. A locking script that starts with OP_FALSE OP_RETURNAn opcode that ends the script, so nothing can spend the output followed by data pushes keeps the data on chain, and no unlocking script can satisfy it, because OP_RETURN ends the script with a false value on top of the stack. This example builds one:

data.mjs
import { Script } from '@bsv/sdk'

const lockingScript = Script.fromASM('OP_FALSE OP_RETURN 68656c6c6f')

console.log(lockingScript.toHex())
console.log(lockingScript.toASM())
006a0568656c6c6f
OP_0 OP_RETURN 68656c6c6f

toASM writes OP_FALSE as OP_0. Use PushDrop instead when the output has to stay spendable.

Scripts in a wallet

A BRC-100BSV Request for Comments 100, the standard interface between a wallet and an app wallet takes and returns scripts as hex strings. Each output of createAction has a lockingScript in hex, which is what toHex() returns, and listOutputs returns the locking script of an output only when you pass include: 'locking scripts'. An input of createAction takes an unlockingScript in hex, or an unlockingScriptLength when you supply the script later with signAction. BRC-100 Wallet Interface describes the calls.

To learn more about Script on the BSV blockchain, review these articles: