Fix incorrect comments
[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 0x01 0x00 [0x5a]
136                 codeBytes.Add((byte)instruction.OP_PUSHDATA2);
137
138                 var szBytes = BitConverter.GetBytes((ushort)nCount);
139                 codeBytes.AddRange(szBytes);
140             }
141             else if (nCount < 0xffffffff)
142             {
143                 // OP_PUSHDATA1 0x01 0x00 0x00 0x00 [0x5a]
144                 codeBytes.Add((byte)instruction.OP_PUSHDATA4);
145
146                 var szBytes = BitConverter.GetBytes((uint)nCount);
147                 codeBytes.AddRange(szBytes);
148             }
149
150             // Add data bytes
151             codeBytes.AddRange(dataBytes);
152         }
153
154         /// <summary>
155         /// Just insert data array without including any prefixes. Please make sure that you know what you're doing, 
156         ///    it is recommended to use AddInstruction, AddHash or PushData instead.
157         /// </summary>
158         /// <param name="dataBytes">Data bytes</param>
159         public void AddRawData(byte[] dataBytes)
160         {
161             // Add data bytes
162             codeBytes.AddRange(dataBytes);
163         }
164
165         /// <summary>
166         /// Scan pushed data bytes for pattern and, in case of exact match, remove it.
167         /// </summary>
168         /// <param name="pattern">Pattern sequence</param>
169         /// <returns>Matches count</returns>
170         public int RemovePattern(byte[] pattern)
171         {
172             // There is no sense to continue if pattern is empty or longer than script itself
173             if (pattern.Length == 0 || pattern.Length > codeBytes.Count)
174             {
175                 return 0;
176             }
177
178             var count = 0;
179             var bq1 = new ByteQueue(codeBytes);
180
181             byte[] pushData;
182             instruction opcode;
183
184             var newScript = new CScript();
185
186             while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
187             {
188                 if (pushData.Length == 0)
189                 {
190                     // No data, put instruction on its place
191                     newScript.AddInstruction(opcode);
192                 }
193                 else if (!pushData.SequenceEqual(pattern))
194                 {
195                     // No match, create push operator
196                     newScript.PushData(pushData);
197                 }
198                 else
199                 {
200                     count++; // match
201                 }
202             }
203
204             if (count > 0)
205             {
206                 // Replace current script if any matches were found
207                 codeBytes = newScript.codeBytes;
208             }
209
210             return count;
211         }
212
213         /// <summary>
214         /// Scan script for specific instruction and remove it if there are some matches.
215         /// </summary>
216         /// <param name="op">Instruction</param>
217         /// <returns>Matches count</returns>
218         public int RemoveInstruction(instruction op)
219         {
220             byte[] pushData;
221             instruction opcode;
222
223             var count = 0;
224             var newScript = new CScript();
225             var bq1 = new ByteQueue(codeBytes);
226
227             while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
228             {
229                 if (pushData.Length != 0 && op != opcode)
230                 {
231                     // If instruction didn't match then push its data again
232                     newScript.PushData(pushData);
233                 }
234                 else if (Enum.IsDefined(typeof(instruction), op) && op != opcode)
235                 {
236                     // Instruction didn't match
237                     newScript.AddInstruction(opcode);
238                 }
239                 else
240                 {
241                     count++; // match
242                 }
243             }
244
245             if (count > 0)
246             {
247                 // Replace current script if any matches were found
248                 codeBytes = newScript.codeBytes;
249             }
250
251             return count;
252         }
253
254         /// <summary>
255         /// Is it true that script doesn't contain anything except push value operations?
256         /// </summary>
257         public bool IsPushOnly
258         {
259             get
260             {
261                 var wCodeBytes = new ByteQueue(codeBytes);
262
263                 instruction opcode; // Current instruction
264                 byte[] pushArgs; // OP_PUSHDATAn argument
265
266                 // Scan instructions sequence
267                 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
268                 {
269                     if (opcode > instruction.OP_16)
270                     {
271                         // We don't allow control instructions here
272                         return false;
273                     }
274                 }
275
276                 return true;
277             }
278         }
279
280         /// <summary>
281         /// Is it true that script doesn't contain non-canonical push operations?
282         /// </summary>
283         public bool HasOnlyCanonicalPushes
284         {
285             get
286             {
287                 var wCodeBytes = new ByteQueue(codeBytes);
288
289                 byte[] pushArgs; // OP_PUSHDATAn argument
290                 instruction opcode; // Current instruction
291
292                 // Scan instructions sequence
293                 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
294                 {
295                     var data = pushArgs;
296
297                     if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
298                     {
299                         // Could have used an OP_n code, rather than a 1-byte push.
300                         return false;
301                     }
302                     if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
303                     {
304                         // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
305                         return false;
306                     }
307                     if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
308                     {
309                         // Could have used an OP_PUSHDATA1.
310                         return false;
311                     }
312                     if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
313                     {
314                         // Could have used an OP_PUSHDATA2.
315                         return false;
316                     }
317                 }
318
319                 return true;
320             }
321         }
322
323         /// <summary>
324         /// Quick test for pay-to-script-hash CScripts
325         /// </summary>
326         public bool IsPayToScriptHash
327         {
328             get
329             {
330                 // Sender provides redeem script hash, receiver provides signature list and redeem script
331                 // OP_HASH160 20 [20 byte hash] OP_EQUAL
332                 return (codeBytes.Count() == 23 &&
333                         codeBytes[0] == (byte)instruction.OP_HASH160 &&
334                         codeBytes[1] == 0x14 && // 20 bytes hash length prefix
335                         codeBytes[22] == (byte)instruction.OP_EQUAL);
336             }
337         }
338
339         /// <summary>
340         /// Quick test for pay-to-pubkeyhash CScripts
341         /// </summary>
342         public bool IsPayToPubKeyHash
343         {
344             get
345             {
346                 // Sender provides hash of pubkey, receiver provides signature and pubkey
347                 // OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
348                 return (codeBytes.Count == 25 &&
349                         codeBytes[0] == (byte)instruction.OP_DUP &&
350                         codeBytes[1] == (byte)instruction.OP_HASH160 &&
351                         codeBytes[2] == 0x14 && // 20 bytes hash length prefix
352                         codeBytes[23] == (byte)instruction.OP_EQUALVERIFY &&
353                         codeBytes[24] == (byte)instruction.OP_CHECKSIG);
354             }
355         }
356
357         /// <summary>
358         /// Quick test for Null destination
359         /// </summary>
360         public bool IsNull
361         {
362             get { return codeBytes.Count == 0; }
363         }
364
365         /// <summary>
366         /// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
367         /// as 20 sigops. With pay-to-script-hash, that changed:
368         /// CHECKMULTISIGs serialized in scriptSigs are
369         /// counted more accurately, assuming they are of the form
370         ///  ... OP_N CHECKMULTISIG ...
371         /// </summary>
372         /// <param name="fAccurate">Legacy mode flag</param>
373         /// <returns>Amount of sigops</returns>
374         public int GetSigOpCount(bool fAccurate)
375         {
376             var wCodeBytes = new ByteQueue(codeBytes);
377
378             instruction opcode; // Current instruction
379             byte[] pushArgs; // OP_PUSHDATAn argument
380
381             int nCount = 0;
382             var lastOpcode = instruction.OP_INVALIDOPCODE;
383
384             // Scan instructions sequence
385             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
386             {
387                 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
388                 {
389                     nCount++;
390                 }
391                 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
392                 {
393                     if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
394                     {
395                         nCount += ScriptCode.DecodeOP_N(lastOpcode);
396                     }
397                     else
398                     {
399                         nCount += 20;
400                     }
401                 }
402             }
403
404             return nCount;
405         }
406
407         /// <summary>
408         /// Accurately count sigOps, including sigOps in
409         /// pay-to-script-hash transactions
410         /// </summary>
411         /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
412         /// <returns>SigOps count</returns>
413         public int GetSigOpCount(CScript scriptSig)
414         {
415             if (!IsPayToScriptHash)
416             {
417                 return GetSigOpCount(true);
418             }
419
420             // This is a pay-to-script-hash scriptPubKey;
421             // get the last item that the scriptSig
422             // pushes onto the stack:
423             ByteQueue wScriptSig = scriptSig.GetByteQUeue();
424
425             instruction opcode; // Current instruction
426             byte[] pushArgs; // OP_PUSHDATAn argument
427
428             while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
429             {
430                 if (opcode > instruction.OP_16)
431                 {
432                     return 0;
433                 }
434             }
435
436             /// ... and return its opcount:
437             var subScript = new CScript(pushArgs);
438
439             return subScript.GetSigOpCount(true);
440
441         }
442
443         /// <summary>
444         /// Set pay-to-pubkey destination.
445         /// </summary>
446         /// <param name="pubKey">Instance of CPubKey.</param>
447         public void SetDestination(CPubKey pubKey)
448         {
449             codeBytes.Clear();
450             PushData(pubKey.PublicBytes);
451             AddInstruction(instruction.OP_CHECKSIG);
452         }
453
454         /// <summary>
455         /// Set pay-to-pubkeyhash destination
456         /// </summary>
457         /// <param name="ID">Public key hash</param>
458         public void SetDestination(CKeyID ID)
459         {
460             codeBytes.Clear();
461             AddInstruction(instruction.OP_DUP);
462             AddInstruction(instruction.OP_HASH160);
463             AddHash(ID);
464             AddInstruction(instruction.OP_EQUALVERIFY);
465             AddInstruction(instruction.OP_CHECKSIG);
466         }
467
468         /// <summary>
469         /// Set pay-to-scripthash destination
470         /// </summary>
471         /// <param name="ID">Script hash</param>
472         public void SetDestination(CScriptID ID)
473         {
474             codeBytes.Clear();
475             AddInstruction(instruction.OP_HASH160);
476             AddHash(ID);
477             AddInstruction(instruction.OP_EQUAL);
478         }
479
480         /// <summary>
481         /// Reset script code buffer.
482         /// </summary>
483         public void SetNullDestination()
484         {
485             codeBytes.Clear();
486         }
487
488         /// <summary>
489         /// Set multisig destination.
490         /// </summary>
491         /// <param name="nRequired">Amount of required signatures.</param>
492         /// <param name="keys">Set of public keys.</param>
493         public void SetMultiSig(int nRequired, CPubKey[] keys)
494         {
495             codeBytes.Clear();
496             AddInstruction(ScriptCode.EncodeOP_N(nRequired));
497
498             foreach (var key in keys)
499             {
500                 PushData(key.PublicBytes);
501             }
502
503             AddInstruction(ScriptCode.EncodeOP_N(keys.Length));
504             AddInstruction(instruction.OP_CHECKMULTISIG);
505         }
506
507         /// <summary>
508         /// Access to script code.
509         /// </summary>
510         public byte[] Bytes
511         {
512             get { return codeBytes.ToArray(); }
513         }
514
515         public CScriptID ScriptID
516         {
517             get { return new CScriptID(Hash160.Compute160(codeBytes.ToArray())); }
518         }
519
520         /// <summary>
521         /// Disassemble current script code
522         /// </summary>
523         /// <returns>Code listing</returns>
524                 public override string ToString()
525                 {
526                         var sb = new StringBuilder();
527             var wCodeBytes = new ByteQueue(codeBytes);
528
529             instruction opcode; // Current instruction
530             byte[] pushArgs; // OP_PUSHDATAn argument
531             while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
532             {
533                 if (sb.Length != 0)
534                 {
535                     sb.Append(" ");
536                 }
537
538                 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
539                 {
540                     sb.Append(ScriptCode.ValueString(pushArgs));
541                 }
542                 else
543                 {
544                     sb.Append(ScriptCode.GetOpName(opcode));
545                 }
546             }
547
548             return sb.ToString();
549                 }
550         }
551 }