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"
10 #include "policy/policy.h"
11 #include "primitives/transaction.h"
12 #include "script/standard.h"
15 #include <boost/foreach.hpp>
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
26 if (!keystore
->GetKey(address
, key
))
29 // Signing with uncompressed keys is disabled in witness scripts
30 if (sigversion
== SIGVERSION_WITNESS_V0
&& !key
.IsCompressed())
33 uint256 hash
= SignatureHash(scriptCode
, *txTo
, nIn
, nHashType
, amount
, sigversion
);
34 if (!key
.Sign(hash
, vchSig
))
36 vchSig
.push_back((unsigned char)nHashType
);
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
))
45 ret
.push_back(vchSig
);
49 static bool SignN(const vector
<valtype
>& multisigdata
, const BaseSignatureCreator
& creator
, const CScript
& scriptCode
, std::vector
<valtype
>& ret
, SigVersion sigversion
)
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
))
60 return nSigned
==nRequired
;
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
)
76 vector
<valtype
> vSolutions
;
77 if (!Solver(scriptPubKey
, whichTypeRet
, vSolutions
))
87 keyID
= CPubKey(vSolutions
[0]).GetID();
88 return Sign1(keyID
, creator
, scriptPubKey
, ret
, sigversion
);
90 keyID
= CKeyID(uint160(vSolutions
[0]));
91 if (!Sign1(keyID
, creator
, scriptPubKey
, ret
, sigversion
))
96 creator
.KeyStore().GetPubKey(keyID
, vch
);
97 ret
.push_back(ToByteVector(vch
));
101 if (creator
.KeyStore().GetCScript(uint160(vSolutions
[0]), scriptRet
)) {
102 ret
.push_back(std::vector
<unsigned char>(scriptRet
.begin(), scriptRet
.end()));
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]);
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()));
128 static CScript
PushAll(const vector
<valtype
>& values
)
131 BOOST_FOREACH(const valtype
& v
, values
) {
134 } else if (v
.size() == 1 && v
[0] >= 1 && v
[0] <= 16) {
135 result
<< CScript::EncodeOP_N(v
[0]);
143 bool ProduceSignature(const BaseSignatureCreator
& creator
, const CScript
& fromPubKey
, SignatureData
& sigdata
)
145 CScript script
= fromPubKey
;
147 std::vector
<valtype
> result
;
148 txnouttype whichType
;
149 solved
= SignStep(creator
, script
, result
, whichType
, SIGVERSION_BASE
);
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
;
164 if (solved
&& whichType
== TX_WITNESS_V0_KEYHASH
)
166 CScript witnessscript
;
167 witnessscript
<< OP_DUP
<< OP_HASH160
<< ToByteVector(result
[0]) << OP_EQUALVERIFY
<< OP_CHECKSIG
;
169 solved
= solved
&& SignStep(creator
, witnessscript
, result
, subType
, SIGVERSION_WITNESS_V0
);
170 sigdata
.scriptWitness
.stack
= result
;
173 else if (solved
&& whichType
== TX_WITNESS_V0_SCRIPTHASH
)
175 CScript
witnessscript(result
[0].begin(), result
[0].end());
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
;
184 result
.push_back(std::vector
<unsigned char>(subscript
.begin(), subscript
.end()));
186 sigdata
.scriptSig
= PushAll(result
);
189 return solved
&& VerifyScript(sigdata
.scriptSig
, fromPubKey
, &sigdata
.scriptWitness
, STANDARD_SCRIPT_VERIFY_FLAGS
, creator
.Checker());
192 SignatureData
DataFromTransaction(const CMutableTransaction
& tx
, unsigned int nIn
)
195 assert(tx
.vin
.size() > nIn
);
196 data
.scriptSig
= tx
.vin
[nIn
].scriptSig
;
197 data
.scriptWitness
= tx
.vin
[nIn
].scriptWitness
;
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
);
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
)
242 BOOST_FOREACH(const valtype
& v
, sigs2
)
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
))
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]]);
279 // Fill any missing with OP_0:
280 for (unsigned int i
= nSigsHave
; i
< nSigsRequired
; i
++)
281 result
.push_back(valtype());
290 std::vector
<valtype
> script
;
291 std::vector
<valtype
> witness
;
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
;
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
)
316 // Don't know anything about this, assume bigger one is correct:
317 if (sigs1
.script
.size() >= sigs2
.script
.size())
322 // Signatures are bigger than placeholders or empty scripts:
323 if (sigs1
.script
.empty() || sigs1
.script
[0].empty())
326 case TX_WITNESS_V0_KEYHASH
:
327 // Signatures are bigger than placeholders or empty scripts:
328 if (sigs1
.witness
.empty() || sigs1
.witness
[0].empty())
332 if (sigs1
.script
.empty() || sigs1
.script
.back().empty())
334 else if (sigs2
.script
.empty() || sigs2
.script
.back().empty())
339 valtype spk
= sigs1
.script
.back();
340 CScript
pubKey2(spk
.begin(), spk
.end());
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
);
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())
356 else if (sigs2
.witness
.empty() || sigs2
.witness
.back().empty())
361 CScript
pubKey2(sigs1
.witness
.back().begin(), sigs1
.witness
.back().end());
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()));
382 SignatureData
CombineSignatures(const CScript
& scriptPubKey
, const BaseSignatureChecker
& checker
,
383 const SignatureData
& scriptSig1
, const SignatureData
& scriptSig2
)
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();
393 /** Dummy signature checker which accepts all signatures. */
394 class DummySignatureChecker
: public BaseSignatureChecker
397 DummySignatureChecker() {}
399 bool CheckSig(const std::vector
<unsigned char>& scriptSig
, const std::vector
<unsigned char>& vchPubKey
, const CScript
& scriptCode
, SigVersion sigversion
) const
404 const DummySignatureChecker dummyChecker
;
407 const BaseSignatureChecker
& DummySignatureCreator::Checker() const
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');
421 vchSig
[4 + 33] = 0x02;
423 vchSig
[6 + 33] = 0x01;
424 vchSig
[6 + 33 + 32] = SIGHASH_ALL
;