PageRenderTime 148ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/coin/Transaction.cpp

https://github.com/libcoin/libcoin
C++ | 415 lines | 277 code | 63 blank | 75 comment | 96 complexity | d90eeedb5424af7ef6b15e3c6d0949e4 MD5 | raw file
  1. /* -*-c++-*- libcoin - Copyright (C) 2012 Michael Gronager
  2. *
  3. * libcoin is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * any later version.
  7. *
  8. * libcoin is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with libcoin. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <coin/util.h>
  17. #include <coin/Transaction.h>
  18. //#include <coin/KeyStore.h>
  19. #include <coin/ExtendedKey.h>
  20. using namespace std;
  21. using namespace boost;
  22. //////////////////////////////////////////////////////////////////////////////
  23. //
  24. // Transaction
  25. //
  26. bool Transaction::isNewerThan(const Transaction& old) const {
  27. if (_inputs.size() != old._inputs.size())
  28. return false;
  29. for (unsigned int i = 0; i < _inputs.size(); i++)
  30. if (_inputs[i].prevout() != old._inputs[i].prevout())
  31. return false;
  32. bool newer = false;
  33. unsigned int lowest = UINT_MAX;
  34. for (unsigned int i = 0; i < _inputs.size(); i++) {
  35. if (_inputs[i].sequence() != old._inputs[i].sequence()) {
  36. if (_inputs[i].sequence() <= lowest) {
  37. newer = false;
  38. lowest = _inputs[i].sequence();
  39. }
  40. if (old._inputs[i].sequence() < lowest) {
  41. newer = true;
  42. lowest = old._inputs[i].sequence();
  43. }
  44. }
  45. }
  46. return newer;
  47. }
  48. int Transaction::getSigOpCount() const {
  49. int n = 0;
  50. BOOST_FOREACH(const Input& input, _inputs)
  51. n += input.signature().getSigOpCount();
  52. BOOST_FOREACH(const Output& output, _outputs)
  53. n += output.script().getSigOpCount();
  54. return n;
  55. }
  56. int64_t Transaction::getValueOut() const
  57. {
  58. int64_t valueOut = 0;
  59. BOOST_FOREACH(const Output& output, _outputs) {
  60. valueOut += output.value();
  61. }
  62. return valueOut;
  63. }
  64. /*
  65. int64_t Transaction::paymentTo(PubKeyHash address) const {
  66. int64_t value = 0;
  67. BOOST_FOREACH(const Output& output, _outputs)
  68. {
  69. if(output.getAddress() == address)
  70. value += output.value();
  71. }
  72. return value;
  73. }
  74. bool Transaction::isSufficient(map<PubKeyHash, int64_t> payments) const {
  75. for (map<PubKeyHash, int64_t>::const_iterator payment = payments.begin(); payment != payments.end(); ++payment) {
  76. if (paymentTo(payment->first) < payment->second)
  77. return false;
  78. }
  79. return true;
  80. }
  81. */
  82. int64_t Transaction::getMinFee(unsigned int nBlockSize, bool fAllowFree, bool fForRelay) const {
  83. // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
  84. int64_t nBaseFee = fForRelay ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
  85. unsigned int nBytes = serialize_size(*this);
  86. unsigned int nNewBlockSize = nBlockSize + nBytes;
  87. int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
  88. if (fAllowFree) {
  89. if (nBlockSize == 1) {
  90. // Transactions under 10K are free
  91. // (about 4500bc if made of 50bc inputs)
  92. if (nBytes < 10000)
  93. nMinFee = 0;
  94. }
  95. else {
  96. // Free transaction area
  97. if (nNewBlockSize < 27000)
  98. nMinFee = 0;
  99. }
  100. }
  101. // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
  102. if (nMinFee < nBaseFee) {
  103. BOOST_FOREACH(const Output& output, _outputs) {
  104. if (output.value() < CENT)
  105. nMinFee = nBaseFee;
  106. }
  107. }
  108. // Raise the price as the block approaches full
  109. if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2) {
  110. if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
  111. return MAX_MONEY;
  112. nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
  113. }
  114. if (!MoneyRange(nMinFee))
  115. nMinFee = MAX_MONEY;
  116. return nMinFee;
  117. }
  118. uint256 Transaction::getSignatureHash(Script scriptCode, unsigned int n, int type) const {
  119. if (n >= _inputs.size()) {
  120. printf("ERROR: SignatureHash() : nIn=%d out of range\n", n);
  121. return uint256(1);
  122. }
  123. Transaction txn(*this);
  124. // In case concatenating two scripts ends up with two codeseparators,
  125. // or an extra one at the end, this prevents all those possible incompatibilities.
  126. scriptCode.findAndDelete(Script(OP_CODESEPARATOR));
  127. // Blank out other inputs' signatures
  128. for (unsigned int i = 0; i < txn._inputs.size(); i++)
  129. txn._inputs[i].signature(Script());
  130. txn._inputs[n].signature(scriptCode);
  131. // Blank out some of the outputs
  132. if ((type & 0x1f) == SIGHASH_NONE) {
  133. // Wildcard payee
  134. txn._outputs.clear();
  135. // Let the others update at will
  136. for (unsigned int i = 0; i < txn._inputs.size(); i++)
  137. if (i != n)
  138. txn._inputs[i].sequence(0);
  139. }
  140. else if ((type & 0x1f) == SIGHASH_SINGLE) {
  141. // Only lock-in the txout payee at same index as txin
  142. if (n >= txn._outputs.size()) {
  143. printf("ERROR: SignatureHash() : nOut=%d out of range\n", n);
  144. return uint256(1);
  145. }
  146. txn._outputs.resize(n + 1);
  147. for (unsigned int i = 0; i < n; i++)
  148. txn._outputs[i].setNull();
  149. // Let the others update at will
  150. for (unsigned int i = 0; i < txn._inputs.size(); i++)
  151. if (i != n)
  152. txn._inputs[i].sequence(0);
  153. }
  154. // Blank out other inputs completely, not recommended for open transactions
  155. if (type & SIGHASH_ANYONECANPAY) {
  156. txn._inputs[0] = txn._inputs[n];
  157. txn._inputs.resize(1);
  158. }
  159. // Serialize and hash
  160. ostringstream os;
  161. os << txn << const_binary<int>(type);
  162. string ss = os.str();
  163. return Hash(ss.begin(), ss.end());
  164. }
  165. static bool CastToBool(const valtype& vch) {
  166. for (unsigned int i = 0; i < vch.size(); i++)
  167. {
  168. if (vch[i] != 0)
  169. {
  170. // Can be negative zero
  171. if (i == vch.size()-1 && vch[i] == 0x80)
  172. return false;
  173. return true;
  174. }
  175. }
  176. return false;
  177. }
  178. bool Transaction::verify(const vector<Script>& scripts, bool strictPayToScriptHash) const {
  179. if (scripts.size() != _inputs.size())
  180. return false;
  181. for (int i = 0; i < scripts.size(); ++i) {
  182. if (!verify(i, scripts[i], 0, strictPayToScriptHash))
  183. return false;
  184. }
  185. return true;
  186. }
  187. bool Transaction::verify(unsigned int n, Script script, int type, bool strictPayToScriptHash) const {
  188. Evaluator::Stack stackCopy;
  189. const Input& input = getInput(n);
  190. const Script& scriptSig = input.signature();
  191. TransactionEvaluator eval(*this, type);
  192. eval.setIndex(n);
  193. if (!eval(scriptSig) || eval.stack().empty())
  194. return false;
  195. if (strictPayToScriptHash)
  196. stackCopy = eval.stack();
  197. if (!eval(script) || eval.stack().empty())
  198. return false;
  199. if (CastToBool(eval.stack().back()) == false)
  200. return false;
  201. // Additional validation for spend-to-script-hash transactions:
  202. if (strictPayToScriptHash && script.isPayToScriptHash()) {
  203. if (!scriptSig.isPushOnly()) // scriptSig must be literals-only
  204. return false; // or validation fails
  205. const Evaluator::Value& pubKeySerialized = stackCopy.back();
  206. Script pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
  207. stackCopy.pop_back();
  208. eval.stack(stackCopy);
  209. if (!eval(pubKey2) || eval.stack().empty())
  210. return false;
  211. return CastToBool(eval.stack().back());
  212. }
  213. return true;
  214. }
  215. static const size_t nMaxNumSize = 4;
  216. static CBigNum CastToBigNum(const valtype& vch)
  217. {
  218. if (vch.size() > nMaxNumSize)
  219. throw runtime_error("CastToBigNum() : overflow");
  220. // Get rid of extra leading zeros
  221. return CBigNum(CBigNum(vch).getvch());
  222. }
  223. boost::tribool TransactionEvaluator::eval(opcodetype opcode) {
  224. boost::tribool result = Evaluator::eval(opcode);
  225. if (result || !result)
  226. return result;
  227. if (needContext())
  228. std::runtime_error("Trying to use TransactionEvaluator without a Transaction context!");
  229. const Value False(0);
  230. const Value True(1, 1);
  231. switch (opcode) {
  232. case OP_CODESEPARATOR: {
  233. // Hash starts after the code separator
  234. _codehash = _current;
  235. _code_separator = true;
  236. break;
  237. }
  238. case OP_CHECKSIG:
  239. case OP_CHECKSIGVERIFY: {
  240. // (sig pubkey -- bool)
  241. if (_stack.size() < 2)
  242. return false;
  243. Value& vchSig = top(-2);
  244. Value& vchPubKey = top(-1);
  245. ////// debug print
  246. //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
  247. //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
  248. // Subset of script starting at the most recent codeseparator
  249. if (!_code_separator)
  250. _codehash = _begin;
  251. Script scriptCode(_codehash, _end);
  252. // Drop the signature, since there's no way for a signature to sign itself
  253. scriptCode.findAndDelete(Script(vchSig));
  254. bool fSuccess = checkSig(vchSig, vchPubKey, scriptCode);
  255. pop(_stack);
  256. pop(_stack);
  257. _stack.push_back(fSuccess ? True : False);
  258. if (opcode == OP_CHECKSIGVERIFY) {
  259. if (fSuccess)
  260. pop(_stack);
  261. else
  262. return false;
  263. }
  264. break;
  265. }
  266. case OP_CHECKMULTISIG:
  267. case OP_CHECKMULTISIGVERIFY: {
  268. // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
  269. unsigned int i = 1;
  270. if (_stack.size() < i)
  271. return false;
  272. int nKeysCount = CastToBigNum(top(-i)).getint();
  273. if (nKeysCount < 0 || nKeysCount > 20)
  274. return false;
  275. _op_count += nKeysCount;
  276. if (_op_count > 201)
  277. return false;
  278. int ikey = ++i;
  279. i += nKeysCount;
  280. if (_stack.size() < i)
  281. return false;
  282. int nSigsCount = CastToBigNum(top(-i)).getint();
  283. if (nSigsCount < 0 || nSigsCount > nKeysCount)
  284. return false;
  285. int isig = ++i;
  286. i += nSigsCount;
  287. if (_stack.size() < i)
  288. return false;
  289. // Subset of script starting at the most recent codeseparator
  290. if (!_code_separator)
  291. _codehash = _begin;
  292. Script scriptCode(_codehash, _end);
  293. // Drop the signatures, since there's no way for a signature to sign itself
  294. for (int k = 0; k < nSigsCount; k++) {
  295. Value& vchSig = top(-isig-k);
  296. scriptCode.findAndDelete(Script(vchSig));
  297. }
  298. bool fSuccess = true;
  299. while (fSuccess && nSigsCount > 0) {
  300. Value& vchSig = top(-isig);
  301. Value& vchPubKey = top(-ikey);
  302. // Check signature
  303. if (checkSig(vchSig, vchPubKey, scriptCode)) {
  304. isig++;
  305. nSigsCount--;
  306. }
  307. ikey++;
  308. nKeysCount--;
  309. // If there are more signatures left than keys left,
  310. // then too many signatures have failed
  311. if (nSigsCount > nKeysCount)
  312. fSuccess = false;
  313. }
  314. while (i-- > 0)
  315. pop(_stack);
  316. _stack.push_back(fSuccess ? True : False);
  317. if (opcode == OP_CHECKMULTISIGVERIFY) {
  318. if (fSuccess)
  319. pop(_stack);
  320. else
  321. return false;
  322. }
  323. break;
  324. }
  325. default:
  326. break;
  327. }
  328. return indeterminate;
  329. }
  330. bool TransactionEvaluator::checkSig(std::vector<unsigned char> vchSig, std::vector<unsigned char> vchPubKey, Script scriptCode)
  331. {
  332. try {
  333. Key key(SecureData(vchPubKey.begin(), vchPubKey.end()));
  334. int hashtype = _hash_type;
  335. // Hash type is one byte tacked on to the end of the signature
  336. if (vchSig.empty())
  337. return false;
  338. if (hashtype == 0)
  339. hashtype = vchSig.back();
  340. else if (hashtype != vchSig.back())
  341. return false;
  342. vchSig.pop_back();
  343. return key.verify(_txn.getSignatureHash(scriptCode, _in, hashtype), vchSig);
  344. }
  345. catch (std::exception& e) {
  346. return false;
  347. }
  348. }