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