github.com/btcsuite/btcd@v0.24.0/txscript/standard.go (about) 1 // Copyright (c) 2013-2020 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/btcutil" 11 "github.com/btcsuite/btcd/chaincfg" 12 "github.com/btcsuite/btcd/wire" 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 ScriptVerifyTaproot | 47 ScriptVerifyDiscourageUpgradeableTaprootVersion | 48 ScriptVerifyDiscourageOpSuccess | 49 ScriptVerifyDiscourageUpgradeablePubkeyType 50 ) 51 52 // ScriptClass is an enumeration for the list of standard types of script. 53 type ScriptClass byte 54 55 // Classes of script payment known about in the blockchain. 56 const ( 57 NonStandardTy ScriptClass = iota // None of the recognized forms. 58 PubKeyTy // Pay pubkey. 59 PubKeyHashTy // Pay pubkey hash. 60 WitnessV0PubKeyHashTy // Pay witness pubkey hash. 61 ScriptHashTy // Pay to script hash. 62 WitnessV0ScriptHashTy // Pay to witness script hash. 63 MultiSigTy // Multi signature. 64 NullDataTy // Empty data-only (provably prunable). 65 WitnessV1TaprootTy // Taproot output 66 WitnessUnknownTy // Witness unknown 67 ) 68 69 // scriptClassToName houses the human-readable strings which describe each 70 // script class. 71 var scriptClassToName = []string{ 72 NonStandardTy: "nonstandard", 73 PubKeyTy: "pubkey", 74 PubKeyHashTy: "pubkeyhash", 75 WitnessV0PubKeyHashTy: "witness_v0_keyhash", 76 ScriptHashTy: "scripthash", 77 WitnessV0ScriptHashTy: "witness_v0_scripthash", 78 MultiSigTy: "multisig", 79 NullDataTy: "nulldata", 80 WitnessV1TaprootTy: "witness_v1_taproot", 81 WitnessUnknownTy: "witness_unknown", 82 } 83 84 // String implements the Stringer interface by returning the name of 85 // the enum script class. If the enum is invalid then "Invalid" will be 86 // returned. 87 func (t ScriptClass) String() string { 88 if int(t) > len(scriptClassToName) || int(t) < 0 { 89 return "Invalid" 90 } 91 return scriptClassToName[t] 92 } 93 94 // extractCompressedPubKey extracts a compressed public key from the passed 95 // script if it is a standard pay-to-compressed-secp256k1-pubkey script. It 96 // will return nil otherwise. 97 func extractCompressedPubKey(script []byte) []byte { 98 // A pay-to-compressed-pubkey script is of the form: 99 // OP_DATA_33 <33-byte compressed pubkey> OP_CHECKSIG 100 101 // All compressed secp256k1 public keys must start with 0x02 or 0x03. 102 if len(script) == 35 && 103 script[34] == OP_CHECKSIG && 104 script[0] == OP_DATA_33 && 105 (script[1] == 0x02 || script[1] == 0x03) { 106 107 return script[1:34] 108 } 109 110 return nil 111 } 112 113 // extractUncompressedPubKey extracts an uncompressed public key from the 114 // passed script if it is a standard pay-to-uncompressed-secp256k1-pubkey 115 // script. It will return nil otherwise. 116 func extractUncompressedPubKey(script []byte) []byte { 117 // A pay-to-uncompressed-pubkey script is of the form: 118 // OP_DATA_65 <65-byte uncompressed pubkey> OP_CHECKSIG 119 // 120 // All non-hybrid uncompressed secp256k1 public keys must start with 0x04. 121 // Hybrid uncompressed secp256k1 public keys start with 0x06 or 0x07: 122 // - 0x06 => hybrid format for even Y coords 123 // - 0x07 => hybrid format for odd Y coords 124 if len(script) == 67 && 125 script[66] == OP_CHECKSIG && 126 script[0] == OP_DATA_65 && 127 (script[1] == 0x04 || script[1] == 0x06 || script[1] == 0x07) { 128 129 return script[1:66] 130 } 131 return nil 132 } 133 134 // extractPubKey extracts either compressed or uncompressed public key from the 135 // passed script if it is a either a standard pay-to-compressed-secp256k1-pubkey 136 // or pay-to-uncompressed-secp256k1-pubkey script, respectively. It will return 137 // nil otherwise. 138 func extractPubKey(script []byte) []byte { 139 if pubKey := extractCompressedPubKey(script); pubKey != nil { 140 return pubKey 141 } 142 return extractUncompressedPubKey(script) 143 } 144 145 // isPubKeyScript returns whether or not the passed script is either a standard 146 // pay-to-compressed-secp256k1-pubkey or pay-to-uncompressed-secp256k1-pubkey 147 // script. 148 func isPubKeyScript(script []byte) bool { 149 return extractPubKey(script) != nil 150 } 151 152 // extractPubKeyHash extracts the public key hash from the passed script if it 153 // is a standard pay-to-pubkey-hash script. It will return nil otherwise. 154 func extractPubKeyHash(script []byte) []byte { 155 // A pay-to-pubkey-hash script is of the form: 156 // OP_DUP OP_HASH160 <20-byte hash> OP_EQUALVERIFY OP_CHECKSIG 157 if len(script) == 25 && 158 script[0] == OP_DUP && 159 script[1] == OP_HASH160 && 160 script[2] == OP_DATA_20 && 161 script[23] == OP_EQUALVERIFY && 162 script[24] == OP_CHECKSIG { 163 164 return script[3:23] 165 } 166 167 return nil 168 } 169 170 // isPubKeyHashScript returns whether or not the passed script is a standard 171 // pay-to-pubkey-hash script. 172 func isPubKeyHashScript(script []byte) bool { 173 return extractPubKeyHash(script) != nil 174 } 175 176 // extractScriptHash extracts the script hash from the passed script if it is a 177 // standard pay-to-script-hash script. It will return nil otherwise. 178 // 179 // NOTE: This function is only valid for version 0 opcodes. Since the function 180 // does not accept a script version, the results are undefined for other script 181 // versions. 182 func extractScriptHash(script []byte) []byte { 183 // A pay-to-script-hash script is of the form: 184 // OP_HASH160 <20-byte scripthash> OP_EQUAL 185 if len(script) == 23 && 186 script[0] == OP_HASH160 && 187 script[1] == OP_DATA_20 && 188 script[22] == OP_EQUAL { 189 190 return script[2:22] 191 } 192 193 return nil 194 } 195 196 // isScriptHashScript returns whether or not the passed script is a standard 197 // pay-to-script-hash script. 198 func isScriptHashScript(script []byte) bool { 199 return extractScriptHash(script) != nil 200 } 201 202 // multiSigDetails houses details extracted from a standard multisig script. 203 type multiSigDetails struct { 204 requiredSigs int 205 numPubKeys int 206 pubKeys [][]byte 207 valid bool 208 } 209 210 // extractMultisigScriptDetails attempts to extract details from the passed 211 // script if it is a standard multisig script. The returned details struct will 212 // have the valid flag set to false otherwise. 213 // 214 // The extract pubkeys flag indicates whether or not the pubkeys themselves 215 // should also be extracted and is provided because extracting them results in 216 // an allocation that the caller might wish to avoid. The pubKeys member of 217 // the returned details struct will be nil when the flag is false. 218 // 219 // NOTE: This function is only valid for version 0 scripts. The returned 220 // details struct will always be empty and have the valid flag set to false for 221 // other script versions. 222 func extractMultisigScriptDetails(scriptVersion uint16, script []byte, extractPubKeys bool) multiSigDetails { 223 // The only currently supported script version is 0. 224 if scriptVersion != 0 { 225 return multiSigDetails{} 226 } 227 228 // A multi-signature script is of the form: 229 // NUM_SIGS PUBKEY PUBKEY PUBKEY ... NUM_PUBKEYS OP_CHECKMULTISIG 230 231 // The script can't possibly be a multisig script if it doesn't end with 232 // OP_CHECKMULTISIG or have at least two small integer pushes preceding it. 233 // Fail fast to avoid more work below. 234 if len(script) < 3 || script[len(script)-1] != OP_CHECKMULTISIG { 235 return multiSigDetails{} 236 } 237 238 // The first opcode must be a small integer specifying the number of 239 // signatures required. 240 tokenizer := MakeScriptTokenizer(scriptVersion, script) 241 if !tokenizer.Next() || !IsSmallInt(tokenizer.Opcode()) { 242 return multiSigDetails{} 243 } 244 requiredSigs := AsSmallInt(tokenizer.Opcode()) 245 246 // The next series of opcodes must either push public keys or be a small 247 // integer specifying the number of public keys. 248 var numPubKeys int 249 var pubKeys [][]byte 250 if extractPubKeys { 251 pubKeys = make([][]byte, 0, MaxPubKeysPerMultiSig) 252 } 253 for tokenizer.Next() { 254 if IsSmallInt(tokenizer.Opcode()) { 255 break 256 } 257 258 data := tokenizer.Data() 259 numPubKeys++ 260 if !isStrictPubKeyEncoding(data) { 261 continue 262 } 263 if extractPubKeys { 264 pubKeys = append(pubKeys, data) 265 } 266 } 267 if tokenizer.Done() { 268 return multiSigDetails{} 269 } 270 271 // The next opcode must be a small integer specifying the number of public 272 // keys required. 273 op := tokenizer.Opcode() 274 if !IsSmallInt(op) || AsSmallInt(op) != numPubKeys { 275 return multiSigDetails{} 276 } 277 278 // There must only be a single opcode left unparsed which will be 279 // OP_CHECKMULTISIG per the check above. 280 if int32(len(tokenizer.Script()))-tokenizer.ByteIndex() != 1 { 281 return multiSigDetails{} 282 } 283 284 return multiSigDetails{ 285 requiredSigs: requiredSigs, 286 numPubKeys: numPubKeys, 287 pubKeys: pubKeys, 288 valid: true, 289 } 290 } 291 292 // isMultisigScript returns whether or not the passed script is a standard 293 // multisig script. 294 // 295 // NOTE: This function is only valid for version 0 scripts. It will always 296 // return false for other script versions. 297 func isMultisigScript(scriptVersion uint16, script []byte) bool { 298 // Since this is only checking the form of the script, don't extract the 299 // public keys to avoid the allocation. 300 details := extractMultisigScriptDetails(scriptVersion, script, false) 301 return details.valid 302 } 303 304 // IsMultisigScript returns whether or not the passed script is a standard 305 // multisignature script. 306 // 307 // NOTE: This function is only valid for version 0 scripts. Since the function 308 // does not accept a script version, the results are undefined for other script 309 // versions. 310 // 311 // The error is DEPRECATED and will be removed in the major version bump. 312 func IsMultisigScript(script []byte) (bool, error) { 313 const scriptVersion = 0 314 return isMultisigScript(scriptVersion, script), nil 315 } 316 317 // IsMultisigSigScript returns whether or not the passed script appears to be a 318 // signature script which consists of a pay-to-script-hash multi-signature 319 // redeem script. Determining if a signature script is actually a redemption of 320 // pay-to-script-hash requires the associated public key script which is often 321 // expensive to obtain. Therefore, this makes a fast best effort guess that has 322 // a high probability of being correct by checking if the signature script ends 323 // with a data push and treating that data push as if it were a p2sh redeem 324 // script 325 // 326 // NOTE: This function is only valid for version 0 scripts. Since the function 327 // does not accept a script version, the results are undefined for other script 328 // versions. 329 func IsMultisigSigScript(script []byte) bool { 330 const scriptVersion = 0 331 332 // The script can't possibly be a multisig signature script if it doesn't 333 // end with OP_CHECKMULTISIG in the redeem script or have at least two small 334 // integers preceding it, and the redeem script itself must be preceded by 335 // at least a data push opcode. Fail fast to avoid more work below. 336 if len(script) < 4 || script[len(script)-1] != OP_CHECKMULTISIG { 337 return false 338 } 339 340 // Parse through the script to find the last opcode and any data it might 341 // push and treat it as a p2sh redeem script even though it might not 342 // actually be one. 343 possibleRedeemScript := finalOpcodeData(scriptVersion, script) 344 if possibleRedeemScript == nil { 345 return false 346 } 347 348 // Finally, return if that possible redeem script is a multisig script. 349 return isMultisigScript(scriptVersion, possibleRedeemScript) 350 } 351 352 // extractWitnessPubKeyHash extracts the witness public key hash from the passed 353 // script if it is a standard pay-to-witness-pubkey-hash script. It will return 354 // nil otherwise. 355 func extractWitnessPubKeyHash(script []byte) []byte { 356 // A pay-to-witness-pubkey-hash script is of the form: 357 // OP_0 OP_DATA_20 <20-byte-hash> 358 if len(script) == witnessV0PubKeyHashLen && 359 script[0] == OP_0 && 360 script[1] == OP_DATA_20 { 361 362 return script[2:witnessV0PubKeyHashLen] 363 } 364 365 return nil 366 } 367 368 // isWitnessPubKeyHashScript returns whether or not the passed script is a 369 // standard pay-to-witness-pubkey-hash script. 370 func isWitnessPubKeyHashScript(script []byte) bool { 371 return extractWitnessPubKeyHash(script) != nil 372 } 373 374 // extractWitnessV0ScriptHash extracts the witness script hash from the passed 375 // script if it is standard pay-to-witness-script-hash script. It will return 376 // nil otherwise. 377 func extractWitnessV0ScriptHash(script []byte) []byte { 378 // A pay-to-witness-script-hash script is of the form: 379 // OP_0 OP_DATA_32 <32-byte-hash> 380 if len(script) == witnessV0ScriptHashLen && 381 script[0] == OP_0 && 382 script[1] == OP_DATA_32 { 383 384 return script[2:34] 385 } 386 387 return nil 388 } 389 390 // extractWitnessV1KeyBytes extracts the raw public key bytes script if it is 391 // standard pay-to-witness-script-hash v1 script. It will return nil otherwise. 392 func extractWitnessV1KeyBytes(script []byte) []byte { 393 // A pay-to-witness-script-hash script is of the form: 394 // OP_1 OP_DATA_32 <32-byte-hash> 395 if len(script) == witnessV1TaprootLen && 396 script[0] == OP_1 && 397 script[1] == OP_DATA_32 { 398 399 return script[2:34] 400 } 401 402 return nil 403 } 404 405 // isWitnessScriptHashScript returns whether or not the passed script is a 406 // standard pay-to-witness-script-hash script. 407 func isWitnessScriptHashScript(script []byte) bool { 408 return extractWitnessV0ScriptHash(script) != nil 409 } 410 411 // extractWitnessProgramInfo returns the version and program if the passed 412 // script constitutes a valid witness program. The last return value indicates 413 // whether or not the script is a valid witness program. 414 func extractWitnessProgramInfo(script []byte) (int, []byte, bool) { 415 // Skip parsing if we know the program is invalid based on size. 416 if len(script) < 4 || len(script) > 42 { 417 return 0, nil, false 418 } 419 420 const scriptVersion = 0 421 tokenizer := MakeScriptTokenizer(scriptVersion, script) 422 423 // The first opcode must be a small int. 424 if !tokenizer.Next() || 425 !IsSmallInt(tokenizer.Opcode()) { 426 427 return 0, nil, false 428 } 429 version := AsSmallInt(tokenizer.Opcode()) 430 431 // The second opcode must be a canonical data push, the length of the 432 // data push is bounded to 40 by the initial check on overall script 433 // length. 434 if !tokenizer.Next() || 435 !isCanonicalPush(tokenizer.Opcode(), tokenizer.Data()) { 436 437 return 0, nil, false 438 } 439 program := tokenizer.Data() 440 441 // The witness program is valid if there are no more opcodes, and we 442 // terminated without a parsing error. 443 valid := tokenizer.Done() && tokenizer.Err() == nil 444 445 return version, program, valid 446 } 447 448 // isWitnessProgramScript returns true if the passed script is a witness 449 // program, and false otherwise. A witness program MUST adhere to the following 450 // constraints: there must be exactly two pops (program version and the program 451 // itself), the first opcode MUST be a small integer (0-16), the push data MUST 452 // be canonical, and finally the size of the push data must be between 2 and 40 453 // bytes. 454 // 455 // The length of the script must be between 4 and 42 bytes. The 456 // smallest program is the witness version, followed by a data push of 457 // 2 bytes. The largest allowed witness program has a data push of 458 // 40-bytes. 459 func isWitnessProgramScript(script []byte) bool { 460 _, _, valid := extractWitnessProgramInfo(script) 461 return valid 462 } 463 464 // isWitnessTaprootScript returns true if the passed script is for a 465 // pay-to-witness-taproot output, false otherwise. 466 func isWitnessTaprootScript(script []byte) bool { 467 return extractWitnessV1KeyBytes(script) != nil 468 } 469 470 // isAnnexedWitness returns true if the passed witness has a final push 471 // that is a witness annex. 472 func isAnnexedWitness(witness wire.TxWitness) bool { 473 if len(witness) < 2 { 474 return false 475 } 476 477 lastElement := witness[len(witness)-1] 478 return len(lastElement) > 0 && lastElement[0] == TaprootAnnexTag 479 } 480 481 // extractAnnex attempts to extract the annex from the passed witness. If the 482 // witness doesn't contain an annex, then an error is returned. 483 func extractAnnex(witness [][]byte) ([]byte, error) { 484 if !isAnnexedWitness(witness) { 485 return nil, scriptError(ErrWitnessHasNoAnnex, "") 486 } 487 488 lastElement := witness[len(witness)-1] 489 return lastElement, nil 490 } 491 492 // isNullDataScript returns whether or not the passed script is a standard 493 // null data script. 494 // 495 // NOTE: This function is only valid for version 0 scripts. It will always 496 // return false for other script versions. 497 func isNullDataScript(scriptVersion uint16, script []byte) bool { 498 // The only currently supported script version is 0. 499 if scriptVersion != 0 { 500 return false 501 } 502 503 // A null script is of the form: 504 // OP_RETURN <optional data> 505 // 506 // Thus, it can either be a single OP_RETURN or an OP_RETURN followed by a 507 // data push up to MaxDataCarrierSize bytes. 508 509 // The script can't possibly be a null data script if it doesn't start 510 // with OP_RETURN. Fail fast to avoid more work below. 511 if len(script) < 1 || script[0] != OP_RETURN { 512 return false 513 } 514 515 // Single OP_RETURN. 516 if len(script) == 1 { 517 return true 518 } 519 520 // OP_RETURN followed by data push up to MaxDataCarrierSize bytes. 521 tokenizer := MakeScriptTokenizer(scriptVersion, script[1:]) 522 return tokenizer.Next() && tokenizer.Done() && 523 (IsSmallInt(tokenizer.Opcode()) || tokenizer.Opcode() <= OP_PUSHDATA4) && 524 len(tokenizer.Data()) <= MaxDataCarrierSize 525 } 526 527 // scriptType returns the type of the script being inspected from the known 528 // standard types. The version version should be 0 if the script is segwit v0 529 // or prior, and 1 for segwit v1 (taproot) scripts. 530 func typeOfScript(scriptVersion uint16, script []byte) ScriptClass { 531 switch scriptVersion { 532 case BaseSegwitWitnessVersion: 533 switch { 534 case isPubKeyScript(script): 535 return PubKeyTy 536 case isPubKeyHashScript(script): 537 return PubKeyHashTy 538 case isScriptHashScript(script): 539 return ScriptHashTy 540 case isWitnessPubKeyHashScript(script): 541 return WitnessV0PubKeyHashTy 542 case isWitnessScriptHashScript(script): 543 return WitnessV0ScriptHashTy 544 case isMultisigScript(scriptVersion, script): 545 return MultiSigTy 546 case isNullDataScript(scriptVersion, script): 547 return NullDataTy 548 } 549 case TaprootWitnessVersion: 550 switch { 551 case isWitnessTaprootScript(script): 552 return WitnessV1TaprootTy 553 } 554 } 555 556 return NonStandardTy 557 } 558 559 // GetScriptClass returns the class of the script passed. 560 // 561 // NonStandardTy will be returned when the script does not parse. 562 func GetScriptClass(script []byte) ScriptClass { 563 const scriptVersionSegWit = 0 564 classSegWit := typeOfScript(scriptVersionSegWit, script) 565 566 if classSegWit != NonStandardTy { 567 return classSegWit 568 } 569 570 const scriptVersionTaproot = 1 571 return typeOfScript(scriptVersionTaproot, script) 572 } 573 574 // NewScriptClass returns the ScriptClass corresponding to the string name 575 // provided as argument. ErrUnsupportedScriptType error is returned if the 576 // name doesn't correspond to any known ScriptClass. 577 // 578 // Not to be confused with GetScriptClass. 579 func NewScriptClass(name string) (*ScriptClass, error) { 580 for i, n := range scriptClassToName { 581 if n == name { 582 value := ScriptClass(i) 583 return &value, nil 584 } 585 } 586 587 return nil, fmt.Errorf("%w: %s", ErrUnsupportedScriptType, name) 588 } 589 590 // expectedInputs returns the number of arguments required by a script. 591 // If the script is of unknown type such that the number can not be determined 592 // then -1 is returned. We are an internal function and thus assume that class 593 // is the real class of pops (and we can thus assume things that were determined 594 // while finding out the type). 595 // 596 // NOTE: This function is only valid for version 0 scripts. Since the function 597 // does not accept a script version, the results are undefined for other script 598 // versions. 599 func expectedInputs(script []byte, class ScriptClass) int { 600 switch class { 601 case PubKeyTy: 602 return 1 603 604 case PubKeyHashTy: 605 return 2 606 607 case WitnessV0PubKeyHashTy: 608 return 2 609 610 case ScriptHashTy: 611 // Not including script. That is handled by the caller. 612 return 1 613 614 case WitnessV0ScriptHashTy: 615 // Not including script. That is handled by the caller. 616 return 1 617 618 case WitnessV1TaprootTy: 619 // Not including script. That is handled by the caller. 620 return 1 621 622 case MultiSigTy: 623 // Standard multisig has a push a small number for the number 624 // of sigs and number of keys. Check the first push instruction 625 // to see how many arguments are expected. typeOfScript already 626 // checked this so we know it'll be a small int. Also, due to 627 // the original bitcoind bug where OP_CHECKMULTISIG pops an 628 // additional item from the stack, add an extra expected input 629 // for the extra push that is required to compensate. 630 return AsSmallInt(script[0]) + 1 631 632 case NullDataTy: 633 fallthrough 634 default: 635 return -1 636 } 637 } 638 639 // ScriptInfo houses information about a script pair that is determined by 640 // CalcScriptInfo. 641 type ScriptInfo struct { 642 // PkScriptClass is the class of the public key script and is equivalent 643 // to calling GetScriptClass on it. 644 PkScriptClass ScriptClass 645 646 // NumInputs is the number of inputs provided by the public key script. 647 NumInputs int 648 649 // ExpectedInputs is the number of outputs required by the signature 650 // script and any pay-to-script-hash scripts. The number will be -1 if 651 // unknown. 652 ExpectedInputs int 653 654 // SigOps is the number of signature operations in the script pair. 655 SigOps int 656 } 657 658 // CalcScriptInfo returns a structure providing data about the provided script 659 // pair. It will error if the pair is in someway invalid such that they can not 660 // be analysed, i.e. if they do not parse or the pkScript is not a push-only 661 // script 662 // 663 // NOTE: This function is only valid for version 0 scripts. Since the function 664 // does not accept a script version, the results are undefined for other script 665 // versions. 666 // 667 // DEPRECATED. This will be removed in the next major version bump. 668 func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness, 669 bip16, segwit bool) (*ScriptInfo, error) { 670 671 // Count the number of opcodes in the signature script while also ensuring 672 // that successfully parses. Since there is a check below to ensure the 673 // script is push only, this equates to the number of inputs to the public 674 // key script. 675 const scriptVersion = 0 676 var numInputs int 677 tokenizer := MakeScriptTokenizer(scriptVersion, sigScript) 678 for tokenizer.Next() { 679 numInputs++ 680 } 681 if err := tokenizer.Err(); err != nil { 682 return nil, err 683 } 684 685 if err := checkScriptParses(scriptVersion, pkScript); err != nil { 686 return nil, err 687 } 688 689 // Can't have a signature script that doesn't just push data. 690 if !IsPushOnlyScript(sigScript) { 691 return nil, scriptError(ErrNotPushOnly, 692 "signature script is not push only") 693 } 694 695 si := new(ScriptInfo) 696 si.PkScriptClass = typeOfScript(scriptVersion, pkScript) 697 698 si.ExpectedInputs = expectedInputs(pkScript, si.PkScriptClass) 699 700 switch { 701 // Count sigops taking into account pay-to-script-hash. 702 case si.PkScriptClass == ScriptHashTy && bip16 && !segwit: 703 // The redeem script is the final data push of the signature script. 704 redeemScript := finalOpcodeData(scriptVersion, sigScript) 705 reedeemClass := typeOfScript(scriptVersion, redeemScript) 706 rsInputs := expectedInputs(redeemScript, reedeemClass) 707 if rsInputs == -1 { 708 si.ExpectedInputs = -1 709 } else { 710 si.ExpectedInputs += rsInputs 711 } 712 si.SigOps = countSigOpsV0(redeemScript, true) 713 714 // All entries pushed to stack (or are OP_RESERVED and exec 715 // will fail). 716 si.NumInputs = numInputs 717 718 // If segwit is active, and this is a regular p2wkh output, then we'll 719 // treat the script as a p2pkh output in essence. 720 case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit: 721 722 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) 723 si.NumInputs = len(witness) 724 725 // We'll attempt to detect the nested p2sh case so we can accurately 726 // count the signature operations involved. 727 case si.PkScriptClass == ScriptHashTy && 728 IsWitnessProgram(sigScript[1:]) && bip16 && segwit: 729 730 // Extract the pushed witness program from the sigScript so we 731 // can determine the number of expected inputs. 732 redeemClass := typeOfScript(scriptVersion, sigScript[1:]) 733 shInputs := expectedInputs(sigScript[1:], redeemClass) 734 if shInputs == -1 { 735 si.ExpectedInputs = -1 736 } else { 737 si.ExpectedInputs += shInputs 738 } 739 740 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) 741 742 si.NumInputs = len(witness) 743 si.NumInputs += numInputs 744 745 // If segwit is active, and this is a p2wsh output, then we'll need to 746 // examine the witness script to generate accurate script info. 747 case si.PkScriptClass == WitnessV0ScriptHashTy && segwit: 748 witnessScript := witness[len(witness)-1] 749 redeemClass := typeOfScript(scriptVersion, witnessScript) 750 shInputs := expectedInputs(witnessScript, redeemClass) 751 if shInputs == -1 { 752 si.ExpectedInputs = -1 753 } else { 754 si.ExpectedInputs += shInputs 755 } 756 757 si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness) 758 si.NumInputs = len(witness) 759 760 default: 761 si.SigOps = countSigOpsV0(pkScript, true) 762 763 // All entries pushed to stack (or are OP_RESERVED and exec 764 // will fail). 765 si.NumInputs = numInputs 766 } 767 768 return si, nil 769 } 770 771 // CalcMultiSigStats returns the number of public keys and signatures from 772 // a multi-signature transaction script. The passed script MUST already be 773 // known to be a multi-signature script. 774 // 775 // NOTE: This function is only valid for version 0 scripts. Since the function 776 // does not accept a script version, the results are undefined for other script 777 // versions. 778 func CalcMultiSigStats(script []byte) (int, int, error) { 779 // The public keys are not needed here, so pass false to avoid the extra 780 // allocation. 781 const scriptVersion = 0 782 details := extractMultisigScriptDetails(scriptVersion, script, false) 783 if !details.valid { 784 str := fmt.Sprintf("script %x is not a multisig script", script) 785 return 0, 0, scriptError(ErrNotMultisigScript, str) 786 } 787 788 return details.numPubKeys, details.requiredSigs, nil 789 } 790 791 // payToPubKeyHashScript creates a new script to pay a transaction 792 // output to a 20-byte pubkey hash. It is expected that the input is a valid 793 // hash. 794 func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { 795 return NewScriptBuilder().AddOp(OP_DUP).AddOp(OP_HASH160). 796 AddData(pubKeyHash).AddOp(OP_EQUALVERIFY).AddOp(OP_CHECKSIG). 797 Script() 798 } 799 800 // payToWitnessPubKeyHashScript creates a new script to pay to a version 0 801 // pubkey hash witness program. The passed hash is expected to be valid. 802 func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { 803 return NewScriptBuilder().AddOp(OP_0).AddData(pubKeyHash).Script() 804 } 805 806 // payToScriptHashScript creates a new script to pay a transaction output to a 807 // script hash. It is expected that the input is a valid hash. 808 func payToScriptHashScript(scriptHash []byte) ([]byte, error) { 809 return NewScriptBuilder().AddOp(OP_HASH160).AddData(scriptHash). 810 AddOp(OP_EQUAL).Script() 811 } 812 813 // payToWitnessPubKeyHashScript creates a new script to pay to a version 0 814 // script hash witness program. The passed hash is expected to be valid. 815 func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, error) { 816 return NewScriptBuilder().AddOp(OP_0).AddData(scriptHash).Script() 817 } 818 819 // payToWitnessTaprootScript creates a new script to pay to a version 1 820 // (taproot) witness program. The passed hash is expected to be valid. 821 func payToWitnessTaprootScript(rawKey []byte) ([]byte, error) { 822 return NewScriptBuilder().AddOp(OP_1).AddData(rawKey).Script() 823 } 824 825 // payToPubkeyScript creates a new script to pay a transaction output to a 826 // public key. It is expected that the input is a valid pubkey. 827 func payToPubKeyScript(serializedPubKey []byte) ([]byte, error) { 828 return NewScriptBuilder().AddData(serializedPubKey). 829 AddOp(OP_CHECKSIG).Script() 830 } 831 832 // PayToAddrScript creates a new script to pay a transaction output to a the 833 // specified address. 834 func PayToAddrScript(addr btcutil.Address) ([]byte, error) { 835 const nilAddrErrStr = "unable to generate payment script for nil address" 836 837 switch addr := addr.(type) { 838 case *btcutil.AddressPubKeyHash: 839 if addr == nil { 840 return nil, scriptError(ErrUnsupportedAddress, 841 nilAddrErrStr) 842 } 843 return payToPubKeyHashScript(addr.ScriptAddress()) 844 845 case *btcutil.AddressScriptHash: 846 if addr == nil { 847 return nil, scriptError(ErrUnsupportedAddress, 848 nilAddrErrStr) 849 } 850 return payToScriptHashScript(addr.ScriptAddress()) 851 852 case *btcutil.AddressPubKey: 853 if addr == nil { 854 return nil, scriptError(ErrUnsupportedAddress, 855 nilAddrErrStr) 856 } 857 return payToPubKeyScript(addr.ScriptAddress()) 858 859 case *btcutil.AddressWitnessPubKeyHash: 860 if addr == nil { 861 return nil, scriptError(ErrUnsupportedAddress, 862 nilAddrErrStr) 863 } 864 return payToWitnessPubKeyHashScript(addr.ScriptAddress()) 865 case *btcutil.AddressWitnessScriptHash: 866 if addr == nil { 867 return nil, scriptError(ErrUnsupportedAddress, 868 nilAddrErrStr) 869 } 870 return payToWitnessScriptHashScript(addr.ScriptAddress()) 871 case *btcutil.AddressTaproot: 872 if addr == nil { 873 return nil, scriptError(ErrUnsupportedAddress, 874 nilAddrErrStr) 875 } 876 return payToWitnessTaprootScript(addr.ScriptAddress()) 877 } 878 879 str := fmt.Sprintf("unable to generate payment script for unsupported "+ 880 "address type %T", addr) 881 return nil, scriptError(ErrUnsupportedAddress, str) 882 } 883 884 // NullDataScript creates a provably-prunable script containing OP_RETURN 885 // followed by the passed data. An Error with the error code ErrTooMuchNullData 886 // will be returned if the length of the passed data exceeds MaxDataCarrierSize. 887 func NullDataScript(data []byte) ([]byte, error) { 888 if len(data) > MaxDataCarrierSize { 889 str := fmt.Sprintf("data size %d is larger than max "+ 890 "allowed size %d", len(data), MaxDataCarrierSize) 891 return nil, scriptError(ErrTooMuchNullData, str) 892 } 893 894 return NewScriptBuilder().AddOp(OP_RETURN).AddData(data).Script() 895 } 896 897 // MultiSigScript returns a valid script for a multisignature redemption where 898 // nrequired of the keys in pubkeys are required to have signed the transaction 899 // for success. An Error with the error code ErrTooManyRequiredSigs will be 900 // returned if nrequired is larger than the number of keys provided. 901 func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, error) { 902 if len(pubkeys) < nrequired { 903 str := fmt.Sprintf("unable to generate multisig script with "+ 904 "%d required signatures when there are only %d public "+ 905 "keys available", nrequired, len(pubkeys)) 906 return nil, scriptError(ErrTooManyRequiredSigs, str) 907 } 908 909 builder := NewScriptBuilder().AddInt64(int64(nrequired)) 910 for _, key := range pubkeys { 911 builder.AddData(key.ScriptAddress()) 912 } 913 builder.AddInt64(int64(len(pubkeys))) 914 builder.AddOp(OP_CHECKMULTISIG) 915 916 return builder.Script() 917 } 918 919 // PushedData returns an array of byte slices containing any pushed data found 920 // in the passed script. This includes OP_0, but not OP_1 - OP_16. 921 func PushedData(script []byte) ([][]byte, error) { 922 const scriptVersion = 0 923 924 var data [][]byte 925 tokenizer := MakeScriptTokenizer(scriptVersion, script) 926 for tokenizer.Next() { 927 if tokenizer.Data() != nil { 928 data = append(data, tokenizer.Data()) 929 } else if tokenizer.Opcode() == OP_0 { 930 data = append(data, nil) 931 } 932 } 933 if err := tokenizer.Err(); err != nil { 934 return nil, err 935 } 936 return data, nil 937 } 938 939 // pubKeyHashToAddrs is a convenience function to attempt to convert the 940 // passed hash to a pay-to-pubkey-hash address housed within an address 941 // slice. It is used to consolidate common code. 942 func pubKeyHashToAddrs(hash []byte, params *chaincfg.Params) []btcutil.Address { 943 // Skip the pubkey hash if it's invalid for some reason. 944 var addrs []btcutil.Address 945 addr, err := btcutil.NewAddressPubKeyHash(hash, params) 946 if err == nil { 947 addrs = append(addrs, addr) 948 } 949 return addrs 950 } 951 952 // scriptHashToAddrs is a convenience function to attempt to convert the passed 953 // hash to a pay-to-script-hash address housed within an address slice. It is 954 // used to consolidate common code. 955 func scriptHashToAddrs(hash []byte, params *chaincfg.Params) []btcutil.Address { 956 // Skip the hash if it's invalid for some reason. 957 var addrs []btcutil.Address 958 addr, err := btcutil.NewAddressScriptHashFromHash(hash, params) 959 if err == nil { 960 addrs = append(addrs, addr) 961 } 962 return addrs 963 } 964 965 // ExtractPkScriptAddrs returns the type of script, addresses and required 966 // signatures associated with the passed PkScript. Note that it only works for 967 // 'standard' transaction script types. Any data such as public keys which are 968 // invalid are omitted from the results. 969 func ExtractPkScriptAddrs(pkScript []byte, 970 chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, error) { 971 972 // Check for pay-to-pubkey-hash script. 973 if hash := extractPubKeyHash(pkScript); hash != nil { 974 return PubKeyHashTy, pubKeyHashToAddrs(hash, chainParams), 1, nil 975 } 976 977 // Check for pay-to-script-hash. 978 if hash := extractScriptHash(pkScript); hash != nil { 979 return ScriptHashTy, scriptHashToAddrs(hash, chainParams), 1, nil 980 } 981 982 // Check for pay-to-pubkey script. 983 if data := extractPubKey(pkScript); data != nil { 984 var addrs []btcutil.Address 985 addr, err := btcutil.NewAddressPubKey(data, chainParams) 986 if err == nil { 987 addrs = append(addrs, addr) 988 } 989 return PubKeyTy, addrs, 1, nil 990 } 991 992 // Check for multi-signature script. 993 const scriptVersion = 0 994 details := extractMultisigScriptDetails(scriptVersion, pkScript, true) 995 if details.valid { 996 // Convert the public keys while skipping any that are invalid. 997 addrs := make([]btcutil.Address, 0, len(details.pubKeys)) 998 for _, pubkey := range details.pubKeys { 999 addr, err := btcutil.NewAddressPubKey(pubkey, chainParams) 1000 if err == nil { 1001 addrs = append(addrs, addr) 1002 } 1003 } 1004 return MultiSigTy, addrs, details.requiredSigs, nil 1005 } 1006 1007 // Check for null data script. 1008 if isNullDataScript(scriptVersion, pkScript) { 1009 // Null data transactions have no addresses or required signatures. 1010 return NullDataTy, nil, 0, nil 1011 } 1012 1013 if hash := extractWitnessPubKeyHash(pkScript); hash != nil { 1014 var addrs []btcutil.Address 1015 addr, err := btcutil.NewAddressWitnessPubKeyHash(hash, chainParams) 1016 if err == nil { 1017 addrs = append(addrs, addr) 1018 } 1019 return WitnessV0PubKeyHashTy, addrs, 1, nil 1020 } 1021 1022 if hash := extractWitnessV0ScriptHash(pkScript); hash != nil { 1023 var addrs []btcutil.Address 1024 addr, err := btcutil.NewAddressWitnessScriptHash(hash, chainParams) 1025 if err == nil { 1026 addrs = append(addrs, addr) 1027 } 1028 return WitnessV0ScriptHashTy, addrs, 1, nil 1029 } 1030 1031 if rawKey := extractWitnessV1KeyBytes(pkScript); rawKey != nil { 1032 var addrs []btcutil.Address 1033 addr, err := btcutil.NewAddressTaproot(rawKey, chainParams) 1034 if err == nil { 1035 addrs = append(addrs, addr) 1036 } 1037 return WitnessV1TaprootTy, addrs, 1, nil 1038 } 1039 1040 // If none of the above passed, then the address must be non-standard. 1041 return NonStandardTy, nil, 0, nil 1042 } 1043 1044 // AtomicSwapDataPushes houses the data pushes found in atomic swap contracts. 1045 type AtomicSwapDataPushes struct { 1046 RecipientHash160 [20]byte 1047 RefundHash160 [20]byte 1048 SecretHash [32]byte 1049 SecretSize int64 1050 LockTime int64 1051 } 1052 1053 // ExtractAtomicSwapDataPushes returns the data pushes from an atomic swap 1054 // contract. If the script is not an atomic swap contract, 1055 // ExtractAtomicSwapDataPushes returns (nil, nil). Non-nil errors are returned 1056 // for unparsable scripts. 1057 // 1058 // NOTE: Atomic swaps are not considered standard script types by the dcrd 1059 // mempool policy and should be used with P2SH. The atomic swap format is also 1060 // expected to change to use a more secure hash function in the future. 1061 // 1062 // This function is only defined in the txscript package due to API limitations 1063 // which prevent callers using txscript to parse nonstandard scripts. 1064 // 1065 // DEPRECATED. This will be removed in the next major version bump. The error 1066 // should also likely be removed if the code is reimplemented by any callers 1067 // since any errors result in a nil result anyway. 1068 func ExtractAtomicSwapDataPushes(version uint16, pkScript []byte) (*AtomicSwapDataPushes, error) { 1069 // An atomic swap is of the form: 1070 // IF 1071 // SIZE <secret size> EQUALVERIFY SHA256 <32-byte secret> EQUALVERIFY DUP 1072 // HASH160 <20-byte recipient hash> 1073 // ELSE 1074 // <locktime> CHECKLOCKTIMEVERIFY DROP DUP HASH160 <20-byte refund hash> 1075 // ENDIF 1076 // EQUALVERIFY CHECKSIG 1077 type templateMatch struct { 1078 expectCanonicalInt bool 1079 maxIntBytes int 1080 opcode byte 1081 extractedInt int64 1082 extractedData []byte 1083 } 1084 var template = [20]templateMatch{ 1085 {opcode: OP_IF}, 1086 {opcode: OP_SIZE}, 1087 {expectCanonicalInt: true, maxIntBytes: maxScriptNumLen}, 1088 {opcode: OP_EQUALVERIFY}, 1089 {opcode: OP_SHA256}, 1090 {opcode: OP_DATA_32}, 1091 {opcode: OP_EQUALVERIFY}, 1092 {opcode: OP_DUP}, 1093 {opcode: OP_HASH160}, 1094 {opcode: OP_DATA_20}, 1095 {opcode: OP_ELSE}, 1096 {expectCanonicalInt: true, maxIntBytes: cltvMaxScriptNumLen}, 1097 {opcode: OP_CHECKLOCKTIMEVERIFY}, 1098 {opcode: OP_DROP}, 1099 {opcode: OP_DUP}, 1100 {opcode: OP_HASH160}, 1101 {opcode: OP_DATA_20}, 1102 {opcode: OP_ENDIF}, 1103 {opcode: OP_EQUALVERIFY}, 1104 {opcode: OP_CHECKSIG}, 1105 } 1106 1107 var templateOffset int 1108 tokenizer := MakeScriptTokenizer(version, pkScript) 1109 for tokenizer.Next() { 1110 // Not an atomic swap script if it has more opcodes than expected in the 1111 // template. 1112 if templateOffset >= len(template) { 1113 return nil, nil 1114 } 1115 1116 op := tokenizer.Opcode() 1117 data := tokenizer.Data() 1118 tplEntry := &template[templateOffset] 1119 if tplEntry.expectCanonicalInt { 1120 switch { 1121 case data != nil: 1122 val, err := MakeScriptNum(data, true, tplEntry.maxIntBytes) 1123 if err != nil { 1124 return nil, err 1125 } 1126 tplEntry.extractedInt = int64(val) 1127 1128 case IsSmallInt(op): 1129 tplEntry.extractedInt = int64(AsSmallInt(op)) 1130 1131 // Not an atomic swap script if the opcode does not push an int. 1132 default: 1133 return nil, nil 1134 } 1135 } else { 1136 if op != tplEntry.opcode { 1137 return nil, nil 1138 } 1139 1140 tplEntry.extractedData = data 1141 } 1142 1143 templateOffset++ 1144 } 1145 if err := tokenizer.Err(); err != nil { 1146 return nil, err 1147 } 1148 if !tokenizer.Done() || templateOffset != len(template) { 1149 return nil, nil 1150 } 1151 1152 // At this point, the script appears to be an atomic swap, so populate and 1153 // return the extacted data. 1154 pushes := AtomicSwapDataPushes{ 1155 SecretSize: template[2].extractedInt, 1156 LockTime: template[11].extractedInt, 1157 } 1158 copy(pushes.SecretHash[:], template[5].extractedData) 1159 copy(pushes.RecipientHash160[:], template[9].extractedData) 1160 copy(pushes.RefundHash160[:], template[16].extractedData) 1161 return &pushes, nil 1162 }