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 wBytes = new ByteQueue(ref txBytes);
274 nVersion = BitConverter.ToUInt32(wBytes.Get(4), 0);
275 nTime = BitConverter.ToUInt32(wBytes.Get(4), 0);
277 int nInputs = (int)wBytes.GetVarInt();
278 vin = new CTxIn[nInputs];
280 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
283 vin[nCurrentInput] = new CTxIn();
285 vin[nCurrentInput].prevout = new COutPoint(wBytes.Get(36));
287 int nScriptSigLen = (int)wBytes.GetVarInt();
288 vin[nCurrentInput].scriptSig = new CScript(wBytes.Get(nScriptSigLen));
290 vin[nCurrentInput].nSequence = BitConverter.ToUInt32(wBytes.Get(4), 0);
293 int nOutputs = (int)wBytes.GetVarInt();
294 vout = new CTxOut[nOutputs];
296 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
298 // Fill outputs array
299 vout[nCurrentOutput] = new CTxOut();
300 vout[nCurrentOutput].nValue = BitConverter.ToUInt64(wBytes.Get(8), 0);
302 int nScriptPKLen = (int)wBytes.GetVarInt();
303 vout[nCurrentOutput].scriptPubKey = new CScript(wBytes.Get(nScriptPKLen));
306 nLockTime = BitConverter.ToUInt32(wBytes.Get(4), 0);
310 throw new TransactionConstructorException("Deserialization failed", e);
321 int nSize = 12; // nVersion, nTime, nLockLime
323 nSize += VarInt.GetEncodedSize(vin.Length);
324 nSize += VarInt.GetEncodedSize(vout.Length);
326 foreach (var input in vin)
331 foreach (var output in vout)
333 nSize += output.Size;
341 /// Read transactions array which is encoded in the block body.
343 /// <param name="wTxBytes">Bytes sequence</param>
344 /// <returns>Transactions array</returns>
345 public static CTransaction[] ReadTransactionsList(ref ByteQueue wTxBytes)
349 // Read amount of transactions
350 int nTransactions = (int)wTxBytes.GetVarInt();
351 var tx = new CTransaction[nTransactions];
353 for (int nTx = 0; nTx < nTransactions; nTx++)
355 // Fill the transactions array
356 tx[nTx] = new CTransaction();
358 tx[nTx].nVersion = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
359 tx[nTx].nTime = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
362 tx[nTx].vin = CTxIn.ReadTxInList(ref wTxBytes);
365 tx[nTx].vout = CTxOut.ReadTxOutList(ref wTxBytes);
367 tx[nTx].nLockTime = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
375 throw new TransactionConstructorException("Deserialization failed", e);
379 public bool IsCoinBase
381 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
384 public bool IsCoinStake
388 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
397 get { return Hash256.Compute256(this); }
401 /// A sequence of bytes, which corresponds to the current state of CTransaction.
403 public static implicit operator byte[] (CTransaction tx)
405 var stream = new MemoryStream();
406 var writer = new BinaryWriter(stream);
408 writer.Write(tx.nVersion);
409 writer.Write(tx.nTime);
410 writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
412 foreach (var input in tx.vin)
417 writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
419 foreach (var output in tx.vout)
421 writer.Write(output);
424 writer.Write(tx.nLockTime);
426 var resultBytes = stream.ToArray();
435 public override string ToString()
437 var sb = new StringBuilder();
439 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
441 foreach (var txin in vin)
443 sb.AppendFormat(" {0},\n", txin.ToString());
446 foreach (var txout in vout)
448 sb.AppendFormat(" {0},\n", txout.ToString());
451 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
453 return sb.ToString();
456 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }