P2PKH Template

Complete examples for using the Pay-to-Public-Key-Hash (P2PKH) template with all SIGHASH types.

Overview

This code feature demonstrates the P2PKH template, the most common Bitcoin transaction type. P2PKH locks coins to a public key hash (Bitcoin address) and requires a signature from the corresponding private key to unlock them. This guide covers all signature hash types and their practical applications.

Related SDK Components:

Basic P2PKH Transaction

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

/**
 * Basic P2PKH Transaction
 *
 * Creates a standard transaction using P2PKH template for both locking and unlocking
 */
class BasicP2PKH {
  /**
   * Create a simple P2PKH payment
   */
  async createPayment(
    fromPrivateKey: PrivateKey,
    toAddress: string,
    amount: number,
    utxo: { txid: string; vout: number; satoshis: number }
  ): Promise<Transaction> {
    const tx = new Transaction()

    // Add input with P2PKH unlocking template
    tx.addInput({
      sourceTXID: utxo.txid,
      sourceOutputIndex: utxo.vout,
      unlockingScriptTemplate: new P2PKH().unlock(fromPrivateKey),
      sequence: 0xffffffff
    })

    // Add output with P2PKH locking script (to address)
    tx.addOutput({
      satoshis: amount,
      lockingScript: Script.fromAddress(toAddress)
    })

    // Add change output with P2PKH locking script (to public key hash)
    const fee = 500
    const changeAmount = utxo.satoshis - amount - fee

    if (changeAmount > 546) { // Above dust limit
      tx.addOutput({
        satoshis: changeAmount,
        lockingScript: new P2PKH().lock(fromPrivateKey.toPublicKey().toHash())
      })
    }

    // Sign the transaction
    await tx.sign()

    return tx
  }

  /**
   * Lock coins to a public key hash
   */
  lockToPublicKeyHash(publicKeyHash: number[]): Script {
    return new P2PKH().lock(publicKeyHash)
  }

  /**
   * Lock coins to an address
   */
  lockToAddress(address: string): Script {
    return Script.fromAddress(address)
  }

  /**
   * Create unlocking template for P2PKH
   */
  createUnlockingTemplate(privateKey: PrivateKey): P2PKH {
    return new P2PKH().unlock(privateKey)
  }
}

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

  const utxo = {
    txid: 'abc123...',
    vout: 0,
    satoshis: 100000
  }

  const tx = await p2pkh.createPayment(
    privateKey,
    '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
    50000,
    utxo
  )

  console.log('Transaction ID:', tx.id('hex'))
  console.log('Transaction hex:', tx.toHex())
}

P2PKH with All SIGHASH Types

Advanced P2PKH Patterns

Crowdfunding with P2PKH and ANYONECANPAY

See Also

SDK Components:

Learning Paths:

Last updated