| 1264 | |
| 1265 | template <class T> |
| 1266 | uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, bool no_forkid, const PrecomputedTransactionData* cache, int forkid) |
| 1267 | { |
| 1268 | assert(nIn < txTo.vin.size()); |
| 1269 | |
| 1270 | bool use_forkid = false; |
| 1271 | int nForkHashType = nHashType; |
| 1272 | if (!no_forkid) { |
| 1273 | use_forkid = UsesForkId(nHashType); |
| 1274 | if (use_forkid) { |
| 1275 | nForkHashType |= forkid << 8; |
| 1276 | } |
| 1277 | } |
| 1278 | |
| 1279 | // force new tx with FORKID to use bip143 transaction digest algorithm |
| 1280 | // see https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki |
| 1281 | if (sigversion == SigVersion::WITNESS_V0 || use_forkid) { |
| 1282 | uint256 hashPrevouts; |
| 1283 | uint256 hashSequence; |
| 1284 | uint256 hashOutputs; |
| 1285 | const bool cacheready = cache && cache->ready; |
| 1286 | |
| 1287 | if (!(nHashType & SIGHASH_ANYONECANPAY)) { |
| 1288 | hashPrevouts = cacheready ? cache->hashPrevouts : GetPrevoutHash(txTo); |
| 1289 | } |
| 1290 | |
| 1291 | if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) { |
| 1292 | hashSequence = cacheready ? cache->hashSequence : GetSequenceHash(txTo); |
| 1293 | } |
| 1294 | |
| 1295 | |
| 1296 | if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) { |
| 1297 | hashOutputs = cacheready ? cache->hashOutputs : GetOutputsHash(txTo); |
| 1298 | } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) { |
| 1299 | CHashWriter ss(SER_GETHASH, 0); |
| 1300 | ss << txTo.vout[nIn]; |
| 1301 | hashOutputs = ss.GetHash(); |
| 1302 | } |
| 1303 | |
| 1304 | CHashWriter ss(SER_GETHASH, 0); |
| 1305 | // Version |
| 1306 | ss << txTo.nVersion; |
| 1307 | // Input prevouts/nSequence (none/all, depending on flags) |
| 1308 | ss << hashPrevouts; |
| 1309 | ss << hashSequence; |
| 1310 | // The input being signed (replacing the scriptSig with scriptCode + amount) |
| 1311 | // The prevout may already be contained in hashPrevout, and the nSequence |
| 1312 | // may already be contain in hashSequence. |
| 1313 | ss << txTo.vin[nIn].prevout; |
| 1314 | ss << scriptCode; |
| 1315 | ss << amount; |
| 1316 | ss << txTo.vin[nIn].nSequence; |
| 1317 | // Outputs (none/one/all, depending on flags) |
| 1318 | ss << hashOutputs; |
| 1319 | // Locktime |
| 1320 | ss << txTo.nLockTime; |
| 1321 | // Sighash type |
| 1322 | ss << nForkHashType; |
| 1323 | |