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(IEnumerable<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 opcode bytes list
79 /// <param name="opcode"></param>
80 public void AddOp(instruction opcode)
82 if (opcode < instruction.OP_0 || opcode > instruction.OP_INVALIDOPCODE)
84 throw new CScriptException("CScript::AddOp() : invalid opcode");
87 codeBytes.Add((byte)opcode);
91 /// Adds hash to opcode bytes 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 opcode bytes 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 opcode bytes list
117 /// <param name="dataBytes">Set of data bytes</param>
118 public void PushData(IEnumerable<byte> dataBytes)
120 long nCount = dataBytes.LongCount();
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 byte[] 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 byte[] szBytes = Interop.BEBytes((uint)nCount);
147 codeBytes.AddRange(szBytes);
151 codeBytes.AddRange(dataBytes);
155 /// Scan code bytes for pattern
157 /// <param name="pattern">Pattern sequence</param>
158 /// <returns>Matches enumerator</returns>
159 private IEnumerable<int> FindPattern(IList<byte> pattern)
161 for (int i = 0; i < codeBytes.Count; i++)
163 if (codeBytes.Skip(i).Take(pattern.Count).SequenceEqual(pattern))
171 /// Scan code bytes for pattern and remove it
173 /// <param name="pattern">Pattern sequence</param>
174 /// <returns>Matches number</returns>
175 public int RemovePattern(IList<byte> pattern)
177 List<byte> resultBytes = new List<byte>(codeBytes);
179 int patternLen = pattern.Count;
181 foreach (int i in FindPattern(pattern))
183 resultBytes.RemoveRange(i - count * patternLen, patternLen);
187 codeBytes = resultBytes;
193 /// Is it true that script doesn't contain anything except push value operations?
195 public bool IsPushOnly
199 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
201 instruction opcode; // Current opcode
202 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
204 // Scan opcodes sequence
205 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
207 if (opcode > instruction.OP_16)
209 // We don't allow control opcodes here
219 /// Is it true that script doesn't contain non-canonical push operations?
221 public bool HasOnlyCanonicalPushes
225 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
227 instruction opcode; // Current opcode
228 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
230 // Scan opcodes sequence
231 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
233 byte[] data = pushArgs.ToArray();
235 if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
237 // Could have used an OP_n code, rather than a 1-byte push.
240 if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
242 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
245 if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
247 // Could have used an OP_PUSHDATA1.
250 if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
252 // Could have used an OP_PUSHDATA2.
262 /// Quick test for pay-to-script-hash CScripts
264 public bool IsPayToScriptHash
268 // Sender provides redeem script hash, receiver provides signature list and redeem script
269 // OP_HASH160 20 [20 byte hash] OP_EQUAL
270 return (codeBytes.Count() == 23 &&
271 codeBytes[0] == (byte)instruction.OP_HASH160 &&
272 codeBytes[1] == 0x14 && // 20 bytes hash length prefix
273 codeBytes[22] == (byte)instruction.OP_EQUAL);
278 /// Quick test for pay-to-pubkeyhash CScripts
280 public bool IsPayToPubKeyHash
284 // Sender provides hash of pubkey, receiver provides signature and pubkey
285 // OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
286 return (codeBytes.Count == 25 &&
287 codeBytes[0] == (byte)instruction.OP_DUP &&
288 codeBytes[1] == (byte)instruction.OP_HASH160 &&
289 codeBytes[2] == 0x14 && // 20 bytes hash length prefix
290 codeBytes[23] == (byte)instruction.OP_EQUALVERIFY &&
291 codeBytes[24] == (byte)instruction.OP_CHECKSIG);
296 /// Quick test for Null destination
300 get { return codeBytes.Count == 0; }
304 /// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
305 /// as 20 sigops. With pay-to-script-hash, that changed:
306 /// CHECKMULTISIGs serialized in scriptSigs are
307 /// counted more accurately, assuming they are of the form
308 /// ... OP_N CHECKMULTISIG ...
310 /// <param name="fAccurate">Legacy mode flag</param>
311 /// <returns>Amount of sigops</returns>
312 public int GetSigOpCount(bool fAccurate)
314 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
316 instruction opcode; // Current opcode
317 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
320 instruction lastOpcode = instruction.OP_INVALIDOPCODE;
322 // Scan opcodes sequence
323 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
325 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
329 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
331 if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
333 nCount += ScriptCode.DecodeOP_N(lastOpcode);
346 /// Accurately count sigOps, including sigOps in
347 /// pay-to-script-hash transactions
349 /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
350 /// <returns>SigOps count</returns>
351 public int GetSigOpCount(CScript scriptSig)
353 if (!IsPayToScriptHash)
355 return GetSigOpCount(true);
358 // This is a pay-to-script-hash scriptPubKey;
359 // get the last item that the scriptSig
360 // pushes onto the stack:
361 ByteQueue wScriptSig = scriptSig.GetByteQUeue();
363 instruction opcode; // Current opcode
364 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
366 while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
368 if (opcode > instruction.OP_16)
374 /// ... and return its opcount:
375 CScript subScript = new CScript(pushArgs);
377 return subScript.GetSigOpCount(true);
382 /// Set pay-to-pubkey destination.
384 /// <param name="pubKey">Instance of CPubKey.</param>
385 public void SetDestination(CPubKey pubKey)
388 PushData(pubKey.PublicBytes);
389 AddOp(instruction.OP_CHECKSIG);
393 /// Set pay-to-pubkeyhash destination
395 /// <param name="ID">Public key hash</param>
396 public void SetDestination(CKeyID ID)
399 AddOp(instruction.OP_DUP);
400 AddOp(instruction.OP_HASH160);
402 AddOp(instruction.OP_EQUALVERIFY);
403 AddOp(instruction.OP_CHECKSIG);
407 /// Set pay-to-scripthash destination
409 /// <param name="ID">Script hash</param>
410 public void SetDestination(CScriptID ID)
413 AddOp(instruction.OP_HASH160);
415 AddOp(instruction.OP_EQUAL);
419 /// Reset script code buffer.
421 public void SetNullDestination()
427 /// Set multisig destination.
429 /// <param name="nRequired">Amount of required signatures.</param>
430 /// <param name="keys">Set of public keys.</param>
431 public void SetMultiSig(int nRequired, IEnumerable<CPubKey> keys)
434 AddOp(ScriptCode.EncodeOP_N(nRequired));
436 foreach (CPubKey key in keys)
438 PushData(key.PublicBytes.ToList());
441 AddOp(ScriptCode.EncodeOP_N(keys.Count()));
442 AddOp(instruction.OP_CHECKMULTISIG);
446 /// Access to script code.
448 public IEnumerable<byte> Bytes
450 get { return codeBytes; }
453 public CScriptID ScriptID
455 get { return new CScriptID(Hash160.Compute160(codeBytes)); }
459 /// Disassemble current script code
461 /// <returns>Code listing</returns>
462 public override string ToString()
464 StringBuilder sb = new StringBuilder();
465 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
467 instruction opcode; // Current opcode
468 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
469 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
476 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
478 sb.Append(ScriptCode.ValueString(pushArgs));
482 sb.Append(ScriptCode.GetOpName(opcode));
486 return sb.ToString();