Transaction Signing

Complete examples for signing BSV transactions with various signature types and patterns.

Overview

This code feature demonstrates practical transaction signing patterns, including single and multi-signature transactions, different SIGHASH types, and advanced signing scenarios.

Related SDK Components:

Basic Transaction Signing

import { Transaction, PrivateKey, P2PKH, SigHash } from '@bsv/sdk'

/**
 * Basic Transaction Signing
 *
 * Sign a simple P2PKH transaction
 */
class BasicSigner {
  /**
   * Sign a transaction with a single key
   */
  async signTransaction(
    tx: Transaction,
    privateKey: PrivateKey,
    inputIndex: number = 0
  ): Promise<Transaction> {
    // Set the unlocking script template for the input
    tx.inputs[inputIndex].unlockingScriptTemplate = new P2PKH().unlock(
      privateKey,
      'all',  // SIGHASH type
      true    // Anyone can pay
    )

    // Sign the transaction
    await tx.sign()

    return tx
  }

  /**
   * Sign transaction with default SIGHASH_ALL
   */
  async signWithSigHashAll(
    tx: Transaction,
    privateKey: PrivateKey
  ): Promise<Transaction> {
    for (let i = 0; i < tx.inputs.length; i++) {
      tx.inputs[i].unlockingScriptTemplate = new P2PKH().unlock(privateKey)
    }

    await tx.sign()
    return tx
  }
}

/**
 * Usage Example
 */
async function example() {
  const signer = new BasicSigner()
  const privateKey = PrivateKey.fromWif('your-wif-key')

  const tx = new Transaction()
  // ... add inputs and outputs ...

  const signedTx = await signer.signTransaction(tx, privateKey)
  console.log('Signed transaction:', signedTx.toHex())
}

SIGHASH Types

Multi-Signature Signing

Advanced Signing Patterns

Crowdfunding Example

See Also

SDK Components:

Learning Paths:

Last updated