Move CTxInWitness inside CTxIn
[bitcoinplatinum.git] / src / script / sign.cpp
blobb008df259178dca0111b4f42eae211a8c4989aab
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include "script/sign.h"
8 #include "key.h"
9 #include "keystore.h"
10 #include "policy/policy.h"
11 #include "primitives/transaction.h"
12 #include "script/standard.h"
13 #include "uint256.h"
15 #include <boost/foreach.hpp>
17 using namespace std;
19 typedef std::vector<unsigned char> valtype;
21 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) {}
23 bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
25 CKey key;
26 if (!keystore->GetKey(address, key))
27 return false;
29 // Signing with uncompressed keys is disabled in witness scripts
30 if (sigversion == SIGVERSION_WITNESS_V0 && !key.IsCompressed())
31 return false;
33 uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);
34 if (!key.Sign(hash, vchSig))
35 return false;
36 vchSig.push_back((unsigned char)nHashType);
37 return true;
40 static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
42 vector<unsigned char> vchSig;
43 if (!creator.CreateSig(vchSig, address, scriptCode, sigversion))
44 return false;
45 ret.push_back(vchSig);
46 return true;
49 static bool SignN(const vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
51 int nSigned = 0;
52 int nRequired = multisigdata.front()[0];
53 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
55 const valtype& pubkey = multisigdata[i];
56 CKeyID keyID = CPubKey(pubkey).GetID();
57 if (Sign1(keyID, creator, scriptCode, ret, sigversion))
58 ++nSigned;
60 return nSigned==nRequired;
63 /**
64 * Sign scriptPubKey using signature made with creator.
65 * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
66 * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
67 * Returns false if scriptPubKey could not be completely satisfied.
69 static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey,
70 std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion)
72 CScript scriptRet;
73 uint160 h160;
74 ret.clear();
76 vector<valtype> vSolutions;
77 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
78 return false;
80 CKeyID keyID;
81 switch (whichTypeRet)
83 case TX_NONSTANDARD:
84 case TX_NULL_DATA:
85 return false;
86 case TX_PUBKEY:
87 keyID = CPubKey(vSolutions[0]).GetID();
88 return Sign1(keyID, creator, scriptPubKey, ret, sigversion);
89 case TX_PUBKEYHASH:
90 keyID = CKeyID(uint160(vSolutions[0]));
91 if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion))
92 return false;
93 else
95 CPubKey vch;
96 creator.KeyStore().GetPubKey(keyID, vch);
97 ret.push_back(ToByteVector(vch));
99 return true;
100 case TX_SCRIPTHASH:
101 if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) {
102 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
103 return true;
105 return false;
107 case TX_MULTISIG:
108 ret.push_back(valtype()); // workaround CHECKMULTISIG bug
109 return (SignN(vSolutions, creator, scriptPubKey, ret, sigversion));
111 case TX_WITNESS_V0_KEYHASH:
112 ret.push_back(vSolutions[0]);
113 return true;
115 case TX_WITNESS_V0_SCRIPTHASH:
116 CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());
117 if (creator.KeyStore().GetCScript(h160, scriptRet)) {
118 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
119 return true;
121 return false;
123 default:
124 return false;
128 static CScript PushAll(const vector<valtype>& values)
130 CScript result;
131 BOOST_FOREACH(const valtype& v, values) {
132 if (v.size() == 0) {
133 result << OP_0;
134 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
135 result << CScript::EncodeOP_N(v[0]);
136 } else {
137 result << v;
140 return result;
143 bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
145 CScript script = fromPubKey;
146 bool solved = true;
147 std::vector<valtype> result;
148 txnouttype whichType;
149 solved = SignStep(creator, script, result, whichType, SIGVERSION_BASE);
150 bool P2SH = false;
151 CScript subscript;
152 sigdata.scriptWitness.stack.clear();
154 if (solved && whichType == TX_SCRIPTHASH)
156 // Solver returns the subscript that needs to be evaluated;
157 // the final scriptSig is the signatures from that
158 // and then the serialized subscript:
159 script = subscript = CScript(result[0].begin(), result[0].end());
160 solved = solved && SignStep(creator, script, result, whichType, SIGVERSION_BASE) && whichType != TX_SCRIPTHASH;
161 P2SH = true;
164 if (solved && whichType == TX_WITNESS_V0_KEYHASH)
166 CScript witnessscript;
167 witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
168 txnouttype subType;
169 solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0);
170 sigdata.scriptWitness.stack = result;
171 result.clear();
173 else if (solved && whichType == TX_WITNESS_V0_SCRIPTHASH)
175 CScript witnessscript(result[0].begin(), result[0].end());
176 txnouttype subType;
177 solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;
178 result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));
179 sigdata.scriptWitness.stack = result;
180 result.clear();
183 if (P2SH) {
184 result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));
186 sigdata.scriptSig = PushAll(result);
188 // Test solution
189 return solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
192 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn)
194 SignatureData data;
195 assert(tx.vin.size() > nIn);
196 data.scriptSig = tx.vin[nIn].scriptSig;
197 data.scriptWitness = tx.vin[nIn].scriptWitness;
198 return data;
201 void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data)
203 assert(tx.vin.size() > nIn);
204 tx.vin[nIn].scriptSig = data.scriptSig;
205 tx.vin[nIn].scriptWitness = data.scriptWitness;
208 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
210 assert(nIn < txTo.vin.size());
212 CTransaction txToConst(txTo);
213 TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType);
215 SignatureData sigdata;
216 bool ret = ProduceSignature(creator, fromPubKey, sigdata);
217 UpdateTransaction(txTo, nIn, sigdata);
218 return ret;
221 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
223 assert(nIn < txTo.vin.size());
224 CTxIn& txin = txTo.vin[nIn];
225 assert(txin.prevout.n < txFrom.vout.size());
226 const CTxOut& txout = txFrom.vout[txin.prevout.n];
228 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
231 static vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
232 const vector<valtype>& vSolutions,
233 const vector<valtype>& sigs1, const vector<valtype>& sigs2, SigVersion sigversion)
235 // Combine all the signatures we've got:
236 set<valtype> allsigs;
237 BOOST_FOREACH(const valtype& v, sigs1)
239 if (!v.empty())
240 allsigs.insert(v);
242 BOOST_FOREACH(const valtype& v, sigs2)
244 if (!v.empty())
245 allsigs.insert(v);
248 // Build a map of pubkey -> signature by matching sigs to pubkeys:
249 assert(vSolutions.size() > 1);
250 unsigned int nSigsRequired = vSolutions.front()[0];
251 unsigned int nPubKeys = vSolutions.size()-2;
252 map<valtype, valtype> sigs;
253 BOOST_FOREACH(const valtype& sig, allsigs)
255 for (unsigned int i = 0; i < nPubKeys; i++)
257 const valtype& pubkey = vSolutions[i+1];
258 if (sigs.count(pubkey))
259 continue; // Already got a sig for this pubkey
261 if (checker.CheckSig(sig, pubkey, scriptPubKey, sigversion))
263 sigs[pubkey] = sig;
264 break;
268 // Now build a merged CScript:
269 unsigned int nSigsHave = 0;
270 std::vector<valtype> result; result.push_back(valtype()); // pop-one-too-many workaround
271 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
273 if (sigs.count(vSolutions[i+1]))
275 result.push_back(sigs[vSolutions[i+1]]);
276 ++nSigsHave;
279 // Fill any missing with OP_0:
280 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
281 result.push_back(valtype());
283 return result;
286 namespace
288 struct Stacks
290 std::vector<valtype> script;
291 std::vector<valtype> witness;
293 Stacks() {}
294 explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_), witness() {}
295 explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
296 EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
299 SignatureData Output() const {
300 SignatureData result;
301 result.scriptSig = PushAll(script);
302 result.scriptWitness.stack = witness;
303 return result;
308 static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
309 const txnouttype txType, const vector<valtype>& vSolutions,
310 Stacks sigs1, Stacks sigs2, SigVersion sigversion)
312 switch (txType)
314 case TX_NONSTANDARD:
315 case TX_NULL_DATA:
316 // Don't know anything about this, assume bigger one is correct:
317 if (sigs1.script.size() >= sigs2.script.size())
318 return sigs1;
319 return sigs2;
320 case TX_PUBKEY:
321 case TX_PUBKEYHASH:
322 // Signatures are bigger than placeholders or empty scripts:
323 if (sigs1.script.empty() || sigs1.script[0].empty())
324 return sigs2;
325 return sigs1;
326 case TX_WITNESS_V0_KEYHASH:
327 // Signatures are bigger than placeholders or empty scripts:
328 if (sigs1.witness.empty() || sigs1.witness[0].empty())
329 return sigs2;
330 return sigs1;
331 case TX_SCRIPTHASH:
332 if (sigs1.script.empty() || sigs1.script.back().empty())
333 return sigs2;
334 else if (sigs2.script.empty() || sigs2.script.back().empty())
335 return sigs1;
336 else
338 // Recur to combine:
339 valtype spk = sigs1.script.back();
340 CScript pubKey2(spk.begin(), spk.end());
342 txnouttype txType2;
343 vector<vector<unsigned char> > vSolutions2;
344 Solver(pubKey2, txType2, vSolutions2);
345 sigs1.script.pop_back();
346 sigs2.script.pop_back();
347 Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, sigversion);
348 result.script.push_back(spk);
349 return result;
351 case TX_MULTISIG:
352 return Stacks(CombineMultisig(scriptPubKey, checker, vSolutions, sigs1.script, sigs2.script, sigversion));
353 case TX_WITNESS_V0_SCRIPTHASH:
354 if (sigs1.witness.empty() || sigs1.witness.back().empty())
355 return sigs2;
356 else if (sigs2.witness.empty() || sigs2.witness.back().empty())
357 return sigs1;
358 else
360 // Recur to combine:
361 CScript pubKey2(sigs1.witness.back().begin(), sigs1.witness.back().end());
362 txnouttype txType2;
363 vector<valtype> vSolutions2;
364 Solver(pubKey2, txType2, vSolutions2);
365 sigs1.witness.pop_back();
366 sigs1.script = sigs1.witness;
367 sigs1.witness.clear();
368 sigs2.witness.pop_back();
369 sigs2.script = sigs2.witness;
370 sigs2.witness.clear();
371 Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, SIGVERSION_WITNESS_V0);
372 result.witness = result.script;
373 result.script.clear();
374 result.witness.push_back(valtype(pubKey2.begin(), pubKey2.end()));
375 return result;
377 default:
378 return Stacks();
382 SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
383 const SignatureData& scriptSig1, const SignatureData& scriptSig2)
385 txnouttype txType;
386 vector<vector<unsigned char> > vSolutions;
387 Solver(scriptPubKey, txType, vSolutions);
389 return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SIGVERSION_BASE).Output();
392 namespace {
393 /** Dummy signature checker which accepts all signatures. */
394 class DummySignatureChecker : public BaseSignatureChecker
396 public:
397 DummySignatureChecker() {}
399 bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
401 return true;
404 const DummySignatureChecker dummyChecker;
407 const BaseSignatureChecker& DummySignatureCreator::Checker() const
409 return dummyChecker;
412 bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const
414 // Create a dummy signature that is a valid DER-encoding
415 vchSig.assign(72, '\000');
416 vchSig[0] = 0x30;
417 vchSig[1] = 69;
418 vchSig[2] = 0x02;
419 vchSig[3] = 33;
420 vchSig[4] = 0x01;
421 vchSig[4 + 33] = 0x02;
422 vchSig[5 + 33] = 32;
423 vchSig[6 + 33] = 0x01;
424 vchSig[6 + 33 + 32] = SIGHASH_ALL;
425 return true;