Spending P2PKH
P2PKH (Pay-to-Public-Key-Hash) is the Output type behind ordinary Addresses. Its Locking Script checks
that the spender’s Public Key hashes to the Address, and that the Signature is valid. The guide’s
Standard script templates page shows the script. In
DartSV the pair is P2PKHLockBuilder (for Outputs) and P2PKHUnlockBuilder (for Inputs). The single-Input case
is covered in Your first transaction.
The examples use the keys and the fundingTransaction helper described in About the examples.
Several Inputs, several keys
Section titled “Several Inputs, several keys”We give each Input the signer for the key that owns it, along with an unlocker holding that key’s Public Key:
// Each Input gets its own signer and its own Unlocking Script builder.final aliceSigner = DefaultTransactionSigner(sighashAll, aliceKey);final bobSigner = DefaultTransactionSigner(sighashAll, bobKey);
final tx = TransactionBuilder() .spendFromTxnWithSigner(aliceSigner, fundingA, 0, TransactionInput.MAX_SEQ_NUMBER, P2PKHUnlockBuilder(aliceKey.publicKey)) .spendFromTxnWithSigner(bobSigner, fundingB, 0, TransactionInput.MAX_SEQ_NUMBER, P2PKHUnlockBuilder(bobKey.publicKey)) .spendToPKH(Address('n3aZKucfWmXeXhX13MREQQnqNfbrWiYKtg'), BigInt.from(40000)) .spendToPKH(Address('mrU9pEmAx26HcbKVrABvgL7AwA5fjNFoDc'), BigInt.from(60000)) .sendChangeToPKH(aliceAddress) .build(true);Then we check every Input against the Output it spends. Each Input is verified on its own:
// Let's verify every Input against the Output it spends.final spent = [fundingA.outputs[0], fundingB.outputs[0]];for (var i = 0; i < tx.inputs.length; i++) { Interpreter().correctlySpends(tx.inputs[i].script!, spent[i].script, tx, i, {VerifyFlag.SIGHASH_FORKID, VerifyFlag.UTXO_AFTER_GENESIS}, Coin.ofSat(spent[i].satoshis));}Reading an Unlocking Script
Section titled “Reading an Unlocking Script”P2PKHUnlockBuilder.fromScript splits a P2PKH Unlocking Script into the Signature and the Public Key. This
comes in handy when we want to see which key signed an Input of a Transaction we received:
// scriptSig: an Input's Unlocking Script, e.g. from a parsed Transaction.final unlock = P2PKHUnlockBuilder.fromScript(scriptSig);
unlock.signerPubkey!.toHex(); // the public key that signedunlock.signatures[0].toTxFormat(); // DER signature plus the sighash byte
