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