1 // Copyright (c) 2013-2017 The btcsuite developers
2 // Use of this source code is governed by an ISC
3 // license that can be found in the LICENSE file.
10 "github.com/btcsuite/btcd/chaincfg"
11 "github.com/btcsuite/btcd/wire"
12 "github.com/btcsuite/btcutil"
16 // MaxDataCarrierSize is the maximum number of bytes allowed in pushed
17 // data to be considered a nulldata transaction
18 MaxDataCarrierSize = 80
20 // StandardVerifyFlags are the script flags which are used when
21 // executing transaction scripts to enforce additional checks which
22 // are required for the script to be considered standard. These checks
23 // help reduce issues related to transaction malleability as well as
24 // allow pay-to-script hash transactions. Note these flags are
25 // different than what is required for the consensus rules in that they
28 // TODO: This definition does not belong here. It belongs in a policy
30 StandardVerifyFlags = ScriptBip16 |
31 ScriptVerifyDERSignatures |
32 ScriptVerifyStrictEncoding |
33 ScriptVerifyMinimalData |
34 ScriptStrictMultiSig |
35 ScriptDiscourageUpgradableNops |
36 ScriptVerifyCleanStack |
37 ScriptVerifyNullFail |
38 ScriptVerifyCheckLockTimeVerify |
39 ScriptVerifyCheckSequenceVerify |
41 ScriptStrictMultiSig |
43 ScriptVerifyDiscourageUpgradeableWitnessProgram |
44 ScriptVerifyMinimalIf |
45 ScriptVerifyWitnessPubKeyType
48 // ScriptClass is an enumeration for the list of standard types of script.
51 // Classes of script payment known about in the blockchain.
53 NonStandardTy ScriptClass = iota // None of the recognized forms.
54 PubKeyTy // Pay pubkey.
55 PubKeyHashTy // Pay pubkey hash.
56 WitnessV0PubKeyHashTy // Pay witness pubkey hash.
57 ScriptHashTy // Pay to script hash.
58 WitnessV0ScriptHashTy // Pay to witness script hash.
59 MultiSigTy // Multi signature.
60 NullDataTy // Empty data-only (provably prunable).
63 // scriptClassToName houses the human-readable strings which describe each
65 var scriptClassToName = []string{
66 NonStandardTy: "nonstandard",
68 PubKeyHashTy: "pubkeyhash",
69 WitnessV0PubKeyHashTy: "witness_v0_keyhash",
70 ScriptHashTy: "scripthash",
71 WitnessV0ScriptHashTy: "witness_v0_scripthash",
72 MultiSigTy: "multisig",
73 NullDataTy: "nulldata",
76 // String implements the Stringer interface by returning the name of
77 // the enum script class. If the enum is invalid then "Invalid" will be
79 func (t ScriptClass) String() string {
80 if int(t) > len(scriptClassToName) || int(t) < 0 {
83 return scriptClassToName[t]
86 // isPubkey returns true if the script passed is a pay-to-pubkey transaction,
88 func isPubkey(pops []parsedOpcode) bool {
89 // Valid pubkeys are either 33 or 65 bytes.
90 return len(pops) == 2 &&
91 (len(pops[0].data) == 33 || len(pops[0].data) == 65) &&
92 pops[1].opcode.value == OP_CHECKSIG
95 // isPubkeyHash returns true if the script passed is a pay-to-pubkey-hash
96 // transaction, false otherwise.
97 func isPubkeyHash(pops []parsedOpcode) bool {
98 return len(pops) == 5 &&
99 pops[0].opcode.value == OP_DUP &&
100 pops[1].opcode.value == OP_HASH160 &&
101 pops[2].opcode.value == OP_DATA_20 &&
102 pops[3].opcode.value == OP_EQUALVERIFY &&
103 pops[4].opcode.value == OP_CHECKSIG
107 // isMultiSig returns true if the passed script is a multisig transaction, false
109 func isMultiSig(pops []parsedOpcode) bool {
110 // The absolute minimum is 1 pubkey:
111 // OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG
116 if !isSmallInt(pops[0].opcode) {
119 if !isSmallInt(pops[l-2].opcode) {
122 if pops[l-1].opcode.value != OP_CHECKMULTISIG {
126 // Verify the number of pubkeys specified matches the actual number
127 // of pubkeys provided.
128 if l-2-1 != asSmallInt(pops[l-2].opcode) {
132 for _, pop := range pops[1 : l-2] {
133 // Valid pubkeys are either 33 or 65 bytes.
134 if len(pop.data) != 33 && len(pop.data) != 65 {
141 // isNullData returns true if the passed script is a null data transaction,
143 func isNullData(pops []parsedOpcode) bool {
144 // A nulldata transaction is either a single OP_RETURN or an
145 // OP_RETURN SMALLDATA (where SMALLDATA is a data push up to
146 // MaxDataCarrierSize bytes).
148 if l == 1 && pops[0].opcode.value == OP_RETURN {
153 pops[0].opcode.value == OP_RETURN &&
154 (isSmallInt(pops[1].opcode) || pops[1].opcode.value <=
156 len(pops[1].data) <= MaxDataCarrierSize
159 // scriptType returns the type of the script being inspected from the known
161 func typeOfScript(pops []parsedOpcode) ScriptClass {
164 } else if isPubkeyHash(pops) {
166 } else if isWitnessPubKeyHash(pops) {
167 return WitnessV0PubKeyHashTy
168 } else if isScriptHash(pops) {
170 } else if isWitnessScriptHash(pops) {
171 return WitnessV0ScriptHashTy
172 } else if isMultiSig(pops) {
174 } else if isNullData(pops) {
180 // GetScriptClass returns the class of the script passed.
182 // NonStandardTy will be returned when the script does not parse.
183 func GetScriptClass(script []byte) ScriptClass {
184 pops, err := parseScript(script)
188 return typeOfScript(pops)
191 // expectedInputs returns the number of arguments required by a script.
192 // If the script is of unknown type such that the number can not be determined
193 // then -1 is returned. We are an internal function and thus assume that class
194 // is the real class of pops (and we can thus assume things that were determined
195 // while finding out the type).
196 func expectedInputs(pops []parsedOpcode, class ScriptClass) int {
204 case WitnessV0PubKeyHashTy:
208 // Not including script. That is handled by the caller.
211 case WitnessV0ScriptHashTy:
212 // Not including script. That is handled by the caller.
216 // Standard multisig has a push a small number for the number
217 // of sigs and number of keys. Check the first push instruction
218 // to see how many arguments are expected. typeOfScript already
219 // checked this so we know it'll be a small int. Also, due to
220 // the original bitcoind bug where OP_CHECKMULTISIG pops an
221 // additional item from the stack, add an extra expected input
222 // for the extra push that is required to compensate.
223 return asSmallInt(pops[0].opcode) + 1
232 // ScriptInfo houses information about a script pair that is determined by
234 type ScriptInfo struct {
235 // PkScriptClass is the class of the public key script and is equivalent
236 // to calling GetScriptClass on it.
237 PkScriptClass ScriptClass
239 // NumInputs is the number of inputs provided by the public key script.
242 // ExpectedInputs is the number of outputs required by the signature
243 // script and any pay-to-script-hash scripts. The number will be -1 if
247 // SigOps is the number of signature operations in the script pair.
251 // CalcScriptInfo returns a structure providing data about the provided script
252 // pair. It will error if the pair is in someway invalid such that they can not
253 // be analysed, i.e. if they do not parse or the pkScript is not a push-only
255 func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
256 bip16, segwit bool) (*ScriptInfo, error) {
258 sigPops, err := parseScript(sigScript)
263 pkPops, err := parseScript(pkScript)
268 // Push only sigScript makes little sense.
269 si := new(ScriptInfo)
270 si.PkScriptClass = typeOfScript(pkPops)
272 // Can't have a signature script that doesn't just push data.
273 if !isPushOnly(sigPops) {
274 return nil, scriptError(ErrNotPushOnly,
275 "signature script is not push only")
278 si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass)
281 // Count sigops taking into account pay-to-script-hash.
282 case si.PkScriptClass == ScriptHashTy && bip16 && !segwit:
283 // The pay-to-hash-script is the final data push of the
285 script := sigPops[len(sigPops)-1].data
286 shPops, err := parseScript(script)
291 shInputs := expectedInputs(shPops, typeOfScript(shPops))
293 si.ExpectedInputs = -1
295 si.ExpectedInputs += shInputs
297 si.SigOps = getSigOpCount(shPops, true)
299 // All entries pushed to stack (or are OP_RESERVED and exec
301 si.NumInputs = len(sigPops)
303 // If segwit is active, and this is a regular p2wkh output, then we'll
304 // treat the script as a p2pkh output in essence.
305 case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit:
307 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
308 si.NumInputs = len(witness)
310 // We'll attempt to detect the nested p2sh case so we can accurately
311 // count the signature operations involved.
312 case si.PkScriptClass == ScriptHashTy &&
313 IsWitnessProgram(sigScript[1:]) && bip16 && segwit:
315 // Extract the pushed witness program from the sigScript so we
316 // can determine the number of expected inputs.
317 pkPops, _ := parseScript(sigScript[1:])
318 shInputs := expectedInputs(pkPops, typeOfScript(pkPops))
320 si.ExpectedInputs = -1
322 si.ExpectedInputs += shInputs
325 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
327 si.NumInputs = len(witness)
328 si.NumInputs += len(sigPops)
330 // If segwit is active, and this is a p2wsh output, then we'll need to
331 // examine the witness script to generate accurate script info.
332 case si.PkScriptClass == WitnessV0ScriptHashTy && segwit:
333 // The witness script is the final element of the witness
335 witnessScript := witness[len(witness)-1]
336 pops, _ := parseScript(witnessScript)
338 shInputs := expectedInputs(pops, typeOfScript(pops))
340 si.ExpectedInputs = -1
342 si.ExpectedInputs += shInputs
345 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
346 si.NumInputs = len(witness)
349 si.SigOps = getSigOpCount(pkPops, true)
351 // All entries pushed to stack (or are OP_RESERVED and exec
353 si.NumInputs = len(sigPops)
359 // CalcMultiSigStats returns the number of public keys and signatures from
360 // a multi-signature transaction script. The passed script MUST already be
361 // known to be a multi-signature script.
362 func CalcMultiSigStats(script []byte) (int, int, error) {
363 pops, err := parseScript(script)
368 // A multi-signature script is of the pattern:
369 // NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG
370 // Therefore the number of signatures is the oldest item on the stack
371 // and the number of pubkeys is the 2nd to last. Also, the absolute
372 // minimum for a multi-signature script is 1 pubkey, so at least 4
373 // items must be on the stack per:
374 // OP_1 PUBKEY OP_1 OP_CHECKMULTISIG
376 str := fmt.Sprintf("script %x is not a multisig script", script)
377 return 0, 0, scriptError(ErrNotMultisigScript, str)
380 numSigs := asSmallInt(pops[0].opcode)
381 numPubKeys := asSmallInt(pops[len(pops)-2].opcode)
382 return numPubKeys, numSigs, nil
385 // payToPubKeyHashScript creates a new script to pay a transaction
386 // output to a 20-byte pubkey hash. It is expected that the input is a valid
388 func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
389 return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160).
390 AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG).
394 // payToWitnessPubKeyHashScript creates a new script to pay to a version 0
395 // pubkey hash witness program. The passed hash is expected to be valid.
396 func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) {
397 return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script()
400 // payToScriptHashScript creates a new script to pay a transaction output to a
401 // script hash. It is expected that the input is a valid hash.
402 func payToScriptHashScript(scriptHash []byte) ([]byte, error) {
403 return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash).
404 AddOp(OP_EQUAL).Script()
407 // payToWitnessPubKeyHashScript creates a new script to pay to a version 0
408 // script hash witness program. The passed hash is expected to be valid.
409 func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) {
410 return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script()
413 // payToPubkeyScript creates a new script to pay a transaction output to a
414 // public key. It is expected that the input is a valid pubkey.
415 func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) {
416 return NewScriptBuilder().AddData(serializedPubKey).
417 AddOp(OP_CHECKSIG).Script()
420 // PayToAddrScript creates a new script to pay a transaction output to a the
421 // specified address.
422 func PayToAddrScript(addr btcutil.Address) ([]byte, error) {
423 const nilAddrErrStr = "unable to generate payment script for nil address"
425 switch addr := addr.(type) {
426 case *btcutil.AddressPubKeyHash:
428 return nil, scriptError(ErrUnsupportedAddress,
431 return payToPubKeyHashScript(addr.ScriptAddress())
433 case *btcutil.AddressScriptHash:
435 return nil, scriptError(ErrUnsupportedAddress,
438 return payToScriptHashScript(addr.ScriptAddress())
440 case *btcutil.AddressPubKey:
442 return nil, scriptError(ErrUnsupportedAddress,
445 return payToPubKeyScript(addr.ScriptAddress())
447 case *btcutil.AddressWitnessPubKeyHash:
449 return nil, scriptError(ErrUnsupportedAddress,
452 return payToWitnessPubKeyHashScript(addr.ScriptAddress())
453 case *btcutil.AddressWitnessScriptHash:
455 return nil, scriptError(ErrUnsupportedAddress,
458 return payToWitnessScriptHashScript(addr.ScriptAddress())
461 str := fmt.Sprintf("unable to generate payment script for unsupported "+
462 "address type %T", addr)
463 return nil, scriptError(ErrUnsupportedAddress, str)
466 // NullDataScript creates a provably-prunable script containing OP_RETURN
467 // followed by the passed data. An Error with the error code ErrTooMuchNullData
468 // will be returned if the length of the passed data exceeds MaxDataCarrierSize.
469 func NullDataScript(data []byte) ([]byte, error) {
470 if len(data) > MaxDataCarrierSize {
471 str := fmt.Sprintf("data size %d is larger than max "+
472 "allowed size %d", len(data), MaxDataCarrierSize)
473 return nil, scriptError(ErrTooMuchNullData, str)
476 return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script()
479 // MultiSigScript returns a valid script for a multisignature redemption where
480 // nrequired of the keys in pubkeys are required to have signed the transaction
481 // for success. An Error with the error code ErrTooManyRequiredSigs will be
482 // returned if nrequired is larger than the number of keys provided.
483 func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) {
484 if len(pubkeys) < nrequired {
485 str := fmt.Sprintf("unable to generate multisig script with "+
486 "%d required signatures when there are only %d public "+
487 "keys available", nrequired, len(pubkeys))
488 return nil, scriptError(ErrTooManyRequiredSigs, str)
491 builder := NewScriptBuilder().AddInt64(int64(nrequired))
492 for _, key := range pubkeys {
493 builder.AddData(key.ScriptAddress())
495 builder.AddInt64(int64(len(pubkeys)))
496 builder.AddOp(OP_CHECKMULTISIG)
498 return builder.Script()
501 // PushedData returns an array of byte slices containing any pushed data found
502 // in the passed script. This includes OP_0, but not OP_1 - OP_16.
503 func PushedData(script []byte) ([][]byte, error) {
504 pops, err := parseScript(script)
510 for _, pop := range pops {
512 data = append(data, pop.data)
513 } else if pop.opcode.value == OP_0 {
514 data = append(data, nil)
520 // ExtractPkScriptAddrs returns the type of script, addresses and required
521 // signatures associated with the passed PkScript. Note that it only works for
522 // 'standard' transaction script types. Any data such as public keys which are
523 // invalid are omitted from the results.
524 func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, error) {
525 var addrs []btcutil.Address
528 // No valid addresses or required signatures if the script doesn't
530 pops, err := parseScript(pkScript)
532 return NonStandardTy, nil, 0, err
535 scriptClass := typeOfScript(pops)
538 // A pay-to-pubkey-hash script is of the form:
539 // OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG
540 // Therefore the pubkey hash is the 3rd item on the stack.
541 // Skip the pubkey hash if it's invalid for some reason.
543 addr, err := btcutil.NewAddressPubKeyHash(pops[2].data,
546 addrs = append(addrs, addr)
549 case WitnessV0PubKeyHashTy:
550 // A pay-to-witness-pubkey-hash script is of thw form:
551 // OP_0 <20-byte hash>
552 // Therefore, the pubkey hash is the second item on the stack.
553 // Skip the pubkey hash if it's invalid for some reason.
555 addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].data,
558 addrs = append(addrs, addr)
562 // A pay-to-pubkey script is of the form:
563 // <pubkey> OP_CHECKSIG
564 // Therefore the pubkey is the first item on the stack.
565 // Skip the pubkey if it's invalid for some reason.
567 addr, err := btcutil.NewAddressPubKey(pops[0].data, chainParams)
569 addrs = append(addrs, addr)
573 // A pay-to-script-hash script is of the form:
574 // OP_HASH160 <scripthash> OP_EQUAL
575 // Therefore the script hash is the 2nd item on the stack.
576 // Skip the script hash if it's invalid for some reason.
578 addr, err := btcutil.NewAddressScriptHashFromHash(pops[1].data,
581 addrs = append(addrs, addr)
584 case WitnessV0ScriptHashTy:
585 // A pay-to-witness-script-hash script is of the form:
586 // OP_0 <32-byte hash>
587 // Therefore, the script hash is the second item on the stack.
588 // Skip the script hash if it's invalid for some reason.
590 addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].data,
593 addrs = append(addrs, addr)
597 // A multi-signature script is of the form:
598 // <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG
599 // Therefore the number of required signatures is the 1st item
600 // on the stack and the number of public keys is the 2nd to last
601 // item on the stack.
602 requiredSigs = asSmallInt(pops[0].opcode)
603 numPubKeys := asSmallInt(pops[len(pops)-2].opcode)
605 // Extract the public keys while skipping any that are invalid.
606 addrs = make([]btcutil.Address, 0, numPubKeys)
607 for i := 0; i < numPubKeys; i++ {
608 addr, err := btcutil.NewAddressPubKey(pops[i+1].data,
611 addrs = append(addrs, addr)
616 // Null data transactions have no addresses or required
620 // Don't attempt to extract addresses or required signatures for
621 // nonstandard transactions.
624 return scriptClass, addrs, requiredSigs, nil