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 0x00 0x01 [0x5a]
136 codeBytes.Add((byte)instruction.OP_PUSHDATA2);
138 var szBytes = Interop.BEBytes((ushort)nCount);
139 codeBytes.AddRange(szBytes);
141 else if (nCount < 0xffffffff)
143 // OP_PUSHDATA1 0x00 0x00 0x00 0x01 [0x5a]
144 codeBytes.Add((byte)instruction.OP_PUSHDATA4);
146 var szBytes = Interop.BEBytes((uint)nCount);
147 codeBytes.AddRange(szBytes);
151 codeBytes.AddRange(dataBytes);
155 /// Scan pushed data bytes for pattern and, in case of exact match, remove it.
157 /// <param name="pattern">Pattern sequence</param>
158 /// <returns>Matches count</returns>
159 public int RemovePattern(byte[] pattern)
161 // There is no sense to continue if pattern is longer than script itself
162 if (pattern.Length == 0 || pattern.Length > codeBytes.Count)
168 var bq1 = new ByteQueue(codeBytes);
174 var newScript = new CScript();
176 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
178 if (pushData.Length == 0)
180 // No data, put instruction on its place
181 newScript.AddInstruction(opcode);
183 else if (!pushData.SequenceEqual(pattern))
185 // No match, create push operator
186 newScript.PushData(pushData);
194 codeBytes = newScript.codeBytes;
200 /// Scan script for specific instruction and remove it if there are some matches.
202 /// <param name="op">Instruction</param>
203 /// <returns>Matches count</returns>
204 public int RemoveInstruction(instruction op)
207 var bq1 = new ByteQueue(codeBytes);
213 var newScript = new CScript();
215 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
217 if (pushData.Length != 0)
219 newScript.PushData(pushData);
221 else if (Enum.IsDefined(typeof(instruction), op) && op != opcode)
223 newScript.AddInstruction(opcode);
231 codeBytes = newScript.codeBytes;
237 /// Is it true that script doesn't contain anything except push value operations?
239 public bool IsPushOnly
243 var wCodeBytes = new ByteQueue(codeBytes);
245 instruction opcode; // Current instruction
246 byte[] pushArgs; // OP_PUSHDATAn argument
248 // Scan instructions sequence
249 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
251 if (opcode > instruction.OP_16)
253 // We don't allow control instructions here
263 /// Is it true that script doesn't contain non-canonical push operations?
265 public bool HasOnlyCanonicalPushes
269 var wCodeBytes = new ByteQueue(codeBytes);
271 byte[] pushArgs; // OP_PUSHDATAn argument
272 instruction opcode; // Current instruction
274 // Scan instructions sequence
275 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
279 if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
281 // Could have used an OP_n code, rather than a 1-byte push.
284 if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
286 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
289 if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
291 // Could have used an OP_PUSHDATA1.
294 if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
296 // Could have used an OP_PUSHDATA2.
306 /// Quick test for pay-to-script-hash CScripts
308 public bool IsPayToScriptHash
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);
322 /// Quick test for pay-to-pubkeyhash CScripts
324 public bool IsPayToPubKeyHash
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);
340 /// Quick test for Null destination
344 get { return codeBytes.Count == 0; }
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 ...
354 /// <param name="fAccurate">Legacy mode flag</param>
355 /// <returns>Amount of sigops</returns>
356 public int GetSigOpCount(bool fAccurate)
358 var wCodeBytes = new ByteQueue(codeBytes);
360 instruction opcode; // Current instruction
361 byte[] pushArgs; // OP_PUSHDATAn argument
364 var lastOpcode = instruction.OP_INVALIDOPCODE;
366 // Scan instructions sequence
367 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
369 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
373 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
375 if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
377 nCount += ScriptCode.DecodeOP_N(lastOpcode);
390 /// Accurately count sigOps, including sigOps in
391 /// pay-to-script-hash transactions
393 /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
394 /// <returns>SigOps count</returns>
395 public int GetSigOpCount(CScript scriptSig)
397 if (!IsPayToScriptHash)
399 return GetSigOpCount(true);
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();
407 instruction opcode; // Current instruction
408 byte[] pushArgs; // OP_PUSHDATAn argument
410 while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
412 if (opcode > instruction.OP_16)
418 /// ... and return its opcount:
419 var subScript = new CScript(pushArgs);
421 return subScript.GetSigOpCount(true);
426 /// Set pay-to-pubkey destination.
428 /// <param name="pubKey">Instance of CPubKey.</param>
429 public void SetDestination(CPubKey pubKey)
432 PushData(pubKey.PublicBytes);
433 AddInstruction(instruction.OP_CHECKSIG);
437 /// Set pay-to-pubkeyhash destination
439 /// <param name="ID">Public key hash</param>
440 public void SetDestination(CKeyID ID)
443 AddInstruction(instruction.OP_DUP);
444 AddInstruction(instruction.OP_HASH160);
446 AddInstruction(instruction.OP_EQUALVERIFY);
447 AddInstruction(instruction.OP_CHECKSIG);
451 /// Set pay-to-scripthash destination
453 /// <param name="ID">Script hash</param>
454 public void SetDestination(CScriptID ID)
457 AddInstruction(instruction.OP_HASH160);
459 AddInstruction(instruction.OP_EQUAL);
463 /// Reset script code buffer.
465 public void SetNullDestination()
471 /// Set multisig destination.
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)
478 AddInstruction(ScriptCode.EncodeOP_N(nRequired));
480 foreach (var key in keys)
482 PushData(key.PublicBytes);
485 AddInstruction(ScriptCode.EncodeOP_N(keys.Length));
486 AddInstruction(instruction.OP_CHECKMULTISIG);
490 /// Access to script code.
494 get { return codeBytes.ToArray(); }
497 public CScriptID ScriptID
499 get { return new CScriptID(Hash160.Compute160(codeBytes.ToArray())); }
503 /// Disassemble current script code
505 /// <returns>Code listing</returns>
506 public override string ToString()
508 var sb = new StringBuilder();
509 var wCodeBytes = new ByteQueue(codeBytes);
511 instruction opcode; // Current instruction
512 byte[] pushArgs; // OP_PUSHDATAn argument
513 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
520 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
522 sb.Append(ScriptCode.ValueString(pushArgs));
526 sb.Append(ScriptCode.GetOpName(opcode));
530 return sb.ToString();