script.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. "bytes"
  8. "encoding/binary"
  9. "github.com/pkt-cash/pktd/btcutil/er"
  10. "github.com/pkt-cash/pktd/txscript/opcode"
  11. "github.com/pkt-cash/pktd/txscript/params"
  12. "github.com/pkt-cash/pktd/txscript/parsescript"
  13. "github.com/pkt-cash/pktd/chaincfg/chainhash"
  14. "github.com/pkt-cash/pktd/wire"
  15. )
  16. // isSmallInt returns whether or not the opcode is considered a small integer,
  17. // which is an OP_0, or OP_1 through OP_16.
  18. func isSmallInt(op opcode.Opcode) bool {
  19. if op.Value == opcode.OP_0 || (op.Value >= opcode.OP_1 && op.Value <= opcode.OP_16) {
  20. return true
  21. }
  22. return false
  23. }
  24. // isScriptHash returns true if the script passed is a pay-to-script-hash
  25. // transaction, false otherwise.
  26. func isScriptHash(pops []parsescript.ParsedOpcode) bool {
  27. return len(pops) == 3 &&
  28. pops[0].Opcode.Value == opcode.OP_HASH160 &&
  29. pops[1].Opcode.Value == opcode.OP_DATA_20 &&
  30. pops[2].Opcode.Value == opcode.OP_EQUAL
  31. }
  32. // IsPayToScriptHash returns true if the script is in the standard
  33. // pay-to-script-hash (P2SH) format, false otherwise.
  34. func IsPayToScriptHash(script []byte) bool {
  35. pops, err := parsescript.ParseScript(script)
  36. if err != nil {
  37. return false
  38. }
  39. return isScriptHash(pops)
  40. }
  41. // isWitnessScriptHash returns true if the passed script is a
  42. // pay-to-witness-script-hash transaction, false otherwise.
  43. func isWitnessScriptHash(pops []parsescript.ParsedOpcode) bool {
  44. return len(pops) == 2 &&
  45. pops[0].Opcode.Value == opcode.OP_0 &&
  46. pops[1].Opcode.Value == opcode.OP_DATA_32
  47. }
  48. // ElectionGetVotesForAgainst gets the candidates who are voted for and voted against
  49. // by the provided pkScript
  50. func ElectionGetVotesForAgainst(pkScript []byte) (voteFor, voteAgainst []byte) {
  51. pops, err := parsescript.ParseScript(pkScript)
  52. if err != nil {
  53. return nil, nil
  54. }
  55. for i, op := range pops {
  56. if op.Opcode.Value != opcode.OP_VOTE {
  57. continue
  58. }
  59. if i < 2 {
  60. // invalid, too short
  61. continue
  62. }
  63. if pops[i-1].Opcode.Value == opcode.OP_0 {
  64. } else if canonicalPush(pops[i-1]) && len(pops[i-1].Data) > 0 && len(pops[i-1].Data) < 80 {
  65. voteAgainst = pops[i-1].Data
  66. } else {
  67. continue
  68. }
  69. if pops[i-2].Opcode.Value == opcode.OP_0 {
  70. } else if canonicalPush(pops[i-2]) && len(pops[i-2].Data) > 0 && len(pops[i-2].Data) < 80 {
  71. voteFor = pops[i-2].Data
  72. } else {
  73. voteAgainst = nil
  74. continue
  75. }
  76. break
  77. }
  78. return
  79. }
  80. // IsPayToWitnessScriptHash returns true if the is in the standard
  81. // pay-to-witness-script-hash (P2WSH) format, false otherwise.
  82. func IsPayToWitnessScriptHash(script []byte) bool {
  83. pops, err := parsescript.ParseScript(script)
  84. if err != nil {
  85. return false
  86. }
  87. return isWitnessScriptHash(pops)
  88. }
  89. // IsPayToWitnessPubKeyHash returns true if the is in the standard
  90. // pay-to-witness-pubkey-hash (P2WKH) format, false otherwise.
  91. func IsPayToWitnessPubKeyHash(script []byte) bool {
  92. pops, err := parsescript.ParseScript(script)
  93. if err != nil {
  94. return false
  95. }
  96. return isWitnessPubKeyHash(pops)
  97. }
  98. // isWitnessPubKeyHash returns true if the passed script is a
  99. // pay-to-witness-pubkey-hash, and false otherwise.
  100. func isWitnessPubKeyHash(pops []parsescript.ParsedOpcode) bool {
  101. return len(pops) == 2 &&
  102. pops[0].Opcode.Value == opcode.OP_0 &&
  103. pops[1].Opcode.Value == opcode.OP_DATA_20
  104. }
  105. // IsWitnessProgram returns true if the passed script is a valid witness
  106. // program which is encoded according to the passed witness program version. A
  107. // witness program must be a small integer (from 0-16), followed by 2-40 bytes
  108. // of pushed data.
  109. func IsWitnessProgram(script []byte) bool {
  110. // The length of the script must be between 4 and 42 bytes. The
  111. // smallest program is the witness version, followed by a data push of
  112. // 2 bytes. The largest allowed witness program has a data push of
  113. // 40-bytes.
  114. if len(script) < 4 || len(script) > 42 {
  115. return false
  116. }
  117. pops, err := parsescript.ParseScript(script)
  118. if err != nil {
  119. return false
  120. }
  121. return isWitnessProgram(pops)
  122. }
  123. // isWitnessProgram returns true if the passed script is a witness program, and
  124. // false otherwise. A witness program MUST adhere to the following constraints:
  125. // there must be exactly two pops (program version and the program itself), the
  126. // first opcode MUST be a small integer (0-16), the push data MUST be
  127. // canonical, and finally the size of the push data must be between 2 and 40
  128. // bytes.
  129. func isWitnessProgram(pops []parsescript.ParsedOpcode) bool {
  130. return len(pops) == 2 &&
  131. isSmallInt(pops[0].Opcode) &&
  132. canonicalPush(pops[1]) &&
  133. (len(pops[1].Data) >= 2 && len(pops[1].Data) <= 40)
  134. }
  135. // ExtractWitnessProgramInfo attempts to extract the witness program version,
  136. // as well as the witness program itself from the passed script.
  137. func ExtractWitnessProgramInfo(script []byte) (int, []byte, er.R) {
  138. pops, err := parsescript.ParseScript(script)
  139. if err != nil {
  140. return 0, nil, err
  141. }
  142. // If at this point, the scripts doesn't resemble a witness program,
  143. // then we'll exit early as there isn't a valid version or program to
  144. // extract.
  145. if !isWitnessProgram(pops) {
  146. return 0, nil, er.Errorf("script is not a witness program, " +
  147. "unable to extract version or witness program")
  148. }
  149. witnessVersion := asSmallInt(pops[0].Opcode)
  150. witnessProgram := pops[1].Data
  151. return witnessVersion, witnessProgram, nil
  152. }
  153. // IsPushOnlyScript returns whether or not the passed script only pushes data.
  154. //
  155. // False will be returned when the script does not parse.
  156. func IsPushOnlyScript(script []byte) bool {
  157. pops, err := parsescript.ParseScript(script)
  158. if err != nil {
  159. return false
  160. }
  161. return parsescript.IsPushOnly(pops)
  162. }
  163. // unparseScript reversed the action of parseScript and returns the
  164. // parsedOpcodes as a list of bytes
  165. func unparseScript(pops []parsescript.ParsedOpcode) ([]byte, er.R) {
  166. script := make([]byte, 0, len(pops))
  167. for _, pop := range pops {
  168. b, err := popBytes(&pop)
  169. if err != nil {
  170. return nil, err
  171. }
  172. script = append(script, b...)
  173. }
  174. return script, nil
  175. }
  176. // DisasmString formats a disassembled script for one line printing. When the
  177. // script fails to parse, the returned string will contain the disassembled
  178. // script up to the point the failure occurred along with the string '[error]'
  179. // appended. In addition, the reason the script failed to parse is returned
  180. // if the caller wants more information about the failure.
  181. func DisasmString(buf []byte) (string, er.R) {
  182. var disbuf bytes.Buffer
  183. opcodes, err := parsescript.ParseScript(buf)
  184. for _, pop := range opcodes {
  185. disbuf.WriteString(popPrint(&pop, true))
  186. disbuf.WriteByte(' ')
  187. }
  188. if disbuf.Len() > 0 {
  189. disbuf.Truncate(disbuf.Len() - 1)
  190. }
  191. if err != nil {
  192. disbuf.WriteString("[error]")
  193. }
  194. return disbuf.String(), err
  195. }
  196. // removeOpcode will remove any opcode matching ``opcode'' from the opcode
  197. // stream in pkscript
  198. func removeOpcode(pkscript []parsescript.ParsedOpcode, opcode byte) []parsescript.ParsedOpcode {
  199. retScript := make([]parsescript.ParsedOpcode, 0, len(pkscript))
  200. for _, pop := range pkscript {
  201. if pop.Opcode.Value != opcode {
  202. retScript = append(retScript, pop)
  203. }
  204. }
  205. return retScript
  206. }
  207. // canonicalPush returns true if the object is either not a push instruction
  208. // or the push instruction contained wherein is matches the canonical form
  209. // or using the smallest instruction to do the job. False otherwise.
  210. func canonicalPush(pop parsescript.ParsedOpcode) bool {
  211. op := pop.Opcode.Value
  212. data := pop.Data
  213. dataLen := len(pop.Data)
  214. if op > opcode.OP_16 {
  215. return true
  216. }
  217. if op < opcode.OP_PUSHDATA1 && op > opcode.OP_0 && (dataLen == 1 && data[0] <= 16) {
  218. return false
  219. }
  220. if op == opcode.OP_PUSHDATA1 && dataLen < opcode.OP_PUSHDATA1 {
  221. return false
  222. }
  223. if op == opcode.OP_PUSHDATA2 && dataLen <= 0xff {
  224. return false
  225. }
  226. if op == opcode.OP_PUSHDATA4 && dataLen <= 0xffff {
  227. return false
  228. }
  229. return true
  230. }
  231. // removeOpcodeByData will return the script minus any opcodes that would push
  232. // the passed data to the stack.
  233. func removeOpcodeByData(pkscript []parsescript.ParsedOpcode, data []byte) []parsescript.ParsedOpcode {
  234. retScript := make([]parsescript.ParsedOpcode, 0, len(pkscript))
  235. for _, pop := range pkscript {
  236. if !canonicalPush(pop) || !bytes.Contains(pop.Data, data) {
  237. retScript = append(retScript, pop)
  238. }
  239. }
  240. return retScript
  241. }
  242. // calcHashPrevOuts calculates a single hash of all the previous outputs
  243. // (txid:index) referenced within the passed transaction. This calculated hash
  244. // can be re-used when validating all inputs spending segwit outputs, with a
  245. // signature hash type of SigHashAll. This allows validation to re-use previous
  246. // hashing computation, reducing the complexity of validating SigHashAll inputs
  247. // from O(N^2) to O(N).
  248. func calcHashPrevOuts(tx *wire.MsgTx) chainhash.Hash {
  249. var b bytes.Buffer
  250. for _, in := range tx.TxIn {
  251. // First write out the 32-byte transaction ID one of whose
  252. // outputs are being referenced by this input.
  253. b.Write(in.PreviousOutPoint.Hash[:])
  254. // Next, we'll encode the index of the referenced output as a
  255. // little endian integer.
  256. var buf [4]byte
  257. binary.LittleEndian.PutUint32(buf[:], in.PreviousOutPoint.Index)
  258. b.Write(buf[:])
  259. }
  260. return chainhash.DoubleHashH(b.Bytes())
  261. }
  262. // calcHashSequence computes an aggregated hash of each of the sequence numbers
  263. // within the inputs of the passed transaction. This single hash can be re-used
  264. // when validating all inputs spending segwit outputs, which include signatures
  265. // using the SigHashAll sighash type. This allows validation to re-use previous
  266. // hashing computation, reducing the complexity of validating SigHashAll inputs
  267. // from O(N^2) to O(N).
  268. func calcHashSequence(tx *wire.MsgTx) chainhash.Hash {
  269. var b bytes.Buffer
  270. for _, in := range tx.TxIn {
  271. var buf [4]byte
  272. binary.LittleEndian.PutUint32(buf[:], in.Sequence)
  273. b.Write(buf[:])
  274. }
  275. return chainhash.DoubleHashH(b.Bytes())
  276. }
  277. // calcHashOutputs computes a hash digest of all outputs created by the
  278. // transaction encoded using the wire format. This single hash can be re-used
  279. // when validating all inputs spending witness programs, which include
  280. // signatures using the SigHashAll sighash type. This allows computation to be
  281. // cached, reducing the total hashing complexity from O(N^2) to O(N).
  282. func calcHashOutputs(tx *wire.MsgTx) chainhash.Hash {
  283. var b bytes.Buffer
  284. for _, out := range tx.TxOut {
  285. wire.WriteTxOut(&b, 0, 0, out)
  286. }
  287. return chainhash.DoubleHashH(b.Bytes())
  288. }
  289. // CalcWitnessSigHash computes the sighash digest for the specified input of
  290. // the target transaction observing the desired sig hash type.
  291. func CalcWitnessSigHash(script []byte, sigHashes *TxSigHashes, hType params.SigHashType,
  292. tx *wire.MsgTx, idx int, amt int64) ([]byte, er.R) {
  293. parsedScript, err := parsescript.ParseScript(script)
  294. if err != nil {
  295. return nil, er.Errorf("cannot parse output script: %v", err)
  296. }
  297. return calcWitnessSignatureHash(parsedScript, sigHashes, hType, tx, idx,
  298. amt)
  299. }
  300. // calcWitnessSignatureHash computes the sighash digest of a transaction's
  301. // segwit input using the new, optimized digest calculation algorithm defined
  302. // in BIP0143: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.
  303. // This function makes use of pre-calculated sighash fragments stored within
  304. // the passed HashCache to eliminate duplicate hashing computations when
  305. // calculating the final digest, reducing the complexity from O(N^2) to O(N).
  306. // Additionally, signatures now cover the input value of the referenced unspent
  307. // output. This allows offline, or hardware wallets to compute the exact amount
  308. // being spent, in addition to the final transaction fee. In the case the
  309. // wallet if fed an invalid input amount, the real sighash will differ causing
  310. // the produced signature to be invalid.
  311. func calcWitnessSignatureHash(subScript []parsescript.ParsedOpcode, sigHashes *TxSigHashes,
  312. hashType params.SigHashType, tx *wire.MsgTx, idx int, amt int64) ([]byte, er.R) {
  313. // As a sanity check, ensure the passed input index for the transaction
  314. // is valid.
  315. if idx > len(tx.TxIn)-1 {
  316. return nil, er.Errorf("idx %d but %d txins", idx, len(tx.TxIn))
  317. }
  318. // We'll utilize this buffer throughout to incrementally calculate
  319. // the signature hash for this transaction.
  320. var sigHash bytes.Buffer
  321. // First write out, then encode the transaction's version number.
  322. var bVersion [4]byte
  323. binary.LittleEndian.PutUint32(bVersion[:], uint32(tx.Version))
  324. sigHash.Write(bVersion[:])
  325. // Next write out the possibly pre-calculated hashes for the sequence
  326. // numbers of all inputs, and the hashes of the previous outs for all
  327. // outputs.
  328. var zeroHash chainhash.Hash
  329. // If anyone can pay isn't active, then we can use the cached
  330. // hashPrevOuts, otherwise we just write zeroes for the prev outs.
  331. if hashType&params.SigHashAnyOneCanPay == 0 {
  332. sigHash.Write(sigHashes.HashPrevOuts[:])
  333. } else {
  334. sigHash.Write(zeroHash[:])
  335. }
  336. // If the sighash isn't anyone can pay, single, or none, the use the
  337. // cached hash sequences, otherwise write all zeroes for the
  338. // hashSequence.
  339. if hashType&params.SigHashAnyOneCanPay == 0 &&
  340. hashType&params.SigHashMask != params.SigHashSingle &&
  341. hashType&params.SigHashMask != params.SigHashNone {
  342. sigHash.Write(sigHashes.HashSequence[:])
  343. } else {
  344. sigHash.Write(zeroHash[:])
  345. }
  346. txIn := tx.TxIn[idx]
  347. // Next, write the outpoint being spent.
  348. sigHash.Write(txIn.PreviousOutPoint.Hash[:])
  349. var bIndex [4]byte
  350. binary.LittleEndian.PutUint32(bIndex[:], txIn.PreviousOutPoint.Index)
  351. sigHash.Write(bIndex[:])
  352. if isWitnessPubKeyHash(subScript) {
  353. // The script code for a p2wkh is a length prefix varint for
  354. // the next 25 bytes, followed by a re-creation of the original
  355. // p2pkh pk script.
  356. sigHash.Write([]byte{0x19})
  357. sigHash.Write([]byte{opcode.OP_DUP})
  358. sigHash.Write([]byte{opcode.OP_HASH160})
  359. sigHash.Write([]byte{opcode.OP_DATA_20})
  360. sigHash.Write(subScript[1].Data)
  361. sigHash.Write([]byte{opcode.OP_EQUALVERIFY})
  362. sigHash.Write([]byte{opcode.OP_CHECKSIG})
  363. } else {
  364. // For p2wsh outputs, and future outputs, the script code is
  365. // the original script, with all code separators removed,
  366. // serialized with a var int length prefix.
  367. rawScript, _ := unparseScript(subScript)
  368. wire.WriteVarBytes(&sigHash, 0, rawScript)
  369. }
  370. // Next, add the input amount, and sequence number of the input being
  371. // signed.
  372. var bAmount [8]byte
  373. binary.LittleEndian.PutUint64(bAmount[:], uint64(amt))
  374. sigHash.Write(bAmount[:])
  375. var bSequence [4]byte
  376. binary.LittleEndian.PutUint32(bSequence[:], txIn.Sequence)
  377. sigHash.Write(bSequence[:])
  378. // If the current signature mode isn't single, or none, then we can
  379. // re-use the pre-generated hashoutputs sighash fragment. Otherwise,
  380. // we'll serialize and add only the target output index to the signature
  381. // pre-image.
  382. if hashType&params.SigHashSingle != params.SigHashSingle &&
  383. hashType&params.SigHashNone != params.SigHashNone {
  384. sigHash.Write(sigHashes.HashOutputs[:])
  385. } else if hashType&params.SigHashMask == params.SigHashSingle && idx < len(tx.TxOut) {
  386. var b bytes.Buffer
  387. wire.WriteTxOut(&b, 0, 0, tx.TxOut[idx])
  388. sigHash.Write(chainhash.DoubleHashB(b.Bytes()))
  389. } else {
  390. sigHash.Write(zeroHash[:])
  391. }
  392. // Finally, write out the transaction's locktime, and the sig hash
  393. // type.
  394. var bLockTime [4]byte
  395. binary.LittleEndian.PutUint32(bLockTime[:], tx.LockTime)
  396. sigHash.Write(bLockTime[:])
  397. var bHashType [4]byte
  398. binary.LittleEndian.PutUint32(bHashType[:], uint32(hashType))
  399. sigHash.Write(bHashType[:])
  400. return chainhash.DoubleHashB(sigHash.Bytes()), nil
  401. }
  402. // shallowCopyTx creates a shallow copy of the transaction for use when
  403. // calculating the signature hash. It is used over the Copy method on the
  404. // transaction itself since that is a deep copy and therefore does more work and
  405. // allocates much more space than needed.
  406. func shallowCopyTx(tx *wire.MsgTx) wire.MsgTx {
  407. // As an additional memory optimization, use contiguous backing arrays
  408. // for the copied inputs and outputs and point the final slice of
  409. // pointers into the contiguous arrays. This avoids a lot of small
  410. // allocations.
  411. txCopy := wire.MsgTx{
  412. Version: tx.Version,
  413. TxIn: make([]*wire.TxIn, len(tx.TxIn)),
  414. TxOut: make([]*wire.TxOut, len(tx.TxOut)),
  415. LockTime: tx.LockTime,
  416. }
  417. txIns := make([]wire.TxIn, len(tx.TxIn))
  418. for i, oldTxIn := range tx.TxIn {
  419. txIns[i] = *oldTxIn
  420. txCopy.TxIn[i] = &txIns[i]
  421. }
  422. txOuts := make([]wire.TxOut, len(tx.TxOut))
  423. for i, oldTxOut := range tx.TxOut {
  424. txOuts[i] = *oldTxOut
  425. txCopy.TxOut[i] = &txOuts[i]
  426. }
  427. return txCopy
  428. }
  429. // CalcSignatureHash will, given a script and hash type for the current script
  430. // engine instance, calculate the signature hash to be used for signing and
  431. // verification.
  432. func CalcSignatureHash(script []byte, hashType params.SigHashType, tx *wire.MsgTx, idx int) ([]byte, er.R) {
  433. parsedScript, err := parsescript.ParseScript(script)
  434. if err != nil {
  435. return nil, er.Errorf("cannot parse output script: %v", err)
  436. }
  437. return calcSignatureHash(parsedScript, hashType, tx, idx), nil
  438. }
  439. // calcSignatureHash will, given a script and hash type for the current script
  440. // engine instance, calculate the signature hash to be used for signing and
  441. // verification.
  442. func calcSignatureHash(script []parsescript.ParsedOpcode, hashType params.SigHashType, tx *wire.MsgTx, idx int) []byte {
  443. // The SigHashSingle signature type signs only the corresponding input
  444. // and output (the output with the same index number as the input).
  445. //
  446. // Since transactions can have more inputs than outputs, this means it
  447. // is improper to use SigHashSingle on input indices that don't have a
  448. // corresponding output.
  449. //
  450. // A bug in the original Satoshi client implementation means specifying
  451. // an index that is out of range results in a signature hash of 1 (as a
  452. // uint256 little endian). The original intent appeared to be to
  453. // indicate failure, but unfortunately, it was never checked and thus is
  454. // treated as the actual signature hash. This buggy behavior is now
  455. // part of the consensus and a hard fork would be required to fix it.
  456. //
  457. // Due to this, care must be taken by software that creates transactions
  458. // which make use of SigHashSingle because it can lead to an extremely
  459. // dangerous situation where the invalid inputs will end up signing a
  460. // hash of 1. This in turn presents an opportunity for attackers to
  461. // cleverly construct transactions which can steal those coins provided
  462. // they can reuse signatures.
  463. if hashType&params.SigHashMask == params.SigHashSingle && idx >= len(tx.TxOut) {
  464. var hash chainhash.Hash
  465. hash[0] = 0x01
  466. return hash[:]
  467. }
  468. // Remove all instances of OP_CODESEPARATOR from the script.
  469. script = removeOpcode(script, opcode.OP_CODESEPARATOR)
  470. // Make a shallow copy of the transaction, zeroing out the script for
  471. // all inputs that are not currently being processed.
  472. txCopy := shallowCopyTx(tx)
  473. for i := range txCopy.TxIn {
  474. if i == idx {
  475. // UnparseScript cannot fail here because removeOpcode
  476. // above only returns a valid script.
  477. sigScript, _ := unparseScript(script)
  478. txCopy.TxIn[idx].SignatureScript = sigScript
  479. } else {
  480. txCopy.TxIn[i].SignatureScript = nil
  481. }
  482. }
  483. switch hashType & params.SigHashMask {
  484. case params.SigHashNone:
  485. txCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.
  486. for i := range txCopy.TxIn {
  487. if i != idx {
  488. txCopy.TxIn[i].Sequence = 0
  489. }
  490. }
  491. case params.SigHashSingle:
  492. // Resize output array to up to and including requested index.
  493. txCopy.TxOut = txCopy.TxOut[:idx+1]
  494. // All but current output get zeroed out.
  495. for i := 0; i < idx; i++ {
  496. txCopy.TxOut[i].Value = -1
  497. txCopy.TxOut[i].PkScript = nil
  498. }
  499. // Sequence on all other inputs is 0, too.
  500. for i := range txCopy.TxIn {
  501. if i != idx {
  502. txCopy.TxIn[i].Sequence = 0
  503. }
  504. }
  505. case params.SigHashOld:
  506. fallthrough
  507. case params.SigHashAll:
  508. fallthrough
  509. default:
  510. // Consensus treats undefined hashtypes like normal SigHashAll
  511. // for purposes of hash generation.
  512. }
  513. if hashType&params.SigHashAnyOneCanPay != 0 {
  514. txCopy.TxIn = txCopy.TxIn[idx : idx+1]
  515. }
  516. // The final hash is the double sha256 of both the serialized modified
  517. // transaction and the hash type (encoded as a 4-byte little-endian
  518. // value) appended.
  519. wbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))
  520. txCopy.SerializeNoWitness(wbuf)
  521. errr := binary.Write(wbuf, binary.LittleEndian, hashType)
  522. if errr != nil {
  523. panic("calcSignatureHash: binary.Write failed")
  524. }
  525. return chainhash.DoubleHashB(wbuf.Bytes())
  526. }
  527. // asSmallInt returns the passed opcode, which must be true according to
  528. // isSmallInt(), as an integer.
  529. func asSmallInt(op opcode.Opcode) int {
  530. if op.Value == opcode.OP_0 {
  531. return 0
  532. }
  533. return int(op.Value - (opcode.OP_1 - 1))
  534. }
  535. // getSigOpCount is the implementation function for counting the number of
  536. // signature operations in the script provided by pops. If precise mode is
  537. // requested then we attempt to count the number of operations for a multisig
  538. // op. Otherwise we use the maximum.
  539. func getSigOpCount(pops []parsescript.ParsedOpcode, precise bool) int {
  540. nSigs := 0
  541. for i, pop := range pops {
  542. switch pop.Opcode.Value {
  543. case opcode.OP_CHECKSIG:
  544. fallthrough
  545. case opcode.OP_CHECKSIGVERIFY:
  546. nSigs++
  547. case opcode.OP_CHECKMULTISIG:
  548. fallthrough
  549. case opcode.OP_CHECKMULTISIGVERIFY:
  550. // If we are being precise then look for familiar
  551. // patterns for multisig, for now all we recognize is
  552. // OP_1 - OP_16 to signify the number of pubkeys.
  553. // Otherwise, we use the max of 20.
  554. if precise && i > 0 &&
  555. pops[i-1].Opcode.Value >= opcode.OP_1 &&
  556. pops[i-1].Opcode.Value <= opcode.OP_16 {
  557. nSigs += asSmallInt(pops[i-1].Opcode)
  558. } else {
  559. nSigs += params.MaxPubKeysPerMultiSig
  560. }
  561. default:
  562. // Not a sigop.
  563. }
  564. }
  565. return nSigs
  566. }
  567. // GetSigOpCount provides a quick count of the number of signature operations
  568. // in a script. a CHECKSIG operations counts for 1, and a CHECK_MULTISIG for 20.
  569. // If the script fails to parse, then the count up to the point of failure is
  570. // returned.
  571. func GetSigOpCount(script []byte) int {
  572. // Don't check error since parseScript returns the parsed-up-to-error
  573. // list of pops.
  574. pops, _ := parsescript.ParseScript(script)
  575. return getSigOpCount(pops, false)
  576. }
  577. // GetPreciseSigOpCount returns the number of signature operations in
  578. // scriptPubKey. If bip16 is true then scriptSig may be searched for the
  579. // Pay-To-Script-Hash script in order to find the precise number of signature
  580. // operations in the transaction. If the script fails to parse, then the count
  581. // up to the point of failure is returned.
  582. func GetPreciseSigOpCount(scriptSig, scriptPubKey []byte, bip16 bool) int {
  583. // Don't check error since parseScript returns the parsed-up-to-error
  584. // list of pops.
  585. pops, _ := parsescript.ParseScript(scriptPubKey)
  586. // Treat non P2SH transactions as normal.
  587. if !(bip16 && isScriptHash(pops)) {
  588. return getSigOpCount(pops, true)
  589. }
  590. // The public key script is a pay-to-script-hash, so parse the signature
  591. // script to get the final item. Scripts that fail to fully parse count
  592. // as 0 signature operations.
  593. sigPops, err := parsescript.ParseScript(scriptSig)
  594. if err != nil {
  595. return 0
  596. }
  597. // The signature script must only push data to the stack for P2SH to be
  598. // a valid pair, so the signature operation count is 0 when that is not
  599. // the case.
  600. if !parsescript.IsPushOnly(sigPops) || len(sigPops) == 0 {
  601. return 0
  602. }
  603. // The P2SH script is the last item the signature script pushes to the
  604. // stack. When the script is empty, there are no signature operations.
  605. shScript := sigPops[len(sigPops)-1].Data
  606. if len(shScript) == 0 {
  607. return 0
  608. }
  609. // Parse the P2SH script and don't check the error since parseScript
  610. // returns the parsed-up-to-error list of pops and the consensus rules
  611. // dictate signature operations are counted up to the first parse
  612. // failure.
  613. shPops, _ := parsescript.ParseScript(shScript)
  614. return getSigOpCount(shPops, true)
  615. }
  616. // GetWitnessSigOpCount returns the number of signature operations generated by
  617. // spending the passed pkScript with the specified witness, or sigScript.
  618. // Unlike GetPreciseSigOpCount, this function is able to accurately count the
  619. // number of signature operations generated by spending witness programs, and
  620. // nested p2sh witness programs. If the script fails to parse, then the count
  621. // up to the point of failure is returned.
  622. func GetWitnessSigOpCount(sigScript, pkScript []byte, witness wire.TxWitness) int {
  623. // If this is a regular witness program, then we can proceed directly
  624. // to counting its signature operations without any further processing.
  625. if IsWitnessProgram(pkScript) {
  626. return getWitnessSigOps(pkScript, witness)
  627. }
  628. // Next, we'll check the sigScript to see if this is a nested p2sh
  629. // witness program. This is a case wherein the sigScript is actually a
  630. // datapush of a p2wsh witness program.
  631. sigPops, err := parsescript.ParseScript(sigScript)
  632. if err != nil {
  633. return 0
  634. }
  635. if IsPayToScriptHash(pkScript) && parsescript.IsPushOnly(sigPops) &&
  636. IsWitnessProgram(sigScript[1:]) {
  637. return getWitnessSigOps(sigScript[1:], witness)
  638. }
  639. return 0
  640. }
  641. // getWitnessSigOps returns the number of signature operations generated by
  642. // spending the passed witness program wit the passed witness. The exact
  643. // signature counting heuristic is modified by the version of the passed
  644. // witness program. If the version of the witness program is unable to be
  645. // extracted, then 0 is returned for the sig op count.
  646. func getWitnessSigOps(pkScript []byte, witness wire.TxWitness) int {
  647. // Attempt to extract the witness program version.
  648. witnessVersion, witnessProgram, err := ExtractWitnessProgramInfo(
  649. pkScript,
  650. )
  651. if err != nil {
  652. return 0
  653. }
  654. switch witnessVersion {
  655. case 0:
  656. switch {
  657. case len(witnessProgram) == params.PayToWitnessPubKeyHashDataSize:
  658. return 1
  659. case len(witnessProgram) == params.PayToWitnessScriptHashDataSize &&
  660. len(witness) > 0:
  661. witnessScript := witness[len(witness)-1]
  662. pops, _ := parsescript.ParseScript(witnessScript)
  663. return getSigOpCount(pops, true)
  664. }
  665. }
  666. return 0
  667. }
  668. // IsUnspendable returns whether the passed public key script is unspendable, or
  669. // guaranteed to fail at execution. This allows inputs to be pruned instantly
  670. // when entering the UTXO set.
  671. func IsUnspendable(pkScript []byte) bool {
  672. pops, err := parsescript.ParseScript(pkScript)
  673. if err != nil {
  674. return true
  675. }
  676. return len(pops) > 0 && pops[0].Opcode.Value == opcode.OP_RETURN
  677. }