4 using System.Collections.Generic;
8 public class CScriptException : Exception
10 public CScriptException()
14 public CScriptException(string message)
19 public CScriptException(string message, Exception inner)
20 : base(message, inner)
26 /// Representation of script code
30 private List<byte> codeBytes;
33 /// Initializes an empty instance of CScript
37 codeBytes = new List<byte>();
41 /// Initializes new instance of CScript and fills it with supplied bytes
43 /// <param name="bytes">Enumerator interface for byte sequence</param>
44 public CScript(IEnumerable<byte> bytes)
46 codeBytes = new List<byte>(bytes);
50 /// Return a new instance of ByteQueue object for current code bytes
52 /// <returns></returns>
53 public ByteQueue GetByteQUeue()
55 return new ByteQueue(codeBytes);
59 /// Adds specified operation to opcode bytes list
61 /// <param name="opcode"></param>
62 public void AddOp(opcodetype opcode)
64 if (opcode < opcodetype.OP_0 || opcode > opcodetype.OP_INVALIDOPCODE)
66 throw new CScriptException("CScript::AddOp() : invalid opcode");
69 codeBytes.Add((byte)opcode);
73 /// Adds hash to opcode bytes list.
74 /// New items are added in this format:
75 /// hash_length_byte hash_bytes
77 /// <param name="hash">Hash160 instance</param>
78 public void AddHash(Hash160 hash)
80 codeBytes.Add((byte)hash.hashSize);
81 codeBytes.AddRange(hash.hashBytes);
85 /// Adds hash to opcode bytes list.
86 /// New items are added in this format:
87 /// hash_length_byte hash_bytes
89 /// <param name="hash">Hash256 instance</param>
90 public void AddHash(Hash256 hash)
92 codeBytes.Add((byte)hash.hashSize);
93 codeBytes.AddRange(hash.hashBytes);
97 /// Create new OP_PUSHDATAn operator and add it to opcode bytes list
99 /// <param name="dataBytes">Set of data bytes</param>
100 public void PushData(IEnumerable<byte> dataBytes)
102 long nCount = dataBytes.LongCount();
104 if (nCount < (int)opcodetype.OP_PUSHDATA1)
107 codeBytes.Add((byte)nCount);
109 else if (nCount < 0xff)
111 // OP_PUSHDATA1 0x01 [0x5a]
112 codeBytes.Add((byte)opcodetype.OP_PUSHDATA1);
113 codeBytes.Add((byte)nCount);
115 else if (nCount < 0xffff)
117 // OP_PUSHDATA1 0x00 0x01 [0x5a]
118 codeBytes.Add((byte)opcodetype.OP_PUSHDATA2);
120 byte[] szBytes = Interop.BEBytes((ushort)nCount);
121 codeBytes.AddRange(szBytes);
123 else if (nCount < 0xffffffff)
125 // OP_PUSHDATA1 0x00 0x00 0x00 0x01 [0x5a]
126 codeBytes.Add((byte)opcodetype.OP_PUSHDATA4);
128 byte[] szBytes = Interop.BEBytes((uint)nCount);
129 codeBytes.AddRange(szBytes);
133 codeBytes.AddRange(dataBytes);
137 /// Scan code bytes for pattern
139 /// <param name="pattern">Pattern sequence</param>
140 /// <returns>Matches enumerator</returns>
141 private IEnumerable<int> FindPattern(IList<byte> pattern)
143 for (int i = 0; i < codeBytes.Count; i++)
145 if (codeBytes.Skip(i).Take(pattern.Count).SequenceEqual(pattern))
153 /// Scan code bytes for pattern and remove it
155 /// <param name="pattern">Pattern sequence</param>
156 /// <returns>Matches number</returns>
157 public int RemovePattern(IList<byte> pattern)
159 List<byte> resultBytes = new List<byte>(codeBytes);
161 int patternLen = pattern.Count;
163 foreach (int i in FindPattern(pattern))
165 resultBytes.RemoveRange(i - count * patternLen, patternLen);
169 codeBytes = resultBytes;
175 /// Is it true that script doesn't contain anything except push value operations?
177 public bool IsPushonly
181 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
183 opcodetype opcode; // Current opcode
184 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
186 // Scan opcodes sequence
187 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
189 if (opcode > opcodetype.OP_16)
191 // We don't allow control opcodes here
201 /// Is it true that script doesn't contain non-canonical push operations?
203 public bool HasOnlyCanonicalPushes
207 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
209 opcodetype opcode; // Current opcode
210 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
212 // Scan opcodes sequence
213 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
215 byte[] data = pushArgs.ToArray();
217 if (opcode < opcodetype.OP_PUSHDATA1 && opcode > opcodetype.OP_0 && (data.Length == 1 && data[0] <= 16))
219 // Could have used an OP_n code, rather than a 1-byte push.
222 if (opcode == opcodetype.OP_PUSHDATA1 && data.Length < (int)opcodetype.OP_PUSHDATA1)
224 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
227 if (opcode == opcodetype.OP_PUSHDATA2 && data.Length <= 0xFF)
229 // Could have used an OP_PUSHDATA1.
232 if (opcode == opcodetype.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
234 // Could have used an OP_PUSHDATA2.
244 /// Quick test for pay-to-script-hash CScripts
246 public bool IsPayToScriptHash
250 // Sender provides redeem script hash, receiver provides signature list and redeem script
251 // OP_HASH160 20 [20 byte hash] OP_EQUAL
252 return (codeBytes.Count() == 23 &&
253 codeBytes[0] == (byte)opcodetype.OP_HASH160 &&
254 codeBytes[1] == 0x14 && // 20 bytes hash length prefix
255 codeBytes[22] == (byte)opcodetype.OP_EQUAL);
260 /// Quick test for pay-to-pubkeyhash CScripts
262 public bool IsPayToPubKeyHash
266 // Sender provides hash of pubkey, receiver provides signature and pubkey
267 // OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
268 return (codeBytes.Count == 25 &&
269 codeBytes[0] == (byte)opcodetype.OP_DUP &&
270 codeBytes[1] == (byte)opcodetype.OP_HASH160 &&
271 codeBytes[2] == 0x14 && // 20 bytes hash length prefix
272 codeBytes[23] == (byte)opcodetype.OP_EQUALVERIFY &&
273 codeBytes[24] == (byte)opcodetype.OP_CHECKSIG);
278 /// Quick test for Null destination
282 get { return codeBytes.Count == 0; }
286 /// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
287 /// as 20 sigops. With pay-to-script-hash, that changed:
288 /// CHECKMULTISIGs serialized in scriptSigs are
289 /// counted more accurately, assuming they are of the form
290 /// ... OP_N CHECKMULTISIG ...
292 /// <param name="fAccurate">Legacy mode flag</param>
293 /// <returns>Amount of sigops</returns>
294 public int GetSigOpCount(bool fAccurate)
296 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
298 opcodetype opcode; // Current opcode
299 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
302 opcodetype lastOpcode = opcodetype.OP_INVALIDOPCODE;
304 // Scan opcodes sequence
305 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
307 if (opcode == opcodetype.OP_CHECKSIG || opcode == opcodetype.OP_CHECKSIGVERIFY)
311 else if (opcode == opcodetype.OP_CHECKMULTISIG || opcode == opcodetype.OP_CHECKMULTISIGVERIFY)
313 if (fAccurate && lastOpcode >= opcodetype.OP_1 && lastOpcode <= opcodetype.OP_16)
315 nCount += ScriptCode.DecodeOP_N(lastOpcode);
328 /// Accurately count sigOps, including sigOps in
329 /// pay-to-script-hash transactions
331 /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
332 /// <returns>SigOps count</returns>
333 public int GetSigOpCount(CScript scriptSig)
335 if (!IsPayToScriptHash)
337 return GetSigOpCount(true);
340 // This is a pay-to-script-hash scriptPubKey;
341 // get the last item that the scriptSig
342 // pushes onto the stack:
343 ByteQueue wScriptSig = scriptSig.GetByteQUeue();
345 opcodetype opcode; // Current opcode
346 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
348 while (ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
350 if (opcode > opcodetype.OP_16)
356 /// ... and return its opcount:
357 CScript subScript = new CScript(pushArgs);
359 return subScript.GetSigOpCount(true);
364 /// Set pay-to-pubkey destination.
366 /// <param name="pubKey">Instance of CPubKey.</param>
367 public void SetDestination(CPubKey pubKey)
370 PushData(pubKey.PublicBytes);
371 AddOp(opcodetype.OP_CHECKSIG);
375 /// Set pay-to-pubkeyhash destination
377 /// <param name="ID">Public key hash</param>
378 public void SetDestination(CKeyID ID)
381 AddOp(opcodetype.OP_DUP);
382 AddOp(opcodetype.OP_HASH160);
384 AddOp(opcodetype.OP_EQUALVERIFY);
385 AddOp(opcodetype.OP_CHECKSIG);
389 /// Set pay-to-scripthash destination
391 /// <param name="ID">Script hash</param>
392 public void SetDestination(CScriptID ID)
395 AddOp(opcodetype.OP_HASH160);
397 AddOp(opcodetype.OP_EQUAL);
401 /// Reset script code buffer.
403 public void SetNullDestination()
409 /// Set multisig destination.
411 /// <param name="nRequired">Amount of required signatures.</param>
412 /// <param name="keys">Set of public keys.</param>
413 public void SetMultiSig(int nRequired, IEnumerable<CPubKey> keys)
416 AddOp(ScriptCode.EncodeOP_N(nRequired));
418 foreach (CPubKey key in keys)
420 PushData(key.PublicBytes.ToList());
423 AddOp(ScriptCode.EncodeOP_N(keys.Count()));
424 AddOp(opcodetype.OP_CHECKMULTISIG);
428 /// Access to script code.
430 public IEnumerable<byte> Bytes
432 get { return codeBytes; }
435 public CScriptID ScriptID
437 get { return new CScriptID(Hash160.Compute160(codeBytes)); }
441 /// Disassemble current script code
443 /// <returns>Code listing</returns>
444 public override string ToString()
446 StringBuilder sb = new StringBuilder();
447 ByteQueue wCodeBytes = new ByteQueue(codeBytes);
449 opcodetype opcode; // Current opcode
450 IEnumerable<byte> pushArgs; // OP_PUSHDATAn argument
451 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
458 if (0 <= opcode && opcode <= opcodetype.OP_PUSHDATA4)
460 sb.Append(ScriptCode.ValueString(pushArgs));
464 sb.Append(ScriptCode.GetOpName(opcode));
468 return sb.ToString();