You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sign.cpp 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "script/sign.h"
  6. #include "key.h"
  7. #include "keystore.h"
  8. #include "policy/policy.h"
  9. #include "primitives/transaction.h"
  10. #include "script/standard.h"
  11. #include "uint256.h"
  12. typedef std::vector<unsigned char> valtype;
  13. TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn) : BaseSignatureCreator(keystoreIn), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), amount(amountIn), checker(txTo, nIn, amountIn) {}
  14. bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
  15. {
  16. CKey key;
  17. if (!keystore->GetKey(address, key))
  18. return false;
  19. // Signing with uncompressed keys is disabled in witness scripts
  20. if (sigversion == SIGVERSION_WITNESS_V0 && !key.IsCompressed())
  21. return false;
  22. uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);
  23. if (!key.Sign(hash, vchSig))
  24. return false;
  25. vchSig.push_back((unsigned char)nHashType);
  26. return true;
  27. }
  28. static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
  29. {
  30. std::vector<unsigned char> vchSig;
  31. if (!creator.CreateSig(vchSig, address, scriptCode, sigversion))
  32. return false;
  33. ret.push_back(vchSig);
  34. return true;
  35. }
  36. static bool SignN(const std::vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
  37. {
  38. int nSigned = 0;
  39. int nRequired = multisigdata.front()[0];
  40. for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
  41. {
  42. const valtype& pubkey = multisigdata[i];
  43. CKeyID keyID = CPubKey(pubkey).GetID();
  44. if (Sign1(keyID, creator, scriptCode, ret, sigversion))
  45. ++nSigned;
  46. }
  47. return nSigned==nRequired;
  48. }
  49. /**
  50. * Sign scriptPubKey using signature made with creator.
  51. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
  52. * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
  53. * Returns false if scriptPubKey could not be completely satisfied.
  54. */
  55. static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey,
  56. std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion)
  57. {
  58. CScript scriptRet;
  59. uint160 h160;
  60. ret.clear();
  61. std::vector<valtype> vSolutions;
  62. if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
  63. return false;
  64. CKeyID keyID;
  65. switch (whichTypeRet)
  66. {
  67. case TX_NONSTANDARD:
  68. case TX_NULL_DATA:
  69. return false;
  70. case TX_PUBKEY:
  71. keyID = CPubKey(vSolutions[0]).GetID();
  72. return Sign1(keyID, creator, scriptPubKey, ret, sigversion);
  73. case TX_PUBKEYHASH:
  74. keyID = CKeyID(uint160(vSolutions[0]));
  75. if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion))
  76. return false;
  77. else
  78. {
  79. CPubKey vch;
  80. creator.KeyStore().GetPubKey(keyID, vch);
  81. ret.push_back(ToByteVector(vch));
  82. }
  83. return true;
  84. case TX_SCRIPTHASH:
  85. if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) {
  86. ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
  87. return true;
  88. }
  89. return false;
  90. case TX_MULTISIG:
  91. ret.push_back(valtype()); // workaround CHECKMULTISIG bug
  92. return (SignN(vSolutions, creator, scriptPubKey, ret, sigversion));
  93. case TX_WITNESS_V0_KEYHASH:
  94. ret.push_back(vSolutions[0]);
  95. return true;
  96. case TX_WITNESS_V0_SCRIPTHASH:
  97. CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());
  98. if (creator.KeyStore().GetCScript(h160, scriptRet)) {
  99. ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
  100. return true;
  101. }
  102. return false;
  103. default:
  104. return false;
  105. }
  106. }
  107. static CScript PushAll(const std::vector<valtype>& values)
  108. {
  109. CScript result;
  110. for (const valtype& v : values) {
  111. if (v.size() == 0) {
  112. result << OP_0;
  113. } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
  114. result << CScript::EncodeOP_N(v[0]);
  115. } else {
  116. result << v;
  117. }
  118. }
  119. return result;
  120. }
  121. bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
  122. {
  123. CScript script = fromPubKey;
  124. std::vector<valtype> result;
  125. txnouttype whichType;
  126. bool solved = SignStep(creator, script, result, whichType, SIGVERSION_BASE);
  127. bool P2SH = false;
  128. CScript subscript;
  129. sigdata.scriptWitness.stack.clear();
  130. if (solved && whichType == TX_SCRIPTHASH)
  131. {
  132. // Solver returns the subscript that needs to be evaluated;
  133. // the final scriptSig is the signatures from that
  134. // and then the serialized subscript:
  135. script = subscript = CScript(result[0].begin(), result[0].end());
  136. solved = solved && SignStep(creator, script, result, whichType, SIGVERSION_BASE) && whichType != TX_SCRIPTHASH;
  137. P2SH = true;
  138. }
  139. if (solved && whichType == TX_WITNESS_V0_KEYHASH)
  140. {
  141. CScript witnessscript;
  142. witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
  143. txnouttype subType;
  144. solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0);
  145. sigdata.scriptWitness.stack = result;
  146. result.clear();
  147. }
  148. else if (solved && whichType == TX_WITNESS_V0_SCRIPTHASH)
  149. {
  150. CScript witnessscript(result[0].begin(), result[0].end());
  151. txnouttype subType;
  152. solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;
  153. result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));
  154. sigdata.scriptWitness.stack = result;
  155. result.clear();
  156. }
  157. if (P2SH) {
  158. result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));
  159. }
  160. sigdata.scriptSig = PushAll(result);
  161. // Test solution
  162. return solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
  163. }
  164. SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn)
  165. {
  166. SignatureData data;
  167. assert(tx.vin.size() > nIn);
  168. data.scriptSig = tx.vin[nIn].scriptSig;
  169. data.scriptWitness = tx.vin[nIn].scriptWitness;
  170. return data;
  171. }
  172. void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data)
  173. {
  174. assert(tx.vin.size() > nIn);
  175. tx.vin[nIn].scriptSig = data.scriptSig;
  176. tx.vin[nIn].scriptWitness = data.scriptWitness;
  177. }
  178. bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
  179. {
  180. assert(nIn < txTo.vin.size());
  181. CTransaction txToConst(txTo);
  182. TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType);
  183. SignatureData sigdata;
  184. bool ret = ProduceSignature(creator, fromPubKey, sigdata);
  185. UpdateTransaction(txTo, nIn, sigdata);
  186. return ret;
  187. }
  188. bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
  189. {
  190. assert(nIn < txTo.vin.size());
  191. CTxIn& txin = txTo.vin[nIn];
  192. assert(txin.prevout.n < txFrom.vout.size());
  193. const CTxOut& txout = txFrom.vout[txin.prevout.n];
  194. return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
  195. }
  196. static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
  197. const std::vector<valtype>& vSolutions,
  198. const std::vector<valtype>& sigs1, const std::vector<valtype>& sigs2, SigVersion sigversion)
  199. {
  200. // Combine all the signatures we've got:
  201. std::set<valtype> allsigs;
  202. for (const valtype& v : sigs1)
  203. {
  204. if (!v.empty())
  205. allsigs.insert(v);
  206. }
  207. for (const valtype& v : sigs2)
  208. {
  209. if (!v.empty())
  210. allsigs.insert(v);
  211. }
  212. // Build a map of pubkey -> signature by matching sigs to pubkeys:
  213. assert(vSolutions.size() > 1);
  214. unsigned int nSigsRequired = vSolutions.front()[0];
  215. unsigned int nPubKeys = vSolutions.size()-2;
  216. std::map<valtype, valtype> sigs;
  217. for (const valtype& sig : allsigs)
  218. {
  219. for (unsigned int i = 0; i < nPubKeys; i++)
  220. {
  221. const valtype& pubkey = vSolutions[i+1];
  222. if (sigs.count(pubkey))
  223. continue; // Already got a sig for this pubkey
  224. if (checker.CheckSig(sig, pubkey, scriptPubKey, sigversion))
  225. {
  226. sigs[pubkey] = sig;
  227. break;
  228. }
  229. }
  230. }
  231. // Now build a merged CScript:
  232. unsigned int nSigsHave = 0;
  233. std::vector<valtype> result; result.push_back(valtype()); // pop-one-too-many workaround
  234. for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
  235. {
  236. if (sigs.count(vSolutions[i+1]))
  237. {
  238. result.push_back(sigs[vSolutions[i+1]]);
  239. ++nSigsHave;
  240. }
  241. }
  242. // Fill any missing with OP_0:
  243. for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
  244. result.push_back(valtype());
  245. return result;
  246. }
  247. namespace
  248. {
  249. struct Stacks
  250. {
  251. std::vector<valtype> script;
  252. std::vector<valtype> witness;
  253. Stacks() {}
  254. explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_), witness() {}
  255. explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
  256. EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
  257. }
  258. SignatureData Output() const {
  259. SignatureData result;
  260. result.scriptSig = PushAll(script);
  261. result.scriptWitness.stack = witness;
  262. return result;
  263. }
  264. };
  265. }
  266. static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
  267. const txnouttype txType, const std::vector<valtype>& vSolutions,
  268. Stacks sigs1, Stacks sigs2, SigVersion sigversion)
  269. {
  270. switch (txType)
  271. {
  272. case TX_NONSTANDARD:
  273. case TX_NULL_DATA:
  274. // Don't know anything about this, assume bigger one is correct:
  275. if (sigs1.script.size() >= sigs2.script.size())
  276. return sigs1;
  277. return sigs2;
  278. case TX_PUBKEY:
  279. case TX_PUBKEYHASH:
  280. // Signatures are bigger than placeholders or empty scripts:
  281. if (sigs1.script.empty() || sigs1.script[0].empty())
  282. return sigs2;
  283. return sigs1;
  284. case TX_WITNESS_V0_KEYHASH:
  285. // Signatures are bigger than placeholders or empty scripts:
  286. if (sigs1.witness.empty() || sigs1.witness[0].empty())
  287. return sigs2;
  288. return sigs1;
  289. case TX_SCRIPTHASH:
  290. if (sigs1.script.empty() || sigs1.script.back().empty())
  291. return sigs2;
  292. else if (sigs2.script.empty() || sigs2.script.back().empty())
  293. return sigs1;
  294. else
  295. {
  296. // Recur to combine:
  297. valtype spk = sigs1.script.back();
  298. CScript pubKey2(spk.begin(), spk.end());
  299. txnouttype txType2;
  300. std::vector<std::vector<unsigned char> > vSolutions2;
  301. Solver(pubKey2, txType2, vSolutions2);
  302. sigs1.script.pop_back();
  303. sigs2.script.pop_back();
  304. Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, sigversion);
  305. result.script.push_back(spk);
  306. return result;
  307. }
  308. case TX_MULTISIG:
  309. return Stacks(CombineMultisig(scriptPubKey, checker, vSolutions, sigs1.script, sigs2.script, sigversion));
  310. case TX_WITNESS_V0_SCRIPTHASH:
  311. if (sigs1.witness.empty() || sigs1.witness.back().empty())
  312. return sigs2;
  313. else if (sigs2.witness.empty() || sigs2.witness.back().empty())
  314. return sigs1;
  315. else
  316. {
  317. // Recur to combine:
  318. CScript pubKey2(sigs1.witness.back().begin(), sigs1.witness.back().end());
  319. txnouttype txType2;
  320. std::vector<valtype> vSolutions2;
  321. Solver(pubKey2, txType2, vSolutions2);
  322. sigs1.witness.pop_back();
  323. sigs1.script = sigs1.witness;
  324. sigs1.witness.clear();
  325. sigs2.witness.pop_back();
  326. sigs2.script = sigs2.witness;
  327. sigs2.witness.clear();
  328. Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, SIGVERSION_WITNESS_V0);
  329. result.witness = result.script;
  330. result.script.clear();
  331. result.witness.push_back(valtype(pubKey2.begin(), pubKey2.end()));
  332. return result;
  333. }
  334. default:
  335. return Stacks();
  336. }
  337. }
  338. SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
  339. const SignatureData& scriptSig1, const SignatureData& scriptSig2)
  340. {
  341. txnouttype txType;
  342. std::vector<std::vector<unsigned char> > vSolutions;
  343. Solver(scriptPubKey, txType, vSolutions);
  344. return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SIGVERSION_BASE).Output();
  345. }
  346. namespace {
  347. /** Dummy signature checker which accepts all signatures. */
  348. class DummySignatureChecker : public BaseSignatureChecker
  349. {
  350. public:
  351. DummySignatureChecker() {}
  352. bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
  353. {
  354. return true;
  355. }
  356. };
  357. const DummySignatureChecker dummyChecker;
  358. } // namespace
  359. const BaseSignatureChecker& DummySignatureCreator::Checker() const
  360. {
  361. return dummyChecker;
  362. }
  363. bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const
  364. {
  365. // Create a dummy signature that is a valid DER-encoding
  366. vchSig.assign(72, '\000');
  367. vchSig[0] = 0x30;
  368. vchSig[1] = 69;
  369. vchSig[2] = 0x02;
  370. vchSig[3] = 33;
  371. vchSig[4] = 0x01;
  372. vchSig[4 + 33] = 0x02;
  373. vchSig[5 + 33] = 32;
  374. vchSig[6 + 33] = 0x01;
  375. vchSig[6 + 33 + 32] = SIGHASH_ALL;
  376. return true;
  377. }