1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or https://www.opensource.org/licenses/mit-license.php .
6 #include "script/standard.h"
9 #include "script/script.h"
11 #include "utilstrencodings.h"
12 #include "script/cc.h"
15 #include "pbaas/identity.h"
16 #include "pbaas/reserves.h"
18 #include "cc/CCinclude.h"
20 #include <boost/foreach.hpp>
24 typedef vector<unsigned char> valtype;
26 unsigned nMaxDatacarrierBytes = MAX_OP_RETURN_RELAY;
28 COptCCParams::COptCCParams(const std::vector<unsigned char> &vch)
30 CScript inScr = CScript(vch.begin(), vch.end());
33 CScript::const_iterator pc = inScr.begin();
35 std::vector<std::vector<unsigned char>> data;
36 std::vector<unsigned char> param;
39 while (pc < inScr.end())
42 if (inScr.GetOp(pc, opcode, param))
48 data.push_back(param);
50 else if (opcode >= OP_1 && opcode <= OP_16)
53 param[0] = (opcode - OP_1) + 1;
54 data.push_back(param);
56 else if (opcode > 0 && opcode <= OP_PUSHDATA4 && param.size() > 0)
58 data.push_back(param);
68 if (valid && pc == inScr.end() && data.size() > 0)
72 if (param.size() == 4)
78 if (version == 0 || version > VERSION_V3 || m > n || ((version < VERSION_V3 && n < 1) || n > 4) || (version < VERSION_V3 ? data.size() <= n : data.size() < n))
89 for (i = 1; version != 0 && i <= n; i++)
91 std::vector<unsigned char> &keyVec = data[i];
92 if (keyVec.size() == 20)
94 vKeys.push_back(CKeyID(uint160(keyVec)));
96 else if (keyVec.size() == 33)
101 vKeys.push_back(CTxDestination(key));
108 else if (version > VERSION_V2 && (keyVec.size() == 21 || keyVec.size() == 34))
110 // the first byte is an indicator of type of destination, the
111 // rest is either a hash of an ID or another type of address
116 if (keyVec.size() == 34)
118 CPubKey key(std::vector<unsigned char>(keyVec.begin() + 1, keyVec.end()));
121 vKeys.push_back(CTxDestination(key));
132 if (keyVec.size() == 21)
134 vKeys.push_back(CKeyID(uint160(std::vector<unsigned char>(keyVec.begin() + 1, keyVec.end()))));
144 if (keyVec.size() == 21)
146 vKeys.push_back(CScriptID(uint160(std::vector<unsigned char>(keyVec.begin() + 1, keyVec.end()))));
156 if (keyVec.size() == 21)
158 vKeys.push_back(CIdentityID(uint160(std::vector<unsigned char>(keyVec.begin() + 1, keyVec.end()))));
168 if (keyVec.size() == 21)
170 vKeys.push_back(CIndexID(uint160(std::vector<unsigned char>(keyVec.begin() + 1, keyVec.end()))));
190 // get the rest of the data
191 for ( ; i < data.size(); i++)
193 vData.push_back(data[i]);
202 std::vector<unsigned char> COptCCParams::AsVector() const
204 CScript cData = CScript();
206 cData << std::vector<unsigned char>({version, evalCode, m, n});
209 std::vector<unsigned char> keyBytes = GetDestinationBytes(k);
210 if (version > VERSION_V2 && k.which() != ADDRTYPE_PK && k.which() != ADDRTYPE_PKH)
212 keyBytes.insert(keyBytes.begin(), (uint8_t)k.which());
218 cData << std::vector<unsigned char>(d);
220 return std::vector<unsigned char>(cData.begin(), cData.end());
223 bool IsPayToCryptoCondition(const CScript &scr, COptCCParams &ccParams)
225 return scr.IsPayToCryptoCondition(ccParams);
228 CScriptID::CScriptID(const CScript& in) : uint160(Hash160(in.begin(), in.end())) {}
230 const char* GetTxnOutputType(txnouttype t)
234 case TX_NONSTANDARD: return "nonstandard";
235 case TX_PUBKEY: return "pubkey";
236 case TX_PUBKEYHASH: return "pubkeyhash";
237 case TX_SCRIPTHASH: return "scripthash";
238 case TX_MULTISIG: return "multisig";
239 case TX_NULL_DATA: return "nulldata";
240 case TX_CRYPTOCONDITION: return "cryptocondition";
241 default: return "invalid";
247 * Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
249 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
251 if (IsCryptoConditionsEnabled()) {
252 // Shortcut for pay-to-crypto-condition
253 CScript ccSubScript = CScript();
254 std::vector<std::vector<unsigned char>> vParams;
256 if (scriptPubKey.IsPayToCryptoCondition(cp))
258 if (cp.IsValid() && cp.version >= cp.VERSION_V3)
260 typeRet = TX_CRYPTOCONDITION;
261 static std::set<int> VALID_EVAL_CODES({
264 EVAL_CURRENCY_DEFINITION,
265 EVAL_NOTARY_EVIDENCE,
266 EVAL_EARNEDNOTARIZATION,
267 EVAL_ACCEPTEDNOTARIZATION,
268 EVAL_FINALIZE_NOTARIZATION,
270 EVAL_RESERVE_TRANSFER,
272 EVAL_RESERVE_EXCHANGE,
273 EVAL_RESERVE_DEPOSIT,
274 EVAL_CROSSCHAIN_EXPORT,
275 EVAL_CROSSCHAIN_IMPORT,
276 EVAL_IDENTITY_PRIMARY,
277 EVAL_IDENTITY_REVOKE,
278 EVAL_IDENTITY_RECOVER,
279 EVAL_IDENTITY_COMMITMENT,
280 EVAL_IDENTITY_RESERVATION,
281 EVAL_FINALIZE_EXPORT,
284 if (VALID_EVAL_CODES.count(cp.evalCode))
286 for (auto k : cp.vKeys)
288 if (k.which() == COptCCParams::ADDRTYPE_SH || k.which() == COptCCParams::ADDRTYPE_ID)
290 std::vector<unsigned char> vch(GetDestinationBytes(k));
291 vch.insert(vch.begin(), (uint8_t)k.which());
292 vSolutionsRet.push_back(vch);
296 vSolutionsRet.push_back(GetDestinationBytes(k));
302 else if (scriptPubKey.IsPayToCryptoCondition(&ccSubScript, vParams))
304 typeRet = TX_CRYPTOCONDITION;
308 if (cp.evalCode != EVAL_STAKEGUARD)
310 LogPrintf("unrecognized smart transaction script type\n");
313 for (auto k : cp.vKeys)
315 vSolutionsRet.push_back(GetDestinationBytes(k));
320 scrHash = Hash160(ccSubScript);
321 vSolutionsRet.push_back(std::vector<unsigned char>(scrHash.begin(), scrHash.end()));
329 static multimap<txnouttype, CScript> mTemplates;
330 if (mTemplates.empty())
332 // Standard tx, sender provides pubkey, receiver adds signature
333 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
335 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
336 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
338 // Sender provides N pubkeys, receivers provides M signatures
339 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
341 // Empty, provably prunable, data-carrying output
342 if (GetBoolArg("-datacarrier", true))
343 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
344 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
347 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
348 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
349 if (scriptPubKey.IsPayToScriptHash())
351 typeRet = TX_SCRIPTHASH;
352 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
353 vSolutionsRet.push_back(hashBytes);
358 const CScript& script1 = scriptPubKey;
359 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
361 const CScript& script2 = tplate.second;
362 vSolutionsRet.clear();
364 opcodetype opcode1, opcode2;
365 vector<unsigned char> vch1, vch2;
368 CScript::const_iterator pc1 = script1.begin();
369 CScript::const_iterator pc2 = script2.begin();
372 if (pc1 == script1.end() && pc2 == script2.end())
375 typeRet = tplate.first;
376 if (typeRet == TX_MULTISIG)
378 // Additional checks for TX_MULTISIG:
379 unsigned char m = vSolutionsRet.front()[0];
380 unsigned char n = vSolutionsRet.back()[0];
381 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
386 if (!script1.GetOp(pc1, opcode1, vch1))
388 if (!script2.GetOp(pc2, opcode2, vch2))
391 // Template matching opcodes:
392 if (opcode2 == OP_PUBKEYS)
394 while (vch1.size() >= 33 && vch1.size() <= 65)
396 vSolutionsRet.push_back(vch1);
397 if (!script1.GetOp(pc1, opcode1, vch1))
400 if (!script2.GetOp(pc2, opcode2, vch2))
402 // Normal situation is to fall through
403 // to other if/else statements
406 if (opcode2 == OP_PUBKEY)
408 if (vch1.size() < 33 || vch1.size() > 65)
410 vSolutionsRet.push_back(vch1);
412 else if (opcode2 == OP_PUBKEYHASH)
414 if (vch1.size() != sizeof(uint160))
416 vSolutionsRet.push_back(vch1);
418 else if (opcode2 == OP_SMALLINTEGER)
419 { // Single-byte small integer pushed onto vSolutions
420 if (opcode1 == OP_0 ||
421 (opcode1 >= OP_1 && opcode1 <= OP_16))
423 char n = (char)CScript::DecodeOP_N(opcode1);
424 vSolutionsRet.push_back(valtype(1, n));
429 else if (opcode2 == OP_SMALLDATA)
431 // small pushdata, <= nMaxDatacarrierBytes
432 if (vch1.size() > nMaxDatacarrierBytes)
434 //fprintf(stderr,"size.%d > nMaxDatacarrier.%d\n",(int32_t)vch1.size(),(int32_t)nMaxDatacarrierBytes);
438 else if (opcode1 != opcode2 || vch1 != vch2)
440 // Others must match exactly
446 vSolutionsRet.clear();
447 typeRet = TX_NONSTANDARD;
451 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
463 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
465 return vSolutions[0][0] + 1;
467 return 1; // doesn't include args needed by the script
468 case TX_CRYPTOCONDITION:
474 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
476 vector<valtype> vSolutions;
477 if (!Solver(scriptPubKey, whichType, vSolutions))
479 //int32_t i; uint8_t *ptr = (uint8_t *)scriptPubKey.data();
480 //for (i=0; i<scriptPubKey.size(); i++)
481 // fprintf(stderr,"%02x",ptr[i]);
482 //fprintf(stderr," non-standard scriptPubKey\n");
486 if (whichType == TX_MULTISIG)
488 unsigned char m = vSolutions.front()[0];
489 unsigned char n = vSolutions.back()[0];
490 // Support up to x-of-9 multisig txns as standard
496 return whichType != TX_NONSTANDARD;
499 bool ExtractDestination(const CScript& _scriptPubKey, CTxDestination& addressRet, bool returnPubKey)
501 vector<valtype> vSolutions;
502 txnouttype whichType;
503 CScript scriptPubKey = _scriptPubKey;
505 // if this is a CLTV script, get the destination after CLTV
506 if (scriptPubKey.IsCheckLockTimeVerify())
508 uint8_t pushOp = scriptPubKey[0];
509 uint32_t scriptStart = pushOp + 3;
511 // check post CLTV script
512 scriptPubKey = CScript(scriptPubKey.size() > scriptStart ? scriptPubKey.begin() + scriptStart : scriptPubKey.end(), scriptPubKey.end());
515 if (!Solver(scriptPubKey, whichType, vSolutions))
518 if (whichType == TX_PUBKEY)
520 CPubKey pubKey(vSolutions[0]);
521 if (!pubKey.IsValid())
523 fprintf(stderr,"TX_PUBKEY invalid pubkey\n");
530 addressRet = pubKey.GetID();
534 else if (whichType == TX_PUBKEYHASH)
536 addressRet = CKeyID(uint160(vSolutions[0]));
539 else if (whichType == TX_SCRIPTHASH)
541 addressRet = CScriptID(uint160(vSolutions[0]));
545 else if (IsCryptoConditionsEnabled() != 0 && whichType == TX_CRYPTOCONDITION)
548 if (scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid() && p.vKeys.size())
550 addressRet = p.vKeys[0];
554 // Multisig txns have more than one address...
558 bool ExtractDestinations(const CScript& scriptPubKey,
560 std::vector<CTxDestination>& addressRet,
562 const CKeyStore *pKeyStore,
566 std::map<uint160, CKey> *pPrivKeys)
569 typeRet = TX_NONSTANDARD;
570 vector<valtype> vSolutions;
572 // if this is a CLTV script, get the destinations after CLTV
573 if (scriptPubKey.IsCheckLockTimeVerify())
575 uint8_t pushOp = scriptPubKey[0];
576 uint32_t scriptStart = pushOp + 3;
578 // check post CLTV script
579 CScript postfix = CScript(scriptPubKey.size() > scriptStart ? scriptPubKey.begin() + scriptStart : scriptPubKey.end(), scriptPubKey.end());
581 // check again with only postfix subscript
582 return(ExtractDestinations(postfix, typeRet, addressRet, nRequiredRet, pKeyStore, pCanSign, pCanSpend, nHeight, pPrivKeys));
585 int canSpendCount = 0;
586 bool canSign = false;
597 COptCCParams master, p;
599 if (scriptPubKey.IsPayToCryptoCondition(p))
601 std::set<CScriptID> idSet;
605 p.vKeys.size() >= p.n)
607 typeRet = TX_CRYPTOCONDITION;
608 if (p.version < p.VERSION_V3)
610 for (auto dest : p.vKeys)
612 uint160 destId = GetDestinationID(dest);
613 addressRet.push_back(dest);
614 if (dest.which() == COptCCParams::ADDRTYPE_ID)
616 // lookup identity, we must have all registered target identity scripts in our keystore, or we try as if they are a keyID, which will be the same
617 // if revoked or undefined
618 std::pair<CIdentityMapKey, CIdentityMapValue> identity;
619 idSet.insert(destId);
621 if (pKeyStore && pKeyStore->GetIdentity(destId, identity, std::max((uint32_t)1, nHeight - 1)) && identity.second.IsValidUnrevoked())
623 int canSignCount = 0;
624 for (auto oneKey : identity.second.primaryAddresses)
626 uint160 oneKeyID = GetDestinationID(oneKey);
628 if (pKeyStore->GetKey(oneKeyID, privKey))
634 (*pPrivKeys)[oneKeyID] = privKey;
638 if (canSignCount >= identity.second.minSigs)
647 if (pKeyStore->GetKey(destId, privKey))
653 (*pPrivKeys)[destId] = privKey;
659 if (canSpendCount >= p.m && pCanSpend)
663 if (canSign && pCanSign)
668 else if (p.vData.size() && (ccValid = (master = COptCCParams(p.vData.back())).IsValid()))
670 // always add the index keys to destinations, but that has nothing to do with whether or not
671 // an ID present in that index represents an address that can sign or spend. ids in this block
672 // are ignored, as all IDs in an output are always indexed in the address and unspent indexes.
673 std::set<CTxDestination> indexSet;
674 for (auto dest : master.vKeys)
677 if (dest.which() != COptCCParams::ADDRTYPE_ID)
679 // include all non-name addresses from master as destinations as well
680 // name addresses can only be destinations if they are at least "cansign" on one of the subconditions
681 if (!indexSet.count(dest))
683 addressRet.push_back(dest);
685 indexSet.insert(dest);
689 // handle the case where we have no object in the params, but a valid transaction
690 int loopEnd = p.vData.size() == 1 ? 1 : p.vData.size() - 1;
691 for (int i = 0; ccValid && i < loopEnd; i++)
693 // first, process P, then any sub-conditions
695 COptCCParams &oneP = (i == 0) ? p : (_oneP = COptCCParams(p.vData[i]));
697 if (ccValid = oneP.IsValid())
699 int canSpendOneCount = 0;
701 for (auto dest : oneP.vKeys)
703 uint160 destId = GetDestinationID(dest);
704 if (!indexSet.count(dest))
706 addressRet.push_back(dest);
708 if (dest.which() == COptCCParams::ADDRTYPE_ID)
710 // lookup identity, we must have all registered target identity scripts in our keystore, or we try as if they are a keyID, which will be the same
711 // as if revoked or undefined
712 std::pair<CIdentityMapKey, CIdentityMapValue> identity;
713 idSet.insert(destId);
715 //printf("checking: %s\n", EncodeDestination(dest).c_str());
717 if (pKeyStore && pKeyStore->GetIdentity(destId, identity, std::max((uint32_t)1, nHeight - 1)) && identity.second.IsValidUnrevoked())
719 int canSignCount = 0;
720 for (auto oneKey : identity.second.primaryAddresses)
722 uint160 oneKeyID = GetDestinationID(oneKey);
725 if (pKeyStore->GetKey(oneKeyID, privKey))
731 (*pPrivKeys)[oneKeyID] = privKey;
735 if (canSignCount >= identity.second.minSigs)
746 if (pKeyStore->GetKey(destId, privKey))
752 (*pPrivKeys)[destId] = privKey;
758 if (canSpendOneCount >= oneP.m)
767 LogPrintf("Invalid smart transaction %d\n", p.evalCode);
771 // if this is a compound cc, the master m of n is the top level as an m of n of the sub-conditions
772 nRequiredRet = p.vData.size() > 2 ? master.m : p.m;
773 if (canSpendCount >= nRequiredRet && pCanSpend)
777 if (canSign && pCanSign)
785 if (scriptPubKey.IsPayToCryptoCondition(&subScr))
787 // this kind of ID is defined as a CKeyID, since use of script hash type in CCs are reserved for IDs
788 addressRet.push_back(CKeyID(Hash160(subScr)));
812 if (!Solver(scriptPubKey, typeRet, vSolutions))
815 if (typeRet == TX_NULL_DATA){
816 // This is data, not addresses
820 if (typeRet == TX_MULTISIG)
822 nRequiredRet = vSolutions.front()[0];
824 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
826 CPubKey pubKey(vSolutions[i]);
827 if (!pubKey.IsValid())
830 CTxDestination address = pubKey.GetID();
831 addressRet.push_back(address);
833 // if we were asked to see whether we can sign or spend, determine
834 if ((pCanSign || pCanSpend) && pKeyStore)
836 if (pKeyStore->HaveKey(GetDestinationID(address)))
843 if (addressRet.empty())
846 if (pCanSign && nHaveKeys)
850 if (pCanSpend && nHaveKeys >= nRequiredRet)
858 CTxDestination address;
859 if (!ExtractDestination(scriptPubKey, address))
863 addressRet.push_back(address);
864 if ((pCanSign || pCanSpend) && pKeyStore)
866 if (pKeyStore->HaveKey(GetDestinationID(address)))
886 class CScriptVisitor : public boost::static_visitor<bool>
891 CScriptVisitor(CScript *scriptin) { script = scriptin; }
893 bool operator()(const CNoDestination &dest) const {
898 bool operator()(const CIndexID &dest) const {
903 bool operator()(const CQuantumID &dest) const {
908 bool operator()(const CPubKey &key) const {
910 *script << ToByteVector(key) << OP_CHECKSIG;
914 bool operator()(const CKeyID &keyID) const {
916 *script << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG;
920 bool operator()(const CIdentityID &idID) const {
921 *script = CIdentity::TransparentOutput(idID);
925 bool operator()(const CScriptID &scriptID) const {
927 *script << OP_HASH160 << ToByteVector(scriptID) << OP_EQUAL;
933 CScript GetScriptForDestination(const CTxDestination& dest)
937 boost::apply_visitor(CScriptVisitor(&script), dest);
941 CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys)
945 script << CScript::EncodeOP_N(nRequired);
946 BOOST_FOREACH(const CPubKey& key, keys)
947 script << ToByteVector(key);
948 script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
952 bool IsValidDestination(const CTxDestination& dest) {
953 return dest.which() != 0;
956 bool IsTransparentAddress(const CTxDestination& dest) {
957 return dest.which() == 1 || dest.which() == 2;
960 CTxDestination DestFromAddressHash(int scriptType, uint160& addressHash)
962 switch (scriptType) {
964 return CTxDestination(CKeyID(addressHash));
966 return CTxDestination(CIdentityID(addressHash));
968 return CTxDestination(CScriptID(addressHash));
970 return CTxDestination(CIndexID(addressHash));
972 return CTxDestination(CQuantumID(addressHash));
974 // This probably won't ever happen, because it would mean that
975 // the addressindex contains a type (say, 3) that we (currently)
976 // don't recognize; maybe we "dropped support" for it?
977 return CNoDestination();
981 CScript::ScriptType AddressTypeFromDest(const CTxDestination &dest)
983 switch (dest.which()) {
985 case COptCCParams::ADDRTYPE_PK:
986 case COptCCParams::ADDRTYPE_PKH:
987 return CScript::P2PKH;
988 case COptCCParams::ADDRTYPE_SH:
989 return CScript::P2SH;
990 case COptCCParams::ADDRTYPE_ID:
991 return CScript::P2ID;
992 case COptCCParams::ADDRTYPE_INDEX:
993 return CScript::P2IDX;
994 case COptCCParams::ADDRTYPE_QUANTUM:
995 return CScript::P2QRK;
997 // This probably won't ever happen, because it would mean that
998 // the addressindex contains a type (say, 3) that we (currently)
999 // don't recognize; maybe we "dropped support" for it?
1000 return CScript::UNKNOWN;