OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / btcsuite / btcd / txscript / standard.go
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.
4
5 package txscript
6
7 import (
8         "fmt"
9
10         "github.com/btcsuite/btcd/chaincfg"
11         "github.com/btcsuite/btcd/wire"
12         "github.com/btcsuite/btcutil"
13 )
14
15 const (
16         // MaxDataCarrierSize is the maximum number of bytes allowed in pushed
17         // data to be considered a nulldata transaction
18         MaxDataCarrierSize = 80
19
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
26         // are more strict.
27         //
28         // TODO: This definition does not belong here.  It belongs in a policy
29         // package.
30         StandardVerifyFlags = ScriptBip16 |
31                 ScriptVerifyDERSignatures |
32                 ScriptVerifyStrictEncoding |
33                 ScriptVerifyMinimalData |
34                 ScriptStrictMultiSig |
35                 ScriptDiscourageUpgradableNops |
36                 ScriptVerifyCleanStack |
37                 ScriptVerifyNullFail |
38                 ScriptVerifyCheckLockTimeVerify |
39                 ScriptVerifyCheckSequenceVerify |
40                 ScriptVerifyLowS |
41                 ScriptStrictMultiSig |
42                 ScriptVerifyWitness |
43                 ScriptVerifyDiscourageUpgradeableWitnessProgram |
44                 ScriptVerifyMinimalIf |
45                 ScriptVerifyWitnessPubKeyType
46 )
47
48 // ScriptClass is an enumeration for the list of standard types of script.
49 type ScriptClass byte
50
51 // Classes of script payment known about in the blockchain.
52 const (
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).
61 )
62
63 // scriptClassToName houses the human-readable strings which describe each
64 // script class.
65 var scriptClassToName = []string{
66         NonStandardTy:         "nonstandard",
67         PubKeyTy:              "pubkey",
68         PubKeyHashTy:          "pubkeyhash",
69         WitnessV0PubKeyHashTy: "witness_v0_keyhash",
70         ScriptHashTy:          "scripthash",
71         WitnessV0ScriptHashTy: "witness_v0_scripthash",
72         MultiSigTy:            "multisig",
73         NullDataTy:            "nulldata",
74 }
75
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
78 // returned.
79 func (t ScriptClass) String() string {
80         if int(t) > len(scriptClassToName) || int(t) < 0 {
81                 return "Invalid"
82         }
83         return scriptClassToName[t]
84 }
85
86 // isPubkey returns true if the script passed is a pay-to-pubkey transaction,
87 // false otherwise.
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
93 }
94
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
104
105 }
106
107 // isMultiSig returns true if the passed script is a multisig transaction, false
108 // otherwise.
109 func isMultiSig(pops []parsedOpcode) bool {
110         // The absolute minimum is 1 pubkey:
111         // OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG
112         l := len(pops)
113         if l < 4 {
114                 return false
115         }
116         if !isSmallInt(pops[0].opcode) {
117                 return false
118         }
119         if !isSmallInt(pops[l-2].opcode) {
120                 return false
121         }
122         if pops[l-1].opcode.value != OP_CHECKMULTISIG {
123                 return false
124         }
125
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) {
129                 return false
130         }
131
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 {
135                         return false
136                 }
137         }
138         return true
139 }
140
141 // isNullData returns true if the passed script is a null data transaction,
142 // false otherwise.
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).
147         l := len(pops)
148         if l == 1 && pops[0].opcode.value == OP_RETURN {
149                 return true
150         }
151
152         return l == 2 &&
153                 pops[0].opcode.value == OP_RETURN &&
154                 (isSmallInt(pops[1].opcode) || pops[1].opcode.value <=
155                         OP_PUSHDATA4) &&
156                 len(pops[1].data) <= MaxDataCarrierSize
157 }
158
159 // scriptType returns the type of the script being inspected from the known
160 // standard types.
161 func typeOfScript(pops []parsedOpcode) ScriptClass {
162         if isPubkey(pops) {
163                 return PubKeyTy
164         } else if isPubkeyHash(pops) {
165                 return PubKeyHashTy
166         } else if isWitnessPubKeyHash(pops) {
167                 return WitnessV0PubKeyHashTy
168         } else if isScriptHash(pops) {
169                 return ScriptHashTy
170         } else if isWitnessScriptHash(pops) {
171                 return WitnessV0ScriptHashTy
172         } else if isMultiSig(pops) {
173                 return MultiSigTy
174         } else if isNullData(pops) {
175                 return NullDataTy
176         }
177         return NonStandardTy
178 }
179
180 // GetScriptClass returns the class of the script passed.
181 //
182 // NonStandardTy will be returned when the script does not parse.
183 func GetScriptClass(script []byte) ScriptClass {
184         pops, err := parseScript(script)
185         if err != nil {
186                 return NonStandardTy
187         }
188         return typeOfScript(pops)
189 }
190
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 {
197         switch class {
198         case PubKeyTy:
199                 return 1
200
201         case PubKeyHashTy:
202                 return 2
203
204         case WitnessV0PubKeyHashTy:
205                 return 2
206
207         case ScriptHashTy:
208                 // Not including script.  That is handled by the caller.
209                 return 1
210
211         case WitnessV0ScriptHashTy:
212                 // Not including script.  That is handled by the caller.
213                 return 1
214
215         case MultiSigTy:
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
224
225         case NullDataTy:
226                 fallthrough
227         default:
228                 return -1
229         }
230 }
231
232 // ScriptInfo houses information about a script pair that is determined by
233 // CalcScriptInfo.
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
238
239         // NumInputs is the number of inputs provided by the public key script.
240         NumInputs int
241
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
244         // unknown.
245         ExpectedInputs int
246
247         // SigOps is the number of signature operations in the script pair.
248         SigOps int
249 }
250
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
254 // script
255 func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
256         bip16, segwit bool) (*ScriptInfo, error) {
257
258         sigPops, err := parseScript(sigScript)
259         if err != nil {
260                 return nil, err
261         }
262
263         pkPops, err := parseScript(pkScript)
264         if err != nil {
265                 return nil, err
266         }
267
268         // Push only sigScript makes little sense.
269         si := new(ScriptInfo)
270         si.PkScriptClass = typeOfScript(pkPops)
271
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")
276         }
277
278         si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass)
279
280         switch {
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
284                 // signature script.
285                 script := sigPops[len(sigPops)-1].data
286                 shPops, err := parseScript(script)
287                 if err != nil {
288                         return nil, err
289                 }
290
291                 shInputs := expectedInputs(shPops, typeOfScript(shPops))
292                 if shInputs == -1 {
293                         si.ExpectedInputs = -1
294                 } else {
295                         si.ExpectedInputs += shInputs
296                 }
297                 si.SigOps = getSigOpCount(shPops, true)
298
299                 // All entries pushed to stack (or are OP_RESERVED and exec
300                 // will fail).
301                 si.NumInputs = len(sigPops)
302
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:
306
307                 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
308                 si.NumInputs = len(witness)
309
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:
314
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))
319                 if shInputs == -1 {
320                         si.ExpectedInputs = -1
321                 } else {
322                         si.ExpectedInputs += shInputs
323                 }
324
325                 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
326
327                 si.NumInputs = len(witness)
328                 si.NumInputs += len(sigPops)
329
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
334                 // stack.
335                 witnessScript := witness[len(witness)-1]
336                 pops, _ := parseScript(witnessScript)
337
338                 shInputs := expectedInputs(pops, typeOfScript(pops))
339                 if shInputs == -1 {
340                         si.ExpectedInputs = -1
341                 } else {
342                         si.ExpectedInputs += shInputs
343                 }
344
345                 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
346                 si.NumInputs = len(witness)
347
348         default:
349                 si.SigOps = getSigOpCount(pkPops, true)
350
351                 // All entries pushed to stack (or are OP_RESERVED and exec
352                 // will fail).
353                 si.NumInputs = len(sigPops)
354         }
355
356         return si, nil
357 }
358
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)
364         if err != nil {
365                 return 0, 0, err
366         }
367
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
375         if len(pops) < 4 {
376                 str := fmt.Sprintf("script %x is not a multisig script", script)
377                 return 0, 0, scriptError(ErrNotMultisigScript, str)
378         }
379
380         numSigs := asSmallInt(pops[0].opcode)
381         numPubKeys := asSmallInt(pops[len(pops)-2].opcode)
382         return numPubKeys, numSigs, nil
383 }
384
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
387 // hash.
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).
391                 Script()
392 }
393
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()
398 }
399
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()
405 }
406
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()
411 }
412
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()
418 }
419
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"
424
425         switch addr := addr.(type) {
426         case *btcutil.AddressPubKeyHash:
427                 if addr == nil {
428                         return nil, scriptError(ErrUnsupportedAddress,
429                                 nilAddrErrStr)
430                 }
431                 return payToPubKeyHashScript(addr.ScriptAddress())
432
433         case *btcutil.AddressScriptHash:
434                 if addr == nil {
435                         return nil, scriptError(ErrUnsupportedAddress,
436                                 nilAddrErrStr)
437                 }
438                 return payToScriptHashScript(addr.ScriptAddress())
439
440         case *btcutil.AddressPubKey:
441                 if addr == nil {
442                         return nil, scriptError(ErrUnsupportedAddress,
443                                 nilAddrErrStr)
444                 }
445                 return payToPubKeyScript(addr.ScriptAddress())
446
447         case *btcutil.AddressWitnessPubKeyHash:
448                 if addr == nil {
449                         return nil, scriptError(ErrUnsupportedAddress,
450                                 nilAddrErrStr)
451                 }
452                 return payToWitnessPubKeyHashScript(addr.ScriptAddress())
453         case *btcutil.AddressWitnessScriptHash:
454                 if addr == nil {
455                         return nil, scriptError(ErrUnsupportedAddress,
456                                 nilAddrErrStr)
457                 }
458                 return payToWitnessScriptHashScript(addr.ScriptAddress())
459         }
460
461         str := fmt.Sprintf("unable to generate payment script for unsupported "+
462                 "address type %T", addr)
463         return nil, scriptError(ErrUnsupportedAddress, str)
464 }
465
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)
474         }
475
476         return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script()
477 }
478
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)
489         }
490
491         builder := NewScriptBuilder().AddInt64(int64(nrequired))
492         for _, key := range pubkeys {
493                 builder.AddData(key.ScriptAddress())
494         }
495         builder.AddInt64(int64(len(pubkeys)))
496         builder.AddOp(OP_CHECKMULTISIG)
497
498         return builder.Script()
499 }
500
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)
505         if err != nil {
506                 return nil, err
507         }
508
509         var data [][]byte
510         for _, pop := range pops {
511                 if pop.data != nil {
512                         data = append(data, pop.data)
513                 } else if pop.opcode.value == OP_0 {
514                         data = append(data, nil)
515                 }
516         }
517         return data, nil
518 }
519
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
526         var requiredSigs int
527
528         // No valid addresses or required signatures if the script doesn't
529         // parse.
530         pops, err := parseScript(pkScript)
531         if err != nil {
532                 return NonStandardTy, nil, 0, err
533         }
534
535         scriptClass := typeOfScript(pops)
536         switch scriptClass {
537         case PubKeyHashTy:
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.
542                 requiredSigs = 1
543                 addr, err := btcutil.NewAddressPubKeyHash(pops[2].data,
544                         chainParams)
545                 if err == nil {
546                         addrs = append(addrs, addr)
547                 }
548
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.
554                 requiredSigs = 1
555                 addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].data,
556                         chainParams)
557                 if err == nil {
558                         addrs = append(addrs, addr)
559                 }
560
561         case PubKeyTy:
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.
566                 requiredSigs = 1
567                 addr, err := btcutil.NewAddressPubKey(pops[0].data, chainParams)
568                 if err == nil {
569                         addrs = append(addrs, addr)
570                 }
571
572         case ScriptHashTy:
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.
577                 requiredSigs = 1
578                 addr, err := btcutil.NewAddressScriptHashFromHash(pops[1].data,
579                         chainParams)
580                 if err == nil {
581                         addrs = append(addrs, addr)
582                 }
583
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.
589                 requiredSigs = 1
590                 addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].data,
591                         chainParams)
592                 if err == nil {
593                         addrs = append(addrs, addr)
594                 }
595
596         case MultiSigTy:
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)
604
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,
609                                 chainParams)
610                         if err == nil {
611                                 addrs = append(addrs, addr)
612                         }
613                 }
614
615         case NullDataTy:
616                 // Null data transactions have no addresses or required
617                 // signatures.
618
619         case NonStandardTy:
620                 // Don't attempt to extract addresses or required signatures for
621                 // nonstandard transactions.
622         }
623
624         return scriptClass, addrs, requiredSigs, nil
625 }