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;
23 using System.Diagnostics.Contracts;
24 using System.Numerics;
29 public class TransactionConstructorException : Exception
31 public TransactionConstructorException()
35 public TransactionConstructorException(string message)
40 public TransactionConstructorException(string message, Exception inner)
41 : base(message, inner)
47 /// Represents the transaction.
49 public class CTransaction
52 /// One cent = 10000 satoshis.
54 public const ulong nCent = 10000;
57 /// One coin = 1000000 satoshis.
59 public const ulong nCoin = 1000000;
61 /// Sanity checking threshold.
63 public const ulong nMaxMoney = 2000000000 * nCoin;
66 /// Maximum transaction size is 250Kb
68 public const uint nMaxTxSize = 250000;
71 /// Version of transaction schema.
76 /// Transaction timestamp.
81 /// Array of transaction inputs
86 /// Array of transaction outputs
91 /// Block height or timestamp when transaction is final
93 public uint nLockTime;
96 /// Initialize an empty instance
100 // Initialize empty input and output arrays. Please note that such
101 // configuration is not valid for real transaction, you have to supply
102 // at least one input and one output.
106 vout = new CTxOut[0];
111 /// Initialize new instance as a copy of another transaction
113 /// <param name="tx">Transaction to copy from</param>
114 public CTransaction(CTransaction tx)
116 nVersion = tx.nVersion;
119 vin = new CTxIn[tx.vin.Length];
121 for (int i = 0; i < vin.Length; i++)
123 vin[i] = new CTxIn(tx.vin[i]);
126 vout = new CTxOut[tx.vout.Length];
128 for (int i = 0; i < vout.Length; i++)
130 vout[i] = new CTxOut(tx.vout[i]);
133 nLockTime = tx.nLockTime;
137 /// Attempts to execute all transaction scripts and validate the results.
139 /// <returns>Checking result.</returns>
140 public bool VerifyScripts()
147 TxOutItem txOutCursor = null;
148 for (int i = 0; i < vin.Length; i++)
150 var outpoint = vin[i].prevout;
152 if (!CBlockStore.Instance.GetTxOutCursor(outpoint, ref txOutCursor))
155 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txOutCursor.scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
163 /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
165 public uint LegacySigOpCount
170 foreach (var txin in vin)
172 nSigOps += txin.scriptSig.GetSigOpCount(false);
174 foreach (var txout in vout)
176 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
184 /// Basic sanity checkings
186 /// <returns>Checking result</returns>
187 public bool CheckTransaction()
189 if (Size > nMaxTxSize || vin.Length == 0 || vout.Length == 0)
194 // Check for empty or overflow output values
196 for (int i = 0; i < vout.Length; i++)
198 CTxOut txout = vout[i];
199 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
201 // Empty outputs aren't allowed for user transactions.
205 nValueOut += txout.nValue;
206 if (!MoneyRange(nValueOut))
212 // Check for duplicate inputs
213 var InOutPoints = new List<COutPoint>();
214 foreach (var txin in vin)
216 if (InOutPoints.IndexOf(txin.prevout) != -1)
221 InOutPoints.Add(txin.prevout);
226 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
228 // Script size is invalid
234 foreach (var txin in vin)
236 if (txin.prevout.IsNull)
238 // Null input in non-coinbase transaction.
247 public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
249 // Time based nLockTime
254 if (nBlockHeight == 0)
256 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
260 nBlockTime = NetInfo.GetAdjustedTime();
262 if (nLockTime < (nLockTime < NetInfo.nLockTimeThreshold ? nBlockHeight : nBlockTime))
266 foreach (var txin in vin)
277 /// Parse byte sequence and initialize new instance of CTransaction
279 /// <param name="txBytes">Byte sequence</param>
280 public CTransaction(byte[] txBytes)
284 var stream = new MemoryStream(txBytes);
285 var reader = new BinaryReader(stream);
287 nVersion = reader.ReadUInt32();
288 nTime = reader.ReadUInt32();
290 int nInputs = (int)VarInt.ReadVarInt(ref reader);
291 vin = new CTxIn[nInputs];
293 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
296 vin[nCurrentInput] = new CTxIn();
298 vin[nCurrentInput].prevout = new COutPoint(reader.ReadBytes(36));
300 int nScriptSigLen = (int)VarInt.ReadVarInt(ref reader);
301 vin[nCurrentInput].scriptSig = new CScript(reader.ReadBytes(nScriptSigLen));
303 vin[nCurrentInput].nSequence = reader.ReadUInt32();
306 int nOutputs = (int)VarInt.ReadVarInt(ref reader);
307 vout = new CTxOut[nOutputs];
309 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
311 // Fill outputs array
312 vout[nCurrentOutput] = new CTxOut();
313 vout[nCurrentOutput].nValue = reader.ReadUInt64();
315 int nScriptPKLen = (int)VarInt.ReadVarInt(ref reader);
316 vout[nCurrentOutput].scriptPubKey = new CScript(reader.ReadBytes(nScriptPKLen));
319 nLockTime = reader.ReadUInt32();
323 throw new TransactionConstructorException("Deserialization failed", e);
334 int nSize = 12; // nVersion, nTime, nLockLime
336 nSize += VarInt.GetEncodedSize(vin.Length);
337 nSize += VarInt.GetEncodedSize(vout.Length);
339 foreach (var input in vin)
344 foreach (var output in vout)
346 nSize += output.Size;
354 /// Read transactions array which is encoded in the block body.
356 /// <param name="wTxBytes">Bytes sequence</param>
357 /// <returns>Transactions array</returns>
358 internal static CTransaction[] ReadTransactionsList(ref BinaryReader reader)
362 // Read amount of transactions
363 int nTransactions = (int)VarInt.ReadVarInt(ref reader);
364 var tx = new CTransaction[nTransactions];
366 for (int nTx = 0; nTx < nTransactions; nTx++)
368 // Fill the transactions array
369 tx[nTx] = new CTransaction();
371 tx[nTx].nVersion = reader.ReadUInt32();
372 tx[nTx].nTime = reader.ReadUInt32();
375 tx[nTx].vin = CTxIn.ReadTxInList(ref reader);
378 tx[nTx].vout = CTxOut.ReadTxOutList(ref reader);
380 tx[nTx].nLockTime = reader.ReadUInt32();
388 throw new TransactionConstructorException("Deserialization failed", e);
392 public bool IsCoinBase
394 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
397 public bool IsCoinStake
401 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
410 get { return CryptoUtils.ComputeHash256(this); }
414 /// Amount of novacoins spent by this transaction.
416 public ulong nValueOut
421 foreach (var txout in vout)
423 nValueOut += txout.nValue;
424 Contract.Assert(MoneyRange(txout.nValue) && MoneyRange(nValueOut));
431 /// A sequence of bytes, which corresponds to the current state of CTransaction.
433 public static implicit operator byte[] (CTransaction tx)
435 var stream = new MemoryStream();
436 var writer = new BinaryWriter(stream);
438 writer.Write(tx.nVersion);
439 writer.Write(tx.nTime);
440 writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
442 foreach (var input in tx.vin)
447 writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
449 foreach (var output in tx.vout)
451 writer.Write(output);
454 writer.Write(tx.nLockTime);
455 var resultBytes = stream.ToArray();
461 public override string ToString()
463 var sb = new StringBuilder();
465 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
467 foreach (var txin in vin)
469 sb.AppendFormat(" {0},\n", txin);
472 foreach (var txout in vout)
474 sb.AppendFormat(" {0},\n", txout);
477 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
479 return sb.ToString();
482 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }
484 internal uint GetP2SHSigOpCount(Dictionary<COutPoint, TxOutItem> inputs)
486 throw new NotImplementedException();
489 internal ulong GetValueIn(Dictionary<COutPoint, TxOutItem> inputs)
491 throw new NotImplementedException();