standard.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Copyright (c) 2019 Caleb James DeLisle
  3. // Use of this source code is governed by an ISC
  4. // license that can be found in the LICENSE file.
  5. package txscript
  6. import (
  7. "fmt"
  8. "github.com/pkt-cash/pktd/btcutil/er"
  9. "github.com/pkt-cash/pktd/btcutil/util"
  10. "github.com/pkt-cash/pktd/txscript/opcode"
  11. "github.com/pkt-cash/pktd/txscript/parsescript"
  12. "github.com/pkt-cash/pktd/txscript/scriptbuilder"
  13. "github.com/pkt-cash/pktd/txscript/txscripterr"
  14. "github.com/pkt-cash/pktd/btcutil"
  15. "github.com/pkt-cash/pktd/chaincfg"
  16. "github.com/pkt-cash/pktd/wire"
  17. )
  18. const (
  19. // MaxDataCarrierSize is the maximum number of bytes allowed in pushed
  20. // data to be considered a nulldata transaction
  21. MaxDataCarrierSize = 80
  22. // StandardVerifyFlags are the script flags which are used when
  23. // executing transaction scripts to enforce additional checks which
  24. // are required for the script to be considered standard. These checks
  25. // help reduce issues related to transaction malleability as well as
  26. // allow pay-to-script hash transactions. Note these flags are
  27. // different than what is required for the consensus rules in that they
  28. // are more strict.
  29. //
  30. // TODO: This definition does not belong here. It belongs in a policy
  31. // package.
  32. StandardVerifyFlags = ScriptBip16 |
  33. ScriptVerifyDERSignatures |
  34. ScriptVerifyStrictEncoding |
  35. ScriptVerifyMinimalData |
  36. ScriptStrictMultiSig |
  37. ScriptDiscourageUpgradableNops |
  38. ScriptVerifyCleanStack |
  39. ScriptVerifyNullFail |
  40. ScriptVerifyCheckLockTimeVerify |
  41. ScriptVerifyCheckSequenceVerify |
  42. ScriptVerifyLowS |
  43. ScriptStrictMultiSig |
  44. ScriptVerifyWitness |
  45. ScriptVerifyDiscourageUpgradeableWitnessProgram |
  46. ScriptVerifyMinimalIf |
  47. ScriptVerifyWitnessPubKeyType
  48. )
  49. // ScriptClass is an enumeration for the list of standard types of script.
  50. type ScriptClass byte
  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. // scriptClassToName houses the human-readable strings which describe each
  63. // script class.
  64. var scriptClassToName = []string{
  65. NonStandardTy: "nonstandard",
  66. PubKeyTy: "pubkey",
  67. PubKeyHashTy: "pubkeyhash",
  68. WitnessV0PubKeyHashTy: "witness_v0_keyhash",
  69. ScriptHashTy: "scripthash",
  70. WitnessV0ScriptHashTy: "witness_v0_scripthash",
  71. MultiSigTy: "multisig",
  72. NullDataTy: "nulldata",
  73. }
  74. // String implements the Stringer interface by returning the name of
  75. // the enum script class. If the enum is invalid then "Invalid" will be
  76. // returned.
  77. func (t ScriptClass) String() string {
  78. if int(t) > len(scriptClassToName) || int(t) < 0 {
  79. return "Invalid"
  80. }
  81. return scriptClassToName[t]
  82. }
  83. // IsSegwit returns true if the script is a known segwit type.
  84. func (t ScriptClass) IsSegwit() bool {
  85. return t == WitnessV0PubKeyHashTy || t == WitnessV0ScriptHashTy
  86. }
  87. // isPubkey returns true if the script passed is a pay-to-pubkey transaction,
  88. // false otherwise.
  89. func isPubkey(pops []parsescript.ParsedOpcode) bool {
  90. // Valid pubkeys are either 33 or 65 bytes.
  91. return len(pops) == 2 &&
  92. (len(pops[0].Data) == 33 || len(pops[0].Data) == 65) &&
  93. pops[1].Opcode.Value == opcode.OP_CHECKSIG
  94. }
  95. // isPubkeyHash returns true if the script passed is a pay-to-pubkey-hash
  96. // transaction, false otherwise.
  97. func isPubkeyHash(pops []parsescript.ParsedOpcode) bool {
  98. return len(pops) == 5 &&
  99. pops[0].Opcode.Value == opcode.OP_DUP &&
  100. pops[1].Opcode.Value == opcode.OP_HASH160 &&
  101. pops[2].Opcode.Value == opcode.OP_DATA_20 &&
  102. pops[3].Opcode.Value == opcode.OP_EQUALVERIFY &&
  103. pops[4].Opcode.Value == opcode.OP_CHECKSIG
  104. }
  105. // isMultiSig returns true if the passed script is a multisig transaction, false
  106. // otherwise.
  107. func isMultiSig(pops []parsescript.ParsedOpcode) bool {
  108. // The absolute minimum is 1 pubkey:
  109. // OP_0/OP_1-16 <pubkey> OP_1 OP_CHECKMULTISIG
  110. l := len(pops)
  111. if l < 4 {
  112. return false
  113. }
  114. if !isSmallInt(pops[0].Opcode) {
  115. return false
  116. }
  117. if !isSmallInt(pops[l-2].Opcode) {
  118. return false
  119. }
  120. if pops[l-1].Opcode.Value != opcode.OP_CHECKMULTISIG {
  121. return false
  122. }
  123. // Verify the number of pubkeys specified matches the actual number
  124. // of pubkeys provided.
  125. if l-2-1 != asSmallInt(pops[l-2].Opcode) {
  126. return false
  127. }
  128. for _, pop := range pops[1 : l-2] {
  129. // Valid pubkeys are either 33 or 65 bytes.
  130. if len(pop.Data) != 33 && len(pop.Data) != 65 {
  131. return false
  132. }
  133. }
  134. return true
  135. }
  136. // isNullData returns true if the passed script is a null data transaction,
  137. // false otherwise.
  138. func isNullData(pops []parsescript.ParsedOpcode) bool {
  139. // A nulldata transaction is either a single OP_RETURN or an
  140. // OP_RETURN SMALLDATA (where SMALLDATA is a data push up to
  141. // MaxDataCarrierSize bytes).
  142. l := len(pops)
  143. if l == 1 && pops[0].Opcode.Value == opcode.OP_RETURN {
  144. return true
  145. }
  146. return l == 2 &&
  147. pops[0].Opcode.Value == opcode.OP_RETURN &&
  148. (isSmallInt(pops[1].Opcode) || pops[1].Opcode.Value <=
  149. opcode.OP_PUSHDATA4) &&
  150. len(pops[1].Data) <= MaxDataCarrierSize
  151. }
  152. // scriptType returns the type of the script being inspected from the known
  153. // standard types.
  154. func typeOfScript(pops []parsescript.ParsedOpcode) ScriptClass {
  155. if isPubkey(pops) {
  156. return PubKeyTy
  157. } else if isPubkeyHash(pops) {
  158. return PubKeyHashTy
  159. } else if isWitnessPubKeyHash(pops) {
  160. return WitnessV0PubKeyHashTy
  161. } else if isScriptHash(pops) {
  162. return ScriptHashTy
  163. } else if isWitnessScriptHash(pops) {
  164. return WitnessV0ScriptHashTy
  165. } else if isMultiSig(pops) {
  166. return MultiSigTy
  167. } else if isNullData(pops) {
  168. return NullDataTy
  169. }
  170. return NonStandardTy
  171. }
  172. // GetScriptClass returns the class of the script passed.
  173. //
  174. // NonStandardTy will be returned when the script does not parse.
  175. func GetScriptClass(script []byte) ScriptClass {
  176. pops, err := parsescript.ParseScript(script)
  177. if err != nil {
  178. return NonStandardTy
  179. }
  180. pops = stripVote(pops)
  181. return typeOfScript(pops)
  182. }
  183. // expectedInputs returns the number of arguments required by a script.
  184. // If the script is of unknown type such that the number can not be determined
  185. // then -1 is returned. We are an internal function and thus assume that class
  186. // is the real class of pops (and we can thus assume things that were determined
  187. // while finding out the type).
  188. func expectedInputs(pops []parsescript.ParsedOpcode, class ScriptClass) int {
  189. switch class {
  190. case PubKeyTy:
  191. return 1
  192. case PubKeyHashTy:
  193. return 2
  194. case WitnessV0PubKeyHashTy:
  195. return 2
  196. case ScriptHashTy:
  197. // Not including script. That is handled by the caller.
  198. return 1
  199. case WitnessV0ScriptHashTy:
  200. // Not including script. That is handled by the caller.
  201. return 1
  202. case MultiSigTy:
  203. // Standard multisig has a push a small number for the number
  204. // of sigs and number of keys. Check the first push instruction
  205. // to see how many arguments are expected. typeOfScript already
  206. // checked this so we know it'll be a small int. Also, due to
  207. // the original bitcoind bug where OP_CHECKMULTISIG pops an
  208. // additional item from the stack, add an extra expected input
  209. // for the extra push that is required to compensate.
  210. return asSmallInt(pops[0].Opcode) + 1
  211. case NullDataTy:
  212. fallthrough
  213. default:
  214. return -1
  215. }
  216. }
  217. // ScriptInfo houses information about a script pair that is determined by
  218. // CalcScriptInfo.
  219. type ScriptInfo struct {
  220. // PkScriptClass is the class of the public key script and is equivalent
  221. // to calling GetScriptClass on it.
  222. PkScriptClass ScriptClass
  223. // NumInputs is the number of inputs provided by the public key script.
  224. NumInputs int
  225. // ExpectedInputs is the number of outputs required by the signature
  226. // script and any pay-to-script-hash scripts. The number will be -1 if
  227. // unknown.
  228. ExpectedInputs int
  229. // SigOps is the number of signature operations in the script pair.
  230. SigOps int
  231. }
  232. // CalcScriptInfo returns a structure providing data about the provided script
  233. // pair. It will error if the pair is in someway invalid such that they can not
  234. // be analyzed, i.e. if they do not parse or the pkScript is not a push-only
  235. // script
  236. func CalcScriptInfo(sigScript, pkScript []byte, witness wire.TxWitness,
  237. bip16, segwit bool) (*ScriptInfo, er.R) {
  238. sigPops, err := parsescript.ParseScript(sigScript)
  239. if err != nil {
  240. return nil, err
  241. }
  242. pkPops, err := parsescript.ParseScript(pkScript)
  243. if err != nil {
  244. return nil, err
  245. }
  246. // Push only sigScript makes little sense.
  247. si := new(ScriptInfo)
  248. si.PkScriptClass = typeOfScript(pkPops)
  249. // Can't have a signature script that doesn't just push data.
  250. if !parsescript.IsPushOnly(sigPops) {
  251. return nil, txscripterr.ScriptError(txscripterr.ErrNotPushOnly,
  252. "signature script is not push only")
  253. }
  254. si.ExpectedInputs = expectedInputs(pkPops, si.PkScriptClass)
  255. switch {
  256. // Count sigops taking into account pay-to-script-hash.
  257. case si.PkScriptClass == ScriptHashTy && bip16 && !segwit:
  258. // The pay-to-hash-script is the final data push of the
  259. // signature script.
  260. script := sigPops[len(sigPops)-1].Data
  261. shPops, err := parsescript.ParseScript(script)
  262. if err != nil {
  263. return nil, err
  264. }
  265. shInputs := expectedInputs(shPops, typeOfScript(shPops))
  266. if shInputs == -1 {
  267. si.ExpectedInputs = -1
  268. } else {
  269. si.ExpectedInputs += shInputs
  270. }
  271. si.SigOps = getSigOpCount(shPops, true)
  272. // All entries pushed to stack (or are OP_RESERVED and exec
  273. // will fail).
  274. si.NumInputs = len(sigPops)
  275. // If segwit is active, and this is a regular p2wkh output, then we'll
  276. // treat the script as a p2pkh output in essence.
  277. case si.PkScriptClass == WitnessV0PubKeyHashTy && segwit:
  278. si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
  279. si.NumInputs = len(witness)
  280. // We'll attempt to detect the nested p2sh case so we can accurately
  281. // count the signature operations involved.
  282. case si.PkScriptClass == ScriptHashTy &&
  283. IsWitnessProgram(sigScript[1:]) && bip16 && segwit:
  284. // Extract the pushed witness program from the sigScript so we
  285. // can determine the number of expected inputs.
  286. pkPops, _ := parsescript.ParseScript(sigScript[1:])
  287. shInputs := expectedInputs(pkPops, typeOfScript(pkPops))
  288. if shInputs == -1 {
  289. si.ExpectedInputs = -1
  290. } else {
  291. si.ExpectedInputs += shInputs
  292. }
  293. si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
  294. si.NumInputs = len(witness)
  295. si.NumInputs += len(sigPops)
  296. // If segwit is active, and this is a p2wsh output, then we'll need to
  297. // examine the witness script to generate accurate script info.
  298. case si.PkScriptClass == WitnessV0ScriptHashTy && segwit:
  299. // The witness script is the final element of the witness
  300. // stack.
  301. witnessScript := witness[len(witness)-1]
  302. pops, _ := parsescript.ParseScript(witnessScript)
  303. shInputs := expectedInputs(pops, typeOfScript(pops))
  304. if shInputs == -1 {
  305. si.ExpectedInputs = -1
  306. } else {
  307. si.ExpectedInputs += shInputs
  308. }
  309. si.SigOps = GetWitnessSigOpCount(sigScript, pkScript, witness)
  310. si.NumInputs = len(witness)
  311. default:
  312. si.SigOps = getSigOpCount(pkPops, true)
  313. // All entries pushed to stack (or are OP_RESERVED and exec
  314. // will fail).
  315. si.NumInputs = len(sigPops)
  316. }
  317. return si, nil
  318. }
  319. // CalcMultiSigStats returns the number of public keys and signatures from
  320. // a multi-signature transaction script. The passed script MUST already be
  321. // known to be a multi-signature script.
  322. func CalcMultiSigStats(script []byte) (int, int, er.R) {
  323. pops, err := parsescript.ParseScript(script)
  324. if err != nil {
  325. return 0, 0, err
  326. }
  327. // A multi-signature script is of the pattern:
  328. // NUM_SIGS PUBKEY PUBKEY PUBKEY... NUM_PUBKEYS OP_CHECKMULTISIG
  329. // Therefore the number of signatures is the oldest item on the stack
  330. // and the number of pubkeys is the 2nd to last. Also, the absolute
  331. // minimum for a multi-signature script is 1 pubkey, so at least 4
  332. // items must be on the stack per:
  333. // OP_1 PUBKEY OP_1 OP_CHECKMULTISIG
  334. if len(pops) < 4 {
  335. str := fmt.Sprintf("script %x is not a multisig script", script)
  336. return 0, 0, txscripterr.ScriptError(txscripterr.ErrNotMultisigScript, str)
  337. }
  338. numSigs := asSmallInt(pops[0].Opcode)
  339. numPubKeys := asSmallInt(pops[len(pops)-2].Opcode)
  340. return numPubKeys, numSigs, nil
  341. }
  342. // payToPubKeyHashScriptBuilder creates a new script to pay a transaction
  343. // output to a 20-byte pubkey hash. It is expected that the input is a valid
  344. // hash.
  345. func payToPubKeyHashScriptBuilder(pubKeyHash []byte) *scriptbuilder.ScriptBuilder {
  346. return scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_DUP).AddOp(opcode.OP_HASH160).
  347. AddData(pubKeyHash).AddOp(opcode.OP_EQUALVERIFY).AddOp(opcode.OP_CHECKSIG)
  348. }
  349. func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, er.R) {
  350. return payToPubKeyHashScriptBuilder(pubKeyHash).Script()
  351. }
  352. // payToWitnessPubKeyHashScriptBuilder creates a new script to pay to a version 0
  353. // pubkey hash witness program. The passed hash is expected to be valid.
  354. func payToWitnessPubKeyHashScriptBuilder(pubKeyHash []byte) *scriptbuilder.ScriptBuilder {
  355. return scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_0).AddData(pubKeyHash)
  356. }
  357. func payToWitnessPubKeyHashScript(pubKeyHash []byte) ([]byte, er.R) {
  358. return payToWitnessPubKeyHashScriptBuilder(pubKeyHash).Script()
  359. }
  360. // payToScriptHashScriptBuilder creates a new script to pay a transaction output to a
  361. // script hash. It is expected that the input is a valid hash.
  362. func payToScriptHashScriptBuilder(scriptHash []byte) *scriptbuilder.ScriptBuilder {
  363. return scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_HASH160).AddData(scriptHash).
  364. AddOp(opcode.OP_EQUAL)
  365. }
  366. func payToScriptHashScript(scriptHash []byte) ([]byte, er.R) {
  367. return payToScriptHashScriptBuilder(scriptHash).Script()
  368. }
  369. // payToWitnessScriptHashScriptBuilder creates a new script to pay to a version 0
  370. // script hash witness program. The passed hash is expected to be valid.
  371. func payToWitnessScriptHashScriptBuilder(scriptHash []byte) *scriptbuilder.ScriptBuilder {
  372. return scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_0).AddData(scriptHash)
  373. }
  374. func payToWitnessScriptHashScript(scriptHash []byte) ([]byte, er.R) {
  375. return payToWitnessScriptHashScriptBuilder(scriptHash).Script()
  376. }
  377. // payToPubKeyScriptBuilder creates a new script to pay a transaction output to a
  378. // public key. It is expected that the input is a valid pubkey.
  379. func payToPubKeyScriptBuilder(serializedPubKey []byte) *scriptbuilder.ScriptBuilder {
  380. return scriptbuilder.NewScriptBuilder().AddData(serializedPubKey).
  381. AddOp(opcode.OP_CHECKSIG)
  382. }
  383. // appendVote adds a vote to the end of a ScriptBuilder if a voteFor and/or voteAgainst
  384. // is specified. If neither is specified then it will not alter the ScriptBuilder at
  385. // all. The result is the same ScriptBuilder which was passed in.
  386. func appendVote(sb *scriptbuilder.ScriptBuilder, voteFor, voteAgainst []byte) *scriptbuilder.ScriptBuilder {
  387. if voteFor == nil && voteAgainst == nil {
  388. return sb
  389. }
  390. if voteFor != nil {
  391. sb = sb.AddData(voteFor)
  392. } else {
  393. sb = sb.AddOp(opcode.OP_0)
  394. }
  395. if voteAgainst != nil {
  396. sb = sb.AddData(voteAgainst)
  397. } else {
  398. sb = sb.AddOp(opcode.OP_0)
  399. }
  400. return sb.AddOp(opcode.OP_VOTE)
  401. }
  402. func payToNonStandardScriptBuilder(pkScript, voteFor, voteAgainst []byte) ([]byte, er.R) {
  403. pops, err := parsescript.ParseScript(pkScript)
  404. if err != nil {
  405. // There's an error parsing, lets not touch it
  406. return pkScript, nil
  407. }
  408. pops = stripVote(pops)
  409. scriptClass := typeOfScript(pops)
  410. if scriptClass.IsSegwit() {
  411. // It's not possible to append votes to a segwit script
  412. return pkScript, nil
  413. }
  414. vf, va := ElectionGetVotesForAgainst(pkScript)
  415. if vf != nil || va != nil {
  416. // Respect first the vote which is in the address itself
  417. return pkScript, nil
  418. }
  419. // Append our vote to the script address
  420. sb := scriptbuilder.ScriptBuilder{ScriptInt: util.CloneBytes(pkScript)}
  421. return appendVote(&sb, voteFor, voteAgainst).Script()
  422. }
  423. // PayToAddrScriptWithVote creates a new script to pay a transaction output to a the
  424. // specified address and adds a vote for the specified network steward, if voteFor
  425. // and/or voteAgainst are non-null and if the address type is non-segwit.
  426. func PayToAddrScriptWithVote(addr btcutil.Address, voteFor, voteAgainst []byte) ([]byte, er.R) {
  427. if util.IsNil(addr) {
  428. return nil, txscripterr.ScriptError(txscripterr.ErrUnsupportedAddress,
  429. "unable to generate payment script for nil address")
  430. }
  431. switch addr := addr.(type) {
  432. case *btcutil.AddressPubKeyHash:
  433. return appendVote(payToPubKeyHashScriptBuilder(addr.ScriptAddress()),
  434. voteFor, voteAgainst).Script()
  435. case *btcutil.AddressScriptHash:
  436. return appendVote(payToScriptHashScriptBuilder(addr.ScriptAddress()),
  437. voteFor, voteAgainst).Script()
  438. case *btcutil.AddressPubKey:
  439. return appendVote(payToPubKeyScriptBuilder(addr.ScriptAddress()),
  440. voteFor, voteAgainst).Script()
  441. case *btcutil.AddressWitnessPubKeyHash:
  442. return payToWitnessPubKeyHashScript(addr.ScriptAddress())
  443. case *btcutil.AddressWitnessScriptHash:
  444. return payToWitnessScriptHashScript(addr.ScriptAddress())
  445. case *btcutil.AddressNonStandard:
  446. return payToNonStandardScriptBuilder(addr.ScriptAddress(), voteFor, voteAgainst)
  447. }
  448. str := fmt.Sprintf("unable to generate payment script for unsupported "+
  449. "address type %T", addr)
  450. return nil, txscripterr.ScriptError(txscripterr.ErrUnsupportedAddress, str)
  451. }
  452. // PayToAddrScript creates a new script to pay a transaction output to the
  453. // specified address.
  454. func PayToAddrScript(addr btcutil.Address) ([]byte, er.R) {
  455. return PayToAddrScriptWithVote(addr, nil, nil)
  456. }
  457. // stripVote removes any votes from a script so that it will appear as a canonical
  458. // transaction.
  459. func stripVote(pops []parsescript.ParsedOpcode) []parsescript.ParsedOpcode {
  460. out := make([]parsescript.ParsedOpcode, 0, len(pops))
  461. for _, pop := range pops {
  462. out = append(out, pop)
  463. if pop.Opcode.Value != opcode.OP_VOTE {
  464. continue
  465. }
  466. if len(out) < 3 {
  467. continue
  468. }
  469. last := out[len(out)-2]
  470. secondLast := out[len(out)-3]
  471. if last.Opcode.Value != opcode.OP_0 && !canonicalPush(last) {
  472. continue
  473. }
  474. if secondLast.Opcode.Value != opcode.OP_0 && !canonicalPush(secondLast) {
  475. continue
  476. }
  477. // pop second op, last op, vote
  478. out = out[:len(out)-3]
  479. }
  480. return out
  481. }
  482. // NullDataScript creates a provably-prunable script containing OP_RETURN
  483. // followed by the passed data. An Error with the error code ErrTooMuchNullData
  484. // will be returned if the length of the passed data exceeds MaxDataCarrierSize.
  485. func NullDataScript(data []byte) ([]byte, er.R) {
  486. if len(data) > MaxDataCarrierSize {
  487. str := fmt.Sprintf("data size %d is larger than max "+
  488. "allowed size %d", len(data), MaxDataCarrierSize)
  489. return nil, txscripterr.ScriptError(txscripterr.ErrTooMuchNullData, str)
  490. }
  491. return scriptbuilder.NewScriptBuilder().AddOp(opcode.OP_RETURN).AddData(data).Script()
  492. }
  493. // MultiSigScript returns a valid script for a multisignature redemption where
  494. // nrequired of the keys in pubkeys are required to have signed the transaction
  495. // for success. An Error with the error code ErrTooManyRequiredSigs will be
  496. // returned if nrequired is larger than the number of keys provided.
  497. func MultiSigScript(pubkeys []*btcutil.AddressPubKey, nrequired int) ([]byte, er.R) {
  498. if len(pubkeys) < nrequired {
  499. str := fmt.Sprintf("unable to generate multisig script with "+
  500. "%d required signatures when there are only %d public "+
  501. "keys available", nrequired, len(pubkeys))
  502. return nil, txscripterr.ScriptError(txscripterr.ErrTooManyRequiredSigs, str)
  503. }
  504. builder := scriptbuilder.NewScriptBuilder().AddInt64(int64(nrequired))
  505. for _, key := range pubkeys {
  506. builder.AddData(key.ScriptAddress())
  507. }
  508. builder.AddInt64(int64(len(pubkeys)))
  509. builder.AddOp(opcode.OP_CHECKMULTISIG)
  510. return builder.Script()
  511. }
  512. // PushedData returns an array of byte slices containing any pushed data found
  513. // in the passed script. This includes OP_0, but not OP_1 - OP_16.
  514. func PushedData(script []byte) ([][]byte, er.R) {
  515. pops, err := parsescript.ParseScript(script)
  516. if err != nil {
  517. return nil, err
  518. }
  519. var data [][]byte
  520. for _, pop := range pops {
  521. if pop.Data != nil {
  522. data = append(data, pop.Data)
  523. } else if pop.Opcode.Value == opcode.OP_0 {
  524. data = append(data, nil)
  525. }
  526. }
  527. return data, nil
  528. }
  529. // ExtractPkScriptAddrs returns the type of script, addresses and required
  530. // signatures associated with the passed PkScript. Note that it only works for
  531. // 'standard' transaction script types. Any data such as public keys which are
  532. // invalid are omitted from the results.
  533. func ExtractPkScriptAddrs(pkScript []byte, chainParams *chaincfg.Params) (ScriptClass, []btcutil.Address, int, er.R) {
  534. var addrs []btcutil.Address
  535. var requiredSigs int
  536. // No valid addresses or required signatures if the script doesn't
  537. // parse.
  538. pops, err := parsescript.ParseScript(pkScript)
  539. if err != nil {
  540. return NonStandardTy, nil, 0, err
  541. }
  542. pops = stripVote(pops)
  543. scriptClass := typeOfScript(pops)
  544. switch scriptClass {
  545. case PubKeyHashTy:
  546. // A pay-to-pubkey-hash script is of the form:
  547. // OP_DUP OP_HASH160 <hash> OP_EQUALVERIFY OP_CHECKSIG
  548. // Therefore the pubkey hash is the 3rd item on the stack.
  549. // Skip the pubkey hash if it's invalid for some reason.
  550. requiredSigs = 1
  551. addr, err := btcutil.NewAddressPubKeyHash(pops[2].Data,
  552. chainParams)
  553. if err == nil {
  554. addrs = append(addrs, addr)
  555. }
  556. case WitnessV0PubKeyHashTy:
  557. // A pay-to-witness-pubkey-hash script is of thw form:
  558. // OP_0 <20-byte hash>
  559. // Therefore, the pubkey hash is the second item on the stack.
  560. // Skip the pubkey hash if it's invalid for some reason.
  561. requiredSigs = 1
  562. addr, err := btcutil.NewAddressWitnessPubKeyHash(pops[1].Data,
  563. chainParams)
  564. if err == nil {
  565. addrs = append(addrs, addr)
  566. }
  567. case PubKeyTy:
  568. // A pay-to-pubkey script is of the form:
  569. // <pubkey> OP_CHECKSIG
  570. // Therefore the pubkey is the first item on the stack.
  571. // Skip the pubkey if it's invalid for some reason.
  572. requiredSigs = 1
  573. addr, err := btcutil.NewAddressPubKey(pops[0].Data, chainParams)
  574. if err == nil {
  575. addrs = append(addrs, addr)
  576. }
  577. case ScriptHashTy:
  578. // A pay-to-script-hash script is of the form:
  579. // OP_HASH160 <scripthash> OP_EQUAL
  580. // Therefore the script hash is the 2nd item on the stack.
  581. // Skip the script hash if it's invalid for some reason.
  582. requiredSigs = 1
  583. addr, err := btcutil.NewAddressScriptHashFromHash(pops[1].Data,
  584. chainParams)
  585. if err == nil {
  586. addrs = append(addrs, addr)
  587. }
  588. case WitnessV0ScriptHashTy:
  589. // A pay-to-witness-script-hash script is of the form:
  590. // OP_0 <32-byte hash>
  591. // Therefore, the script hash is the second item on the stack.
  592. // Skip the script hash if it's invalid for some reason.
  593. requiredSigs = 1
  594. addr, err := btcutil.NewAddressWitnessScriptHash(pops[1].Data,
  595. chainParams)
  596. if err == nil {
  597. addrs = append(addrs, addr)
  598. }
  599. case MultiSigTy:
  600. // A multi-signature script is of the form:
  601. // <numsigs> <pubkey> <pubkey> <pubkey>... <numpubkeys> OP_CHECKMULTISIG
  602. // Therefore the number of required signatures is the 1st item
  603. // on the stack and the number of public keys is the 2nd to last
  604. // item on the stack.
  605. requiredSigs = asSmallInt(pops[0].Opcode)
  606. numPubKeys := asSmallInt(pops[len(pops)-2].Opcode)
  607. // Extract the public keys while skipping any that are invalid.
  608. addrs = make([]btcutil.Address, 0, numPubKeys)
  609. for i := 0; i < numPubKeys; i++ {
  610. addr, err := btcutil.NewAddressPubKey(pops[i+1].Data,
  611. chainParams)
  612. if err == nil {
  613. addrs = append(addrs, addr)
  614. }
  615. }
  616. case NullDataTy:
  617. // Null data transactions have no addresses or required
  618. // signatures.
  619. case NonStandardTy:
  620. // Don't attempt to extract addresses or required signatures for
  621. // nonstandard transactions.
  622. }
  623. return scriptClass, addrs, requiredSigs, nil
  624. }
  625. // PkScriptToAddress returns the address corresponding to a script.
  626. // Because most multi-signature scripts are segwit and are thus able to be represented as
  627. // addresses, most scripts are able to be represented directly as addresses, but if there
  628. // is a script which is not directly parsable, this function will return "script:" followed
  629. // by a base-64 representation of the pkScript itself such that it can be decoded later.
  630. func PkScriptToAddress(pkScript []byte, chainParams *chaincfg.Params) btcutil.Address {
  631. _, addrs, requiredSigs, err := ExtractPkScriptAddrs(pkScript, chainParams)
  632. if err != nil || len(addrs) != 1 || requiredSigs != 1 {
  633. return btcutil.NewAddressNonStandard(pkScript)
  634. }
  635. return addrs[0]
  636. }