Script

Overview

The Script class in the BSV TypeScript SDK provides a comprehensive implementation of Bitcoin Script, the stack-based programming language used to define spending conditions for Bitcoin transactions. It enables creation, manipulation, parsing, and execution of Bitcoin scripts with support for all opcodes, script templates, and advanced scripting patterns.

Purpose

  • Create and parse Bitcoin scripts (locking and unlocking scripts)

  • Execute Bitcoin Script operations with a stack-based virtual machine

  • Support all Bitcoin opcodes including arithmetic, cryptographic, and flow control operations

  • Serialize scripts to binary, hexadecimal, and ASM (assembly) formats

  • Parse scripts from various formats (hex, binary, ASM)

  • Build custom spending conditions and smart contracts

  • Implement standard script templates (P2PKH, P2PK, OP_RETURN, etc.)

Basic Usage

import { Script, OP } from '@bsv/sdk';

// Create a simple script using opcodes
const script = new Script()
  .writeOpCode(OP.OP_DUP)
  .writeOpCode(OP.OP_HASH160)
  .writeBin(Buffer.from('89abcdefabbaabbaabbaabbaabbaabbaabbaabba', 'hex'))
  .writeOpCode(OP.OP_EQUALVERIFY)
  .writeOpCode(OP.OP_CHECKSIG);

// Serialize to hex
console.log('Script hex:', script.toHex());

// Parse from hex
const parsedScript = Script.fromHex('76a91489abcdefabbaabbaabbaabbaabbaabbaabbaabba88ac');

// Convert to ASM (assembly format)
console.log('Script ASM:', parsedScript.toASM());
// Output: "OP_DUP OP_HASH160 89abcdefabbaabbaabbaabbaabbaabbaabbaabba OP_EQUALVERIFY OP_CHECKSIG"

// Get script binary
const binary = script.toBinary();
console.log('Script length:', binary.length);

Key Features

1. Script Construction with Opcodes

Build scripts using the complete set of Bitcoin opcodes:

2. Script Parsing and Serialization

Convert scripts between different formats:

3. Script Execution and Validation

Execute scripts with the Bitcoin Script interpreter:

4. Advanced Script Patterns

Implement complex spending conditions:

API Reference

Constructor

Creates a new empty Script instance.

Static Methods

Script.fromHex(hex: string): Script

Parses a script from hexadecimal string.

Parameters:

  • hex: string - Hexadecimal representation of the script

Returns: Script - The parsed script

Example:

Script.fromBinary(bin: number[]): Script

Parses a script from binary array.

Parameters:

  • bin: number[] - Binary representation of the script

Returns: Script - The parsed script

Script.fromASM(asm: string): Script

Parses a script from ASM (assembly) string.

Parameters:

  • asm: string - ASM representation (e.g., "OP_DUP OP_HASH160 ... OP_CHECKSIG")

Returns: Script - The parsed script

Example:

Instance Methods

writeOpCode(opcode: number): Script

Appends an opcode to the script.

Parameters:

  • opcode: number - The opcode to append (from OP enum)

Returns: Script - The script instance (for chaining)

Example:

writeBin(data: number[] | Buffer): Script

Appends data to the script with appropriate push operation.

Parameters:

  • data: number[] | Buffer - The data to append

Returns: Script - The script instance (for chaining)

Example:

writeNumber(num: number): Script

Appends a number to the script.

Parameters:

  • num: number - The number to append

Returns: Script - The script instance (for chaining)

Example:

toHex(): string

Converts the script to hexadecimal string.

Returns: string - Hexadecimal representation

toBinary(): number[]

Converts the script to binary array.

Returns: number[] - Binary representation

toASM(): string

Converts the script to ASM (assembly) format.

Returns: string - Human-readable ASM representation

Example:

isPublicKeyHashOutput(): boolean

Checks if the script is a standard P2PKH output.

Returns: boolean - True if P2PKH format

isPublicKeyHashInput(): boolean

Checks if the script is a standard P2PKH input.

Returns: boolean - True if P2PKH input format

isPushOnly(): boolean

Checks if the script contains only data push operations.

Returns: boolean - True if push-only

Instance Properties

Script Chunk Structure

Common Patterns

Pattern 1: Creating Standard Transaction Scripts

Build standard Bitcoin transaction scripts:

Pattern 2: Script Templates for Smart Contracts

Create reusable script templates:

Pattern 3: Script Analysis and Validation

Analyze and validate scripts:

Security Considerations

  1. Script Size Limits: BSV allows larger scripts than BTC, but validate reasonable limits for your use case.

  2. Disabled Opcodes: Some opcodes were disabled in early Bitcoin but are being re-enabled in BSV. Verify which opcodes are available on your target network.

  3. Stack Size: The maximum stack size is 1,000 elements. Design scripts that stay within this limit.

  4. Push Data Size: Individual data pushes are limited to 520 bytes in standard transactions.

  5. Script Validation: Always validate scripts before broadcasting to prevent rejection and fee loss.

  6. OP_RETURN Data: While BSV allows large OP_RETURN outputs, miners may have different policies. Verify with your mining pool.

Performance Considerations

  1. Script Complexity: More complex scripts require more computation. Keep scripts as simple as possible.

  2. Data Size: Large data outputs increase transaction size and fees. Consider using overlay networks for large data.

  3. Branching: IF/ELSE statements add complexity. Minimize branching when possible.

  4. Push Operations: Multiple small pushes are less efficient than fewer larger pushes.

  5. Parsing Overhead: ASM parsing is slower than binary parsing. Use binary format when performance matters.

Code Examples

See complete working examples in:

Best Practices

  1. Use standard templates when possible (P2PKH, P2PK) for better compatibility

  2. Test scripts thoroughly before deploying with real funds

  3. Validate script size before broadcasting transactions

  4. Use OP_RETURN for data storage, not other opcodes

  5. Document custom scripts with clear comments explaining logic

  6. Minimize script complexity to reduce validation time and potential bugs

  7. Use ASM format for human readability during development

  8. Store scripts as hex in production for efficiency

  9. Implement proper error handling for script parsing and execution

  10. Follow BRC standards for script templates and protocols

Troubleshooting

Issue: Script parsing fails

Solution: Ensure the hex/binary format is valid and complete.

Issue: Script too large

Solution: Optimize script or split data across multiple outputs.

Issue: OP_RETURN data not extracted correctly

Solution: Ensure proper parsing of OP_RETURN chunks.

Issue: Script execution fails

Solution: Verify all required data is on the stack and opcodes are valid.

Further Reading

Status

✅ Complete

Last updated