Define TEST_DATA_DIR so unit tests can be run from any current working directory
[novacoin.git] / src / test / script_tests.cpp
1 #include <iostream>
2 #include <fstream>
3 #include <vector>
4 #include <boost/algorithm/string/classification.hpp>
5 #include <boost/algorithm/string/predicate.hpp>
6 #include <boost/algorithm/string/replace.hpp>
7 #include <boost/algorithm/string/split.hpp>
8 #include <boost/foreach.hpp>
9 #include <boost/preprocessor/stringize.hpp>
10 #include <boost/test/unit_test.hpp>
11 #include "json/json_spirit_reader_template.h"
12 #include "json/json_spirit_writer_template.h"
13 #include "json/json_spirit_utils.h"
14
15 #include "main.h"
16 #include "wallet.h"
17
18 using namespace std;
19 using namespace json_spirit;
20 using namespace boost::algorithm;
21
22 extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
23 extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
24                          bool fValidatePayToScriptHash, int nHashType);
25
26 CScript
27 ParseScript(string s)
28 {
29     CScript result;
30
31     static map<string, opcodetype> mapOpNames;
32
33     if (mapOpNames.size() == 0)
34     {
35         for (int op = OP_NOP; op <= OP_NOP10; op++)
36         {
37             const char* name = GetOpName((opcodetype)op);
38             if (strcmp(name, "OP_UNKNOWN") == 0)
39                 continue;
40             string strName(name);
41             mapOpNames[strName] = (opcodetype)op;
42             // Convenience: OP_ADD and just ADD are both recognized:
43             replace_first(strName, "OP_", "");
44             mapOpNames[strName] = (opcodetype)op;
45         }
46     }
47
48     vector<string> words;
49     split(words, s, is_any_of(" \t\n"), token_compress_on);
50
51     BOOST_FOREACH(string w, words)
52     {
53         if (all(w, is_digit()) ||
54             (starts_with(w, "-") && all(string(w.begin()+1, w.end()), is_digit())))
55         {
56             // Number
57             int64 n = atoi64(w);
58             result << n;
59         }
60         else if (starts_with(w, "0x") && IsHex(string(w.begin()+2, w.end())))
61         {
62             // Hex data:
63             result << ParseHex(string(w.begin()+2, w.end()));
64         }
65         else if (s.size() >= 2 && starts_with(w, "'") && ends_with(w, "'"))
66         {
67             // Single-quoted string, pushed as data:
68             std::vector<unsigned char> value(s.begin()+1, s.end()-1);
69             result << value;
70         }
71         else if (mapOpNames.count(w))
72         {
73             // opcode, e.g. OP_ADD or OP_1:
74             result << mapOpNames[w];
75         }
76         else
77         {
78             BOOST_ERROR("Parse error: " << s);
79             return CScript();
80         }                        
81     }
82
83     return result;
84 }
85
86 Array
87 read_json(const std::string& filename)
88 {
89     namespace fs = boost::filesystem;
90     fs::path testFile = fs::current_path() / "test" / "data" / filename;
91
92 #ifdef TEST_DATA_DIR
93     if (!fs::exists(testFile))
94     {
95         testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename;
96     }
97 #endif
98
99     ifstream ifs(testFile.string().c_str(), ifstream::in);
100     Value v;
101     if (!read_stream(ifs, v))
102     {
103         BOOST_ERROR("Cound not find/open " << filename);
104         return Array();
105     }
106     if (v.type() != array_type)
107     {
108         BOOST_ERROR(filename << " does not contain a json array");
109         return Array();
110     }
111
112     return v.get_array();
113 }
114
115 BOOST_AUTO_TEST_SUITE(script_tests)
116
117 BOOST_AUTO_TEST_CASE(script_valid)
118 {
119     // Read tests from test/data/script_valid.json
120     // Format is an array of arrays
121     // Inner arrays are [ "scriptSig", "scriptPubKey" ]
122     // ... where scriptSig and scriptPubKey are stringified
123     // scripts.
124     Array tests = read_json("script_valid.json");
125
126     BOOST_FOREACH(Value& tv, tests)
127     {
128         Array test = tv.get_array();
129         string strTest = write_string(tv, false);
130         if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments)
131         {
132             BOOST_ERROR("Bad test: " << strTest);
133             continue;
134         }
135         string scriptSigString = test[0].get_str();
136         CScript scriptSig = ParseScript(scriptSigString);
137         string scriptPubKeyString = test[1].get_str();
138         CScript scriptPubKey = ParseScript(scriptPubKeyString);
139
140         CTransaction tx;
141         BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest);
142     }
143 }
144
145 BOOST_AUTO_TEST_CASE(script_invalid)
146 {
147     // Scripts that should evaluate as invalid
148     Array tests = read_json("script_invalid.json");
149
150     BOOST_FOREACH(Value& tv, tests)
151     {
152         Array test = tv.get_array();
153         string strTest = write_string(tv, false);
154         if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments)
155         {
156             BOOST_ERROR("Bad test: " << strTest);
157             continue;
158         }
159         string scriptSigString = test[0].get_str();
160         CScript scriptSig = ParseScript(scriptSigString);
161         string scriptPubKeyString = test[1].get_str();
162         CScript scriptPubKey = ParseScript(scriptPubKeyString);
163
164         CTransaction tx;
165         BOOST_CHECK_MESSAGE(!VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest);
166     }
167 }
168
169 BOOST_AUTO_TEST_CASE(script_PushData)
170 {
171     // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
172     // the stack as the 1-75 opcodes do.
173     static const unsigned char direct[] = { 1, 0x5a };
174     static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
175     static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
176     static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
177
178     vector<vector<unsigned char> > directStack;
179     BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), CTransaction(), 0, 0));
180
181     vector<vector<unsigned char> > pushdata1Stack;
182     BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), CTransaction(), 0, 0));
183     BOOST_CHECK(pushdata1Stack == directStack);
184
185     vector<vector<unsigned char> > pushdata2Stack;
186     BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), CTransaction(), 0, 0));
187     BOOST_CHECK(pushdata2Stack == directStack);
188
189     vector<vector<unsigned char> > pushdata4Stack;
190     BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), CTransaction(), 0, 0));
191     BOOST_CHECK(pushdata4Stack == directStack);
192 }
193
194 CScript
195 sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction)
196 {
197     uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL);
198
199     CScript result;
200     //
201     // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
202     // one extra item on the stack, before the signatures.
203     // Putting OP_0 on the stack is the workaround;
204     // fixing the bug would mean splitting the blockchain (old
205     // clients would not accept new CHECKMULTISIG transactions,
206     // and vice-versa)
207     //
208     result << OP_0;
209     BOOST_FOREACH(CKey key, keys)
210     {
211         vector<unsigned char> vchSig;
212         BOOST_CHECK(key.Sign(hash, vchSig));
213         vchSig.push_back((unsigned char)SIGHASH_ALL);
214         result << vchSig;
215     }
216     return result;
217 }
218 CScript
219 sign_multisig(CScript scriptPubKey, CKey key, CTransaction transaction)
220 {
221     std::vector<CKey> keys;
222     keys.push_back(key);
223     return sign_multisig(scriptPubKey, keys, transaction);
224 }
225
226 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
227 {
228     CKey key1, key2, key3;
229     key1.MakeNewKey(true);
230     key2.MakeNewKey(false);
231     key3.MakeNewKey(true);
232
233     CScript scriptPubKey12;
234     scriptPubKey12 << OP_1 << key1.GetPubKey() << key2.GetPubKey() << OP_2 << OP_CHECKMULTISIG;
235
236     CTransaction txFrom12;
237     txFrom12.vout.resize(1);
238     txFrom12.vout[0].scriptPubKey = scriptPubKey12;
239
240     CTransaction txTo12;
241     txTo12.vin.resize(1);
242     txTo12.vout.resize(1);
243     txTo12.vin[0].prevout.n = 0;
244     txTo12.vin[0].prevout.hash = txFrom12.GetHash();
245     txTo12.vout[0].nValue = 1;
246
247     CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);
248     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
249     txTo12.vout[0].nValue = 2;
250     BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
251
252     CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);
253     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, txTo12, 0, true, 0));
254
255     CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);
256     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, txTo12, 0, true, 0));
257 }
258
259 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
260 {
261     CKey key1, key2, key3, key4;
262     key1.MakeNewKey(true);
263     key2.MakeNewKey(false);
264     key3.MakeNewKey(true);
265     key4.MakeNewKey(false);
266
267     CScript scriptPubKey23;
268     scriptPubKey23 << OP_2 << key1.GetPubKey() << key2.GetPubKey() << key3.GetPubKey() << OP_3 << OP_CHECKMULTISIG;
269
270     CTransaction txFrom23;
271     txFrom23.vout.resize(1);
272     txFrom23.vout[0].scriptPubKey = scriptPubKey23;
273
274     CTransaction txTo23;
275     txTo23.vin.resize(1);
276     txTo23.vout.resize(1);
277     txTo23.vin[0].prevout.n = 0;
278     txTo23.vin[0].prevout.hash = txFrom23.GetHash();
279     txTo23.vout[0].nValue = 1;
280
281     std::vector<CKey> keys;
282     keys.push_back(key1); keys.push_back(key2);
283     CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
284     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, txTo23, 0, true, 0));
285
286     keys.clear();
287     keys.push_back(key1); keys.push_back(key3);
288     CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
289     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, txTo23, 0, true, 0));
290
291     keys.clear();
292     keys.push_back(key2); keys.push_back(key3);
293     CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
294     BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, txTo23, 0, true, 0));
295
296     keys.clear();
297     keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
298     CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
299     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, txTo23, 0, true, 0));
300
301     keys.clear();
302     keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
303     CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
304     BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, txTo23, 0, true, 0));
305
306     keys.clear();
307     keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
308     CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
309     BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, txTo23, 0, true, 0));
310
311     keys.clear();
312     keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
313     CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);
314     BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, txTo23, 0, true, 0));
315
316     keys.clear();
317     keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
318     CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);
319     BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, txTo23, 0, true, 0));
320
321     keys.clear(); // Must have signatures
322     CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);
323     BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, txTo23, 0, true, 0));
324 }    
325
326
327 BOOST_AUTO_TEST_SUITE_END()