Class: BSV::Transaction::P2PKH

Inherits:
UnlockingScriptTemplate show all
Defined in:
lib/bsv/transaction/p2pkh.rb

Overview

P2PKH unlocking script template for deferred transaction signing.

Holds a private key and sighash type, generating the unlocking script (signature + public key) when #sign is called with the full transaction.

Examples:

Attach a P2PKH template to an input

input.unlocking_script_template = BSV::Transaction::P2PKH.new(private_key)
tx.sign_all  # generates the unlocking script

Constant Summary collapse

ESTIMATED_SCRIPT_LENGTH =

Estimated unlocking script length: 1 + ~72 (DER sig + hashtype) + 1 + 33 (compressed pubkey).

107

Instance Method Summary collapse

Constructor Details

#initialize(private_key, sighash_type: Sighash::ALL_FORK_ID) ⇒ P2PKH

Returns a new instance of P2PKH.

Parameters:

  • private_key (Primitives::PrivateKey)

    the signing key

  • sighash_type (Integer) (defaults to: Sighash::ALL_FORK_ID)

    sighash flags (default: ALL_FORK_ID)



19
20
21
22
23
# File 'lib/bsv/transaction/p2pkh.rb', line 19

def initialize(private_key, sighash_type: Sighash::ALL_FORK_ID)
  super()
  @private_key = private_key
  @sighash_type = sighash_type
end

Instance Method Details

#estimated_length(_tx, _input_index) ⇒ Integer

Returns estimated script length for fee calculation.

Returns:

  • (Integer)

    estimated script length for fee calculation



39
40
41
# File 'lib/bsv/transaction/p2pkh.rb', line 39

def estimated_length(_tx, _input_index)
  ESTIMATED_SCRIPT_LENGTH
end

#sign(tx, input_index) ⇒ Script::Script

Generate the P2PKH unlocking script for the given input.

Parameters:

  • tx (Transaction)

    the transaction being signed

  • input_index (Integer)

    the input index to sign

Returns:



30
31
32
33
34
35
36
# File 'lib/bsv/transaction/p2pkh.rb', line 30

def sign(tx, input_index)
  hash = tx.sighash(input_index, @sighash_type)
  signature = @private_key.sign(hash)
  sig_with_hashtype = signature.to_der + [@sighash_type].pack('C')
  pubkey_bytes = @private_key.public_key.compressed
  BSV::Script::Script.p2pkh_unlock(sig_with_hashtype, pubkey_bytes)
end