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.
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 /// Maximum transaction size is 250Kb
61 public const uint nMaxTxSize = 250000;
64 /// Version of transaction schema.
69 /// Transaction timestamp.
74 /// Array of transaction inputs
79 /// Array of transaction outputs
84 /// Block height or timestamp when transaction is final
86 public uint nLockTime;
89 /// Initialize an empty instance
93 // Initialize empty input and output arrays. Please note that such
94 // configuration is not valid for real transaction, you have to supply
95 // at least one input and one output.
104 /// Initialize new instance as a copy of another transaction
106 /// <param name="tx">Transaction to copy from</param>
107 public CTransaction(CTransaction tx)
109 nVersion = tx.nVersion;
112 vin = new CTxIn[tx.vin.Length];
114 for (int i = 0; i < vin.Length; i++)
116 vin[i] = new CTxIn(tx.vin[i]);
119 vout = new CTxOut[tx.vout.Length];
121 for (int i = 0; i < vout.Length; i++)
123 vout[i] = new CTxOut(tx.vout[i]);
126 nLockTime = tx.nLockTime;
130 /// Attempts to execute all transaction scripts and validate the results.
132 /// <returns>Checking result.</returns>
133 public bool VerifyScripts()
140 CTransaction txPrev = null;
141 for (int i = 0; i < vin.Length; i++)
143 var outpoint = vin[i].prevout;
145 if (!CBlockStore.Instance.GetTransaction(outpoint.hash, ref txPrev))
148 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txPrev.vout[outpoint.n].scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
156 /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
158 public uint LegacySigOpCount
163 foreach (var txin in vin)
165 nSigOps += txin.scriptSig.GetSigOpCount(false);
167 foreach (var txout in vout)
169 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
177 /// Basic sanity checkings
179 /// <returns>Checking result</returns>
180 public bool CheckTransaction()
182 if (Size > nMaxTxSize || vin.Length == 0 || vout.Length == 0)
187 // Check for empty or overflow output values
189 for (int i = 0; i < vout.Length; i++)
191 CTxOut txout = vout[i];
192 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
194 // Empty outputs aren't allowed for user transactions.
198 nValueOut += txout.nValue;
199 if (!MoneyRange(nValueOut))
205 // Check for duplicate inputs
206 var InOutPoints = new List<COutPoint>();
207 foreach (var txin in vin)
209 if (InOutPoints.IndexOf(txin.prevout) != -1)
214 InOutPoints.Add(txin.prevout);
219 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
221 // Script size is invalid
227 foreach (var txin in vin)
229 if (txin.prevout.IsNull)
231 // Null input in non-coinbase transaction.
240 public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
242 // Time based nLockTime
247 if (nBlockHeight == 0)
249 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
253 nBlockTime = NetUtils.GetAdjustedTime();
255 if (nLockTime < (nLockTime < NetUtils.nLockTimeThreshold ? nBlockHeight : nBlockTime))
259 foreach (var txin in vin)
270 /// Parse byte sequence and initialize new instance of CTransaction
272 /// <param name="txBytes">Byte sequence</param>
273 public CTransaction(byte[] txBytes)
277 var stream = new MemoryStream(txBytes);
278 var reader = new BinaryReader(stream);
280 nVersion = reader.ReadUInt32();
281 nTime = reader.ReadUInt32();
283 int nInputs = (int)VarInt.ReadVarInt(ref reader);
284 vin = new CTxIn[nInputs];
286 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
289 vin[nCurrentInput] = new CTxIn();
291 vin[nCurrentInput].prevout = new COutPoint(reader.ReadBytes(36));
293 int nScriptSigLen = (int)VarInt.ReadVarInt(ref reader);
294 vin[nCurrentInput].scriptSig = new CScript(reader.ReadBytes(nScriptSigLen));
296 vin[nCurrentInput].nSequence = reader.ReadUInt32();
299 int nOutputs = (int)VarInt.ReadVarInt(ref reader);
300 vout = new CTxOut[nOutputs];
302 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
304 // Fill outputs array
305 vout[nCurrentOutput] = new CTxOut();
306 vout[nCurrentOutput].nValue = reader.ReadUInt64();
308 int nScriptPKLen = (int)VarInt.ReadVarInt(ref reader);
309 vout[nCurrentOutput].scriptPubKey = new CScript(reader.ReadBytes(nScriptPKLen));
312 nLockTime = reader.ReadUInt32();
316 throw new TransactionConstructorException("Deserialization failed", e);
327 int nSize = 12; // nVersion, nTime, nLockLime
329 nSize += VarInt.GetEncodedSize(vin.Length);
330 nSize += VarInt.GetEncodedSize(vout.Length);
332 foreach (var input in vin)
337 foreach (var output in vout)
339 nSize += output.Size;
347 /// Read transactions array which is encoded in the block body.
349 /// <param name="wTxBytes">Bytes sequence</param>
350 /// <returns>Transactions array</returns>
351 internal static CTransaction[] ReadTransactionsList(ref BinaryReader reader)
355 // Read amount of transactions
356 int nTransactions = (int)VarInt.ReadVarInt(ref reader);
357 var tx = new CTransaction[nTransactions];
359 for (int nTx = 0; nTx < nTransactions; nTx++)
361 // Fill the transactions array
362 tx[nTx] = new CTransaction();
364 tx[nTx].nVersion = reader.ReadUInt32();
365 tx[nTx].nTime = reader.ReadUInt32();
368 tx[nTx].vin = CTxIn.ReadTxInList(ref reader);
371 tx[nTx].vout = CTxOut.ReadTxOutList(ref reader);
373 tx[nTx].nLockTime = reader.ReadUInt32();
381 throw new TransactionConstructorException("Deserialization failed", e);
385 public bool IsCoinBase
387 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
390 public bool IsCoinStake
394 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
403 get { return CryptoUtils.ComputeHash256(this); }
407 /// A sequence of bytes, which corresponds to the current state of CTransaction.
409 public static implicit operator byte[] (CTransaction tx)
411 var stream = new MemoryStream();
412 var writer = new BinaryWriter(stream);
414 writer.Write(tx.nVersion);
415 writer.Write(tx.nTime);
416 writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
418 foreach (var input in tx.vin)
423 writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
425 foreach (var output in tx.vout)
427 writer.Write(output);
430 writer.Write(tx.nLockTime);
431 var resultBytes = stream.ToArray();
437 public override string ToString()
439 var sb = new StringBuilder();
441 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
443 foreach (var txin in vin)
445 sb.AppendFormat(" {0},\n", txin);
448 foreach (var txout in vout)
450 sb.AppendFormat(" {0},\n", txout);
453 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
455 return sb.ToString();
458 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }