2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
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.
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.
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/>.
22 using System.Collections.Generic;
26 public class CScriptException : Exception
28 public CScriptException()
32 public CScriptException(string message)
37 public CScriptException(string message, Exception inner)
38 : base(message, inner)
44 /// Representation of script code
48 private List<byte> codeBytes;
51 /// Initializes an empty instance of CScript
55 codeBytes = new List<byte>();
59 /// Initializes new instance of CScript and fills it with supplied bytes
61 /// <param name="bytes">Enumerator interface for byte sequence</param>
62 public CScript(byte[] bytes)
64 codeBytes = new List<byte>(bytes);
68 /// Return a new instance of ByteQueue object for current code bytes
70 /// <returns></returns>
71 public ByteQueue GetByteQUeue()
73 return new ByteQueue(codeBytes);
77 /// Adds specified operation to instruction list
79 /// <param name="opcode"></param>
80 public void AddInstruction(instruction opcode)
82 if (opcode < instruction.OP_0 || opcode > instruction.OP_INVALIDOPCODE)
84 throw new CScriptException("CScript::AddInstruction() : invalid instruction");
87 codeBytes.Add((byte)opcode);
91 /// Adds hash to instruction list.
92 /// New items are added in this format:
93 /// hash_length_byte hash_bytes
95 /// <param name="hash">Hash160 instance</param>
96 public void AddHash(Hash160 hash)
98 codeBytes.Add((byte)hash.hashSize);
99 codeBytes.AddRange(hash.hashBytes);
103 /// Adds hash to instruction list.
104 /// New items are added in this format:
105 /// hash_length_byte hash_bytes
107 /// <param name="hash">Hash256 instance</param>
108 public void AddHash(Hash256 hash)
110 codeBytes.Add((byte)hash.hashSize);
111 codeBytes.AddRange(hash.hashBytes);
115 /// Create new OP_PUSHDATAn operator and add it to instruction list
117 /// <param name="dataBytes">Set of data bytes</param>
118 public void PushData(byte[] dataBytes)
120 var nCount = dataBytes.LongLength;
122 if (nCount < (int)instruction.OP_PUSHDATA1)
125 codeBytes.Add((byte)nCount);
127 else if (nCount < 0xff)
129 // OP_PUSHDATA1 0x01 [0x5a]
130 codeBytes.Add((byte)instruction.OP_PUSHDATA1);
131 codeBytes.Add((byte)nCount);
133 else if (nCount < 0xffff)
135 // OP_PUSHDATA1 0x01 0x00 [0x5a]
136 codeBytes.Add((byte)instruction.OP_PUSHDATA2);
138 var szBytes = BitConverter.GetBytes((ushort)nCount);
139 codeBytes.AddRange(szBytes);
141 else if (nCount < 0xffffffff)
143 // OP_PUSHDATA1 0x01 0x00 0x00 0x00 [0x5a]
144 codeBytes.Add((byte)instruction.OP_PUSHDATA4);
146 var szBytes = BitConverter.GetBytes((uint)nCount);
147 codeBytes.AddRange(szBytes);
151 codeBytes.AddRange(dataBytes);
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.
158 /// <param name="dataBytes">Data bytes</param>
159 public void AddRawData(byte[] dataBytes)
162 codeBytes.AddRange(dataBytes);
166 /// Scan pushed data bytes for pattern and, in case of exact match, remove it.
168 /// <param name="pattern">Pattern sequence</param>
169 /// <returns>Matches count</returns>
170 public int RemovePattern(byte[] pattern)
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)
179 var bq1 = new ByteQueue(codeBytes);
184 var newScript = new CScript();
186 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
188 if (pushData.Length == 0)
190 // No data, put instruction on its place
191 newScript.AddInstruction(opcode);
193 else if (!pushData.SequenceEqual(pattern))
195 // No match, create push operator
196 newScript.PushData(pushData);
206 // Replace current script if any matches were found
207 codeBytes = newScript.codeBytes;
214 /// Scan script for specific instruction and remove it if there are some matches.
216 /// <param name="op">Instruction</param>
217 /// <returns>Matches count</returns>
218 public int RemoveInstruction(instruction op)
224 var newScript = new CScript();
225 var bq1 = new ByteQueue(codeBytes);
227 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
229 if (pushData.Length != 0 && op != opcode)
231 // If instruction didn't match then push its data again
232 newScript.PushData(pushData);
234 else if (Enum.IsDefined(typeof(instruction), op) && op != opcode)
236 // Instruction didn't match
237 newScript.AddInstruction(opcode);
247 // Replace current script if any matches were found
248 codeBytes = newScript.codeBytes;
255 /// Is it true that script doesn't contain anything except push value operations?
257 public bool IsPushOnly
261 var wCodeBytes = new ByteQueue(codeBytes);
263 instruction opcode; // Current instruction
264 byte[] pushArgs; // OP_PUSHDATAn argument
266 // Scan instructions sequence
267 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
269 if (opcode > instruction.OP_16)
271 // We don't allow control instructions here
281 /// Is it true that script doesn't contain non-canonical push operations?
283 public bool HasOnlyCanonicalPushes
287 var wCodeBytes = new ByteQueue(codeBytes);
289 byte[] pushArgs; // OP_PUSHDATAn argument
290 instruction opcode; // Current instruction
292 // Scan instructions sequence
293 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
297 if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
299 // Could have used an OP_n code, rather than a 1-byte push.
302 if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
304 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
307 if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
309 // Could have used an OP_PUSHDATA1.
312 if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
314 // Could have used an OP_PUSHDATA2.
324 /// Quick test for pay-to-script-hash CScripts
326 public bool IsPayToScriptHash
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);
340 /// Quick test for pay-to-pubkeyhash CScripts
342 public bool IsPayToPubKeyHash
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);
358 /// Quick test for Null destination
362 get { return codeBytes.Count == 0; }
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 ...
372 /// <param name="fAccurate">Legacy mode flag</param>
373 /// <returns>Amount of sigops</returns>
374 public int GetSigOpCount(bool fAccurate)
376 var wCodeBytes = new ByteQueue(codeBytes);
378 instruction opcode; // Current instruction
379 byte[] pushArgs; // OP_PUSHDATAn argument
382 var lastOpcode = instruction.OP_INVALIDOPCODE;
384 // Scan instructions sequence
385 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
387 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
391 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
393 if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
395 nCount += ScriptCode.DecodeOP_N(lastOpcode);
408 /// Accurately count sigOps, including sigOps in
409 /// pay-to-script-hash transactions
411 /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
412 /// <returns>SigOps count</returns>
413 public int GetSigOpCount(CScript scriptSig)
415 if (!IsPayToScriptHash)
417 return GetSigOpCount(true);
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();
425 instruction opcode; // Current instruction
426 byte[] pushArgs; // OP_PUSHDATAn argument
428 while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
430 if (opcode > instruction.OP_16)
436 /// ... and return its opcount:
437 var subScript = new CScript(pushArgs);
439 return subScript.GetSigOpCount(true);
444 /// Set pay-to-pubkey destination.
446 /// <param name="pubKey">Instance of CPubKey.</param>
447 public void SetDestination(CPubKey pubKey)
450 PushData(pubKey.PublicBytes);
451 AddInstruction(instruction.OP_CHECKSIG);
455 /// Set pay-to-pubkeyhash destination
457 /// <param name="ID">Public key hash</param>
458 public void SetDestination(CKeyID ID)
461 AddInstruction(instruction.OP_DUP);
462 AddInstruction(instruction.OP_HASH160);
464 AddInstruction(instruction.OP_EQUALVERIFY);
465 AddInstruction(instruction.OP_CHECKSIG);
469 /// Set pay-to-scripthash destination
471 /// <param name="ID">Script hash</param>
472 public void SetDestination(CScriptID ID)
475 AddInstruction(instruction.OP_HASH160);
477 AddInstruction(instruction.OP_EQUAL);
481 /// Reset script code buffer.
483 public void SetNullDestination()
489 /// Set multisig destination.
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)
496 AddInstruction(ScriptCode.EncodeOP_N(nRequired));
498 foreach (var key in keys)
500 PushData(key.PublicBytes);
503 AddInstruction(ScriptCode.EncodeOP_N(keys.Length));
504 AddInstruction(instruction.OP_CHECKMULTISIG);
508 /// Access to script code.
512 get { return codeBytes.ToArray(); }
515 public CScriptID ScriptID
517 get { return new CScriptID(Hash160.Compute160(codeBytes.ToArray())); }
521 /// Disassemble current script code
523 /// <returns>Code listing</returns>
524 public override string ToString()
526 var sb = new StringBuilder();
527 var wCodeBytes = new ByteQueue(codeBytes);
529 instruction opcode; // Current instruction
530 byte[] pushArgs; // OP_PUSHDATAn argument
531 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
538 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
540 sb.Append(ScriptCode.ValueString(pushArgs));
544 sb.Append(ScriptCode.GetOpName(opcode));
548 return sb.ToString();