script.cpp raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-present The Limenka developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #include <script/script.h>
   7  
   8  #include <crypto/common.h>
   9  #include <crypto/hex_base.h>
  10  #include <hash.h>
  11  #include <script/interpreter.h>
  12  #include <uint256.h>
  13  #include <util/hash_type.h>
  14  
  15  #include <string>
  16  
  17  CScriptID::CScriptID(const CScript& in) : BaseHash(Hash160(in)) {}
  18  
  19  std::string GetOpName(opcodetype opcode)
  20  {
  21      switch (opcode)
  22      {
  23      // push value
  24      case OP_0                      : return "0";
  25      case OP_PUSHDATA1              : return "OP_PUSHDATA1";
  26      case OP_PUSHDATA2              : return "OP_PUSHDATA2";
  27      case OP_PUSHDATA4              : return "OP_PUSHDATA4";
  28      case OP_1NEGATE                : return "-1";
  29      case OP_RESERVED               : return "OP_RESERVED";
  30      case OP_1                      : return "1";
  31      case OP_2                      : return "2";
  32      case OP_3                      : return "3";
  33      case OP_4                      : return "4";
  34      case OP_5                      : return "5";
  35      case OP_6                      : return "6";
  36      case OP_7                      : return "7";
  37      case OP_8                      : return "8";
  38      case OP_9                      : return "9";
  39      case OP_10                     : return "10";
  40      case OP_11                     : return "11";
  41      case OP_12                     : return "12";
  42      case OP_13                     : return "13";
  43      case OP_14                     : return "14";
  44      case OP_15                     : return "15";
  45      case OP_16                     : return "16";
  46  
  47      // control
  48      case OP_NOP                    : return "OP_NOP";
  49      case OP_VER                    : return "OP_VER";
  50      case OP_IF                     : return "OP_IF";
  51      case OP_NOTIF                  : return "OP_NOTIF";
  52      case OP_VERIF                  : return "OP_VERIF";
  53      case OP_VERNOTIF               : return "OP_VERNOTIF";
  54      case OP_ELSE                   : return "OP_ELSE";
  55      case OP_ENDIF                  : return "OP_ENDIF";
  56      case OP_VERIFY                 : return "OP_VERIFY";
  57      case OP_RETURN                 : return "OP_RETURN";
  58  
  59      // stack ops
  60      case OP_TOALTSTACK             : return "OP_TOALTSTACK";
  61      case OP_FROMALTSTACK           : return "OP_FROMALTSTACK";
  62      case OP_2DROP                  : return "OP_2DROP";
  63      case OP_2DUP                   : return "OP_2DUP";
  64      case OP_3DUP                   : return "OP_3DUP";
  65      case OP_2OVER                  : return "OP_2OVER";
  66      case OP_2ROT                   : return "OP_2ROT";
  67      case OP_2SWAP                  : return "OP_2SWAP";
  68      case OP_IFDUP                  : return "OP_IFDUP";
  69      case OP_DEPTH                  : return "OP_DEPTH";
  70      case OP_DROP                   : return "OP_DROP";
  71      case OP_DUP                    : return "OP_DUP";
  72      case OP_NIP                    : return "OP_NIP";
  73      case OP_OVER                   : return "OP_OVER";
  74      case OP_PICK                   : return "OP_PICK";
  75      case OP_ROLL                   : return "OP_ROLL";
  76      case OP_ROT                    : return "OP_ROT";
  77      case OP_SWAP                   : return "OP_SWAP";
  78      case OP_TUCK                   : return "OP_TUCK";
  79  
  80      // splice ops
  81      case OP_CAT                    : return "OP_CAT";
  82      case OP_SUBSTR                 : return "OP_SUBSTR";
  83      case OP_LEFT                   : return "OP_LEFT";
  84      case OP_RIGHT                  : return "OP_RIGHT";
  85      case OP_SIZE                   : return "OP_SIZE";
  86  
  87      // bit logic
  88      case OP_INVERT                 : return "OP_INVERT";
  89      case OP_AND                    : return "OP_AND";
  90      case OP_OR                     : return "OP_OR";
  91      case OP_XOR                    : return "OP_XOR";
  92      case OP_EQUAL                  : return "OP_EQUAL";
  93      case OP_EQUALVERIFY            : return "OP_EQUALVERIFY";
  94      case OP_RESERVED1              : return "OP_RESERVED1";
  95      case OP_RESERVED2              : return "OP_RESERVED2";
  96  
  97      // numeric
  98      case OP_1ADD                   : return "OP_1ADD";
  99      case OP_1SUB                   : return "OP_1SUB";
 100      case OP_2MUL                   : return "OP_2MUL";
 101      case OP_2DIV                   : return "OP_2DIV";
 102      case OP_NEGATE                 : return "OP_NEGATE";
 103      case OP_ABS                    : return "OP_ABS";
 104      case OP_NOT                    : return "OP_NOT";
 105      case OP_0NOTEQUAL              : return "OP_0NOTEQUAL";
 106      case OP_ADD                    : return "OP_ADD";
 107      case OP_SUB                    : return "OP_SUB";
 108      case OP_MUL                    : return "OP_MUL";
 109      case OP_DIV                    : return "OP_DIV";
 110      case OP_MOD                    : return "OP_MOD";
 111      case OP_LSHIFT                 : return "OP_LSHIFT";
 112      case OP_RSHIFT                 : return "OP_RSHIFT";
 113      case OP_BOOLAND                : return "OP_BOOLAND";
 114      case OP_BOOLOR                 : return "OP_BOOLOR";
 115      case OP_NUMEQUAL               : return "OP_NUMEQUAL";
 116      case OP_NUMEQUALVERIFY         : return "OP_NUMEQUALVERIFY";
 117      case OP_NUMNOTEQUAL            : return "OP_NUMNOTEQUAL";
 118      case OP_LESSTHAN               : return "OP_LESSTHAN";
 119      case OP_GREATERTHAN            : return "OP_GREATERTHAN";
 120      case OP_LESSTHANOREQUAL        : return "OP_LESSTHANOREQUAL";
 121      case OP_GREATERTHANOREQUAL     : return "OP_GREATERTHANOREQUAL";
 122      case OP_MIN                    : return "OP_MIN";
 123      case OP_MAX                    : return "OP_MAX";
 124      case OP_WITHIN                 : return "OP_WITHIN";
 125  
 126      // crypto
 127      case OP_RIPEMD160              : return "OP_RIPEMD160";
 128      case OP_SHA1                   : return "OP_SHA1";
 129      case OP_SHA256                 : return "OP_SHA256";
 130      case OP_HASH160                : return "OP_HASH160";
 131      case OP_HASH256                : return "OP_HASH256";
 132      case OP_CODESEPARATOR          : return "OP_CODESEPARATOR";
 133      case OP_CHECKSIG               : return "OP_CHECKSIG";
 134      case OP_CHECKSIGVERIFY         : return "OP_CHECKSIGVERIFY";
 135      case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
 136      case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
 137  
 138      // expansion
 139      case OP_NOP1                   : return "OP_NOP1";
 140      case OP_CHECKLOCKTIMEVERIFY    : return "OP_CHECKLOCKTIMEVERIFY";
 141      case OP_CHECKSEQUENCEVERIFY    : return "OP_CHECKSEQUENCEVERIFY";
 142      case OP_NOP4                   : return "OP_NOP4";
 143      case OP_NOP5                   : return "OP_NOP5";
 144      case OP_NOP6                   : return "OP_NOP6";
 145      case OP_NOP7                   : return "OP_NOP7";
 146      case OP_NOP8                   : return "OP_NOP8";
 147      case OP_NOP9                   : return "OP_NOP9";
 148      case OP_NOP10                  : return "OP_NOP10";
 149  
 150      // Opcode added by BIP 342 (Tapscript)
 151      case OP_CHECKSIGADD            : return "OP_CHECKSIGADD";
 152  
 153      case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";
 154  
 155      default:
 156          return "OP_UNKNOWN";
 157      }
 158  }
 159  
 160  unsigned int CScript::GetSigOpCount(bool fAccurate) const
 161  {
 162      unsigned int n = 0;
 163      const_iterator pc = begin();
 164      opcodetype lastOpcode = OP_INVALIDOPCODE;
 165      while (pc < end())
 166      {
 167          opcodetype opcode;
 168          if (!GetOp(pc, opcode))
 169              break;
 170          if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
 171              n++;
 172          else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
 173          {
 174              if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
 175                  n += DecodeOP_N(lastOpcode);
 176              else
 177                  n += MAX_PUBKEYS_PER_MULTISIG;
 178          }
 179          lastOpcode = opcode;
 180      }
 181      return n;
 182  }
 183  
 184  unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
 185  {
 186      if (!IsPayToScriptHash())
 187          return GetSigOpCount(true);
 188  
 189      // This is a pay-to-script-hash scriptPubKey;
 190      // get the last item that the scriptSig
 191      // pushes onto the stack:
 192      const_iterator pc = scriptSig.begin();
 193      std::vector<unsigned char> vData;
 194      while (pc < scriptSig.end())
 195      {
 196          opcodetype opcode;
 197          if (!scriptSig.GetOp(pc, opcode, vData))
 198              return 0;
 199          if (opcode > OP_16)
 200              return 0;
 201      }
 202  
 203      /// ... and return its opcount:
 204      CScript subscript(vData.begin(), vData.end());
 205      return subscript.GetSigOpCount(true);
 206  }
 207  
 208  bool CScript::IsPayToAnchor() const
 209  {
 210      return (this->size() == 4 &&
 211          (*this)[0] == OP_1 &&
 212          (*this)[1] == 0x02 &&
 213          (*this)[2] == 0x4e &&
 214          (*this)[3] == 0x73);
 215  }
 216  
 217  bool CScript::IsPayToAnchor(int version, const std::vector<unsigned char>& program)
 218  {
 219      return version == 1 &&
 220          program.size() == 2 &&
 221          program[0] == 0x4e &&
 222          program[1] == 0x73;
 223  }
 224  
 225  bool CScript::IsPayToScriptHash() const
 226  {
 227      // Extra-fast test for pay-to-script-hash CScripts:
 228      return (this->size() == 23 &&
 229              (*this)[0] == OP_HASH160 &&
 230              (*this)[1] == 0x14 &&
 231              (*this)[22] == OP_EQUAL);
 232  }
 233  
 234  bool CScript::IsPayToWitnessScriptHash() const
 235  {
 236      // Extra-fast test for pay-to-witness-script-hash CScripts:
 237      return (this->size() == 34 &&
 238              (*this)[0] == OP_0 &&
 239              (*this)[1] == 0x20);
 240  }
 241  
 242  // A witness program is any valid CScript that consists of a 1-byte push opcode
 243  // followed by a data push between 2 and 40 bytes.
 244  bool CScript::IsWitnessProgram(int& version, std::vector<unsigned char>& program) const
 245  {
 246      if (this->size() < 4 || this->size() > 42) {
 247          return false;
 248      }
 249      if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) {
 250          return false;
 251      }
 252      if ((size_t)((*this)[1] + 2) == this->size()) {
 253          version = DecodeOP_N((opcodetype)(*this)[0]);
 254          program = std::vector<unsigned char>(this->begin() + 2, this->end());
 255          return true;
 256      }
 257      return false;
 258  }
 259  
 260  bool CScript::IsPushOnly(const_iterator pc) const
 261  {
 262      while (pc < end())
 263      {
 264          opcodetype opcode;
 265          if (!GetOp(pc, opcode))
 266              return false;
 267          // Note that IsPushOnly() *does* consider OP_RESERVED to be a
 268          // push-type opcode, however execution of OP_RESERVED fails, so
 269          // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
 270          // the P2SH special validation code being executed.
 271          if (opcode > OP_16)
 272              return false;
 273      }
 274      return true;
 275  }
 276  
 277  bool CScript::IsPushOnly() const
 278  {
 279      return this->IsPushOnly(begin());
 280  }
 281  
 282  std::string CScriptWitness::ToString() const
 283  {
 284      std::string ret = "CScriptWitness(";
 285      for (unsigned int i = 0; i < stack.size(); i++) {
 286          if (i) {
 287              ret += ", ";
 288          }
 289          ret += HexStr(stack[i]);
 290      }
 291      return ret + ")";
 292  }
 293  
 294  bool CScript::HasValidOps() const
 295  {
 296      CScript::const_iterator it = begin();
 297      while (it < end()) {
 298          opcodetype opcode;
 299          std::vector<unsigned char> item;
 300          if (!GetOp(it, opcode, item) || opcode > MAX_OPCODE || item.size() > MAX_SCRIPT_ELEMENT_SIZE) {
 301              return false;
 302          }
 303      }
 304      return true;
 305  }
 306  
 307  size_t CScript::IsOLGA(const size_t remaining_outputs) const
 308  {
 309      if (!IsPayToWitnessScriptHash()) {
 310          return 0;
 311      }
 312  
 313      const size_t olga_payload_size{(size_t{(*this)[2]} << 8) | (*this)[3]};
 314      const size_t olga_outputs{(olga_payload_size + 1) / WITNESS_V0_SCRIPTHASH_SIZE + 1};
 315      if (remaining_outputs < olga_outputs) {
 316          return 0;
 317      }
 318  
 319      if (((*this)[4] | 0x20) != 's') return 0;
 320      if (((*this)[5] | 0x20) != 't') return 0;
 321      if (((*this)[6] | 0x20) != 'a') return 0;
 322      if (((*this)[7] | 0x20) != 'm') return 0;
 323      if (((*this)[8] | 0x20) != 'p') return 0;
 324      if ((*this)[9] != ':') return 0;
 325  
 326      return olga_outputs * (WITNESS_V0_SCRIPTHASH_SIZE + /* script length */ 1 + /* amount */ 8);
 327  }
 328  
 329  size_t CScript::OPNetWitnessSize(const CScriptWitness& witness) const
 330  {
 331      const auto& stack = witness.stack;
 332  
 333      if (stack.size() != 5) return 0;
 334      if (stack[4].size() != 65) return 0;
 335  
 336      const CScript tapscript{stack[3].begin(), stack[3].end()};
 337      bool found_opnet{false};
 338      size_t deduct{0};
 339  
 340      CScript::const_iterator pc = tapscript.begin();
 341      opcodetype opcode{OP_INVALIDOPCODE}, last_opcode{OP_INVALIDOPCODE};
 342      std::vector<unsigned char> data;
 343      while (pc < tapscript.end()) {
 344          last_opcode = opcode;
 345          if (!tapscript.GetOp(pc, opcode, data)) break;
 346  
 347          if (data.size() == 2 && data[0] == 0x6f && data[1] == 0x70) {
 348              found_opnet = true;
 349          }
 350          if (opcode == OP_CHECKSIGVERIFY && last_opcode == 0x20) {
 351              deduct += 34;
 352          }
 353      }
 354  
 355      if (!found_opnet) return 0;
 356      return stack[0].size() + stack[3].size() - deduct;
 357  }
 358  
 359  std::pair<size_t, size_t> CScript::DatacarrierBytes(const size_t remaining_outputs, const CScriptWitness* witness) const
 360  {
 361      if (size_t olga_bytes = IsOLGA(remaining_outputs); olga_bytes) {
 362          return {0, olga_bytes};
 363      }
 364  
 365      if (witness) {
 366          if (uint32_t opnet_bytes = OPNetWitnessSize(*witness); opnet_bytes) {
 367              return {0, opnet_bytes};
 368          }
 369      }
 370  
 371      size_t counted{0};
 372      opcodetype opcode, last_opcode{OP_INVALIDOPCODE};
 373      std::vector<unsigned char> push_data;
 374      unsigned int inside_noop{0}, inside_conditional{0};
 375      CScript::const_iterator opcode_it = begin(), data_began = begin();
 376      for (CScript::const_iterator it = begin(); it < end(); last_opcode = opcode) {
 377          opcode_it = it;
 378          if (!GetOp(it, opcode, push_data)) {
 379              // Invalid scripts are necessarily all data
 380              return {0, size()};
 381          }
 382  
 383          if (opcode == OP_IF || opcode == OP_NOTIF) {
 384              ++inside_conditional;
 385          } else if (opcode == OP_ENDIF) {
 386              if (!inside_conditional) return {0, size()};  // invalid
 387              --inside_conditional;
 388          } else if (opcode == OP_RETURN && !inside_conditional) {
 389              // unconditional OP_RETURN is unspendable
 390              return {size(), 0};
 391          }
 392  
 393          // Match OP_FALSE OP_IF
 394          if (inside_noop) {
 395              switch (opcode) {
 396              case OP_IF: case OP_NOTIF:
 397                  ++inside_noop;
 398                  break;
 399              case OP_ENDIF:
 400                  if (0 == --inside_noop) {
 401                      counted += it - data_began + 1;
 402                  }
 403                  break;
 404              default: /* do nothing */;
 405              }
 406          } else if (opcode == OP_IF && last_opcode == OP_FALSE) {
 407              inside_noop = 1;
 408              data_began = opcode_it;
 409          // Match <data> OP_DROP
 410          } else if (opcode <= OP_PUSHDATA4) {
 411              data_began = opcode_it;
 412          } else if (opcode == OP_DROP && last_opcode <= OP_PUSHDATA4) {
 413              counted += it - data_began;
 414          }
 415      }
 416      return {0, counted};
 417  }
 418  
 419  bool GetScriptOp(CScriptBase::const_iterator& pc, CScriptBase::const_iterator end, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet)
 420  {
 421      opcodeRet = OP_INVALIDOPCODE;
 422      if (pvchRet)
 423          pvchRet->clear();
 424      if (pc >= end)
 425          return false;
 426  
 427      // Read instruction
 428      if (end - pc < 1)
 429          return false;
 430      unsigned int opcode = *pc++;
 431  
 432      // Immediate operand
 433      if (opcode <= OP_PUSHDATA4)
 434      {
 435          unsigned int nSize = 0;
 436          if (opcode < OP_PUSHDATA1)
 437          {
 438              nSize = opcode;
 439          }
 440          else if (opcode == OP_PUSHDATA1)
 441          {
 442              if (end - pc < 1)
 443                  return false;
 444              nSize = *pc++;
 445          }
 446          else if (opcode == OP_PUSHDATA2)
 447          {
 448              if (end - pc < 2)
 449                  return false;
 450              nSize = ReadLE16(&pc[0]);
 451              pc += 2;
 452          }
 453          else if (opcode == OP_PUSHDATA4)
 454          {
 455              if (end - pc < 4)
 456                  return false;
 457              nSize = ReadLE32(&pc[0]);
 458              pc += 4;
 459          }
 460          if (end - pc < 0 || (unsigned int)(end - pc) < nSize)
 461              return false;
 462          if (pvchRet)
 463              pvchRet->assign(pc, pc + nSize);
 464          pc += nSize;
 465      }
 466  
 467      opcodeRet = static_cast<opcodetype>(opcode);
 468      return true;
 469  }
 470  
 471  bool IsOpSuccess(const opcodetype& opcode)
 472  {
 473      return opcode == 80 || opcode == 98 || (opcode >= 126 && opcode <= 129) ||
 474             (opcode >= 131 && opcode <= 134) || (opcode >= 137 && opcode <= 138) ||
 475             (opcode >= 141 && opcode <= 142) || (opcode >= 149 && opcode <= 153) ||
 476             (opcode >= 187 && opcode <= 254);
 477  }
 478  
 479  bool CheckMinimalPush(const std::vector<unsigned char>& data, opcodetype opcode) {
 480      // Excludes OP_1NEGATE, OP_1-16 since they are by definition minimal
 481      assert(0 <= opcode && opcode <= OP_PUSHDATA4);
 482      if (data.size() == 0) {
 483          // Should have used OP_0.
 484          return opcode == OP_0;
 485      } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
 486          // Should have used OP_1 .. OP_16.
 487          return false;
 488      } else if (data.size() == 1 && data[0] == 0x81) {
 489          // Should have used OP_1NEGATE.
 490          return false;
 491      } else if (data.size() <= 75) {
 492          // Must have used a direct push (opcode indicating number of bytes pushed + those bytes).
 493          return opcode == data.size();
 494      } else if (data.size() <= 255) {
 495          // Must have used OP_PUSHDATA.
 496          return opcode == OP_PUSHDATA1;
 497      } else if (data.size() <= 65535) {
 498          // Must have used OP_PUSHDATA2.
 499          return opcode == OP_PUSHDATA2;
 500      }
 501      return true;
 502  }
 503