Replace INT_MAX with INT32_MAX to avoid compile err
[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             // Raw hex data, inserted NOT pushed onto stack:
63             std::vector<unsigned char> raw = ParseHex(string(w.begin()+2, w.end()));
64             result.insert(result.end(), raw.begin(), raw.end());
65         }
66         else if (w.size() >= 2 && starts_with(w, "'") && ends_with(w, "'"))
67         {
68             // Single-quoted string, pushed as data. NOTE: this is poor-man's
69             // parsing, spaces/tabs/newlines in single-quoted strings won't work.
70             std::vector<unsigned char> value(w.begin()+1, w.end()-1);
71             result << value;
72         }
73         else if (mapOpNames.count(w))
74         {
75             // opcode, e.g. OP_ADD or OP_1:
76             result << mapOpNames[w];
77         }
78         else
79         {
80             BOOST_ERROR("Parse error: " << s);
81             return CScript();
82         }                        
83     }
84
85     return result;
86 }
87
88 Array
89 read_json(const std::string& filename)
90 {
91     namespace fs = boost::filesystem;
92     fs::path testFile = fs::current_path() / "test" / "data" / filename;
93
94 #ifdef TEST_DATA_DIR
95     if (!fs::exists(testFile))
96     {
97         testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename;
98     }
99 #endif
100
101     ifstream ifs(testFile.string().c_str(), ifstream::in);
102     Value v;
103     if (!read_stream(ifs, v))
104     {
105         if (ifs.fail())
106             BOOST_ERROR("Cound not find/open " << filename);
107         else
108             BOOST_ERROR("JSON syntax error in " << filename);
109         return Array();
110     }
111     if (v.type() != array_type)
112     {
113         BOOST_ERROR(filename << " does not contain a json array");
114         return Array();
115     }
116
117     return v.get_array();
118 }
119
120 BOOST_AUTO_TEST_SUITE(script_tests)
121
122 BOOST_AUTO_TEST_CASE(script_valid)
123 {
124     // Read tests from test/data/script_valid.json
125     // Format is an array of arrays
126     // Inner arrays are [ "scriptSig", "scriptPubKey" ]
127     // ... where scriptSig and scriptPubKey are stringified
128     // scripts.
129     Array tests = read_json("script_valid.json");
130
131     BOOST_FOREACH(Value& tv, tests)
132     {
133         Array test = tv.get_array();
134         string strTest = write_string(tv, false);
135         if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments)
136         {
137             BOOST_ERROR("Bad test: " << strTest);
138             continue;
139         }
140         string scriptSigString = test[0].get_str();
141         CScript scriptSig = ParseScript(scriptSigString);
142         string scriptPubKeyString = test[1].get_str();
143         CScript scriptPubKey = ParseScript(scriptPubKeyString);
144
145         CTransaction tx;
146         BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest);
147     }
148 }
149
150 BOOST_AUTO_TEST_CASE(script_invalid)
151 {
152     // Scripts that should evaluate as invalid
153     Array tests = read_json("script_invalid.json");
154
155     BOOST_FOREACH(Value& tv, tests)
156     {
157         Array test = tv.get_array();
158         string strTest = write_string(tv, false);
159         if (test.size() < 2) // Allow size > 2; extra stuff ignored (useful for comments)
160         {
161             BOOST_ERROR("Bad test: " << strTest);
162             continue;
163         }
164         string scriptSigString = test[0].get_str();
165         CScript scriptSig = ParseScript(scriptSigString);
166         string scriptPubKeyString = test[1].get_str();
167         CScript scriptPubKey = ParseScript(scriptPubKeyString);
168
169         CTransaction tx;
170         BOOST_CHECK_MESSAGE(!VerifyScript(scriptSig, scriptPubKey, tx, 0, true, SIGHASH_NONE), strTest);
171     }
172 }
173
174 BOOST_AUTO_TEST_CASE(script_PushData)
175 {
176     // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
177     // the stack as the 1-75 opcodes do.
178     static const unsigned char direct[] = { 1, 0x5a };
179     static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
180     static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
181     static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
182
183     vector<vector<unsigned char> > directStack;
184     BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), CTransaction(), 0, 0));
185
186     vector<vector<unsigned char> > pushdata1Stack;
187     BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), CTransaction(), 0, 0));
188     BOOST_CHECK(pushdata1Stack == directStack);
189
190     vector<vector<unsigned char> > pushdata2Stack;
191     BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), CTransaction(), 0, 0));
192     BOOST_CHECK(pushdata2Stack == directStack);
193
194     vector<vector<unsigned char> > pushdata4Stack;
195     BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), CTransaction(), 0, 0));
196     BOOST_CHECK(pushdata4Stack == directStack);
197 }
198
199 CScript
200 sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction)
201 {
202     uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL);
203
204     CScript result;
205     //
206     // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
207     // one extra item on the stack, before the signatures.
208     // Putting OP_0 on the stack is the workaround;
209     // fixing the bug would mean splitting the blockchain (old
210     // clients would not accept new CHECKMULTISIG transactions,
211     // and vice-versa)
212     //
213     result << OP_0;
214     BOOST_FOREACH(CKey key, keys)
215     {
216         vector<unsigned char> vchSig;
217         BOOST_CHECK(key.Sign(hash, vchSig));
218         vchSig.push_back((unsigned char)SIGHASH_ALL);
219         result << vchSig;
220     }
221     return result;
222 }
223 CScript
224 sign_multisig(CScript scriptPubKey, CKey key, CTransaction transaction)
225 {
226     std::vector<CKey> keys;
227     keys.push_back(key);
228     return sign_multisig(scriptPubKey, keys, transaction);
229 }
230
231 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
232 {
233     CKey key1, key2, key3;
234     key1.MakeNewKey(true);
235     key2.MakeNewKey(false);
236     key3.MakeNewKey(true);
237
238     CScript scriptPubKey12;
239     scriptPubKey12 << OP_1 << key1.GetPubKey() << key2.GetPubKey() << OP_2 << OP_CHECKMULTISIG;
240
241     CTransaction txFrom12;
242     txFrom12.vout.resize(1);
243     txFrom12.vout[0].scriptPubKey = scriptPubKey12;
244
245     CTransaction txTo12;
246     txTo12.vin.resize(1);
247     txTo12.vout.resize(1);
248     txTo12.vin[0].prevout.n = 0;
249     txTo12.vin[0].prevout.hash = txFrom12.GetHash();
250     txTo12.vout[0].nValue = 1;
251
252     CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);
253     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
254     txTo12.vout[0].nValue = 2;
255     BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, txTo12, 0, true, 0));
256
257     CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);
258     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, txTo12, 0, true, 0));
259
260     CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);
261     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, txTo12, 0, true, 0));
262 }
263
264 BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
265 {
266     CKey key1, key2, key3, key4;
267     key1.MakeNewKey(true);
268     key2.MakeNewKey(false);
269     key3.MakeNewKey(true);
270     key4.MakeNewKey(false);
271
272     CScript scriptPubKey23;
273     scriptPubKey23 << OP_2 << key1.GetPubKey() << key2.GetPubKey() << key3.GetPubKey() << OP_3 << OP_CHECKMULTISIG;
274
275     CTransaction txFrom23;
276     txFrom23.vout.resize(1);
277     txFrom23.vout[0].scriptPubKey = scriptPubKey23;
278
279     CTransaction txTo23;
280     txTo23.vin.resize(1);
281     txTo23.vout.resize(1);
282     txTo23.vin[0].prevout.n = 0;
283     txTo23.vin[0].prevout.hash = txFrom23.GetHash();
284     txTo23.vout[0].nValue = 1;
285
286     std::vector<CKey> keys;
287     keys.push_back(key1); keys.push_back(key2);
288     CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
289     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, txTo23, 0, true, 0));
290
291     keys.clear();
292     keys.push_back(key1); keys.push_back(key3);
293     CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
294     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, txTo23, 0, true, 0));
295
296     keys.clear();
297     keys.push_back(key2); keys.push_back(key3);
298     CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
299     BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, txTo23, 0, true, 0));
300
301     keys.clear();
302     keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
303     CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
304     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, txTo23, 0, true, 0));
305
306     keys.clear();
307     keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
308     CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
309     BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, txTo23, 0, true, 0));
310
311     keys.clear();
312     keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
313     CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
314     BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, txTo23, 0, true, 0));
315
316     keys.clear();
317     keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
318     CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);
319     BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, txTo23, 0, true, 0));
320
321     keys.clear();
322     keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
323     CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);
324     BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, txTo23, 0, true, 0));
325
326     keys.clear(); // Must have signatures
327     CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);
328     BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, txTo23, 0, true, 0));
329 }    
330
331 BOOST_AUTO_TEST_CASE(script_combineSigs)
332 {
333     // Test the CombineSignatures function
334     CBasicKeyStore keystore;
335     vector<CKey> keys;
336     for (int i = 0; i < 3; i++)
337     {
338         CKey key;
339         key.MakeNewKey(i%2 == 1);
340         keys.push_back(key);
341         keystore.AddKey(key);
342     }
343
344     CTransaction txFrom;
345     txFrom.vout.resize(1);
346     txFrom.vout[0].scriptPubKey.SetDestination(keys[0].GetPubKey().GetID());
347     CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
348     CTransaction txTo;
349     txTo.vin.resize(1);
350     txTo.vout.resize(1);
351     txTo.vin[0].prevout.n = 0;
352     txTo.vin[0].prevout.hash = txFrom.GetHash();
353     CScript& scriptSig = txTo.vin[0].scriptSig;
354     txTo.vout[0].nValue = 1;
355
356     CScript empty;
357     CScript combined = CombineSignatures(scriptPubKey, txTo, 0, empty, empty);
358     BOOST_CHECK(combined.empty());
359
360     // Single signature case:
361     SignSignature(keystore, txFrom, txTo, 0); // changes scriptSig
362     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
363     BOOST_CHECK(combined == scriptSig);
364     combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
365     BOOST_CHECK(combined == scriptSig);
366     CScript scriptSigCopy = scriptSig;
367     // Signing again will give a different, valid signature:
368     SignSignature(keystore, txFrom, txTo, 0);
369     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
370     BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);
371
372     // P2SH, single-signature case:
373     CScript pkSingle; pkSingle << keys[0].GetPubKey() << OP_CHECKSIG;
374     keystore.AddCScript(pkSingle);
375     scriptPubKey.SetDestination(pkSingle.GetID());
376     SignSignature(keystore, txFrom, txTo, 0);
377     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
378     BOOST_CHECK(combined == scriptSig);
379     combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
380     BOOST_CHECK(combined == scriptSig);
381     scriptSigCopy = scriptSig;
382     SignSignature(keystore, txFrom, txTo, 0);
383     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
384     BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);
385     // dummy scriptSigCopy with placeholder, should always choose non-placeholder:
386     scriptSigCopy = CScript() << OP_0 << static_cast<vector<unsigned char> >(pkSingle);
387     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
388     BOOST_CHECK(combined == scriptSig);
389     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy);
390     BOOST_CHECK(combined == scriptSig);
391
392     // Hardest case:  Multisig 2-of-3
393     scriptPubKey.SetMultisig(2, keys);
394     keystore.AddCScript(scriptPubKey);
395     SignSignature(keystore, txFrom, txTo, 0);
396     combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
397     BOOST_CHECK(combined == scriptSig);
398     combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
399     BOOST_CHECK(combined == scriptSig);
400
401     // A couple of partially-signed versions:
402     vector<unsigned char> sig1;
403     uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL);
404     BOOST_CHECK(keys[0].Sign(hash1, sig1));
405     sig1.push_back(SIGHASH_ALL);
406     vector<unsigned char> sig2;
407     uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE);
408     BOOST_CHECK(keys[1].Sign(hash2, sig2));
409     sig2.push_back(SIGHASH_NONE);
410     vector<unsigned char> sig3;
411     uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE);
412     BOOST_CHECK(keys[2].Sign(hash3, sig3));
413     sig3.push_back(SIGHASH_SINGLE);
414
415     // Not fussy about order (or even existence) of placeholders or signatures:
416     CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
417     CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
418     CScript partial2a = CScript() << OP_0 << sig2;
419     CScript partial2b = CScript() << sig2 << OP_0;
420     CScript partial3a = CScript() << sig3;
421     CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
422     CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
423     CScript complete12 = CScript() << OP_0 << sig1 << sig2;
424     CScript complete13 = CScript() << OP_0 << sig1 << sig3;
425     CScript complete23 = CScript() << OP_0 << sig2 << sig3;
426
427     combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b);
428     BOOST_CHECK(combined == partial1a);
429     combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a);
430     BOOST_CHECK(combined == complete12);
431     combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a);
432     BOOST_CHECK(combined == complete12);
433     combined = CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b);
434     BOOST_CHECK(combined == complete12);
435     combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b);
436     BOOST_CHECK(combined == complete13);
437     combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a);
438     BOOST_CHECK(combined == complete23);
439     combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b);
440     BOOST_CHECK(combined == complete23);
441     combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a);
442     BOOST_CHECK(combined == partial3c);
443 }
444
445 BOOST_AUTO_TEST_SUITE_END()