1 // Copyright (c) 2009-2014 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "core/transaction.h"
8 #include "script/script.h"
11 #include "univalue/univalue.h"
13 #include "utilstrencodings.h"
16 #include <boost/algorithm/string/classification.hpp>
17 #include <boost/algorithm/string/predicate.hpp>
18 #include <boost/algorithm/string/replace.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 #include <boost/assign/list_of.hpp>
22 using namespace boost;
23 using namespace boost::algorithm;
26 CScript ParseScript(std::string s)
30 static map<string, opcodetype> mapOpNames;
32 if (mapOpNames.empty())
34 for (int op = 0; op <= OP_NOP10; op++)
36 // Allow OP_RESERVED to get into mapOpNames
37 if (op < OP_NOP && op != OP_RESERVED)
40 const char* name = GetOpName((opcodetype)op);
41 if (strcmp(name, "OP_UNKNOWN") == 0)
44 mapOpNames[strName] = (opcodetype)op;
45 // Convenience: OP_ADD and just ADD are both recognized:
46 replace_first(strName, "OP_", "");
47 mapOpNames[strName] = (opcodetype)op;
52 split(words, s, is_any_of(" \t\n"), token_compress_on);
54 for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
58 // Empty string, ignore. (boost::split given '' will return one word)
60 else if (all(*w, is_digit()) ||
61 (starts_with(*w, "-") && all(string(w->begin()+1, w->end()), is_digit())))
64 int64_t n = atoi64(*w);
67 else if (starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(string(w->begin()+2, w->end())))
69 // Raw hex data, inserted NOT pushed onto stack:
70 std::vector<unsigned char> raw = ParseHex(string(w->begin()+2, w->end()));
71 result.insert(result.end(), raw.begin(), raw.end());
73 else if (w->size() >= 2 && starts_with(*w, "'") && ends_with(*w, "'"))
75 // Single-quoted string, pushed as data. NOTE: this is poor-man's
76 // parsing, spaces/tabs/newlines in single-quoted strings won't work.
77 std::vector<unsigned char> value(w->begin()+1, w->end()-1);
80 else if (mapOpNames.count(*w))
82 // opcode, e.g. OP_ADD or ADD:
83 result << mapOpNames[*w];
87 throw runtime_error("script parse error");
94 bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx)
99 vector<unsigned char> txData(ParseHex(strHexTx));
100 CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
104 catch (const std::exception &) {
111 uint256 ParseHashUV(const UniValue& v, const string& strName)
115 strHex = v.getValStr();
116 if (!IsHex(strHex)) // Note: IsHex("") is false
117 throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
120 result.SetHex(strHex);
124 vector<unsigned char> ParseHexUV(const UniValue& v, const string& strName)
128 strHex = v.getValStr();
130 throw runtime_error(strName+" must be hexadecimal string (not '"+strHex+"')");
131 return ParseHex(strHex);