[tests] Add -blocknotify functional test
[bitcoinplatinum.git] / src / script / sign.cpp
blobac58b690a2f1f6d99f11345ef701ad5c8df5b17c
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"
16 typedef std::vector<unsigned char> valtype;
18 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) {}
20 bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
22 CKey key;
23 if (!keystore->GetKey(address, key))
24 return false;
26 // Signing with uncompressed keys is disabled in witness scripts
27 if (sigversion == SIGVERSION_WITNESS_V0 && !key.IsCompressed())
28 return false;
30 uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion);
31 if (!key.Sign(hash, vchSig))
32 return false;
33 vchSig.push_back((unsigned char)nHashType);
34 return true;
37 static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
39 std::vector<unsigned char> vchSig;
40 if (!creator.CreateSig(vchSig, address, scriptCode, sigversion))
41 return false;
42 ret.push_back(vchSig);
43 return true;
46 static bool SignN(const std::vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, std::vector<valtype>& ret, SigVersion sigversion)
48 int nSigned = 0;
49 int nRequired = multisigdata.front()[0];
50 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
52 const valtype& pubkey = multisigdata[i];
53 CKeyID keyID = CPubKey(pubkey).GetID();
54 if (Sign1(keyID, creator, scriptCode, ret, sigversion))
55 ++nSigned;
57 return nSigned==nRequired;
60 /**
61 * Sign scriptPubKey using signature made with creator.
62 * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
63 * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
64 * Returns false if scriptPubKey could not be completely satisfied.
66 static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey,
67 std::vector<valtype>& ret, txnouttype& whichTypeRet, SigVersion sigversion)
69 CScript scriptRet;
70 uint160 h160;
71 ret.clear();
73 std::vector<valtype> vSolutions;
74 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
75 return false;
77 CKeyID keyID;
78 switch (whichTypeRet)
80 case TX_NONSTANDARD:
81 case TX_NULL_DATA:
82 case TX_WITNESS_UNKNOWN:
83 return false;
84 case TX_PUBKEY:
85 keyID = CPubKey(vSolutions[0]).GetID();
86 return Sign1(keyID, creator, scriptPubKey, ret, sigversion);
87 case TX_PUBKEYHASH:
88 keyID = CKeyID(uint160(vSolutions[0]));
89 if (!Sign1(keyID, creator, scriptPubKey, ret, sigversion))
90 return false;
91 else
93 CPubKey vch;
94 creator.KeyStore().GetPubKey(keyID, vch);
95 ret.push_back(ToByteVector(vch));
97 return true;
98 case TX_SCRIPTHASH:
99 if (creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptRet)) {
100 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
101 return true;
103 return false;
105 case TX_MULTISIG:
106 ret.push_back(valtype()); // workaround CHECKMULTISIG bug
107 return (SignN(vSolutions, creator, scriptPubKey, ret, sigversion));
109 case TX_WITNESS_V0_KEYHASH:
110 ret.push_back(vSolutions[0]);
111 return true;
113 case TX_WITNESS_V0_SCRIPTHASH:
114 CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(h160.begin());
115 if (creator.KeyStore().GetCScript(h160, scriptRet)) {
116 ret.push_back(std::vector<unsigned char>(scriptRet.begin(), scriptRet.end()));
117 return true;
119 return false;
121 default:
122 return false;
126 static CScript PushAll(const std::vector<valtype>& values)
128 CScript result;
129 for (const valtype& v : values) {
130 if (v.size() == 0) {
131 result << OP_0;
132 } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
133 result << CScript::EncodeOP_N(v[0]);
134 } else {
135 result << v;
138 return result;
141 bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
143 CScript script = fromPubKey;
144 std::vector<valtype> result;
145 txnouttype whichType;
146 bool solved = SignStep(creator, script, result, whichType, SIGVERSION_BASE);
147 bool P2SH = false;
148 CScript subscript;
149 sigdata.scriptWitness.stack.clear();
151 if (solved && whichType == TX_SCRIPTHASH)
153 // Solver returns the subscript that needs to be evaluated;
154 // the final scriptSig is the signatures from that
155 // and then the serialized subscript:
156 script = subscript = CScript(result[0].begin(), result[0].end());
157 solved = solved && SignStep(creator, script, result, whichType, SIGVERSION_BASE) && whichType != TX_SCRIPTHASH;
158 P2SH = true;
161 if (solved && whichType == TX_WITNESS_V0_KEYHASH)
163 CScript witnessscript;
164 witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
165 txnouttype subType;
166 solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0);
167 sigdata.scriptWitness.stack = result;
168 result.clear();
170 else if (solved && whichType == TX_WITNESS_V0_SCRIPTHASH)
172 CScript witnessscript(result[0].begin(), result[0].end());
173 txnouttype subType;
174 solved = solved && SignStep(creator, witnessscript, result, subType, SIGVERSION_WITNESS_V0) && subType != TX_SCRIPTHASH && subType != TX_WITNESS_V0_SCRIPTHASH && subType != TX_WITNESS_V0_KEYHASH;
175 result.push_back(std::vector<unsigned char>(witnessscript.begin(), witnessscript.end()));
176 sigdata.scriptWitness.stack = result;
177 result.clear();
180 if (P2SH) {
181 result.push_back(std::vector<unsigned char>(subscript.begin(), subscript.end()));
183 sigdata.scriptSig = PushAll(result);
185 // Test solution
186 return solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
189 SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn)
191 SignatureData data;
192 assert(tx.vin.size() > nIn);
193 data.scriptSig = tx.vin[nIn].scriptSig;
194 data.scriptWitness = tx.vin[nIn].scriptWitness;
195 return data;
198 void UpdateTransaction(CMutableTransaction& tx, unsigned int nIn, const SignatureData& data)
200 assert(tx.vin.size() > nIn);
201 tx.vin[nIn].scriptSig = data.scriptSig;
202 tx.vin[nIn].scriptWitness = data.scriptWitness;
205 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType)
207 assert(nIn < txTo.vin.size());
209 CTransaction txToConst(txTo);
210 TransactionSignatureCreator creator(&keystore, &txToConst, nIn, amount, nHashType);
212 SignatureData sigdata;
213 bool ret = ProduceSignature(creator, fromPubKey, sigdata);
214 UpdateTransaction(txTo, nIn, sigdata);
215 return ret;
218 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
220 assert(nIn < txTo.vin.size());
221 CTxIn& txin = txTo.vin[nIn];
222 assert(txin.prevout.n < txFrom.vout.size());
223 const CTxOut& txout = txFrom.vout[txin.prevout.n];
225 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType);
228 static std::vector<valtype> CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
229 const std::vector<valtype>& vSolutions,
230 const std::vector<valtype>& sigs1, const std::vector<valtype>& sigs2, SigVersion sigversion)
232 // Combine all the signatures we've got:
233 std::set<valtype> allsigs;
234 for (const valtype& v : sigs1)
236 if (!v.empty())
237 allsigs.insert(v);
239 for (const valtype& v : sigs2)
241 if (!v.empty())
242 allsigs.insert(v);
245 // Build a map of pubkey -> signature by matching sigs to pubkeys:
246 assert(vSolutions.size() > 1);
247 unsigned int nSigsRequired = vSolutions.front()[0];
248 unsigned int nPubKeys = vSolutions.size()-2;
249 std::map<valtype, valtype> sigs;
250 for (const valtype& sig : allsigs)
252 for (unsigned int i = 0; i < nPubKeys; i++)
254 const valtype& pubkey = vSolutions[i+1];
255 if (sigs.count(pubkey))
256 continue; // Already got a sig for this pubkey
258 if (checker.CheckSig(sig, pubkey, scriptPubKey, sigversion))
260 sigs[pubkey] = sig;
261 break;
265 // Now build a merged CScript:
266 unsigned int nSigsHave = 0;
267 std::vector<valtype> result; result.push_back(valtype()); // pop-one-too-many workaround
268 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
270 if (sigs.count(vSolutions[i+1]))
272 result.push_back(sigs[vSolutions[i+1]]);
273 ++nSigsHave;
276 // Fill any missing with OP_0:
277 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
278 result.push_back(valtype());
280 return result;
283 namespace
285 struct Stacks
287 std::vector<valtype> script;
288 std::vector<valtype> witness;
290 Stacks() {}
291 explicit Stacks(const std::vector<valtype>& scriptSigStack_) : script(scriptSigStack_), witness() {}
292 explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
293 EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SIGVERSION_BASE);
296 SignatureData Output() const {
297 SignatureData result;
298 result.scriptSig = PushAll(script);
299 result.scriptWitness.stack = witness;
300 return result;
305 static Stacks CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
306 const txnouttype txType, const std::vector<valtype>& vSolutions,
307 Stacks sigs1, Stacks sigs2, SigVersion sigversion)
309 switch (txType)
311 case TX_NONSTANDARD:
312 case TX_NULL_DATA:
313 case TX_WITNESS_UNKNOWN:
314 // Don't know anything about this, assume bigger one is correct:
315 if (sigs1.script.size() >= sigs2.script.size())
316 return sigs1;
317 return sigs2;
318 case TX_PUBKEY:
319 case TX_PUBKEYHASH:
320 // Signatures are bigger than placeholders or empty scripts:
321 if (sigs1.script.empty() || sigs1.script[0].empty())
322 return sigs2;
323 return sigs1;
324 case TX_WITNESS_V0_KEYHASH:
325 // Signatures are bigger than placeholders or empty scripts:
326 if (sigs1.witness.empty() || sigs1.witness[0].empty())
327 return sigs2;
328 return sigs1;
329 case TX_SCRIPTHASH:
330 if (sigs1.script.empty() || sigs1.script.back().empty())
331 return sigs2;
332 else if (sigs2.script.empty() || sigs2.script.back().empty())
333 return sigs1;
334 else
336 // Recur to combine:
337 valtype spk = sigs1.script.back();
338 CScript pubKey2(spk.begin(), spk.end());
340 txnouttype txType2;
341 std::vector<std::vector<unsigned char> > vSolutions2;
342 Solver(pubKey2, txType2, vSolutions2);
343 sigs1.script.pop_back();
344 sigs2.script.pop_back();
345 Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, sigversion);
346 result.script.push_back(spk);
347 return result;
349 case TX_MULTISIG:
350 return Stacks(CombineMultisig(scriptPubKey, checker, vSolutions, sigs1.script, sigs2.script, sigversion));
351 case TX_WITNESS_V0_SCRIPTHASH:
352 if (sigs1.witness.empty() || sigs1.witness.back().empty())
353 return sigs2;
354 else if (sigs2.witness.empty() || sigs2.witness.back().empty())
355 return sigs1;
356 else
358 // Recur to combine:
359 CScript pubKey2(sigs1.witness.back().begin(), sigs1.witness.back().end());
360 txnouttype txType2;
361 std::vector<valtype> vSolutions2;
362 Solver(pubKey2, txType2, vSolutions2);
363 sigs1.witness.pop_back();
364 sigs1.script = sigs1.witness;
365 sigs1.witness.clear();
366 sigs2.witness.pop_back();
367 sigs2.script = sigs2.witness;
368 sigs2.witness.clear();
369 Stacks result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2, SIGVERSION_WITNESS_V0);
370 result.witness = result.script;
371 result.script.clear();
372 result.witness.push_back(valtype(pubKey2.begin(), pubKey2.end()));
373 return result;
375 default:
376 return Stacks();
380 SignatureData CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker,
381 const SignatureData& scriptSig1, const SignatureData& scriptSig2)
383 txnouttype txType;
384 std::vector<std::vector<unsigned char> > vSolutions;
385 Solver(scriptPubKey, txType, vSolutions);
387 return CombineSignatures(scriptPubKey, checker, txType, vSolutions, Stacks(scriptSig1), Stacks(scriptSig2), SIGVERSION_BASE).Output();
390 namespace {
391 /** Dummy signature checker which accepts all signatures. */
392 class DummySignatureChecker : public BaseSignatureChecker
394 public:
395 DummySignatureChecker() {}
397 bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
399 return true;
402 const DummySignatureChecker dummyChecker;
403 } // namespace
405 const BaseSignatureChecker& DummySignatureCreator::Checker() const
407 return dummyChecker;
410 bool DummySignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const
412 // Create a dummy signature that is a valid DER-encoding
413 vchSig.assign(72, '\000');
414 vchSig[0] = 0x30;
415 vchSig[1] = 69;
416 vchSig[2] = 0x02;
417 vchSig[3] = 33;
418 vchSig[4] = 0x01;
419 vchSig[4 + 33] = 0x02;
420 vchSig[5 + 33] = 32;
421 vchSig[6 + 33] = 0x01;
422 vchSig[6 + 33 + 32] = SIGHASH_ALL;
423 return true;