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;
23 using System.Diagnostics.Contracts;
28 /// Representation of script code
32 private List<byte> codeBytes;
35 /// Initializes an empty instance of CScript
39 codeBytes = new List<byte>();
43 /// Initializes new instance of CScript and fills it with supplied bytes
45 /// <param name="bytes">Enumerator interface for byte sequence</param>
46 public CScript(byte[] bytes)
48 codeBytes = new List<byte>(bytes);
52 /// Return a new instance of ByteQueue object for current code bytes
54 /// <returns></returns>
55 public InstructionQueue GetInstructionQueue()
57 return new InstructionQueue(ref codeBytes);
61 /// Adds specified operation to instruction list
63 /// <param name="opcode"></param>
64 public void AddInstruction(instruction opcode)
66 Contract.Requires<ArgumentException>(opcode >= instruction.OP_0 && opcode <= instruction.OP_INVALIDOPCODE, "Invalid instruction.");
68 codeBytes.Add((byte)opcode);
72 /// Adds hash to instruction list.
73 /// New items are added in this format:
74 /// hash_length_byte hash_bytes
76 /// <param name="hash">Hash160 instance</param>
77 public void AddHash(Hash160 hash)
79 codeBytes.Add((byte)hash.hashSize);
80 codeBytes.AddRange((byte[])hash);
84 /// Adds hash to instruction list.
85 /// New items are added in this format:
86 /// hash_length_byte hash_bytes
88 /// <param name="hash">Hash256 instance</param>
89 public void AddHash(Hash256 hash)
91 codeBytes.Add((byte)hash.hashSize);
92 codeBytes.AddRange((byte[])hash);
96 /// Create new OP_PUSHDATAn operator and add it to instruction list
98 /// <param name="dataBytes">Set of data bytes</param>
99 public void PushData(byte[] dataBytes)
101 var nCount = dataBytes.LongLength;
103 if (nCount < (int)instruction.OP_PUSHDATA1)
106 codeBytes.Add((byte)nCount);
108 else if (nCount < 0xff)
110 // OP_PUSHDATA1 0x01 [0x5a]
111 codeBytes.Add((byte)instruction.OP_PUSHDATA1);
112 codeBytes.Add((byte)nCount);
114 else if (nCount < 0xffff)
116 // OP_PUSHDATA1 0x01 0x00 [0x5a]
117 codeBytes.Add((byte)instruction.OP_PUSHDATA2);
119 var szBytes = BitConverter.GetBytes((ushort)nCount);
120 codeBytes.AddRange(szBytes);
122 else if (nCount < 0xffffffff)
124 // OP_PUSHDATA1 0x01 0x00 0x00 0x00 [0x5a]
125 codeBytes.Add((byte)instruction.OP_PUSHDATA4);
127 var szBytes = BitConverter.GetBytes((uint)nCount);
128 codeBytes.AddRange(szBytes);
132 codeBytes.AddRange(dataBytes);
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.
139 /// <param name="dataBytes">Data bytes</param>
140 public void AddRawData(byte[] dataBytes)
143 codeBytes.AddRange(dataBytes);
147 /// Scan pushed data bytes for pattern and, in case of exact match, remove it.
149 /// <param name="pattern">Pattern sequence</param>
150 /// <returns>Matches count</returns>
151 public int RemovePattern(byte[] pattern)
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)
160 var bq1 = new InstructionQueue(ref codeBytes);
165 var newScript = new CScript();
167 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
169 if (pushData.Length == 0)
171 // No data, put instruction on its place
172 newScript.AddInstruction(opcode);
174 else if (!pushData.SequenceEqual(pattern))
176 // No match, create push operator
177 newScript.PushData(pushData);
187 // Replace current script if any matches were found
188 codeBytes = newScript.codeBytes;
195 /// Scan script for specific instruction and remove it if there are some matches.
197 /// <param name="op">Instruction</param>
198 /// <returns>Matches count</returns>
199 public int RemoveInstruction(instruction op)
205 var newScript = new CScript();
206 var bq1 = new InstructionQueue(ref codeBytes);
208 while (ScriptCode.GetOp(ref bq1, out opcode, out pushData))
210 if (pushData.Length != 0 && op != opcode)
212 // If instruction didn't match then push its data again
213 newScript.PushData(pushData);
215 else if (Enum.IsDefined(typeof(instruction), op) && op != opcode)
217 // Instruction didn't match
218 newScript.AddInstruction(opcode);
228 // Replace current script if any matches were found
229 codeBytes = newScript.codeBytes;
236 /// Is it true that script doesn't contain anything except push value operations?
238 public bool IsPushOnly
242 var wCodeBytes = new InstructionQueue(ref codeBytes);
244 instruction opcode; // Current instruction
245 byte[] pushArgs; // OP_PUSHDATAn argument
247 // Scan instructions sequence
248 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
250 if (opcode > instruction.OP_16)
252 // We don't allow control instructions here
262 /// Is it true that script doesn't contain non-canonical push operations?
264 public bool HasOnlyCanonicalPushes
268 var wCodeBytes = new InstructionQueue(ref codeBytes);
270 byte[] pushArgs; // OP_PUSHDATAn argument
271 instruction opcode; // Current instruction
273 // Scan instructions sequence
274 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
278 if (opcode < instruction.OP_PUSHDATA1 && opcode > instruction.OP_0 && (data.Length == 1 && data[0] <= 16))
280 // Could have used an OP_n code, rather than a 1-byte push.
283 if (opcode == instruction.OP_PUSHDATA1 && data.Length < (int)instruction.OP_PUSHDATA1)
285 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
288 if (opcode == instruction.OP_PUSHDATA2 && data.Length <= 0xFF)
290 // Could have used an OP_PUSHDATA1.
293 if (opcode == instruction.OP_PUSHDATA4 && data.LongLength <= 0xFFFF)
295 // Could have used an OP_PUSHDATA2.
305 /// Quick test for pay-to-script-hash CScripts
307 public bool IsPayToScriptHash
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);
321 /// Quick test for pay-to-pubkeyhash CScripts
323 public bool IsPayToPubKeyHash
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);
339 /// Quick test for Null destination
343 get { return codeBytes.Count == 0; }
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 ...
353 /// <param name="fAccurate">Legacy mode flag</param>
354 /// <returns>Amount of sigops</returns>
355 public uint GetSigOpCount(bool fAccurate)
357 var wCodeBytes = new InstructionQueue(ref codeBytes);
359 instruction opcode; // Current instruction
360 byte[] pushArgs; // OP_PUSHDATAn argument
363 var lastOpcode = instruction.OP_INVALIDOPCODE;
365 // Scan instructions sequence
366 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
368 if (opcode == instruction.OP_CHECKSIG || opcode == instruction.OP_CHECKSIGVERIFY)
372 else if (opcode == instruction.OP_CHECKMULTISIG || opcode == instruction.OP_CHECKMULTISIGVERIFY)
374 if (fAccurate && lastOpcode >= instruction.OP_1 && lastOpcode <= instruction.OP_16)
376 nCount += (uint)ScriptCode.DecodeOP_N(lastOpcode);
389 /// Accurately count sigOps, including sigOps in
390 /// pay-to-script-hash transactions
392 /// <param name="scriptSig">pay-to-script-hash scriptPubKey</param>
393 /// <returns>SigOps count</returns>
394 public uint GetSigOpCount(CScript scriptSig)
396 if (!IsPayToScriptHash)
398 return GetSigOpCount(true);
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;
407 instruction opcode; // Current instruction
408 byte[] pushArgs = new byte[0]; // OP_PUSHDATAn argument
411 while (wScriptSig.Index < nScriptSigSize)
413 if (!ScriptCode.GetOp(ref wScriptSig, out opcode, out pushArgs))
418 if (opcode > instruction.OP_16)
424 /// ... and return its opcount:
425 var subScript = new CScript(pushArgs);
427 return subScript.GetSigOpCount(true);
432 /// Set pay-to-pubkey destination.
434 /// <param name="pubKey">Instance of CPubKey.</param>
435 public void SetDestination(CPubKey pubKey)
439 AddInstruction(instruction.OP_CHECKSIG);
443 /// Set pay-to-pubkeyhash destination
445 /// <param name="ID">Public key hash</param>
446 public void SetDestination(CKeyID ID)
449 AddInstruction(instruction.OP_DUP);
450 AddInstruction(instruction.OP_HASH160);
452 AddInstruction(instruction.OP_EQUALVERIFY);
453 AddInstruction(instruction.OP_CHECKSIG);
457 /// Set pay-to-scripthash destination
459 /// <param name="ID">Script hash</param>
460 public void SetDestination(CScriptID ID)
463 AddInstruction(instruction.OP_HASH160);
465 AddInstruction(instruction.OP_EQUAL);
469 /// Reset script code buffer.
471 public void SetNullDestination()
477 /// Set multisig destination.
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)
484 AddInstruction(ScriptCode.EncodeOP_N(nRequired));
486 foreach (var key in keys)
491 AddInstruction(ScriptCode.EncodeOP_N(keys.Length));
492 AddInstruction(instruction.OP_CHECKMULTISIG);
496 /// Access to script code.
498 public static implicit operator byte[] (CScript script)
500 return script.codeBytes.ToArray();
508 get { return codeBytes.Count; }
511 public CScriptID ScriptID
513 get { return new CScriptID(Hash160.Compute160(codeBytes.ToArray())); }
517 /// Disassemble current script code
519 /// <returns>Code listing</returns>
520 public override string ToString()
522 var sb = new StringBuilder();
523 var wCodeBytes = new InstructionQueue(ref codeBytes);
525 instruction opcode; // Current instruction
526 byte[] pushArgs; // OP_PUSHDATAn argument
527 while (ScriptCode.GetOp(ref wCodeBytes, out opcode, out pushArgs))
534 if (0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
536 sb.Append(ScriptCode.ValueString(pushArgs));
540 sb.Append(ScriptCode.GetOpName(opcode));
544 return sb.ToString();