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;
28 public class TransactionConstructorException : Exception
30 public TransactionConstructorException()
34 public TransactionConstructorException(string message)
39 public TransactionConstructorException(string message, Exception inner)
40 : base(message, inner)
46 /// Represents the transaction.
48 public class CTransaction
51 /// One coin = 1000000 satoshis.
53 public const ulong nCoin = 1000000;
55 /// Sanity checking threshold.
57 public const ulong nMaxMoney = 2000000000 * nCoin;
60 /// Maximum transaction size is 250Kb
62 public const uint nMaxTxSize = 250000;
65 /// Version of transaction schema.
70 /// Transaction timestamp.
75 /// Array of transaction inputs
80 /// Array of transaction outputs
85 /// Block height or timestamp when transaction is final
87 public uint nLockTime;
90 /// Initialize an empty instance
94 // Initialize empty input and output arrays. Please note that such
95 // configuration is not valid for real transaction, you have to supply
96 // at least one input and one output.
100 vout = new CTxOut[0];
105 /// Initialize new instance as a copy of another transaction
107 /// <param name="tx">Transaction to copy from</param>
108 public CTransaction(CTransaction tx)
110 nVersion = tx.nVersion;
113 vin = new CTxIn[tx.vin.Length];
115 for (int i = 0; i < vin.Length; i++)
117 vin[i] = new CTxIn(tx.vin[i]);
120 vout = new CTxOut[tx.vout.Length];
122 for (int i = 0; i < vout.Length; i++)
124 vout[i] = new CTxOut(tx.vout[i]);
127 nLockTime = tx.nLockTime;
131 /// Attempts to execute all transaction scripts and validate the results.
133 /// <returns>Checking result.</returns>
134 public bool VerifyScripts()
141 CTransaction txPrev = null;
142 for (int i = 0; i < vin.Length; i++)
144 var outpoint = vin[i].prevout;
146 if (!CBlockStore.Instance.GetTransaction(outpoint.hash, ref txPrev))
149 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txPrev.vout[outpoint.n].scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
157 /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
159 public uint LegacySigOpCount
164 foreach (var txin in vin)
166 nSigOps += txin.scriptSig.GetSigOpCount(false);
168 foreach (var txout in vout)
170 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
178 /// Basic sanity checkings
180 /// <returns>Checking result</returns>
181 public bool CheckTransaction()
183 if (Size > nMaxTxSize || vin.Length == 0 || vout.Length == 0)
188 // Check for empty or overflow output values
190 for (int i = 0; i < vout.Length; i++)
192 CTxOut txout = vout[i];
193 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
195 // Empty outputs aren't allowed for user transactions.
199 nValueOut += txout.nValue;
200 if (!MoneyRange(nValueOut))
206 // Check for duplicate inputs
207 var InOutPoints = new List<COutPoint>();
208 foreach (var txin in vin)
210 if (InOutPoints.IndexOf(txin.prevout) != -1)
215 InOutPoints.Add(txin.prevout);
220 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
222 // Script size is invalid
228 foreach (var txin in vin)
230 if (txin.prevout.IsNull)
232 // Null input in non-coinbase transaction.
241 public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
243 // Time based nLockTime
248 if (nBlockHeight == 0)
250 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
254 nBlockTime = NetUtils.GetAdjustedTime();
256 if (nLockTime < (nLockTime < NetUtils.nLockTimeThreshold ? nBlockHeight : nBlockTime))
260 foreach (var txin in vin)
271 /// Parse byte sequence and initialize new instance of CTransaction
273 /// <param name="txBytes">Byte sequence</param>
274 public CTransaction(byte[] txBytes)
278 var stream = new MemoryStream(txBytes);
279 var reader = new BinaryReader(stream);
281 nVersion = reader.ReadUInt32();
282 nTime = reader.ReadUInt32();
284 int nInputs = (int)VarInt.ReadVarInt(ref reader);
285 vin = new CTxIn[nInputs];
287 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
290 vin[nCurrentInput] = new CTxIn();
292 vin[nCurrentInput].prevout = new COutPoint(reader.ReadBytes(36));
294 int nScriptSigLen = (int)VarInt.ReadVarInt(ref reader);
295 vin[nCurrentInput].scriptSig = new CScript(reader.ReadBytes(nScriptSigLen));
297 vin[nCurrentInput].nSequence = reader.ReadUInt32();
300 int nOutputs = (int)VarInt.ReadVarInt(ref reader);
301 vout = new CTxOut[nOutputs];
303 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
305 // Fill outputs array
306 vout[nCurrentOutput] = new CTxOut();
307 vout[nCurrentOutput].nValue = reader.ReadUInt64();
309 int nScriptPKLen = (int)VarInt.ReadVarInt(ref reader);
310 vout[nCurrentOutput].scriptPubKey = new CScript(reader.ReadBytes(nScriptPKLen));
313 nLockTime = reader.ReadUInt32();
317 throw new TransactionConstructorException("Deserialization failed", e);
328 int nSize = 12; // nVersion, nTime, nLockLime
330 nSize += VarInt.GetEncodedSize(vin.Length);
331 nSize += VarInt.GetEncodedSize(vout.Length);
333 foreach (var input in vin)
338 foreach (var output in vout)
340 nSize += output.Size;
348 /// Read transactions array which is encoded in the block body.
350 /// <param name="wTxBytes">Bytes sequence</param>
351 /// <returns>Transactions array</returns>
352 internal static CTransaction[] ReadTransactionsList(ref BinaryReader reader)
356 // Read amount of transactions
357 int nTransactions = (int)VarInt.ReadVarInt(ref reader);
358 var tx = new CTransaction[nTransactions];
360 for (int nTx = 0; nTx < nTransactions; nTx++)
362 // Fill the transactions array
363 tx[nTx] = new CTransaction();
365 tx[nTx].nVersion = reader.ReadUInt32();
366 tx[nTx].nTime = reader.ReadUInt32();
369 tx[nTx].vin = CTxIn.ReadTxInList(ref reader);
372 tx[nTx].vout = CTxOut.ReadTxOutList(ref reader);
374 tx[nTx].nLockTime = reader.ReadUInt32();
382 throw new TransactionConstructorException("Deserialization failed", e);
386 public bool IsCoinBase
388 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
391 public bool IsCoinStake
395 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
404 get { return CryptoUtils.ComputeHash256(this); }
408 /// Amount of novacoins spent by this transaction.
410 public ulong ValueOut
415 foreach (var txout in vout)
417 nValueOut += txout.nValue;
418 Contract.Assert(MoneyRange(txout.nValue) && MoneyRange(nValueOut));
425 /// A sequence of bytes, which corresponds to the current state of CTransaction.
427 public static implicit operator byte[] (CTransaction tx)
429 var stream = new MemoryStream();
430 var writer = new BinaryWriter(stream);
432 writer.Write(tx.nVersion);
433 writer.Write(tx.nTime);
434 writer.Write(VarInt.EncodeVarInt(tx.vin.LongLength));
436 foreach (var input in tx.vin)
441 writer.Write(VarInt.EncodeVarInt(tx.vout.LongLength));
443 foreach (var output in tx.vout)
445 writer.Write(output);
448 writer.Write(tx.nLockTime);
449 var resultBytes = stream.ToArray();
455 public override string ToString()
457 var sb = new StringBuilder();
459 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
461 foreach (var txin in vin)
463 sb.AppendFormat(" {0},\n", txin);
466 foreach (var txout in vout)
468 sb.AppendFormat(" {0},\n", txout);
471 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
473 return sb.ToString();
476 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }