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/>.
21 using System.Collections.Generic;
27 public class TransactionConstructorException : Exception
29 public TransactionConstructorException()
33 public TransactionConstructorException(string message)
38 public TransactionConstructorException(string message, Exception inner)
39 : base(message, inner)
45 /// Represents the transaction. Any transaction must provide one input and one output at least.
47 public class CTransaction
50 /// One coin = 1000000 satoshis.
52 public const ulong nCoin = 1000000;
54 /// Sanity checking threshold.
56 public const ulong nMaxMoney = 2000000000 * nCoin;
59 /// Version of transaction schema.
64 /// Transaction timestamp.
69 /// Array of transaction inputs
74 /// Array of transaction outputs
79 /// Block height or timestamp when transaction is final
81 public uint nLockTime;
84 /// Initialize an empty instance
88 // Initialize empty input and output arrays. Please note that such
89 // configuration is not valid for real transaction, you have to supply
90 // at least one input and one output.
99 /// Initialize new instance as a copy of another transaction
101 /// <param name="tx">Transaction to copy from</param>
102 public CTransaction(CTransaction tx)
104 nVersion = tx.nVersion;
107 vin = new CTxIn[tx.vin.Length];
109 for (int i = 0; i < vin.Length; i++)
111 vin[i] = new CTxIn(tx.vin[i]);
114 vout = new CTxOut[tx.vout.Length];
116 for (int i = 0; i < vout.Length; i++)
118 vout[i] = new CTxOut(tx.vout[i]);
121 nLockTime = tx.nLockTime;
125 /// Attempts to execute all transaction scripts and validate the results.
127 /// <returns>Checking result.</returns>
128 public bool VerifyScripts()
135 CTransaction txPrev = null;
136 for (int i = 0; i < vin.Length; i++)
138 var outpoint = vin[i].prevout;
140 if (!CBlockStore.Instance.GetTransaction(outpoint.hash, ref txPrev))
143 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txPrev.vout[outpoint.n].scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
151 /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
153 public uint LegacySigOpCount
158 foreach (var txin in vin)
160 nSigOps += txin.scriptSig.GetSigOpCount(false);
162 foreach (var txout in vout)
164 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
172 /// Basic sanity checkings
174 /// <returns>Checking result</returns>
175 public bool CheckTransaction()
177 if (Size > 250000 || vin.Length == 0 || vout.Length == 0)
182 // Check for empty or overflow output values
184 for (int i = 0; i < vout.Length; i++)
186 CTxOut txout = vout[i];
187 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
189 // Empty outputs aren't allowed for user transactions.
193 nValueOut += txout.nValue;
194 if (!MoneyRange(nValueOut))
200 // Check for duplicate inputs
201 var InOutPoints = new List<COutPoint>();
202 foreach (var txin in vin)
204 if (InOutPoints.IndexOf(txin.prevout) != -1)
209 InOutPoints.Add(txin.prevout);
214 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
216 // Script size is invalid
222 foreach (var txin in vin)
224 if (txin.prevout.IsNull)
226 // Null input in non-coinbase transaction.
235 public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
237 // Time based nLockTime
242 if (nBlockHeight == 0)
244 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
248 nBlockTime = NetUtils.GetAdjustedTime();
250 if (nLockTime < (nLockTime < NetUtils.nLockTimeThreshold ? nBlockHeight : nBlockTime))
254 foreach (var txin in vin)
265 /// Parse byte sequence and initialize new instance of CTransaction
267 /// <param name="txBytes">Byte sequence</param>
268 public CTransaction(byte[] txBytes)
272 var stream = new MemoryStream(txBytes);
273 var reader = new BinaryReader(stream);
275 nVersion = reader.ReadUInt32();
276 nTime = reader.ReadUInt32();
278 int nInputs = (int)VarInt.ReadVarInt(ref reader);
279 vin = new CTxIn[nInputs];
281 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
284 vin[nCurrentInput] = new CTxIn();
286 vin[nCurrentInput].prevout = new COutPoint(reader.ReadBytes(36));
288 int nScriptSigLen = (int)VarInt.ReadVarInt(ref reader);
289 vin[nCurrentInput].scriptSig = new CScript(reader.ReadBytes(nScriptSigLen));
291 vin[nCurrentInput].nSequence = reader.ReadUInt32();
294 int nOutputs = (int)VarInt.ReadVarInt(ref reader);
295 vout = new CTxOut[nOutputs];
297 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
299 // Fill outputs array
300 vout[nCurrentOutput] = new CTxOut();
301 vout[nCurrentOutput].nValue = reader.ReadUInt64();
303 int nScriptPKLen = (int)VarInt.ReadVarInt(ref reader);
304 vout[nCurrentOutput].scriptPubKey = new CScript(reader.ReadBytes(nScriptPKLen));
307 nLockTime = reader.ReadUInt32();
311 throw new TransactionConstructorException("Deserialization failed", e);
322 int nSize = 12; // nVersion, nTime, nLockLime
324 nSize += VarInt.GetEncodedSize(vin.Length);
325 nSize += VarInt.GetEncodedSize(vout.Length);
327 foreach (var input in vin)
332 foreach (var output in vout)
334 nSize += output.Size;
342 /// Read transactions array which is encoded in the block body.
344 /// <param name="wTxBytes">Bytes sequence</param>
345 /// <returns>Transactions array</returns>
346 internal static CTransaction[] ReadTransactionsList(ref BinaryReader reader)
350 // Read amount of transactions
351 int nTransactions = (int)VarInt.ReadVarInt(ref reader);
352 var tx = new CTransaction[nTransactions];
354 for (int nTx = 0; nTx < nTransactions; nTx++)
356 // Fill the transactions array
357 tx[nTx] = new CTransaction();
359 tx[nTx].nVersion = reader.ReadUInt32();
360 tx[nTx].nTime = reader.ReadUInt32();
363 tx[nTx].vin = CTxIn.ReadTxInList(ref reader);
366 tx[nTx].vout = CTxOut.ReadTxOutList(ref reader);
368 tx[nTx].nLockTime = reader.ReadUInt32();
376 throw new TransactionConstructorException("Deserialization failed", e);
380 public bool IsCoinBase
382 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
385 public bool IsCoinStake
389 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
398 get { return Hash256.Compute256(this); }
402 /// A sequence of bytes, which corresponds to the current state of CTransaction.
404 public static implicit operator byte[] (CTransaction tx)
406 var stream = new MemoryStream();
407 var writer = new BinaryWriter(stream);
409 writer.Write(tx.nVersion);
410 writer.Write(tx.nTime);
411 writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
413 foreach (var input in tx.vin)
418 writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
420 foreach (var output in tx.vout)
422 writer.Write(output);
425 writer.Write(tx.nLockTime);
426 var resultBytes = stream.ToArray();
434 public override string ToString()
436 var sb = new StringBuilder();
438 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
440 foreach (var txin in vin)
442 sb.AppendFormat(" {0},\n", txin.ToString());
445 foreach (var txout in vout)
447 sb.AppendFormat(" {0},\n", txout.ToString());
450 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
452 return sb.ToString();
455 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }