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;
26 public class TransactionConstructorException : Exception
28 public TransactionConstructorException()
32 public TransactionConstructorException(string message)
37 public TransactionConstructorException(string message, Exception inner)
38 : base(message, inner)
44 /// Represents the transaction. Any transaction must provide one input and one output at least.
46 public class CTransaction
49 /// One coin = 1000000 satoshis.
51 public const ulong nCoin = 1000000;
53 /// Sanity checking threshold.
55 public const ulong nMaxMoney = 2000000000 * nCoin;
58 /// Version of transaction schema.
63 /// Transaction timestamp.
68 /// Array of transaction inputs
73 /// Array of transaction outputs
78 /// Block height or timestamp when transaction is final
80 public uint nLockTime;
83 /// Initialize an empty instance
87 // Initialize empty input and output arrays. Please note that such
88 // configuration is not valid for real transaction, you have to supply
89 // at least one input and one output.
98 /// Initialize new instance as a copy of another transaction
100 /// <param name="tx">Transaction to copy from</param>
101 public CTransaction(CTransaction tx)
103 nVersion = tx.nVersion;
106 vin = new CTxIn[tx.vin.Length];
108 for (int i = 0; i < vin.Length; i++)
110 vin[i] = new CTxIn(tx.vin[i]);
113 vout = new CTxOut[tx.vout.Length];
115 for (int i = 0; i < vout.Length; i++)
117 vout[i] = new CTxOut(tx.vout[i]);
120 nLockTime = tx.nLockTime;
124 /// Attempts to execute all transaction scripts and validate the results.
126 /// <returns>Checking result.</returns>
127 public bool VerifyScripts()
134 CTransaction txPrev = null;
135 for (int i = 0; i < vin.Length; i++)
137 var outpoint = vin[i].prevout;
139 if (!CBlockStore.Instance.GetTransaction(outpoint.hash, ref txPrev))
142 if (!ScriptCode.VerifyScript(vin[i].scriptSig, txPrev.vout[outpoint.n].scriptPubKey, this, i, (int)scriptflag.SCRIPT_VERIFY_P2SH, 0))
150 /// Calculate amount of signature operations without trying to properly evaluate P2SH scripts.
152 public uint LegacySigOpCount
157 foreach (var txin in vin)
159 nSigOps += txin.scriptSig.GetSigOpCount(false);
161 foreach (var txout in vout)
163 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
171 /// Basic sanity checkings
173 /// <returns>Checking result</returns>
174 public bool CheckTransaction()
176 if (Size > 250000 || vin.Length == 0 || vout.Length == 0)
181 // Check for empty or overflow output values
183 for (int i = 0; i < vout.Length; i++)
185 CTxOut txout = vout[i];
186 if (txout.IsEmpty && !IsCoinBase && !IsCoinStake)
188 // Empty outputs aren't allowed for user transactions.
192 nValueOut += txout.nValue;
193 if (!MoneyRange(nValueOut))
199 // Check for duplicate inputs
200 var InOutPoints = new List<COutPoint>();
201 foreach (var txin in vin)
203 if (InOutPoints.IndexOf(txin.prevout) != -1)
208 InOutPoints.Add(txin.prevout);
213 if (vin[0].scriptSig.Size < 2 || vin[0].scriptSig.Size > 100)
215 // Script size is invalid
221 foreach (var txin in vin)
223 if (txin.prevout.IsNull)
225 // Null input in non-coinbase transaction.
234 public bool IsFinal(uint nBlockHeight = 0, uint nBlockTime = 0)
236 // Time based nLockTime
241 if (nBlockHeight == 0)
243 nBlockHeight = uint.MaxValue; // TODO: stupid stub here, should be best height instead.
247 nBlockTime = NetInfo.GetAdjustedTime();
249 if (nLockTime < (nLockTime < NetInfo.nLockTimeThreshold ? nBlockHeight : nBlockTime))
253 foreach (var txin in vin)
264 /// Parse byte sequence and initialize new instance of CTransaction
266 /// <param name="txBytes">Byte sequence</param>
267 public CTransaction(byte[] txBytes)
271 var wBytes = new ByteQueue(txBytes);
273 nVersion = BitConverter.ToUInt32(wBytes.Get(4), 0);
274 nTime = BitConverter.ToUInt32(wBytes.Get(4), 0);
276 int nInputs = (int)wBytes.GetVarInt();
277 vin = new CTxIn[nInputs];
279 for (int nCurrentInput = 0; nCurrentInput < nInputs; nCurrentInput++)
282 vin[nCurrentInput] = new CTxIn();
284 vin[nCurrentInput].prevout = new COutPoint(wBytes.Get(36));
286 int nScriptSigLen = (int)wBytes.GetVarInt();
287 vin[nCurrentInput].scriptSig = new CScript(wBytes.Get(nScriptSigLen));
289 vin[nCurrentInput].nSequence = BitConverter.ToUInt32(wBytes.Get(4), 0);
292 int nOutputs = (int)wBytes.GetVarInt();
293 vout = new CTxOut[nOutputs];
295 for (int nCurrentOutput = 0; nCurrentOutput < nOutputs; nCurrentOutput++)
297 // Fill outputs array
298 vout[nCurrentOutput] = new CTxOut();
299 vout[nCurrentOutput].nValue = BitConverter.ToUInt64(wBytes.Get(8), 0);
301 int nScriptPKLen = (int)wBytes.GetVarInt();
302 vout[nCurrentOutput].scriptPubKey = new CScript(wBytes.Get(nScriptPKLen));
305 nLockTime = BitConverter.ToUInt32(wBytes.Get(4), 0);
309 throw new TransactionConstructorException("Deserialization failed", e);
320 int nSize = 12; // nVersion, nTime, nLockLime
322 nSize += VarInt.GetEncodedSize(vin.Length);
323 nSize += VarInt.GetEncodedSize(vout.Length);
325 foreach (var input in vin)
330 foreach (var output in vout)
332 nSize += output.Size;
340 /// Read transactions array which is encoded in the block body.
342 /// <param name="wTxBytes">Bytes sequence</param>
343 /// <returns>Transactions array</returns>
344 public static CTransaction[] ReadTransactionsList(ref ByteQueue wTxBytes)
348 // Read amount of transactions
349 int nTransactions = (int)wTxBytes.GetVarInt();
350 var tx = new CTransaction[nTransactions];
352 for (int nTx = 0; nTx < nTransactions; nTx++)
354 // Fill the transactions array
355 tx[nTx] = new CTransaction();
357 tx[nTx].nVersion = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
358 tx[nTx].nTime = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
361 tx[nTx].vin = CTxIn.ReadTxInList(ref wTxBytes);
364 tx[nTx].vout = CTxOut.ReadTxOutList(ref wTxBytes);
366 tx[nTx].nLockTime = BitConverter.ToUInt32(wTxBytes.Get(4), 0);
374 throw new TransactionConstructorException("Deserialization failed", e);
378 public bool IsCoinBase
380 get { return (vin.Length == 1 && vin[0].prevout.IsNull && vout.Length >= 1); }
383 public bool IsCoinStake
387 return (vin.Length > 0 && (!vin[0].prevout.IsNull) && vout.Length >= 2 && vout[0].IsEmpty);
396 get { return Hash256.Compute256(this); }
400 /// A sequence of bytes, which corresponds to the current state of CTransaction.
402 public static implicit operator byte[] (CTransaction tx)
404 var resultBytes = new List<byte>();
406 resultBytes.AddRange(BitConverter.GetBytes(tx.nVersion));
407 resultBytes.AddRange(BitConverter.GetBytes(tx.nTime));
408 resultBytes.AddRange(VarInt.EncodeVarInt(tx.vin.LongLength));
410 foreach (var input in tx.vin)
412 resultBytes.AddRange((byte[])input);
415 resultBytes.AddRange(VarInt.EncodeVarInt(tx.vout.LongLength));
417 foreach (var output in tx.vout)
419 resultBytes.AddRange((byte[])output);
422 resultBytes.AddRange(BitConverter.GetBytes(tx.nLockTime));
424 return resultBytes.ToArray();
427 public override string ToString()
429 var sb = new StringBuilder();
431 sb.AppendFormat("CTransaction(\n nVersion={0},\n nTime={1},\n", nVersion, nTime);
433 foreach (var txin in vin)
435 sb.AppendFormat(" {0},\n", txin.ToString());
438 foreach (var txout in vout)
440 sb.AppendFormat(" {0},\n", txout.ToString());
443 sb.AppendFormat("\nnLockTime={0}\n)", nLockTime);
445 return sb.ToString();
448 public static bool MoneyRange(ulong nValue) { return (nValue <= nMaxMoney); }