Use getters instead of Satoshi-style access methods
[NovacoinLibrary.git] / Novacoin / CScript.cs
1 \feffusing System;
2 using System.Linq;
3 using System.Text;
4 using System.Collections.Generic;
5
6 namespace Novacoin
7 {
8     public class CScriptException : Exception
9     {
10         public CScriptException()
11         {
12         }
13
14         public CScriptException(string message)
15             : base(message)
16         {
17         }
18
19         public CScriptException(string message, Exception inner)
20             : base(message, inner)
21         {
22         }
23     }
24
25     /// <summary>
26     /// Representation of script code
27     /// </summary>
28         public class CScript
29         {
30         private List<byte> codeBytes;
31
32         /// <summary>
33         /// Initializes an empty instance of CScript
34         /// </summary>
35                 public CScript ()
36                 {
37             codeBytes = new List<byte>();
38                 }
39
40         /// <summary>
41         /// Initializes new instance of CScript and fills it with supplied bytes
42         /// </summary>
43         /// <param name="bytes">Enumerator interface for byte sequence</param>
44         public CScript(IEnumerable<byte> bytes)
45         {
46             codeBytes = new List<byte>(bytes);
47         }
48
49         /// <summary>
50         /// Return a new instance of WrappedList object for current code bytes
51         /// </summary>
52         /// <returns></returns>
53         public WrappedList<byte> GetWrappedList()
54         {
55              return new WrappedList<byte>(codeBytes);
56         }
57
58         /// <summary>
59         /// Adds specified operation to opcode bytes list
60         /// </summary>
61         /// <param name="opcode"></param>
62         public void AddOp(opcodetype opcode)
63         {
64             if (opcode < opcodetype.OP_0 || opcode > opcodetype.OP_INVALIDOPCODE)
65             {
66                 throw new CScriptException("CScript::AddOp() : invalid opcode");
67             }
68
69             codeBytes.Add((byte)opcode);
70         }
71
72         /// <summary>
73         /// Adds hash to opcode bytes list.
74         ///    New items are added in this format:
75         ///    hash_length_byte hash_bytes
76         /// </summary>
77         /// <param name="hash">Hash160 instance</param>
78         public void AddHash(Hash160 hash)
79         {
80             codeBytes.Add((byte)hash.hashSize);
81             codeBytes.AddRange(hash.hashBytes);
82         }
83
84         /// <summary>
85         /// Adds hash to opcode bytes list.
86         ///    New items are added in this format:
87         ///    hash_length_byte hash_bytes
88         /// </summary>
89         /// <param name="hash">Hash256 instance</param>
90         public void AddHash(Hash256 hash)
91         {
92             codeBytes.Add((byte)hash.hashSize);
93             codeBytes.AddRange(hash.hashBytes);
94         }
95
96         /// <summary>
97         /// Create new OP_PUSHDATAn operator and add it to opcode bytes list
98         /// </summary>
99         /// <param name="dataBytes">List of data bytes</param>
100         public void PushData(IList<byte> dataBytes)
101         {
102             long nCount = dataBytes.LongCount();
103
104             if (nCount < (int)opcodetype.OP_PUSHDATA1)
105             {
106                 // OP_0 and OP_FALSE
107                 codeBytes.Add((byte)nCount);
108             }
109             else if (nCount < 0xff)
110             {
111                 // OP_PUSHDATA1 0x01 [0x5a]
112                 codeBytes.Add((byte)opcodetype.OP_PUSHDATA1);
113                 codeBytes.Add((byte)nCount);
114             }
115             else if (nCount < 0xffff)
116             {
117                 // OP_PUSHDATA1 0x00 0x01 [0x5a]
118                 codeBytes.Add((byte)opcodetype.OP_PUSHDATA2);
119
120                 byte[] szBytes = Interop.BEBytes((ushort)nCount);
121                 codeBytes.AddRange(szBytes);
122             }
123             else if (nCount < 0xffffffff)
124             {
125                 // OP_PUSHDATA1 0x00 0x00 0x00 0x01 [0x5a]
126                 codeBytes.Add((byte)opcodetype.OP_PUSHDATA4);
127
128                 byte[] szBytes = Interop.BEBytes((uint)nCount);
129                 codeBytes.AddRange(szBytes);
130             }
131
132             // Add data bytes
133             codeBytes.AddRange(dataBytes);
134         }
135
136         /// <summary>
137         /// Scan code bytes for pattern
138         /// </summary>
139         /// <param name="pattern">Pattern sequence</param>
140         /// <returns>Matches enumerator</returns>
141         private IEnumerable<int> FindPattern(IList<byte> pattern)
142         {
143             for (int i = 0; i < codeBytes.Count; i++)
144             {
145                 if (codeBytes.Skip(i).Take(pattern.Count).SequenceEqual(pattern))
146                 {
147                     yield return i;
148                 }
149             }
150         }
151
152         /// <summary>
153         /// Scan code bytes for pattern and remove it
154         /// </summary>
155         /// <param name="pattern">Pattern sequence</param>
156         /// <returns>Matches number</returns>
157         public int RemovePattern(IList<byte> pattern)
158         {
159             List<byte> resultBytes = new List<byte>(codeBytes);
160             int count = 0;
161             int patternLen = pattern.Count;
162                         
163             foreach (int i in FindPattern(pattern))
164             {
165                 resultBytes.RemoveRange(i - count * patternLen, patternLen);
166                 count++;
167             }
168
169             codeBytes = resultBytes;
170             
171             return count;
172         }
173
174         /// <summary>
175         /// Is it true that script doesn't contain anything except push value operations?
176         /// </summary>
177         /// <returns>Checking result</returns>
178         public bool IsPushonly()
179         {
180             WrappedList<byte> wCodeBytes = new WrappedList<byte>(codeBytes);
181
182             opcodetype opcode; // Current opcode
183             IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
184             
185             // Scan opcodes sequence
186             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
187             {
188                 if (opcode > opcodetype.OP_16)
189                 {
190                     // We don't allow control opcodes here
191                     return false;
192                 }
193             }
194
195             return true;
196         }
197
198         /// <summary>
199         /// Is it true that script doesn't contain non-canonical push operations?
200         /// </summary>
201         /// <returns>Checking result</returns>
202         public bool HashOnlyCanonicalPushes()
203         {
204             WrappedList<byte> wCodeBytes = new WrappedList<byte>(codeBytes);
205
206             opcodetype opcode; // Current opcode
207             IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
208
209             // Scan opcodes sequence
210             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
211             {
212                 byte[] data = pushArgs.ToArray();
213
214                 if (opcode < opcodetype.OP_PUSHDATA1 && opcode > opcodetype.OP_0 && (data.Length == 1 && data[0] <= 16))
215                 {
216                     // Could have used an OP_n code, rather than a 1-byte push.
217                     return false;
218                 }
219                 if (opcode == opcodetype.OP_PUSHDATA1 && data.Length < (int)opcodetype.OP_PUSHDATA1)
220                 {
221                     // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
222                     return false;
223                 }
224                 if (opcode == opcodetype.OP_PUSHDATA2 && data.Length <= 0xFF)
225                 {
226                     // Could have used an OP_PUSHDATA1.
227                     return false;
228                 }
229                 if (opcode == opcodetype.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
230                 {
231                     // Could have used an OP_PUSHDATA2.
232                     return false;
233                 }
234             }
235
236             return true;
237         }
238
239         /// <summary>
240         /// Quick test for pay-to-script-hash CScripts
241         /// </summary>
242         /// <returns>Checking result</returns>
243         public bool IsPayToScriptHash
244         {
245             get
246             {
247                 // Sender provides redeem script hash, receiver provides signature list and redeem script
248                 // OP_HASH160 20 [20 byte hash] OP_EQUAL
249                 return (codeBytes.Count() == 23 &&
250                         codeBytes[0] == (byte)opcodetype.OP_HASH160 &&
251                         codeBytes[1] == 0x14 && // 20 bytes hash length prefix
252                         codeBytes[22] == (byte)opcodetype.OP_EQUAL);
253             }
254         }
255
256         /// <summary>
257         /// Quick test for pay-to-pubkeyhash CScripts
258         /// </summary>
259         /// <returns>Checking result</returns>
260         public bool IsPayToPubKeyHash
261         {
262             get
263             {
264                 // Sender provides hash of pubkey, receiver provides signature and pubkey
265                 // OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
266
267                 return (codeBytes.Count == 25 &&
268                         codeBytes[0] == (byte)opcodetype.OP_DUP &&
269                         codeBytes[1] == (byte)opcodetype.OP_HASH160 &&
270                         codeBytes[2] == 0x14 && // 20 bytes hash length prefix
271                         codeBytes[23] == (byte)opcodetype.OP_EQUALVERIFY &&
272                         codeBytes[24] == (byte)opcodetype.OP_CHECKSIG);
273             }
274         }
275
276         /// <summary>
277         /// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
278         /// as 20 sigops. With pay-to-script-hash, that changed:
279         /// CHECKMULTISIGs serialized in scriptSigs are
280         /// counted more accurately, assuming they are of the form
281         ///  ... OP_N CHECKMULTISIG ...
282         /// </summary>
283         /// <param name="fAccurate">Legacy mode flag</param>
284         /// <returns>Amount of sigops</returns>
285         public int GetSigOpCount(bool fAccurate)
286         {
287             WrappedList<byte> wCodeBytes = new WrappedList<byte>(codeBytes);
288
289             opcodetype opcode; // Current opcode
290             IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
291
292             int nCount = 0;
293             opcodetype lastOpcode = opcodetype.OP_INVALIDOPCODE;
294
295             // Scan opcodes sequence
296             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
297             {
298                 if (opcode == opcodetype.OP_CHECKSIG || opcode == opcodetype.OP_CHECKSIGVERIFY)
299                 {
300                     nCount++;
301                 }
302                 else if (opcode == opcodetype.OP_CHECKMULTISIG || opcode == opcodetype.OP_CHECKMULTISIGVERIFY)
303                 {
304                     if (fAccurate && lastOpcode >= opcodetype.OP_1 && lastOpcode <= opcodetype.OP_16)
305                     {
306                         nCount += ScriptCode.DecodeOP_N(lastOpcode);
307                     }
308                     else
309                     {
310                         nCount += 20;
311                     }
312                 }
313             }
314
315             return nCount;
316         }
317
318         /// <summary>
319         /// Accurately count sigOps, including sigOps in
320         /// pay-to-script-hash transactions
321         /// </summary>
322         /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
323         /// <returns>SigOps count</returns>
324         public int GetSigOpCount(CScript scriptSig)
325         {
326             if (!IsPayToScriptHash)
327             {
328                 return GetSigOpCount(true);
329             }
330
331             // This is a pay-to-script-hash scriptPubKey;
332             // get the last item that the scriptSig
333             // pushes onto the stack:
334             WrappedList<byte> wScriptSig = scriptSig.GetWrappedList();
335
336             opcodetype opcode; // Current opcode
337             IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
338
339             while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
340             {
341                 if (opcode > opcodetype.OP_16)
342                 {
343                     return 0;
344                 }
345             }
346
347             /// ... and return its opcount:
348             CScript subScript = new CScript(pushArgs);
349
350             return subScript.GetSigOpCount(true);
351
352         }
353
354         public void SetDestination(CKeyID ID)
355         {
356             codeBytes.Clear();
357             AddOp(opcodetype.OP_DUP);
358             AddOp(opcodetype.OP_HASH160);
359             AddHash(ID);
360             AddOp(opcodetype.OP_EQUAL);
361         }
362
363         public void SetDestination(CScriptID ID)
364         {
365             codeBytes.Clear();
366             AddOp(opcodetype.OP_HASH160);
367             AddHash(ID);
368             AddOp(opcodetype.OP_EQUAL);
369         }
370
371         public void SetMultiSig(int nRequired, IEnumerable<CPubKey> keys)
372         {
373             codeBytes.Clear();
374             AddOp(ScriptCode.EncodeOP_N(nRequired));
375
376             foreach (CPubKey key in keys)
377             {
378                 PushData(key.PublicBytes.ToList());
379             }
380             AddOp(ScriptCode.EncodeOP_N(keys.Count()));
381             AddOp(opcodetype.OP_CHECKMULTISIG);
382         }
383
384         /// <summary>
385         /// Access to script code.
386         /// </summary>
387         public IEnumerable<byte> Enumerable
388         {
389             get { return codeBytes; }
390         }
391
392         /// <summary>
393         /// Disassemble current script code
394         /// </summary>
395         /// <returns>Code listing</returns>
396                 public override string ToString()
397                 {
398                         StringBuilder sb = new StringBuilder();
399             WrappedList<byte> wCodeBytes = new WrappedList<byte>(codeBytes);
400
401             opcodetype opcode; // Current opcode
402             IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
403             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
404             {
405                 if (sb.Length != 0)
406                 {
407                     sb.Append(" ");
408                 }
409
410                 if (0 <= opcode && opcode <= opcodetype.OP_PUSHDATA4)
411                 {
412                     sb.Append(ScriptCode.ValueString(pushArgs));
413                 }
414                 else
415                 {
416                     sb.Append(ScriptCode.GetOpName(opcode));
417                 }
418             }
419
420             return sb.ToString();
421                 }
422         }
423 }
424