# How Script works

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Understand locking and unlocking scripts, how a spend is checked on one stack, and how script templates in @bsv/sdk package them.

import ScriptStepper from '/snippets/ScriptStepper.jsx';
import ScriptTemplates from '/snippets/ScriptTemplates.jsx';

Every output on the BSV blockchain carries a locking script (The 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 script (The 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, P2PKH (Pay 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](https://bsvblockchain.com/docs/concepts/transactions/) 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.

```javascript 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:

```text
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.

<ScriptStepper />

The diagram has the unlocking script and the locking script on the left and the stack on the right. Seven steps run in order. Step 1, the unlocking script pushes the signature. Step 2, it pushes the public key. Step 3, OP_DUP copies the public key, so the stack holds the signature and two copies of the public key. Step 4, OP_HASH160 replaces the top copy with its hash. Step 5, the locking script pushes the hash from the address. Step 6, OP_EQUALVERIFY finds the two hashes equal and removes them, leaving the signature and the public key. Step 7, OP_CHECKSIG checks the signature and leaves 01, so the spend is valid. With a different key, the hash of that key differs from the hash in the address at step 6, OP_EQUALVERIFY fails and the script stops before OP_CHECKSIG.

`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:

```javascript 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 satoshis (The 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:

```text
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`, `PushDrop` (A template that locks data fields to a public key, so an output can carry data and still be spent) and `RPuzzle` (A 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.

<ScriptTemplates />

The diagram has a tab for each template and two cards. The left card shows the call to lock and the locking script it returns. The right card shows the call to unlock, which returns an object with sign and estimateLength, the unlocking script that sign builds, and the size estimateLength returns. P2PKH: lock takes an address and returns OP_DUP OP_HASH160, a 20 byte hash, OP_EQUALVERIFY, OP_CHECKSIG. unlock takes a private key, the unlocking script is a signature and a public key, and the estimate is 108 bytes. PushDrop: lock takes fields (one byte array per data field), a protocol ID (a security level of 0, 1 or 2 and a name of 5 to 400 bytes), a key ID and a counterparty (self, anyone or a public key in hex), and returns a public key, OP_CHECKSIG, the fields, a signature, OP_2DROP, OP_DROP. unlock takes a protocol ID, a key ID and a counterparty, the unlocking script is a signature, and the estimate is 73 bytes. RPuzzle: lock takes a value and returns thirteen opcodes and data pushes that end with a 20 byte hash, OP_EQUALVERIFY and OP_CHECKSIG. unlock takes the K value and a private key, the unlocking script is a signature and a public key, and the estimate is 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](https://bsvblockchain.com/docs/concepts/overlays/) 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:

```javascript 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:

```text
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_RETURN` (An 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:

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

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

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

```text
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-100 (BSV 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](https://bsvblockchain.com/docs/concepts/wallet-model/) describes the calls.

## Related articles

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

- [How transactions and fees work](https://bsvblockchain.com/docs/concepts/transactions/)
- [How keys and identity work](https://bsvblockchain.com/docs/concepts/keys-identity/)
- [Script opcodes](https://bsvblockchain.com/docs/reference/script-opcodes/)
- [Write a custom script template](https://bsvblockchain.com/docs/sdk/typescript/low-level/script-templates/)