Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto 2 : // Copyright (c) 2009-2020 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. 5 : 6 : #ifndef BITCOIN_SCRIPT_SIGN_H 7 : #define BITCOIN_SCRIPT_SIGN_H 8 : 9 : #include <coins.h> 10 : #include <hash.h> 11 : #include <pubkey.h> 12 : #include <script/interpreter.h> 13 : #include <script/keyorigin.h> 14 : #include <streams.h> 15 : 16 : class CKey; 17 : class CKeyID; 18 : class CScript; 19 : class CScriptID; 20 : class CTransaction; 21 : class SigningProvider; 22 : 23 : struct CMutableTransaction; 24 : 25 : /** Interface for signature creators. */ 26 28208 : class BaseSignatureCreator { 27 : public: 28 28208 : virtual ~BaseSignatureCreator() {} 29 : virtual const BaseSignatureChecker& Checker() const =0; 30 : 31 : /** Create a singular (non-script) signature. */ 32 : virtual bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const =0; 33 : }; 34 : 35 : /** A signature creator for transactions. */ 36 53492 : class MutableTransactionSignatureCreator : public BaseSignatureCreator { 37 : const CMutableTransaction* txTo; 38 : unsigned int nIn; 39 : int nHashType; 40 : CAmount amount; 41 : const MutableTransactionSignatureChecker checker; 42 : 43 : public: 44 : MutableTransactionSignatureCreator(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, int nHashTypeIn = SIGHASH_ALL); 45 22135 : const BaseSignatureChecker& Checker() const override { return checker; } 46 : bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override; 47 : }; 48 : 49 : /** A signature creator that just produces 71-byte empty signatures. */ 50 : extern const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR; 51 : /** A signature creator that just produces 72-byte empty signatures. */ 52 : extern const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR; 53 : 54 : typedef std::pair<CPubKey, std::vector<unsigned char>> SigPair; 55 : 56 : // This struct contains information from a transaction input and also contains signatures for that input. 57 : // The information contained here can be used to create a signature and is also filled by ProduceSignature 58 : // in order to construct final scriptSigs and scriptWitnesses. 59 2521566 : struct SignatureData { 60 1260696 : bool complete = false; ///< Stores whether the scriptSig and scriptWitness are complete 61 1260696 : bool witness = false; ///< Stores whether the input this SigData corresponds to is a witness input 62 : CScript scriptSig; ///< The scriptSig of an input. Contains complete signatures or the traditional partial signatures format 63 : CScript redeem_script; ///< The redeemScript (if any) for the input 64 : CScript witness_script; ///< The witnessScript (if any) for the input. witnessScripts are used in P2WSH outputs. 65 : CScriptWitness scriptWitness; ///< The scriptWitness of an input. Contains complete signatures or the traditional partial signatures format. scriptWitness is part of a transaction input per BIP 144. 66 : std::map<CKeyID, SigPair> signatures; ///< BIP 174 style partial signatures for the input. May contain all signatures necessary for producing a final scriptSig or scriptWitness. 67 : std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> misc_pubkeys; 68 : std::vector<CKeyID> missing_pubkeys; ///< KeyIDs of pubkeys which could not be found 69 : std::vector<CKeyID> missing_sigs; ///< KeyIDs of pubkeys for signatures which could not be found 70 : uint160 missing_redeem_script; ///< ScriptID of the missing redeemScript (if any) 71 : uint256 missing_witness_script; ///< SHA256 of the missing witnessScript (if any) 72 : 73 2521392 : SignatureData() {} 74 : explicit SignatureData(const CScript& script) : scriptSig(script) {} 75 : void MergeSignatureData(SignatureData sigdata); 76 : }; 77 : 78 : // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream 79 : // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other. 80 : template<typename Stream, typename... X> 81 2268 : void SerializeToVector(Stream& s, const X&... args) 82 : { 83 2268 : WriteCompactSize(s, GetSerializeSizeMany(s.GetVersion(), args...)); 84 2268 : SerializeMany(s, args...); 85 2268 : } 86 : 87 : // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments 88 : template<typename Stream, typename... X> 89 857 : void UnserializeFromVector(Stream& s, X&... args) 90 : { 91 857 : size_t expected_size = ReadCompactSize(s); 92 857 : size_t remaining_before = s.size(); 93 857 : UnserializeMany(s, args...); 94 857 : size_t remaining_after = s.size(); 95 857 : if (remaining_after + expected_size != remaining_before) { 96 0 : throw std::ios_base::failure("Size of value was not the stated size"); 97 : } 98 857 : } 99 : 100 : // Deserialize HD keypaths into a map 101 : template<typename Stream> 102 455 : void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths) 103 : { 104 : // Make sure that the key is the size of pubkey + 1 105 455 : if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) { 106 4 : throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath"); 107 : } 108 : // Read in the pubkey from key 109 451 : CPubKey pubkey(key.begin() + 1, key.end()); 110 451 : if (!pubkey.IsFullyValid()) { 111 0 : throw std::ios_base::failure("Invalid pubkey"); 112 : } 113 451 : if (hd_keypaths.count(pubkey) > 0) { 114 0 : throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided"); 115 : } 116 : 117 : // Read in key path 118 451 : uint64_t value_len = ReadCompactSize(s); 119 451 : if (value_len % 4 || value_len == 0) { 120 0 : throw std::ios_base::failure("Invalid length for HD key path"); 121 : } 122 : 123 451 : KeyOriginInfo keypath; 124 451 : s >> keypath.fingerprint; 125 1760 : for (unsigned int i = 4; i < value_len; i += sizeof(uint32_t)) { 126 1309 : uint32_t index; 127 1309 : s >> index; 128 1309 : keypath.path.push_back(index); 129 1309 : } 130 : 131 : // Add to map 132 451 : hd_keypaths.emplace(pubkey, std::move(keypath)); 133 455 : } 134 : 135 : // Serialize HD keypaths to a stream from a map 136 : template<typename Stream> 137 717 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, uint8_t type) 138 : { 139 1169 : for (auto keypath_pair : hd_keypaths) { 140 452 : if (!keypath_pair.first.IsValid()) { 141 0 : throw std::ios_base::failure("Invalid CPubKey being serialized"); 142 : } 143 452 : SerializeToVector(s, type, MakeSpan(keypath_pair.first)); 144 452 : WriteCompactSize(s, (keypath_pair.second.path.size() + 1) * sizeof(uint32_t)); 145 452 : s << keypath_pair.second.fingerprint; 146 1716 : for (const auto& path : keypath_pair.second.path) { 147 1264 : s << path; 148 : } 149 452 : } 150 717 : } 151 : 152 : /** Produce a script signature using a generic signature creator. */ 153 : bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey, SignatureData& sigdata); 154 : 155 : /** Produce a script signature for a transaction. */ 156 : bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType); 157 : bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType); 158 : 159 : /** Extract signature data from a transaction input, and insert it. */ 160 : SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout); 161 : void UpdateInput(CTxIn& input, const SignatureData& data); 162 : 163 : /* Check whether we know how to sign for an output like this, assuming we 164 : * have all private keys. While this function does not need private keys, the passed 165 : * provider is used to look up public keys and redeemscripts by hash. 166 : * Solvability is unrelated to whether we consider this output to be ours. */ 167 : bool IsSolvable(const SigningProvider& provider, const CScript& script); 168 : 169 : /** Check whether a scriptPubKey is known to be segwit. */ 170 : bool IsSegWitOutput(const SigningProvider& provider, const CScript& script); 171 : 172 : /** Sign the CMutableTransaction */ 173 : bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* provider, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors); 174 : 175 : #endif // BITCOIN_SCRIPT_SIGN_H