Fix RemovePattern issues
[NovacoinLibrary.git] / Novacoin / CScript.cs
1 \feff/**
2  *  Novacoin classes library
3  *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
4
5  *  This program is free software: you can redistribute it and/or modify
6  *  it under the terms of the GNU Affero General Public License as
7  *  published by the Free Software Foundation, either version 3 of the
8  *  License, or (at your option) any later version.
9
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU Affero General Public License for more details.
14
15  *  You should have received a copy of the GNU Affero General Public License
16  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 using System;
20 using System.Linq;
21 using System.Text;
22 using System.Collections.Generic;
23
24 namespace Novacoin
25 {
26     public class CScriptException : Exception
27     {
28         public CScriptException()
29         {
30         }
31
32         public CScriptException(string message)
33             : base(message)
34         {
35         }
36
37         public CScriptException(string message, Exception inner)
38             : base(message, inner)
39         {
40         }
41     }
42
43     /// <summary>
44     /// Representation of script code
45     /// </summary>
46         public class CScript
47         {
48         private List<byte> codeBytes;
49
50         /// <summary>
51         /// Initializes an empty instance of CScript
52         /// </summary>
53                 public CScript ()
54                 {
55             codeBytes = new List<byte>();
56                 }
57
58         /// <summary>
59         /// Initializes new instance of CScript and fills it with supplied bytes
60         /// </summary>
61         /// <param name="bytes">Enumerator interface for byte sequence</param>
62         public CScript(byte[] bytes)
63         {
64             codeBytes = new List<byte>(bytes);
65         }
66
67         /// <summary>
68         /// Return a new instance of ByteQueue object for current code bytes
69         /// </summary>
70         /// <returns></returns>
71         public ByteQueue GetByteQUeue()
72         {
73              return new ByteQueue(codeBytes);
74         }
75
76         /// <summary>
77         /// Adds specified operation to instruction list
78         /// </summary>
79         /// <param name="opcode"></param>
80         public void AddInstruction(instruction opcode)
81         {
82             if (opcode < instruction.OP_0 || opcode > instruction.OP_INVALIDOPCODE)
83             {
84                 throw new CScriptException("CScript::AddInstruction() : invalid instruction");
85             }
86
87             codeBytes.Add((byte)opcode);
88         }
89
90         /// <summary>
91         /// Adds hash to instruction list.
92         ///    New items are added in this format:
93         ///    hash_length_byte hash_bytes
94         /// </summary>
95         /// <param name="hash">Hash160 instance</param>
96         public void AddHash(Hash160 hash)
97         {
98             codeBytes.Add((byte)hash.hashSize);
99             codeBytes.AddRange(hash.hashBytes);
100         }
101
102         /// <summary>
103         /// Adds hash to instruction list.
104         ///    New items are added in this format:
105         ///    hash_length_byte hash_bytes
106         /// </summary>
107         /// <param name="hash">Hash256 instance</param>
108         public void AddHash(Hash256 hash)
109         {
110             codeBytes.Add((byte)hash.hashSize);
111             codeBytes.AddRange(hash.hashBytes);
112         }
113
114         /// <summary>
115         /// Create new OP_PUSHDATAn operator and add it to instruction list
116         /// </summary>
117         /// <param name="dataBytes">Set of data bytes</param>
118         public void PushData(byte[] dataBytes)
119         {
120             var nCount = dataBytes.LongLength;
121
122             if (nCount < (int)instruction.OP_PUSHDATA1)
123             {
124                 // OP_0 and OP_FALSE
125                 codeBytes.Add((byte)nCount);
126             }
127             else if (nCount < 0xff)
128             {
129                 // OP_PUSHDATA1 0x01 [0x5a]
130                 codeBytes.Add((byte)instruction.OP_PUSHDATA1);
131                 codeBytes.Add((byte)nCount);
132             }
133             else if (nCount < 0xffff)
134             {
135                 // OP_PUSHDATA1 0x00 0x01 [0x5a]
136                 codeBytes.Add((byte)instruction.OP_PUSHDATA2);
137
138                 var szBytes = Interop.BEBytes((ushort)nCount);
139                 codeBytes.AddRange(szBytes);
140             }
141             else if (nCount < 0xffffffff)
142             {
143                 // OP_PUSHDATA1 0x00 0x00 0x00 0x01 [0x5a]
144                 codeBytes.Add((byte)instruction.OP_PUSHDATA4);
145
146                 var szBytes = Interop.BEBytes((uint)nCount);
147                 codeBytes.AddRange(szBytes);
148             }
149
150             // Add data bytes
151             codeBytes.AddRange(dataBytes);
152         }
153
154         /// <summary>
155         /// Scan pushed data bytes for pattern and, in case of exact match, remove it.
156         /// </summary>
157         /// <param name="pattern">Pattern sequence</param>
158         /// <returns>Matches count</returns>
159         public int RemovePattern(byte[] pattern)
160         {
161             // There is no sense to continue if pattern is longer than script itself
162             if (pattern.Length == 0 || pattern.Length > codeBytes.Count)
163             {
164                 return 0;
165             }
166
167             var count = 0;
168             var bq1 = new ByteQueue(codeBytes);
169
170
171             byte[] pushData;
172             instruction opcode;
173
174             var newScript = new CScript();
175
176             while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
177             {
178                 if (pushData.Length == 0)
179                 {
180                     // No data, put instruction on its place
181                     newScript.AddInstruction(opcode);
182                 }
183                 else if (!pushData.SequenceEqual(pattern))
184                 {
185                     // No match, create push operator
186                     newScript.PushData(pushData);
187                 }
188                 else
189                 {
190                     count++; // match
191                 }
192             }
193
194             codeBytes = newScript.codeBytes;
195
196             return count;
197         }
198
199         /// <summary>
200         /// Scan script for specific instruction and remove it if there are some matches.
201         /// </summary>
202         /// <param name="op">Instruction</param>
203         /// <returns>Matches count</returns>
204         public int RemoveInstruction(instruction op)
205         {
206             var count = 0;
207             var bq1 = new ByteQueue(codeBytes);
208
209
210             byte[] pushData;
211             instruction opcode;
212
213             var newScript = new CScript();
214
215             while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
216             {
217                 if (pushData.Length != 0)
218                 {
219                     newScript.PushData(pushData);
220                 }
221                 else if (Enum.IsDefined(typeof(instruction), op) && op != opcode)
222                 {
223                     newScript.AddInstruction(opcode);
224                 }
225                 else
226                 {
227                     count++; // match
228                 }
229             }
230
231             codeBytes = newScript.codeBytes;
232
233             return count;
234         }
235
236         /// <summary>
237         /// Is it true that script doesn't contain anything except push value operations?
238         /// </summary>
239         public bool IsPushOnly
240         {
241             get
242             {
243                 var wCodeBytes = new ByteQueue(codeBytes);
244
245                 instruction opcode; // Current instruction
246                 byte[] pushArgs; // OP_PUSHDATAn argument
247
248                 // Scan instructions sequence
249                 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
250                 {
251                     if (opcode > instruction.OP_16)
252                     {
253                         // We don't allow control instructions here
254                         return false;
255                     }
256                 }
257
258                 return true;
259             }
260         }
261
262         /// <summary>
263         /// Is it true that script doesn't contain non-canonical push operations?
264         /// </summary>
265         public bool HasOnlyCanonicalPushes
266         {
267             get
268             {
269                 var wCodeBytes = new ByteQueue(codeBytes);
270
271                 byte[] pushArgs; // OP_PUSHDATAn argument
272                 instruction opcode; // Current instruction
273
274                 // Scan instructions sequence
275                 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
276                 {
277                     var data = pushArgs;
278
279                     if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
280                     {
281                         // Could have used an OP_n code, rather than a 1-byte push.
282                         return false;
283                     }
284                     if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
285                     {
286                         // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
287                         return false;
288                     }
289                     if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
290                     {
291                         // Could have used an OP_PUSHDATA1.
292                         return false;
293                     }
294                     if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
295                     {
296                         // Could have used an OP_PUSHDATA2.
297                         return false;
298                     }
299                 }
300
301                 return true;
302             }
303         }
304
305         /// <summary>
306         /// Quick test for pay-to-script-hash CScripts
307         /// </summary>
308         public bool IsPayToScriptHash
309         {
310             get
311             {
312                 // Sender provides redeem script hash, receiver provides signature list and redeem script
313                 // OP_HASH160 20 [20 byte hash] OP_EQUAL
314                 return (codeBytes.Count() == 23 &&
315                         codeBytes[0] == (byte)instruction.OP_HASH160 &&
316                         codeBytes[1] == 0x14 && // 20 bytes hash length prefix
317                         codeBytes[22] == (byte)instruction.OP_EQUAL);
318             }
319         }
320
321         /// <summary>
322         /// Quick test for pay-to-pubkeyhash CScripts
323         /// </summary>
324         public bool IsPayToPubKeyHash
325         {
326             get
327             {
328                 // Sender provides hash of pubkey, receiver provides signature and pubkey
329                 // OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
330                 return (codeBytes.Count == 25 &&
331                         codeBytes[0] == (byte)instruction.OP_DUP &&
332                         codeBytes[1] == (byte)instruction.OP_HASH160 &&
333                         codeBytes[2] == 0x14 && // 20 bytes hash length prefix
334                         codeBytes[23] == (byte)instruction.OP_EQUALVERIFY &&
335                         codeBytes[24] == (byte)instruction.OP_CHECKSIG);
336             }
337         }
338
339         /// <summary>
340         /// Quick test for Null destination
341         /// </summary>
342         public bool IsNull
343         {
344             get { return codeBytes.Count == 0; }
345         }
346
347         /// <summary>
348         /// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
349         /// as 20 sigops. With pay-to-script-hash, that changed:
350         /// CHECKMULTISIGs serialized in scriptSigs are
351         /// counted more accurately, assuming they are of the form
352         ///  ... OP_N CHECKMULTISIG ...
353         /// </summary>
354         /// <param name="fAccurate">Legacy mode flag</param>
355         /// <returns>Amount of sigops</returns>
356         public int GetSigOpCount(bool fAccurate)
357         {
358             var wCodeBytes = new ByteQueue(codeBytes);
359
360             instruction opcode; // Current instruction
361             byte[] pushArgs; // OP_PUSHDATAn argument
362
363             int nCount = 0;
364             var lastOpcode = instruction.OP_INVALIDOPCODE;
365
366             // Scan instructions sequence
367             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
368             {
369                 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
370                 {
371                     nCount++;
372                 }
373                 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
374                 {
375                     if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
376                     {
377                         nCount += ScriptCode.DecodeOP_N(lastOpcode);
378                     }
379                     else
380                     {
381                         nCount += 20;
382                     }
383                 }
384             }
385
386             return nCount;
387         }
388
389         /// <summary>
390         /// Accurately count sigOps, including sigOps in
391         /// pay-to-script-hash transactions
392         /// </summary>
393         /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
394         /// <returns>SigOps count</returns>
395         public int GetSigOpCount(CScript scriptSig)
396         {
397             if (!IsPayToScriptHash)
398             {
399                 return GetSigOpCount(true);
400             }
401
402             // This is a pay-to-script-hash scriptPubKey;
403             // get the last item that the scriptSig
404             // pushes onto the stack:
405             ByteQueue wScriptSig = scriptSig.GetByteQUeue();
406
407             instruction opcode; // Current instruction
408             byte[] pushArgs; // OP_PUSHDATAn argument
409
410             while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
411             {
412                 if (opcode > instruction.OP_16)
413                 {
414                     return 0;
415                 }
416             }
417
418             /// ... and return its opcount:
419             var subScript = new CScript(pushArgs);
420
421             return subScript.GetSigOpCount(true);
422
423         }
424
425         /// <summary>
426         /// Set pay-to-pubkey destination.
427         /// </summary>
428         /// <param name="pubKey">Instance of CPubKey.</param>
429         public void SetDestination(CPubKey pubKey)
430         {
431             codeBytes.Clear();
432             PushData(pubKey.PublicBytes);
433             AddInstruction(instruction.OP_CHECKSIG);
434         }
435
436         /// <summary>
437         /// Set pay-to-pubkeyhash destination
438         /// </summary>
439         /// <param name="ID">Public key hash</param>
440         public void SetDestination(CKeyID ID)
441         {
442             codeBytes.Clear();
443             AddInstruction(instruction.OP_DUP);
444             AddInstruction(instruction.OP_HASH160);
445             AddHash(ID);
446             AddInstruction(instruction.OP_EQUALVERIFY);
447             AddInstruction(instruction.OP_CHECKSIG);
448         }
449
450         /// <summary>
451         /// Set pay-to-scripthash destination
452         /// </summary>
453         /// <param name="ID">Script hash</param>
454         public void SetDestination(CScriptID ID)
455         {
456             codeBytes.Clear();
457             AddInstruction(instruction.OP_HASH160);
458             AddHash(ID);
459             AddInstruction(instruction.OP_EQUAL);
460         }
461
462         /// <summary>
463         /// Reset script code buffer.
464         /// </summary>
465         public void SetNullDestination()
466         {
467             codeBytes.Clear();
468         }
469
470         /// <summary>
471         /// Set multisig destination.
472         /// </summary>
473         /// <param name="nRequired">Amount of required signatures.</param>
474         /// <param name="keys">Set of public keys.</param>
475         public void SetMultiSig(int nRequired, CPubKey[] keys)
476         {
477             codeBytes.Clear();
478             AddInstruction(ScriptCode.EncodeOP_N(nRequired));
479
480             foreach (var key in keys)
481             {
482                 PushData(key.PublicBytes);
483             }
484
485             AddInstruction(ScriptCode.EncodeOP_N(keys.Length));
486             AddInstruction(instruction.OP_CHECKMULTISIG);
487         }
488
489         /// <summary>
490         /// Access to script code.
491         /// </summary>
492         public byte[] Bytes
493         {
494             get { return codeBytes.ToArray(); }
495         }
496
497         public CScriptID ScriptID
498         {
499             get { return new CScriptID(Hash160.Compute160(codeBytes.ToArray())); }
500         }
501
502         /// <summary>
503         /// Disassemble current script code
504         /// </summary>
505         /// <returns>Code listing</returns>
506                 public override string ToString()
507                 {
508                         var sb = new StringBuilder();
509             var wCodeBytes = new ByteQueue(codeBytes);
510
511             instruction opcode; // Current instruction
512             byte[] pushArgs; // OP_PUSHDATAn argument
513             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
514             {
515                 if (sb.Length != 0)
516                 {
517                     sb.Append(" ");
518                 }
519
520                 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
521                 {
522                     sb.Append(ScriptCode.ValueString(pushArgs));
523                 }
524                 else
525                 {
526                     sb.Append(ScriptCode.GetOpName(opcode));
527                 }
528             }
529
530             return sb.ToString();
531                 }
532         }
533 }