1 /********************************************************************
2 * (C) 2019 Michael Toutonghi
4 * Distributed under the MIT software license, see the accompanying
5 * file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 * This provides support for PBaaS initialization, notarization, and cross-chain token
8 * transactions and enabling liquid or non-liquid tokens across the
15 #include "rpc/pbaasrpc.h"
17 #include "transaction_builder.h"
19 CConnectedChains ConnectedChains;
23 return (strcmp(ASSETCHAINS_SYMBOL, "VRSC") == 0 || strcmp(ASSETCHAINS_SYMBOL, "VRSCTEST") == 0);
26 bool IsVerusMainnetActive()
28 return (strcmp(ASSETCHAINS_SYMBOL, "VRSC") == 0);
31 // this adds an opret to a mutable transaction and returns the voutnum if it could be added
32 int32_t AddOpRetOutput(CMutableTransaction &mtx, const CScript &opRetScript)
34 if (opRetScript.IsOpReturn() && opRetScript.size() <= MAX_OP_RETURN_RELAY)
36 CTxOut vOut = CTxOut();
37 vOut.scriptPubKey = opRetScript;
39 mtx.vout.push_back(vOut);
40 return mtx.vout.size() - 1;
48 // returns a pointer to a base chain object, which can be cast to the
49 // object type indicated in its objType member
50 uint256 GetChainObjectHash(const CBaseChainObject &bo)
53 const CBaseChainObject *retPtr;
54 const CChainObject<CBlockHeaderAndProof> *pNewHeader;
55 const CChainObject<CPartialTransactionProof> *pNewTx;
56 const CChainObject<CBlockHeaderProof> *pNewHeaderRef;
57 const CChainObject<CPriorBlocksCommitment> *pPriors;
58 const CChainObject<uint256> *pNewProofRoot;
59 const CChainObject<CReserveTransfer> *pExport;
60 const CChainObject<CCrossChainProof> *pCrossChainProof;
61 const CChainObject<CCompositeChainObject> *pCompositeChainObject;
69 return pNewHeader->GetHash();
71 case CHAINOBJ_TRANSACTION_PROOF:
72 return pNewTx->GetHash();
74 case CHAINOBJ_HEADER_REF:
75 return pNewHeaderRef->GetHash();
77 case CHAINOBJ_PRIORBLOCKS:
78 return pPriors->GetHash();
80 case CHAINOBJ_PROOF_ROOT:
81 return pNewProofRoot->object;
83 case CHAINOBJ_RESERVETRANSFER:
84 return pExport->GetHash();
86 case CHAINOBJ_CROSSCHAINPROOF:
87 return pCrossChainProof->GetHash();
89 case CHAINOBJ_COMPOSITEOBJECT:
90 return pCrossChainProof->GetHash();
96 // used to export coins from one chain to another, if they are not native, they are represented on the other
98 bool ValidateCrossChainExport(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
103 bool IsCrossChainExportInput(const CScript &scriptSig)
108 // used to validate import of coins from one chain to another. if they are not native and are supported,
109 // they are represented o the chain as tokens
110 bool ValidateCrossChainImport(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
114 bool IsCrossChainImportInput(const CScript &scriptSig)
119 // used to validate a specific service reward based on the spending transaction
120 bool ValidateServiceReward(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
122 // for each type of service reward, we need to check and see if the spender is
123 // correctly formatted to be a valid spend of the service reward. for notarization
124 // we ensure that the notarization and its outputs are valid and that the spend
125 // applies to the correct billing period
128 bool IsServiceRewardInput(const CScript &scriptSig)
133 // used as a proxy token output for a reserve currency on its fractional reserve chain
134 bool ValidateReserveOutput(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
138 bool IsReserveOutputInput(const CScript &scriptSig)
143 bool ValidateReserveTransfer(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
147 bool IsReserveTransferInput(const CScript &scriptSig)
152 bool ValidateReserveDeposit(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
156 bool IsReserveDepositInput(const CScript &scriptSig)
161 bool ValidateCurrencyState(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
165 bool IsCurrencyStateInput(const CScript &scriptSig)
170 // used to convert a fractional reserve currency into its reserve and back
171 bool ValidateReserveExchange(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
175 bool IsReserveExchangeInput(const CScript &scriptSig)
182 * Verifies that the input objects match the hashes and returns the transaction.
184 * If the opRetTx has the op ret, this calculates based on the actual transaction and
185 * validates the hashes. If the opRetTx does not have the opRet itself, this validates
186 * by ensuring that all objects are present on this chain, composing the opRet, and
187 * ensuring that the transaction then hashes to the correct txid.
190 bool ValidateOpretProof(CScript &opRet, COpRetProof &orProof)
192 // enumerate through the objects and validate that they are objects of the expected type that hash
193 // to the value expected. return true if so
197 int8_t ObjTypeCode(const CBlockHeaderProof &obj)
199 return CHAINOBJ_HEADER;
202 int8_t ObjTypeCode(const uint256 &obj)
204 return CHAINOBJ_PROOF_ROOT;
207 int8_t ObjTypeCode(const CPartialTransactionProof &obj)
209 return CHAINOBJ_TRANSACTION_PROOF;
212 int8_t ObjTypeCode(const CBlockHeaderAndProof &obj)
214 return CHAINOBJ_HEADER_REF;
217 int8_t ObjTypeCode(const CPriorBlocksCommitment &obj)
219 return CHAINOBJ_PRIORBLOCKS;
222 int8_t ObjTypeCode(const CReserveTransfer &obj)
224 return CHAINOBJ_RESERVETRANSFER;
227 int8_t ObjTypeCode(const CCrossChainProof &obj)
229 return CHAINOBJ_CROSSCHAINPROOF;
232 int8_t ObjTypeCode(const CCompositeChainObject &obj)
234 return CHAINOBJ_COMPOSITEOBJECT;
237 // this adds an opret to a mutable transaction that provides the necessary evidence of a signed, cheating stake transaction
238 CScript StoreOpRetArray(const std::vector<CBaseChainObject *> &objPtrs)
241 CDataStream s = CDataStream(SER_NETWORK, PROTOCOL_VERSION);
242 s << (int32_t)OPRETTYPE_OBJECTARR;
245 for (auto pobj : objPtrs)
249 if (!DehydrateChainObject(s, pobj))
255 catch(const std::exception& e)
257 std::cerr << e.what() << '\n';
263 //std::vector<unsigned char> schars(s.begin(), s.begin() + 200);
264 //printf("stream vector chars: %s\n", HexBytes(&schars[0], schars.size()).c_str());
266 std::vector<unsigned char> vch(s.begin(), s.end());
267 return error ? CScript() : CScript() << OP_RETURN << vch;
270 void DeleteOpRetObjects(std::vector<CBaseChainObject *> &ora)
272 for (auto pobj : ora)
274 switch(pobj->objectType)
276 case CHAINOBJ_HEADER:
278 delete (CChainObject<CBlockHeaderAndProof> *)pobj;
282 case CHAINOBJ_TRANSACTION_PROOF:
284 delete (CChainObject<CPartialTransactionProof> *)pobj;
288 case CHAINOBJ_PROOF_ROOT:
290 delete (CChainObject<uint256> *)pobj;
294 case CHAINOBJ_HEADER_REF:
296 delete (CChainObject<CBlockHeaderProof> *)pobj;
300 case CHAINOBJ_PRIORBLOCKS:
302 delete (CChainObject<CPriorBlocksCommitment> *)pobj;
306 case CHAINOBJ_RESERVETRANSFER:
308 delete (CChainObject<CReserveTransfer> *)pobj;
312 case CHAINOBJ_CROSSCHAINPROOF:
314 delete (CChainObject<CCrossChainProof> *)pobj;
318 case CHAINOBJ_COMPOSITEOBJECT:
320 delete (CChainObject<CCompositeChainObject> *)pobj;
326 printf("ERROR: invalid object type (%u), likely corrupt pointer %p\n", pobj->objectType, pobj);
327 printf("generate code that won't be optimized away %s\n", CCurrencyValueMap(std::vector<uint160>({ASSETCHAINS_CHAINID}), std::vector<CAmount>({200000000})).ToUniValue().write(1,2).c_str());
328 printf("This is here to generate enough code for a good break point system chain name: %s\n", ConnectedChains.ThisChain().name.c_str());
337 std::vector<CBaseChainObject *> RetrieveOpRetArray(const CScript &opRetScript)
339 std::vector<unsigned char> vch;
340 std::vector<CBaseChainObject *> vRet;
341 if (opRetScript.IsOpReturn() && GetOpReturnData(opRetScript, vch) && vch.size() > 0)
343 CDataStream s = CDataStream(vch, SER_NETWORK, PROTOCOL_VERSION);
350 if (opRetType == OPRETTYPE_OBJECTARR)
352 CBaseChainObject *pobj;
353 while (!s.empty() && (pobj = RehydrateChainObject(s)))
355 vRet.push_back(pobj);
359 printf("failed to load all objects in opret");
360 DeleteOpRetObjects(vRet);
365 catch(const std::exception& e)
367 std::cerr << e.what() << '\n';
368 DeleteOpRetObjects(vRet);
375 CServiceReward::CServiceReward(const CTransaction &tx, bool validate)
377 nVersion = PBAAS_VERSION_INVALID;
378 for (auto out : tx.vout)
381 if (IsPayToCryptoCondition(out.scriptPubKey, p))
383 // always take the first for now
384 if (p.evalCode == EVAL_SERVICEREWARD)
386 FromVector(p.vData[0], *this);
398 CCrossChainExport::CCrossChainExport(const CTransaction &tx, int32_t *pCCXOutputNum)
400 int32_t _ccxOutputNum = 0;
401 int32_t &ccxOutputNum = pCCXOutputNum ? *pCCXOutputNum : _ccxOutputNum;
403 for (int i = 0; i < tx.vout.size(); i++)
406 if (tx.vout[i].scriptPubKey.IsPayToCryptoCondition(p) &&
408 p.evalCode == EVAL_CROSSCHAIN_EXPORT)
410 FromVector(p.vData[0], *this);
417 CCurrencyDefinition::CCurrencyDefinition(const CScript &scriptPubKey)
419 nVersion = PBAAS_VERSION_INVALID;
421 if (scriptPubKey.IsPayToCryptoCondition(p) && p.IsValid())
423 if (p.evalCode == EVAL_CURRENCY_DEFINITION)
425 FromVector(p.vData[0], *this);
430 std::vector<CCurrencyDefinition> CCurrencyDefinition::GetCurrencyDefinitions(const CTransaction &tx)
432 std::vector<CCurrencyDefinition> retVal;
433 for (auto &out : tx.vout)
435 CCurrencyDefinition oneCur = CCurrencyDefinition(out.scriptPubKey);
436 if (oneCur.IsValid())
438 retVal.push_back(oneCur);
444 #define _ASSETCHAINS_TIMELOCKOFF 0xffffffffffffffff
445 extern uint64_t ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_TIMEUNLOCKFROM, ASSETCHAINS_TIMEUNLOCKTO;
446 extern int64_t ASSETCHAINS_SUPPLY, ASSETCHAINS_REWARD[3], ASSETCHAINS_DECAY[3], ASSETCHAINS_HALVING[3], ASSETCHAINS_ENDSUBSIDY[3], ASSETCHAINS_ERAOPTIONS[3];
447 extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK, ASSETCHAINS_LWMAPOS;
448 extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA;
449 extern std::string VERUS_CHAINNAME;
450 extern uint160 VERUS_CHAINID;
452 // ensures that the chain definition is valid and that there are no other definitions of the same name
453 // that have been confirmed.
454 bool ValidateChainDefinition(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
456 // the chain definition output can be spent when the chain is at the end of its life and only then
461 // ensures that the chain definition is valid and that there are no other definitions of the same name
462 // that have been confirmed.
463 bool CheckChainDefinitionOutputs(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn)
465 // checked before a chain definition output script is accepted as a valid transaction
467 // basics - we need a chain definition transaction to kick off a PBaaS chain. it must have:
468 // 1) valid chain definition output with parameters in proper ranges and no duplicate name
469 // 2) notarization output with conformant values
470 // 3) finalization output
471 // 3) notarization funding
474 // get the source transaction
477 if (!GetTransaction(tx.vin[nIn].prevout.hash, thisTx, blkHash))
479 LogPrintf("failed to retrieve transaction %s\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
483 std::vector<CCurrencyDefinition> chainDefs = CCurrencyDefinition::GetCurrencyDefinitions(thisTx);
484 CPBaaSNotarization notarization(thisTx);
485 CTransactionFinalization finalization(thisTx);
486 bool isVerusActive = IsVerusActive();
488 if (!notarization.IsValid() || !finalization.IsValid())
490 LogPrintf("transaction specified, %s, must have valid notarization, and finaization outputs\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
494 std::set<uint160> allCurrencyIDs;
495 for (auto &curPair : ConnectedChains.ReserveCurrencies())
497 allCurrencyIDs.insert(curPair.first);
499 allCurrencyIDs.insert(ConnectedChains.ThisChain().GetID());
502 allCurrencyIDs.insert(ConnectedChains.notaryChain.GetID());
505 bool isCoinbase = thisTx.IsCoinBase();
506 bool isVerified = false;
507 CIdentity activatedID(thisTx);
509 // currency definitions can be valid as follows:
510 // 1. original definition in a transaction that simultaneously sets the active currency bit on the identity of the same
512 // 2. outputs of a coinbase transaction in block 1 that defines the parent currency, new currency, and any reserve currencies
513 // 3. currency import from the defining chain of the currency, which has not been implemented as of this comment
514 if (activatedID.IsValid() &&
515 activatedID.HasActiveCurrency() &&
516 chainDefs.size() == 1 &&
517 activatedID.parent == ASSETCHAINS_CHAINID &&
518 activatedID.GetID() == chainDefs[0].GetID())
522 else if (isCoinbase && chainDefs.size() >= 1 && !isVerusActive)
525 CScript expect = CScript() << height1;
526 opcodetype opcode = (opcodetype)*expect.begin();
528 if (opcode >= OP_1 && opcode <= OP_16)
530 isVerified = (thisTx.vin[0].scriptSig.size() >= 1 && CScript::DecodeOP_N(opcode) == height1) ||
531 (thisTx.vin[0].scriptSig.size() >= 2 && thisTx.vin[0].scriptSig[0] == OP_PUSHDATA1 && (int)thisTx.vin[0].scriptSig[1] == height1);
535 isVerified = thisTx.vin[0].scriptSig.size() >= expect.size() && std::equal(expect.begin(), expect.end(), thisTx.vin[0].scriptSig.begin());
538 for (auto &chainDef : chainDefs)
540 uint160 chainID = chainDef.GetID();
541 if (!chainDef.IsValid())
543 LogPrintf("transaction specified, %s, must not contain invalid chain definitions\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
546 if (!allCurrencyIDs.count(chainID))
548 LogPrintf("transaction specified, %s, must not contain invalid chain definitions\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
551 allCurrencyIDs.erase(chainID);
553 if (allCurrencyIDs.size())
555 LogPrintf("transaction specified, %s, does not contain all required chain definitions\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
563 CCurrencyValueMap CCrossChainExport::CalculateExportFee(const CCurrencyValueMap &fees, int numIn)
565 CCurrencyValueMap retVal;
567 if (numIn > MAX_EXPORT_INPUTS)
571 static const arith_uint256 satoshis(100000000);
573 arith_uint256 ratio(50000000 + ((25000000 / MAX_EXPORT_INPUTS) * (numIn - 1)));
575 for (auto &feePair : fees.valueMap)
577 retVal.valueMap[feePair.first] = (((arith_uint256(feePair.second) * ratio)) / satoshis).GetLow64();
582 CCurrencyValueMap CCrossChainExport::CalculateExportFee() const
584 return CalculateExportFee(totalFees, numInputs);
587 CCurrencyValueMap CCrossChainExport::CalculateImportFee() const
589 CCurrencyValueMap retVal;
591 for (auto &feePair : CalculateExportFee().valueMap)
593 CAmount feeAmount = feePair.second;
594 auto it = totalFees.valueMap.find(feePair.first);
595 retVal.valueMap[feePair.first] = (it != totalFees.valueMap.end() ? it->second : 0) - feeAmount;
600 bool CConnectedChains::RemoveMergedBlock(uint160 chainID)
603 LOCK(cs_mergemining);
605 //printf("RemoveMergedBlock ID: %s\n", chainID.GetHex().c_str());
607 auto chainIt = mergeMinedChains.find(chainID);
608 if (chainIt != mergeMinedChains.end())
610 arith_uint256 target;
611 target.SetCompact(chainIt->second.block.nBits);
612 for (auto removeRange = mergeMinedTargets.equal_range(target); removeRange.first != removeRange.second; removeRange.first++)
614 // make sure we don't just match by target
615 if (removeRange.first->second->GetID() == chainID)
617 mergeMinedTargets.erase(removeRange.first);
621 mergeMinedChains.erase(chainID);
622 dirty = retval = true;
624 // if we get to 0, give the thread a kick to stop waiting for mining
625 //if (!mergeMinedChains.size())
627 // sem_submitthread.post();
633 // remove merge mined chains added and not updated since a specific time
634 void CConnectedChains::PruneOldChains(uint32_t pruneBefore)
636 vector<uint160> toRemove;
638 LOCK(cs_mergemining);
639 for (auto blkData : mergeMinedChains)
641 if (blkData.second.block.nTime < pruneBefore)
643 toRemove.push_back(blkData.first);
647 for (auto id : toRemove)
649 //printf("Pruning chainID: %s\n", id.GetHex().c_str());
650 RemoveMergedBlock(id);
654 // adds or updates merge mined blocks
655 // returns false if failed to add
656 bool CConnectedChains::AddMergedBlock(CPBaaSMergeMinedChainData &blkData)
658 // determine if we should replace one or add to the merge mine vector
660 LOCK(cs_mergemining);
662 arith_uint256 target;
663 uint160 cID = blkData.GetID();
664 auto it = mergeMinedChains.find(cID);
665 if (it != mergeMinedChains.end())
667 RemoveMergedBlock(cID); // remove it if already there
669 target.SetCompact(blkData.block.nBits);
671 //printf("AddMergedBlock name: %s, ID: %s\n", blkData.chainDefinition.name.c_str(), cID.GetHex().c_str());
673 mergeMinedTargets.insert(make_pair(target, &(mergeMinedChains.insert(make_pair(cID, blkData)).first->second)));
679 bool CConnectedChains::GetChainInfo(uint160 chainID, CRPCChainData &rpcChainData)
682 LOCK(cs_mergemining);
683 auto chainIt = mergeMinedChains.find(chainID);
684 if (chainIt != mergeMinedChains.end())
686 rpcChainData = (CRPCChainData)chainIt->second;
693 // this returns a pointer to the data without copy and assumes the lock is held
694 CPBaaSMergeMinedChainData *CConnectedChains::GetChainInfo(uint160 chainID)
697 auto chainIt = mergeMinedChains.find(chainID);
698 if (chainIt != mergeMinedChains.end())
700 return &chainIt->second;
706 void CConnectedChains::QueueNewBlockHeader(CBlockHeader &bh)
708 //printf("QueueNewBlockHeader %s\n", bh.GetHash().GetHex().c_str());
710 LOCK(cs_mergemining);
712 qualifiedHeaders[UintToArith256(bh.GetHash())] = bh;
714 sem_submitthread.post();
717 void CConnectedChains::CheckImports()
719 sem_submitthread.post();
722 // get the latest block header and submit one block at a time, returning after there are no more
723 // matching blocks to be found
724 vector<pair<string, UniValue>> CConnectedChains::SubmitQualifiedBlocks()
726 std::set<uint160> inHeader;
727 bool submissionFound;
728 CPBaaSMergeMinedChainData chainData;
729 vector<pair<string, UniValue>> results;
732 arith_uint256 lastHash;
733 CPBaaSBlockHeader pbh;
737 submissionFound = false;
739 LOCK(cs_mergemining);
740 // attempt to submit with the lowest hash answers first to increase the likelihood of submitting
741 // common, merge mined headers for notarization, drop out on any submission
742 for (auto headerIt = qualifiedHeaders.begin(); !submissionFound && headerIt != qualifiedHeaders.end(); headerIt = qualifiedHeaders.begin())
744 // add the PBaaS chain ids from this header to a set for search
745 for (uint32_t i = 0; headerIt->second.GetPBaaSHeader(pbh, i); i++)
747 inHeader.insert(pbh.chainID);
751 // now look through all targets that are equal to or above the hash of this header
752 for (auto chainIt = mergeMinedTargets.lower_bound(headerIt->first); !submissionFound && chainIt != mergeMinedTargets.end(); chainIt++)
754 chainID = chainIt->second->GetID();
755 if (inHeader.count(chainID))
757 // first, check that the winning header matches the block that is there
758 CPBaaSPreHeader preHeader(chainIt->second->block);
759 preHeader.SetBlockData(headerIt->second);
761 // check if the block header matches the block's specific data, only then can we create a submission from this block
762 if (headerIt->second.CheckNonCanonicalData(chainID))
764 // save block as is, remove the block from merged headers, replace header, and submit
765 chainData = *chainIt->second;
767 *(CBlockHeader *)&chainData.block = headerIt->second;
769 submissionFound = true;
771 //else // not an error condition. code is here for debugging
773 // printf("Mismatch in non-canonical data for chain %s\n", chainIt->second->chainDefinition.name.c_str());
776 //else // not an error condition. code is here for debugging
778 // printf("Not found in header %s\n", chainIt->second->chainDefinition.name.c_str());
782 // if this header matched no block, discard and move to the next, otherwise, we'll drop through
785 // once it is going to be submitted, remove block from this chain until a new one is added again
786 RemoveMergedBlock(chainID);
791 qualifiedHeaders.erase(headerIt);
797 // submit one block and loop again. this approach allows multiple threads
798 // to collectively empty the submission queue, mitigating the impact of
799 // any one stalled daemon
800 UniValue submitParams(UniValue::VARR);
801 submitParams.push_back(EncodeHexBlk(chainData.block));
802 UniValue result, error;
805 result = RPCCall("submitblock", submitParams, chainData.rpcUserPass, chainData.rpcPort, chainData.rpcHost);
806 result = find_value(result, "result");
807 error = find_value(result, "error");
811 result = UniValue(e.what());
813 results.push_back(make_pair(chainData.chainDefinition.name, result));
814 if (result.isStr() || !error.isNull())
816 printf("Error submitting block to %s chain: %s\n", chainData.chainDefinition.name.c_str(), result.isStr() ? result.get_str().c_str() : error.get_str().c_str());
820 printf("Successfully submitted block to %s chain\n", chainData.chainDefinition.name.c_str());
823 } while (submissionFound);
827 // add all merge mined chain PBaaS headers into the blockheader and return the easiest nBits target in the header
828 uint32_t CConnectedChains::CombineBlocks(CBlockHeader &bh)
830 vector<uint160> inHeader;
831 vector<UniValue> toCombine;
832 arith_uint256 blkHash = UintToArith256(bh.GetHash());
833 arith_uint256 target(0);
835 CPBaaSBlockHeader pbh;
838 LOCK(cs_mergemining);
840 CPBaaSSolutionDescriptor descr = CVerusSolutionVector::solutionTools.GetDescriptor(bh.nSolution);
842 for (uint32_t i = 0; i < descr.numPBaaSHeaders; i++)
844 if (bh.GetPBaaSHeader(pbh, i))
846 inHeader.push_back(pbh.chainID);
850 // loop through the existing PBaaS chain ids in the header
851 // remove any that are not either this Chain ID or in our local collection and then add all that are present
852 for (uint32_t i = 0; i < inHeader.size(); i++)
854 auto it = mergeMinedChains.find(inHeader[i]);
855 if (inHeader[i] != ASSETCHAINS_CHAINID && (it == mergeMinedChains.end()))
857 bh.DeletePBaaSHeader(i);
861 for (auto chain : mergeMinedChains)
863 // get the native PBaaS header for each chain and put it into the
864 // header we are given
865 // it must have itself in as a PBaaS header
866 uint160 cid = chain.second.GetID();
867 if (chain.second.block.GetPBaaSHeader(pbh, cid) != -1)
869 if (!bh.AddUpdatePBaaSHeader(pbh))
871 LogPrintf("Failure to add PBaaS block header for %s chain\n", chain.second.chainDefinition.name.c_str());
877 t.SetCompact(chain.second.block.nBits);
886 LogPrintf("Merge mined block for %s does not contain PBaaS information\n", chain.second.chainDefinition.name.c_str());
892 return target.GetCompact();
895 bool CConnectedChains::IsVerusPBaaSAvailable()
897 return notaryChainVersion >= "0.8.0";
900 extern string PBAAS_HOST, PBAAS_USERPASS;
901 extern int32_t PBAAS_PORT;
902 bool CConnectedChains::CheckVerusPBaaSAvailable(UniValue &chainInfoUni, UniValue &chainDefUni)
904 if (chainInfoUni.isObject() && chainDefUni.isObject())
906 UniValue uniVer = find_value(chainInfoUni, "VRSCversion");
909 LOCK(cs_mergemining);
910 notaryChainVersion = uni_get_str(uniVer);
911 notaryChainHeight = uni_get_int(find_value(chainInfoUni, "blocks"));
912 CCurrencyDefinition chainDef(chainDefUni);
913 notaryChain = CRPCChainData(chainDef, PBAAS_HOST, PBAAS_PORT, PBAAS_USERPASS);
916 return IsVerusPBaaSAvailable();
919 uint32_t CConnectedChains::NotaryChainHeight()
921 LOCK(cs_mergemining);
922 return notaryChainHeight;
925 bool CConnectedChains::CheckVerusPBaaSAvailable()
929 notaryChainVersion = "";
933 // if this is a PBaaS chain, poll for presence of Verus / root chain and current Verus block and version number
934 // tolerate only 15 second timeout
935 UniValue chainInfo, chainDef;
938 UniValue params(UniValue::VARR);
939 chainInfo = find_value(RPCCallRoot("getinfo", params), "result");
940 if (!chainInfo.isNull())
942 params.push_back(VERUS_CHAINNAME);
943 chainDef = find_value(RPCCallRoot("getcurrency", params), "result");
945 if (!chainDef.isNull() && CheckVerusPBaaSAvailable(chainInfo, chainDef))
947 // if we have not past block 1 yet, store the best known update of our current state
948 if ((!chainActive.LastTip() || !chainActive.LastTip()->GetHeight()))
950 bool success = false;
952 params.push_back(EncodeDestination(CIdentityID(thisChain.GetID())));
953 chainDef = find_value(RPCCallRoot("getcurrency", params), "result");
954 if (!chainDef.isNull())
956 CCurrencyDefinition currencyDef(chainDef);
957 if (currencyDef.IsValid())
959 thisChain = currencyDef;
960 if (NotaryChainHeight() >= thisChain.startBlock)
962 readyToStart = true; // this only gates mining of block one, to be sure we have the latest definition
972 } catch (exception e)
974 LogPrintf("%s: Error communicating with %s chain\n", __func__, VERUS_CHAINNAME);
977 notaryChainVersion = "";
981 int CConnectedChains::GetThisChainPort() const
985 for (auto node : defaultPeerNodes)
987 SplitHostPort(node.networkAddress, port, host);
996 CCoinbaseCurrencyState CConnectedChains::GetCurrencyState(CCurrencyDefinition &curDef, int32_t height, int32_t curDefHeight)
998 uint160 chainID = curDef.GetID();
999 CCoinbaseCurrencyState currencyState;
1000 std::vector<CAddressIndexDbEntry> notarizationIndex;
1002 if (chainID == ASSETCHAINS_CHAINID)
1005 if (IsVerusActive() ||
1006 CConstVerusSolutionVector::activationHeight.ActiveVersion(height) < CActivationHeight::ACTIVATE_PBAAS ||
1008 height > chainActive.Height() ||
1009 !chainActive[height] ||
1010 !ReadBlockFromDisk(block, chainActive[height], Params().GetConsensus()) ||
1011 !(currencyState = CCoinbaseCurrencyState(block.vtx[0])).IsValid())
1013 currencyState = GetInitialCurrencyState(thisChain);
1016 // if this is a token on this chain, it will be simply notarized
1017 else if (curDef.systemID == ASSETCHAINS_CHAINID)
1019 // get the last unspent notarization for this currency, which is valid by definition for a token
1020 CPBaaSNotarization notarization;
1021 if (notarization.GetLastNotarization(chainID, EVAL_ACCEPTEDNOTARIZATION, curDefHeight, height))
1023 currencyState = notarization.currencyState;
1024 currencyState.ClearForNextBlock();
1026 // if notarization is earlier than start block, get the transactions between this notarization and
1027 // current height to add to currency totals
1028 if (notarization.notarizationHeight < curDef.startBlock)
1030 // get chain transfers that should apply before the start block
1031 // until there is a post-start block notarization, we always consider the
1032 // currency state to be up to just before the start block
1033 std::multimap<uint160, std::pair<CInputDescriptor, CReserveTransfer>> unspentTransfers;
1034 if (GetChainTransfers(unspentTransfers, chainID, notarization.notarizationHeight,
1035 height < curDef.startBlock ? height : curDef.startBlock - 1))
1037 // at this point, all pre-allocation, minted, and pre-converted currency are included
1038 // in the currency state before final notarization
1039 std::map<uint160, int32_t> currencyIndexes = currencyState.GetReserveMap();
1040 if (curDef.IsFractional())
1042 currencyState.supply = curDef.initialFractionalSupply;
1046 // supply is determined by purchases * current conversion rate
1047 currencyState.supply = currencyState.initialSupply;
1050 for (auto &transfer : unspentTransfers)
1052 if (transfer.second.second.flags & CReserveTransfer::PRECONVERT)
1054 CAmount conversionFee = CReserveTransactionDescriptor::CalculateConversionFee(transfer.second.second.nValue);
1056 currencyState.reserveIn[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue;
1057 curDef.preconverted[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue;
1058 if (curDef.IsFractional())
1060 currencyState.reserves[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue - conversionFee;
1064 currencyState.supply += CCurrencyState::ReserveToNativeRaw(transfer.second.second.nValue - conversionFee, currencyState.PriceInReserve(currencyIndexes[transfer.second.second.currencyID]));
1067 if (transfer.second.second.currencyID == curDef.systemID)
1069 currencyState.nativeConversionFees += conversionFee;
1070 currencyState.nativeFees += conversionFee + transfer.second.second.CalculateTransferFee(transfer.second.second.destination);
1074 currencyState.fees[currencyIndexes[transfer.second.second.currencyID]] +=
1075 conversionFee + transfer.second.second.CalculateTransferFee(transfer.second.second.destination);
1076 currencyState.conversionFees[currencyIndexes[transfer.second.second.currencyID]] += conversionFee;
1079 else if (transfer.second.second.flags & CReserveTransfer::PREALLOCATE)
1081 currencyState.emitted += transfer.second.second.nValue;
1084 currencyState.supply += currencyState.emitted;
1085 if (curDef.conversions.size() != curDef.currencies.size())
1087 curDef.conversions = std::vector<int64_t>(curDef.currencies.size());
1089 for (int i = 0; i < curDef.conversions.size(); i++)
1091 currencyState.conversionPrice[i] = curDef.conversions[i] = currencyState.PriceInReserve(i);
1099 CChainNotarizationData cnd;
1100 uint32_t ecode = IsVerusActive() ?
1101 EVAL_ACCEPTEDNOTARIZATION :
1102 (chainID == notaryChain.GetID() ? EVAL_EARNEDNOTARIZATION : EVAL_ACCEPTEDNOTARIZATION);
1103 if (GetNotarizationData(chainID, ecode, cnd))
1105 int32_t transfersFrom = curDefHeight;
1106 if (cnd.lastConfirmed != -1)
1108 transfersFrom = cnd.vtx[cnd.lastConfirmed].second.notarizationHeight;
1110 int32_t transfersUntil = cnd.lastConfirmed == -1 ? curDef.startBlock - 1 :
1111 (cnd.vtx[cnd.lastConfirmed].second.notarizationHeight < curDef.startBlock ?
1112 (height < curDef.startBlock ? height : curDef.startBlock - 1) :
1113 cnd.vtx[cnd.lastConfirmed].second.notarizationHeight);
1114 if (transfersUntil < curDef.startBlock)
1116 // get chain transfers that should apply before the start block
1117 // until there is a post-start block notarization, we always consider the
1118 // currency state to be up to just before the start block
1119 std::multimap<uint160, std::pair<CInputDescriptor, CReserveTransfer>> unspentTransfers;
1120 if (GetChainTransfers(unspentTransfers, chainID, transfersFrom, transfersUntil))
1122 // at this point, all pre-allocation, minted, and pre-converted currency are included
1123 // in the currency state before final notarization
1124 std::map<uint160, int32_t> currencyIndexes = currencyState.GetReserveMap();
1125 if (curDef.IsFractional())
1127 currencyState.supply = curDef.initialFractionalSupply;
1131 // supply is determined by purchases * current conversion rate
1132 currencyState.supply = currencyState.initialSupply;
1135 for (auto &transfer : unspentTransfers)
1137 if (transfer.second.second.flags & CReserveTransfer::PRECONVERT)
1139 CAmount conversionFee = CReserveTransactionDescriptor::CalculateConversionFee(transfer.second.second.nValue);
1141 currencyState.reserveIn[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue;
1142 curDef.preconverted[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue;
1143 if (curDef.IsFractional())
1145 currencyState.reserves[currencyIndexes[transfer.second.second.currencyID]] += transfer.second.second.nValue - conversionFee;
1149 currencyState.supply += CCurrencyState::ReserveToNativeRaw(transfer.second.second.nValue - conversionFee, currencyState.PriceInReserve(currencyIndexes[transfer.second.second.currencyID]));
1152 if (transfer.second.second.currencyID == curDef.systemID)
1154 currencyState.nativeConversionFees += conversionFee;
1155 currencyState.nativeFees += conversionFee + transfer.second.second.CalculateTransferFee(transfer.second.second.destination);
1159 currencyState.fees[currencyIndexes[transfer.second.second.currencyID]] +=
1160 conversionFee + transfer.second.second.CalculateTransferFee(transfer.second.second.destination);
1161 currencyState.conversionFees[currencyIndexes[transfer.second.second.currencyID]] += conversionFee;
1164 else if (transfer.second.second.flags & CReserveTransfer::PREALLOCATE)
1166 currencyState.emitted += transfer.second.second.nValue;
1169 currencyState.supply += currencyState.emitted;
1170 if (curDef.conversions.size() != curDef.currencies.size())
1172 curDef.conversions = std::vector<int64_t>(curDef.currencies.size());
1174 for (int i = 0; i < curDef.conversions.size(); i++)
1176 currencyState.conversionPrice[i] = curDef.conversions[i] = currencyState.PriceInReserve(i);
1182 std::pair<uint256, CPBaaSNotarization> notPair = cnd.lastConfirmed != -1 ? cnd.vtx[cnd.lastConfirmed] : cnd.vtx[cnd.forks[cnd.bestChain][0]];
1183 currencyState = notPair.second.currencyState;
1187 return currencyState;
1190 CCoinbaseCurrencyState CConnectedChains::GetCurrencyState(const uint160 ¤cyID, int32_t height)
1192 int32_t curDefHeight;
1193 CCurrencyDefinition curDef;
1194 if (GetCurrencyDefinition(currencyID, curDef, &curDefHeight))
1196 return GetCurrencyState(curDef, height, curDefHeight);
1200 LogPrintf("%s: currency %s:%s not found\n", __func__, currencyID.GetHex().c_str(), EncodeDestination(CIdentityID(currencyID)).c_str());
1201 printf("%s: currency %s:%s not found\n", __func__, currencyID.GetHex().c_str(), EncodeDestination(CIdentityID(currencyID)).c_str());
1203 return CCoinbaseCurrencyState();
1206 CCoinbaseCurrencyState CConnectedChains::GetCurrencyState(int32_t height)
1208 return GetCurrencyState(thisChain.GetID(), height);
1211 bool CConnectedChains::SetLatestMiningOutputs(const std::vector<pair<int, CScript>> &minerOutputs, CTxDestination &firstDestinationOut)
1213 LOCK(cs_mergemining);
1215 if (!minerOutputs.size() || !ExtractDestination(minerOutputs[0].second, firstDestinationOut))
1219 latestMiningOutputs = minerOutputs;
1220 latestDestination = firstDestinationOut;
1224 CCurrencyDefinition CConnectedChains::GetCachedCurrency(const uint160 ¤cyID)
1226 CCurrencyDefinition currencyDef;
1227 auto it = currencyDefCache.find(currencyID);
1228 if ((it != currencyDefCache.end() && !(currencyDef = it->second).IsValid()) ||
1229 (it == currencyDefCache.end() && !GetCurrencyDefinition(currencyID, currencyDef)))
1231 printf("%s: definition for transfer currency ID %s not found\n\n", __func__, EncodeDestination(CIdentityID(currencyID)).c_str());
1232 LogPrintf("%s: definition for transfer currency ID %s not found\n\n", __func__, EncodeDestination(CIdentityID(currencyID)).c_str());
1235 if (it == currencyDefCache.end())
1237 currencyDefCache[currencyID] = currencyDef;
1239 return currencyDefCache[currencyID];
1242 CCurrencyDefinition CConnectedChains::UpdateCachedCurrency(const uint160 ¤cyID, uint32_t height)
1244 // due to the main lock being taken on the thread that waits for transaction checks,
1245 // low level functions like this must be called either from a thread that holds LOCK(cs_main),
1246 // or script validation, where it is held either by this thread or one waiting for it.
1247 // in the long run, the daemon synchonrization model should be improved
1248 CCurrencyDefinition currencyDef = GetCachedCurrency(currencyID);
1249 CCoinbaseCurrencyState curState = GetCurrencyState(currencyDef, height);
1250 currencyDefCache[currencyID] = currencyDef;
1254 void CConnectedChains::AggregateChainTransfers(const CTxDestination &feeOutput, uint32_t nHeight)
1256 // all chains aggregate reserve transfer transactions, so aggregate and add all necessary export transactions to the mem pool
1263 std::multimap<uint160, std::pair<CInputDescriptor, CReserveTransfer>> transferOutputs;
1267 uint160 thisChainID = ConnectedChains.ThisChain().GetID();
1269 // get all available transfer outputs to aggregate into export transactions
1270 if (GetUnspentChainTransfers(transferOutputs))
1272 if (!transferOutputs.size())
1277 std::vector<pair<CInputDescriptor, CReserveTransfer>> txInputs;
1278 uint160 bookEnd({uint160(ParseHex("ffffffffffffffffffffffffffffffffffffffff"))});
1279 uint160 lastChain = bookEnd;
1280 transferOutputs.insert(std::make_pair(bookEnd, std::make_pair(CInputDescriptor(), CReserveTransfer())));
1281 CCurrencyDefinition lastChainDef;
1283 for (auto &output : transferOutputs)
1285 CCurrencyDefinition sourceDef, destDef, systemDef;
1287 if (output.first != bookEnd)
1289 if (!output.second.second.IsValid())
1291 printf("%s: invalid reserve transfer in index for currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.currencyID)).c_str());
1292 LogPrintf("%s: invalid reserve transfer in index for currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.currencyID)).c_str());
1296 sourceDef = GetCachedCurrency(output.second.second.currencyID);
1297 destDef = GetCachedCurrency(output.second.second.destCurrencyID);
1298 systemDef = GetCachedCurrency(destDef.systemID);
1300 if (!sourceDef.IsValid())
1302 printf("%s: cannot find source currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.currencyID)).c_str());
1303 LogPrintf("%s: cannot find source currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.currencyID)).c_str());
1306 if (!destDef.IsValid())
1308 printf("%s: cannot find destination currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.destCurrencyID)).c_str());
1309 LogPrintf("%s: cannot find destination currency %s\n", __func__, EncodeDestination(CIdentityID(output.second.second.destCurrencyID)).c_str());
1312 if (!systemDef.IsValid())
1314 printf("%s: cannot find destination system definition %s\n", __func__, EncodeDestination(CIdentityID(destDef.systemID)).c_str());
1315 LogPrintf("%s: cannot find destination system definition %s\n", __func__, EncodeDestination(CIdentityID(destDef.systemID)).c_str());
1319 // if destination is a token on the current chain, consider it its own system
1320 if (destDef.systemID == thisChainID)
1322 systemDef = destDef;
1326 // get chain target and see if it is the same
1327 if (lastChain == bookEnd || output.first == lastChain)
1329 txInputs.push_back(output.second);
1333 // when we get here, we have a consecutive number of transfer outputs to consume in txInputs
1334 // we need an unspent export output to export, or use the last one of it is an export to the same
1336 std::multimap<uint160, pair<int, CInputDescriptor>> exportOutputs;
1337 lastChainDef = UpdateCachedCurrency(lastChain, nHeight);
1339 if (GetUnspentChainExports(lastChain, exportOutputs) && exportOutputs.size())
1341 auto &lastExport = *exportOutputs.begin();
1342 bool oneFullSize = txInputs.size() >= CCrossChainExport::MIN_INPUTS;
1344 if (((nHeight - lastExport.second.first) >= CCrossChainExport::MIN_BLOCKS) || oneFullSize)
1346 boost::optional<CTransaction> oneExport;
1348 // make one or more transactions that spends the last export and all possible cross chain transfers
1349 while (txInputs.size())
1351 TransactionBuilder tb(Params().GetConsensus(), nHeight);
1353 int inputsLeft = txInputs.size();
1354 int numInputs = inputsLeft > CCrossChainExport::MAX_EXPORT_INPUTS ? CCrossChainExport::MAX_EXPORT_INPUTS : inputsLeft;
1356 if (numInputs > CCrossChainExport::MAX_EXPORT_INPUTS)
1358 numInputs = CCrossChainExport::MAX_EXPORT_INPUTS;
1360 inputsLeft = txInputs.size() - numInputs;
1362 // if we have already made one and don't have enough to make another
1363 // without going under the input minimum, wait until next time for the others
1364 if (numInputs > 0 && numInputs < CCrossChainExport::MIN_INPUTS && oneFullSize)
1369 // each time through, we make one export transaction with the remainder or a subset of the
1370 // reserve transfer inputs. inputs can be:
1371 // 1. transfers of reserve for fractional reserve chains
1372 // 2. pre-conversions for pre-launch participation in the premine
1373 // 3. reserve market conversions to send between Verus and a fractional reserve chain and always output the native coin
1375 // If we are on the Verus chain, all inputs will include native coins. On a PBaaS chain, inputs can either be native
1376 // or reserve token inputs.
1378 // On the Verus chain, total native amount, minus the fee, must be sent to the reserve address of the specific chain
1379 // as reserve deposit with native coin equivalent. Pre-conversions and conversions will be realized on the PBaaS chain
1380 // as part of the import process
1382 // If we are on the PBaaS chain, conversions must happen before coins are sent this way back to the reserve chain.
1383 // Verus reserve outputs can be directly aggregated and transferred, with fees paid through conversion and the
1384 // remaining Verus reserve coin will be burned on the PBaaS chain as spending it is allowed, once notarized, on the
1387 CCurrencyValueMap totalTxFees;
1388 CCurrencyValueMap totalAmounts;
1389 CAmount exportOutVal = 0;
1390 std::vector<CBaseChainObject *> chainObjects;
1392 // first, we must add the export output from the current export thread to this chain
1393 if (oneExport.is_initialized())
1395 // spend the last export transaction output
1396 CTransaction &tx = oneExport.get();
1399 for (j = 0; j < tx.vout.size(); j++)
1401 if (::IsPayToCryptoCondition(tx.vout[j].scriptPubKey, p) && p.evalCode == EVAL_CROSSCHAIN_EXPORT)
1407 // had to be found and valid if we made the tx
1408 assert(j < tx.vout.size() && p.IsValid());
1410 tb.AddTransparentInput(COutPoint(tx.GetHash(), j), tx.vout[j].scriptPubKey, tx.vout[j].nValue);
1411 exportOutVal = tx.vout[j].nValue;
1415 // spend the recentExportIt output
1416 tb.AddTransparentInput(lastExport.second.second.txIn.prevout, lastExport.second.second.scriptPubKey, lastExport.second.second.nValue);
1417 exportOutVal = lastExport.second.second.nValue;
1421 std::vector<int> toRemove;
1423 for (int j = 0; j < numInputs; j++)
1425 tb.AddTransparentInput(txInputs[j].first.txIn.prevout, txInputs[j].first.scriptPubKey, txInputs[j].first.nValue, txInputs[j].first.txIn.nSequence);
1426 CCurrencyValueMap newTransferInput = txInputs[j].first.scriptPubKey.ReserveOutValue();
1427 newTransferInput.valueMap[ASSETCHAINS_CHAINID] = txInputs[j].first.nValue;
1429 // TODO: make fee currency calculation more flexible on conversion
1430 // rules should be pay fee in native currency of destination system
1431 // if source is same currency
1432 CCurrencyValueMap newTransferOutput;
1433 bool isMint = (txInputs[j].second.flags & (CReserveTransfer::PREALLOCATE | CReserveTransfer::MINT_CURRENCY));
1436 newTransferOutput.valueMap[txInputs[j].second.currencyID] = txInputs[j].second.nFees;
1440 newTransferOutput.valueMap[txInputs[j].second.currencyID] = txInputs[j].second.nValue + txInputs[j].second.nFees;
1443 //printf("input:\n%s\n", newTransferInput.ToUniValue().write().c_str());
1444 //printf("output:\n%s\n", newTransferOutput.ToUniValue().write().c_str());
1446 if ((newTransferInput - newTransferOutput).HasNegative())
1448 // if this transfer is invalid and claims to carry more funds than it does, we consume it since it won't properly verify as a transfer, and
1449 // it is too expensive to let it force evaluation repeatedly. this condition should not get by normal checks, but just in case, don't let it slow transfers
1450 // we should formalize this into a chain contribution or amount adjustment.
1451 printf("%s: transaction %s claims incorrect value:\n%s\nactual:\n%s\n", __func__,
1452 txInputs[j].first.txIn.prevout.hash.GetHex().c_str(),
1453 newTransferInput.ToUniValue().write().c_str(),
1454 newTransferOutput.ToUniValue().write().c_str());
1455 LogPrintf("%s: transaction %s claims incorrect value:\n%s\nactual:\n%s\n", __func__,
1456 txInputs[j].first.txIn.prevout.hash.GetHex().c_str(),
1457 newTransferInput.ToUniValue().write().c_str(),
1458 newTransferOutput.ToUniValue().write().c_str());
1459 toRemove.push_back(j);
1463 CAmount valueOut = isMint ? 0 : txInputs[j].second.nValue;
1464 CCurrencyValueMap newFees;
1465 totalTxFees += txInputs[j].second.CalculateFee(txInputs[j].second.flags, valueOut);
1466 totalAmounts += newTransferInput;
1467 chainObjects.push_back(new CChainObject<CReserveTransfer>(ObjTypeCode(txInputs[j].second), txInputs[j].second));
1471 // remove in reverse order so one removal does not affect the position of the next
1472 for (int j = toRemove.size() - 1; j >= 0; j--)
1474 txInputs.erase(txInputs.begin() + toRemove[j]);
1478 // this logic may cause us to create a tx that will get rejected, but we will never wait too long
1479 if (!numInputs || (oneFullSize && (nHeight - lastExport.second.first) < CCrossChainExport::MIN_BLOCKS && numInputs < CCrossChainExport::MIN_INPUTS))
1484 //printf("%s: total export amounts:\n%s\n", __func__, totalAmounts.ToUniValue().write().c_str());
1486 CCrossChainExport ccx(lastChain, numInputs, totalAmounts, totalTxFees);
1488 // make extra outputs for fees in each currency
1489 for (auto &outPair : ccx.CalculateExportFee().CanonicalMap().valueMap)
1491 CReserveTransfer feeOut(CReserveTransfer::VALID + CReserveTransfer::FEE_OUTPUT,
1492 outPair.first, outPair.second, 0, outPair.first, DestinationToTransferDestination(feeOutput));
1493 chainObjects.push_back(new CChainObject<CReserveTransfer>(ObjTypeCode(feeOut), feeOut));
1496 // do a preliminary check
1497 CReserveTransactionDescriptor rtxd;
1498 std::vector<CTxOut> vOutputs;
1499 CCoinbaseCurrencyState currencyState = GetInitialCurrencyState(lastChainDef);
1500 if (!currencyState.IsValid() ||
1501 !rtxd.AddReserveTransferImportOutputs(ConnectedChains.ThisChain().GetID(), lastChainDef, currencyState, chainObjects, vOutputs))
1503 DeleteOpRetObjects(chainObjects);
1505 printf("%s: failed to create valid exports\n", __func__);
1506 LogPrintf("%s: failed to create valid exports\n", __func__);
1509 printf("%s: failed to export outputs:\n", __func__);
1510 for (auto oneout : vOutputs)
1513 ScriptPubKeyToJSON(oneout.scriptPubKey, uniOut, false);
1514 printf("%s\n", uniOut.write(true, 2).c_str());
1520 CCcontract_info *cp;
1524 printf("%s: exported outputs:\n", __func__);
1525 for (auto &oneout : chainObjects)
1527 if (oneout->objectType == CHAINOBJ_RESERVETRANSFER)
1529 CReserveTransfer &rt = ((CChainObject<CReserveTransfer> *)(oneout))->object;
1530 printf("%s\n", rt.ToUniValue().write(true, 2).c_str());
1535 CScript opRet = StoreOpRetArray(chainObjects);
1536 DeleteOpRetObjects(chainObjects);
1538 // now send transferred currencies to a reserve deposit
1539 cp = CCinit(&CC, EVAL_RESERVE_DEPOSIT);
1541 for (auto &oneCurrencyOut : ccx.totalAmounts.valueMap)
1543 CCurrencyDefinition oneDef = currencyDefCache[oneCurrencyOut.first];
1545 // if the destination is the not the source currency, and
1546 // the destination is not another blockchain that controls the source currency, store in reserve
1547 if (!(oneCurrencyOut.first == lastChain ||
1548 (lastChainDef.systemID != ASSETCHAINS_CHAINID && oneDef.systemID == lastChainDef.systemID)))
1550 CAmount nativeOut = oneDef.GetID() == ASSETCHAINS_CHAINID ? oneCurrencyOut.second : 0;
1552 // send the entire amount to a reserve deposit output of the specific chain
1553 // we receive our fee on the other chain, when it comes back, or if a token,
1554 // when it gets imported back to the chain
1555 std::vector<CTxDestination> indexDests({CKeyID(lastChainDef.GetConditionID(EVAL_RESERVE_DEPOSIT)), CKeyID(lastChainDef.GetID())});
1556 std::vector<CTxDestination> dests({CPubKey(ParseHex(CC.CChexstr))});
1558 CTokenOutput ro = CTokenOutput(oneCurrencyOut.first, nativeOut ? 0 : oneCurrencyOut.second);
1559 tb.AddTransparentOutput(MakeMofNCCScript(CConditionObj<CTokenOutput>(EVAL_RESERVE_DEPOSIT, dests, 1, &ro), &indexDests),
1564 cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT);
1566 // send native amount of zero to a cross chain export output of the specific chain
1567 std::vector<CTxDestination> indexDests = std::vector<CTxDestination>({CKeyID(lastChainDef.GetConditionID(EVAL_CROSSCHAIN_EXPORT))});
1568 if (lastChainDef.systemID != ASSETCHAINS_CHAINID)
1570 indexDests.push_back(CKeyID(CCrossChainRPCData::GetConditionID(lastChainDef.systemID, EVAL_CROSSCHAIN_EXPORT)));
1572 std::vector<CTxDestination> dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr)).GetID()});
1574 tb.AddTransparentOutput(MakeMofNCCScript(CConditionObj<CCrossChainExport>(EVAL_CROSSCHAIN_EXPORT, dests, 1, &ccx), &indexDests),
1577 // when exports are confirmed as having been imported, they are finalized
1578 // until then, a finalization UTXO enables an index search to only find transactions
1579 // that have work to complete on this chain, or have not had their cross-chain import
1581 cp = CCinit(&CC, EVAL_FINALIZE_EXPORT);
1582 CTransactionFinalization finalization(0);
1584 //printf("%s: Finalizing export with index dest %s\n", __func__, EncodeDestination(CKeyID(CCrossChainRPCData::GetConditionID(lastChainDef.systemID, EVAL_FINALIZE_EXPORT))).c_str());
1586 indexDests = std::vector<CTxDestination>({CKeyID(CCrossChainRPCData::GetConditionID(lastChainDef.systemID, EVAL_FINALIZE_EXPORT))});
1587 dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr)).GetID()});
1588 tb.AddTransparentOutput(MakeMofNCCScript(CConditionObj<CTransactionFinalization>(EVAL_FINALIZE_EXPORT, dests, 1, &finalization), &indexDests), 0);
1594 UniValue uni(UniValue::VOBJ);
1595 TxToUniv(tb.mtx, uint256(), uni);
1596 printf("%s: about to send reserve deposits with tx:\n%s\n", __func__, uni.write(1,2).c_str());
1599 TransactionBuilderResult buildResult(tb.Build());
1601 if (!buildResult.IsError() && buildResult.IsTx())
1603 // replace the last one only if we have a valid new one
1604 CTransaction tx = buildResult.GetTxOrThrow();
1606 LOCK2(cs_main, mempool.cs);
1607 static int lastHeight = 0;
1608 // remove conflicts, so that we get in
1609 std::list<CTransaction> removed;
1610 mempool.removeConflicts(tx, removed);
1612 // add to mem pool, prioritize according to the fee we will get, and relay
1613 //printf("Created and signed export transaction %s\n", tx.GetHash().GetHex().c_str());
1614 //LogPrintf("Created and signed export transaction %s\n", tx.GetHash().GetHex().c_str());
1615 if (myAddtomempool(tx))
1617 uint256 hash = tx.GetHash();
1618 CAmount nativeExportFees = ccx.totalFees.valueMap[ASSETCHAINS_CHAINID];
1619 mempool.PrioritiseTransaction(hash, hash.GetHex(), (double)(nativeExportFees << 1), nativeExportFees);
1623 UniValue uni(UniValue::VOBJ);
1624 TxToUniv(tx, uint256(), uni);
1625 //printf("%s: created invalid transaction:\n%s\n", __func__, uni.write(1,2).c_str());
1626 LogPrintf("%s: created invalid transaction:\n%s\n", __func__, uni.write(1,2).c_str());
1632 // we can't do any more useful work for this chain if we failed here
1633 printf("Failed to create export transaction: %s\n", buildResult.GetError().c_str());
1634 LogPrintf("Failed to create export transaction: %s\n", buildResult.GetError().c_str());
1639 // erase the inputs we've attempted to spend
1640 txInputs.erase(txInputs.begin(), txInputs.begin() + numInputs);
1645 lastChain = output.first;
1652 void CConnectedChains::SignAndCommitImportTransactions(const CTransaction &lastImportTx, const std::vector<CTransaction> &transactions)
1654 int nHeight = chainActive.LastTip()->GetHeight();
1655 uint32_t consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus());
1656 LOCK2(cs_main, mempool.cs);
1658 uint256 lastHash, lastSignedHash;
1659 CCoinsViewCache view(pcoinsTip);
1661 // sign and commit the transactions
1662 for (auto &_tx : transactions)
1664 CMutableTransaction newTx(_tx);
1666 if (!lastHash.IsNull())
1668 //printf("last hash before signing: %s\n", lastHash.GetHex().c_str());
1669 for (auto &oneIn : newTx.vin)
1671 //printf("checking input with hash: %s\n", oneIn.prevout.hash.GetHex().c_str());
1672 if (oneIn.prevout.hash == lastHash)
1674 oneIn.prevout.hash = lastSignedHash;
1675 //printf("updated hash before signing: %s\n", lastSignedHash.GetHex().c_str());
1679 lastHash = _tx.GetHash();
1680 CTransaction tx = newTx;
1682 // sign the transaction and submit
1683 bool signSuccess = false;
1684 for (int i = 0; i < tx.vin.size(); i++)
1686 SignatureData sigdata;
1688 CScript outputScript;
1690 if (tx.vin[i].prevout.hash == lastImportTx.GetHash())
1692 value = lastImportTx.vout[tx.vin[i].prevout.n].nValue;
1693 outputScript = lastImportTx.vout[tx.vin[i].prevout.n].scriptPubKey;
1698 if (!view.GetCoins(tx.vin[i].prevout.hash, coins))
1700 fprintf(stderr,"%s: cannot get input coins from tx: %s, output: %d\n", __func__, tx.vin[i].prevout.hash.GetHex().c_str(), tx.vin[i].prevout.n);
1701 LogPrintf("%s: cannot get input coins from tx: %s, output: %d\n", __func__, tx.vin[i].prevout.hash.GetHex().c_str(), tx.vin[i].prevout.n);
1704 value = coins.vout[tx.vin[i].prevout.n].nValue;
1705 outputScript = coins.vout[tx.vin[i].prevout.n].scriptPubKey;
1708 signSuccess = ProduceSignature(TransactionSignatureCreator(nullptr, &tx, i, value, SIGHASH_ALL), outputScript, sigdata, consensusBranchId);
1712 fprintf(stderr,"%s: failure to sign transaction\n", __func__);
1713 LogPrintf("%s: failure to sign transaction\n", __func__);
1716 UpdateTransaction(newTx, i, sigdata);
1722 // push to local node and sync with wallets
1723 CValidationState state;
1724 bool fMissingInputs;
1725 CTransaction signedTx(newTx);
1728 //TxToJSON(tx, uint256(), jsonTX);
1729 //printf("signed transaction:\n%s\n", jsonTX.write(1, 2).c_str());
1731 if (!AcceptToMemoryPool(mempool, state, signedTx, false, &fMissingInputs)) {
1732 if (state.IsInvalid()) {
1733 fprintf(stderr,"%s: rejected by memory pool for %s\n", __func__, state.GetRejectReason().c_str());
1734 LogPrintf("%s: rejected by memory pool for %s\n", __func__, state.GetRejectReason().c_str());
1736 if (fMissingInputs) {
1737 fprintf(stderr,"%s: missing inputs\n", __func__);
1738 LogPrintf("%s: missing inputs\n", __func__);
1742 fprintf(stderr,"%s: rejected by memory pool for\n", __func__);
1743 LogPrintf("%s: rejected by memory pool for\n", __func__);
1750 UpdateCoins(signedTx, view, nHeight);
1751 lastSignedHash = signedTx.GetHash();
1761 CCurrencyValueMap CalculatePreconversions(const CCurrencyDefinition &chainDef, int32_t definitionHeight, CCurrencyValueMap &fees)
1763 // if we are getting information on the current chain, we assume that preconverted amounts have been
1764 // pre-calculated. otherwise, we will calculate them.
1765 CCurrencyValueMap retVal;
1766 if (chainDef.GetID() != ConnectedChains.ThisChain().GetID())
1768 std::multimap<uint160, pair<CInputDescriptor, CReserveTransfer>> transferInputs;
1769 CCurrencyValueMap preconvertedAmounts;
1771 if (GetChainTransfers(transferInputs, chainDef.GetID(), definitionHeight, chainDef.startBlock - 1, CReserveTransfer::PRECONVERT | CReserveTransfer::VALID))
1773 auto curMap = chainDef.GetCurrenciesMap();
1774 for (auto &transfer : transferInputs)
1776 if (!(transfer.second.second.flags & CReserveTransfer::PREALLOCATE) && curMap.count(transfer.second.second.currencyID))
1778 CAmount conversionFee = CReserveTransactionDescriptor::CalculateConversionFee(transfer.second.second.nValue);
1779 preconvertedAmounts.valueMap[transfer.second.second.currencyID] += (transfer.second.second.nValue - conversionFee);
1780 fees.valueMap[transfer.second.second.currencyID] += transfer.second.second.nFees + conversionFee;
1783 retVal = preconvertedAmounts;
1784 if (!chainDef.IsToken() && !(chainDef.ChainOptions() & chainDef.OPTION_FEESASRESERVE))
1792 retVal = CCurrencyValueMap(chainDef.currencies, chainDef.preconverted);
1797 // This creates a new token notarization input and output and attaches them to a new import transaction,
1798 // given the next export transaction about to be imported and its height
1799 bool CConnectedChains::NewImportNotarization(const CCurrencyDefinition &_curDef,
1801 const CTransaction &lastImportTx,
1802 uint32_t exportHeight,
1803 const CTransaction &exportTx,
1804 CMutableTransaction &mnewTx,
1805 CCoinbaseCurrencyState &newCurState)
1807 if (!_curDef.IsValid() || !_curDef.IsToken())
1809 LogPrintf("%s: cannot create import notarization for invalid or non-token currencies\n", __func__);
1813 uint160 currencyID = _curDef.GetID();
1815 CCurrencyDefinition curDef = _curDef;
1817 CPBaaSNotarization lastNotarization(lastImportTx);
1818 if (!lastNotarization.IsValid())
1820 LogPrintf("%s: error getting notarization transaction %s\n", __func__, lastImportTx.GetHash().GetHex().c_str());
1824 CCrossChainExport ccx(exportTx);
1827 LogPrintf("%s: invalid export transaction %s\n", __func__, lastImportTx.GetHash().GetHex().c_str());
1831 std::vector<CCurrencyDefinition> txCurrencies = CCurrencyDefinition::GetCurrencyDefinitions(lastImportTx);
1833 bool isDefinition = false;
1834 for (auto &oneCur : txCurrencies)
1836 if (oneCur.GetID() == currencyID)
1838 isDefinition = true;
1842 int32_t definitionHeight = exportHeight;
1843 CChainNotarizationData cnd;
1846 CTransaction dummyTx;
1849 if (!myGetTransaction(lastImportTx.GetHash(), dummyTx, blkHash) || blkHash.IsNull())
1851 LogPrintf("%s: invalid last import transaction for %s\n", __func__, curDef.name.c_str());
1854 definitionHeight = mapBlockIndex[blkHash]->GetHeight();
1856 else if (GetNotarizationData(curDef.GetID(), EVAL_ACCEPTEDNOTARIZATION, cnd) && cnd.vtx.size())
1858 lastNotarization = cnd.vtx[cnd.forks[cnd.bestChain].back()].second;
1862 LogPrintf("%s: cannot get last notarization for %s\n", __func__, curDef.name.c_str());
1867 CBlockIndex *pindex;
1868 CTxDestination notarizationID = VERUS_DEFAULTID.IsNull() ? CTxDestination(CIdentityID(currencyID)) : CTxDestination(VERUS_DEFAULTID);
1870 // if this is the first notarization after start, make the notarization and determine if we should
1874 bool refunding = false;
1876 pindex = chainActive[curDef.startBlock];
1878 // check if the chain is qualified for a refund
1879 CCurrencyValueMap minPreMap, preConvertedMap, fees;
1880 preConvertedMap = CalculatePreconversions(curDef, definitionHeight, fees).CanonicalMap();
1881 curDef.preconverted = preConvertedMap.AsCurrencyVector(curDef.currencies);
1883 CCoinbaseCurrencyState initialCur = GetInitialCurrencyState(curDef);
1884 newCurState = initialCur;
1886 if (curDef.minPreconvert.size() && curDef.minPreconvert.size() == curDef.currencies.size())
1888 minPreMap = CCurrencyValueMap(curDef.currencies, curDef.minPreconvert).CanonicalMap();
1891 if (minPreMap.valueMap.size() && preConvertedMap < minPreMap)
1893 // we force the supply to zero
1894 // in any case where there was a minimum participation,
1895 // the result of the supply cannot be zero, enabling us to easily determine that this
1896 // represents a failed launch
1897 newCurState.supply = 0;
1898 newCurState.SetRefunding(true);
1901 else if (curDef.IsFractional() &&
1902 exportTx.vout.size() &&
1903 exportTx.vout.back().scriptPubKey.IsOpReturn())
1905 // we are not refunding, and it is possible that we also have
1906 // normal conversions in addition to pre-conversions. add any conversions that may
1907 // be present into the new currency state
1908 CReserveTransactionDescriptor rtxd;
1909 std::vector<CBaseChainObject *> exportObjects;
1910 std::vector<CTxOut> vOutputs;
1912 exportObjects = RetrieveOpRetArray(exportTx.vout.back().scriptPubKey);
1914 bool isValidExport = rtxd.AddReserveTransferImportOutputs(currencyID, curDef, initialCur, exportObjects, vOutputs, &newCurState);
1915 DeleteOpRetObjects(exportObjects);
1918 LogPrintf("%s: invalid export opreturn for transaction %s\n", __func__, exportTx.GetHash().GetHex().c_str());
1925 pindex = chainActive.LastTip();
1928 LogPrintf("%s: invalid active chain\n", __func__);
1932 // this is not the first notarization, so the last notarization will let us know if this is a refund or not
1933 CCurrencyValueMap minPreMap;
1935 CCoinbaseCurrencyState initialCur = lastNotarization.currencyState;
1936 newCurState = initialCur;
1938 if (curDef.minPreconvert.size() && curDef.minPreconvert.size() == curDef.currencies.size())
1940 minPreMap = CCurrencyValueMap(curDef.currencies, curDef.minPreconvert).CanonicalMap();
1943 // we won't change currency state in notarizations after failure to launch, if success, recalculate as needed
1944 if (!(lastNotarization.currencyState.IsRefunding()))
1946 // calculate new currency state from this import
1947 // we are not refunding, and it is possible that we also have
1948 // normal conversions in addition to pre-conversions. add any conversions that may
1949 // be present into the new currency state
1950 CReserveTransactionDescriptor rtxd;
1951 std::vector<CBaseChainObject *> exportObjects;
1952 std::vector<CTxOut> vOutputs;
1954 exportObjects = RetrieveOpRetArray(exportTx.vout.back().scriptPubKey);
1956 bool isValidExport = rtxd.AddReserveTransferImportOutputs(currencyID, curDef, initialCur, exportObjects, vOutputs, &newCurState);
1957 DeleteOpRetObjects(exportObjects);
1960 LogPrintf("%s: invalid export opreturn for transaction %s\n", __func__, exportTx.GetHash().GetHex().c_str());
1966 uint256 lastImportTxHash = lastImportTx.GetHash();
1968 // now, add the initial notarization to the import tx
1969 // we will begin refund or import after notarization is accepted and returned by GetNotarizationData
1970 CPBaaSNotarization pbn = CPBaaSNotarization(curDef.notarizationProtocol,
1973 pindex->GetHeight(),
1974 chainActive.GetMMV().GetRoot(),
1975 chainActive.GetMMRNode(pindex->GetHeight()).hash,
1976 ArithToUint256(GetCompactPower(pindex->nNonce, pindex->nBits, pindex->nVersion)),
1979 lastNotarization.notarizationHeight,
1980 uint256(), 0, COpRetProof(), std::vector<CNodeData>());
1982 // create notarization output
1984 CCcontract_info *cp;
1986 std::vector<CTxDestination> dests;
1987 std::vector<CTxDestination> indexDests;
1989 // make the accepted notarization output
1990 cp = CCinit(&CC, EVAL_ACCEPTEDNOTARIZATION);
1992 if (curDef.notarizationProtocol == curDef.NOTARIZATION_NOTARY_CHAINID)
1994 dests = std::vector<CTxDestination>({CIdentityID(currencyID)});
1996 else if (curDef.notarizationProtocol == curDef.NOTARIZATION_AUTO)
1998 dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});
2004 indexDests = std::vector<CTxDestination>({CKeyID(curDef.GetConditionID(EVAL_ACCEPTEDNOTARIZATION))});
2005 mnewTx.vout.push_back(CTxOut(0, MakeMofNCCScript(CConditionObj<CPBaaSNotarization>(EVAL_ACCEPTEDNOTARIZATION, dests, 1, &pbn), &indexDests)));
2007 // make the finalization output
2008 cp = CCinit(&CC, EVAL_FINALIZE_NOTARIZATION);
2010 if (curDef.notarizationProtocol == curDef.NOTARIZATION_AUTO)
2012 dests = std::vector<CTxDestination>({CPubKey(ParseHex(CC.CChexstr))});
2015 // finish transaction by adding the prior input and finalization, sign, then put it in the mempool
2016 // all output for notarizing will be paid as mining fees, so there's no need to relay
2017 uint32_t confirmedOut, finalizeOut;
2018 if (!GetNotarizationAndFinalization(EVAL_ACCEPTEDNOTARIZATION, lastImportTx, pbn, &confirmedOut, &finalizeOut))
2020 printf("ERROR: could not find expected initial notarization for currency %s\n", curDef.name.c_str());
2024 mnewTx.vin.push_back(CTxIn(COutPoint(lastImportTxHash, confirmedOut)));
2025 mnewTx.vin.push_back(CTxIn(COutPoint(lastImportTxHash, finalizeOut)));
2027 // we need to store the input that we confirmed if we spent finalization outputs
2028 CTransactionFinalization nf(mnewTx.vin.size() - 1);
2030 indexDests = std::vector<CTxDestination>({CKeyID(curDef.GetConditionID(EVAL_FINALIZE_NOTARIZATION))});
2032 // update crypto condition with final notarization output data
2033 mnewTx.vout.push_back(CTxOut(0,
2034 MakeMofNCCScript(CConditionObj<CTransactionFinalization>(EVAL_FINALIZE_NOTARIZATION, dests, 1, &nf), &indexDests)));
2039 // process token related, local imports and exports
2040 void CConnectedChains::ProcessLocalImports()
2042 // first determine all export threads on the current chain that are valid to import
2043 std::multimap<uint160, std::pair<int, CInputDescriptor>> exportOutputs;
2044 std::multimap<uint160, CTransaction> importThreads;
2045 uint160 thisChainID = thisChain.GetID();
2047 LOCK2(cs_main, mempool.cs);
2048 uint32_t nHeight = chainActive.Height();
2050 // get all pending, local exports and put them into a map
2051 std::vector<std::pair<CAddressUnspentKey, CAddressUnspentValue>> unspentOutputs;
2052 std::map<uint160, std::pair<uint32_t, CTransaction>> currenciesToImport; // height of earliest tx
2053 CCurrencyDefinition oneCurrency;
2055 printf("%s: Searching for %s\n", __func__, EncodeDestination(CKeyID(ConnectedChains.ThisChain().GetConditionID(EVAL_FINALIZE_EXPORT))).c_str());
2056 if (GetAddressUnspent(ConnectedChains.ThisChain().GetConditionID(EVAL_FINALIZE_EXPORT), 1, unspentOutputs))
2058 CCrossChainExport ccx, ccxDummy;
2059 CTransaction txOut, txImport;
2060 CPartialTransactionProof lastExport;
2061 CCrossChainImport cci;
2063 for (auto &oneOut : unspentOutputs)
2066 if (oneOut.second.script.IsPayToCryptoCondition(p) &&
2068 p.evalCode == EVAL_FINALIZE_EXPORT &&
2070 CTransactionFinalization(p.vData[0]).IsValid() &&
2071 myGetTransaction(oneOut.first.txhash, txOut, blkHash) &&
2072 (ccx = CCrossChainExport(txOut)).IsValid() &&
2073 (oneCurrency = GetCachedCurrency(ccx.systemID)).IsValid() &&
2074 oneCurrency.startBlock <= nHeight &&
2075 !currenciesToImport.count(ccx.systemID) &&
2076 GetLastImport(ccx.systemID, txImport, lastExport, cci, ccxDummy))
2078 auto blockIt = mapBlockIndex.find(blkHash);
2079 if (blockIt != mapBlockIndex.end() && chainActive.Contains(blockIt->second))
2081 currenciesToImport.insert(make_pair(ccx.systemID, make_pair(blockIt->second->GetHeight(), txImport)));
2087 CMutableTransaction txTemplate = CreateNewContextualCMutableTransaction(Params().GetConsensus(), nHeight);
2088 for (auto &oneIT : currenciesToImport)
2090 std::vector<CTransaction> importTxes;
2091 int32_t importOutNum = 0;
2092 CCrossChainImport oneImportInput(oneIT.second.second, &importOutNum);
2093 if (oneImportInput.IsValid())
2095 std::vector<CAddressUnspentDbEntry> reserveDeposits;
2096 GetAddressUnspent(currencyDefCache[oneIT.first].GetConditionID(EVAL_RESERVE_DEPOSIT), CScript::P2CC, reserveDeposits);
2097 CCurrencyValueMap tokenImportAvailable;
2098 CAmount nativeImportAvailable = 0;
2099 for (auto &oneOut : reserveDeposits)
2101 nativeImportAvailable += oneOut.second.satoshis;
2102 tokenImportAvailable += oneOut.second.script.ReserveOutValue();
2103 //printf("nativeImportAvailable:%ld, tokenImportAvailable:%s\n", nativeImportAvailable, tokenImportAvailable.ToUniValue().write().c_str());
2105 nativeImportAvailable += oneIT.second.second.vout[importOutNum].nValue;
2106 tokenImportAvailable += oneIT.second.second.vout[importOutNum].ReserveOutValue();
2107 //printf("nativeImportAvailable:%ld, tokenImportAvailable:%s\n", nativeImportAvailable, tokenImportAvailable.ToUniValue().write().c_str());
2108 if (CreateLatestImports(currencyDefCache[oneIT.first], oneIT.second.second, txTemplate, CTransaction(), tokenImportAvailable, nativeImportAvailable, importTxes))
2110 // fund the first import transaction with all reserveDeposits
2111 // change amounts are passed through on the import thread
2113 // TODO: manage when this becomes to large by splitting reserve deposits over the
2115 if (importTxes.size())
2117 CMutableTransaction oneImport = importTxes[0];
2119 CCrossChainImport cci(importTxes[0], &outNum);
2122 // add the reserve deposit inputs to the first transaction
2123 // the outputs should have been automatically propagated through
2124 // fixup inputs if necessary
2125 if (reserveDeposits.size())
2127 UniValue jsonTX(UniValue::VOBJ);
2128 std::vector<uint256> prevHashes;
2130 for (int i = 0; i < importTxes.size() - 1; i++)
2132 prevHashes.push_back(importTxes[i].GetHash());
2135 // TODO - get reserve deposits from exports, not all at once, as in refunds
2136 for (auto &oneOut : reserveDeposits)
2138 oneImport.vin.push_back(CTxIn(oneOut.first.txhash, oneOut.first.index));
2141 importTxes[0] = oneImport;
2143 for (int i = 0; i < importTxes.size() - 1; i++)
2145 oneImport = importTxes[i + 1];
2146 for (auto &oneIn : oneImport.vin)
2148 if (oneIn.prevout.hash == prevHashes[i])
2150 //printf("updating hash before signing to new value\nold: %s\nnew: %s\n", oneIn.prevout.hash.GetHex().c_str(), importTxes[i].GetHash().GetHex().c_str());
2151 oneIn.prevout.hash = importTxes[i].GetHash();
2154 importTxes[i + 1] = oneImport;
2158 SignAndCommitImportTransactions(oneIT.second.second, importTxes);
2166 void CConnectedChains::SubmissionThread()
2170 arith_uint256 lastHash;
2171 int64_t lastImportTime = 0;
2172 uint32_t lastHeight = 0;
2174 // wait for something to check on, then submit blocks that should be submitted
2177 boost::this_thread::interruption_point();
2179 if (IsVerusActive())
2181 // blocks get discarded after no refresh for 5 minutes by default, probably should be more often
2182 //printf("SubmissionThread: pruning\n");
2183 PruneOldChains(GetAdjustedTime() - 300);
2184 bool submit = false;
2186 LOCK(cs_mergemining);
2187 if (mergeMinedChains.size() == 0 && qualifiedHeaders.size() != 0)
2189 qualifiedHeaders.clear();
2191 submit = qualifiedHeaders.size() != 0 && mergeMinedChains.size() != 0;
2193 //printf("SubmissionThread: qualifiedHeaders.size(): %lu, mergeMinedChains.size(): %lu\n", qualifiedHeaders.size(), mergeMinedChains.size());
2197 //printf("SubmissionThread: calling submit qualified blocks\n");
2198 SubmitQualifiedBlocks();
2201 ProcessLocalImports();
2205 sem_submitthread.wait();
2210 // if this is a PBaaS chain, poll for presence of Verus / root chain and current Verus block and version number
2211 if (CheckVerusPBaaSAvailable())
2213 // check to see if we have recently earned a block with an earned notarization that qualifies for
2214 // submitting an accepted notarization
2215 if (earnedNotarizationHeight)
2218 int32_t txIndex = -1, height;
2220 LOCK(cs_mergemining);
2221 if (earnedNotarizationHeight && earnedNotarizationHeight <= chainActive.Height() && earnedNotarizationBlock.GetHash() == chainActive[earnedNotarizationHeight]->GetBlockHash())
2223 blk = earnedNotarizationBlock;
2224 earnedNotarizationBlock = CBlock();
2225 txIndex = earnedNotarizationIndex;
2226 height = earnedNotarizationHeight;
2227 earnedNotarizationHeight = 0;
2233 //printf("SubmissionThread: testing notarization\n");
2234 CTransaction lastConfirmed;
2235 uint256 txId = CreateAcceptedNotarization(blk, txIndex, height);
2239 printf("Submitted notarization for acceptance: %s\n", txId.GetHex().c_str());
2240 LogPrintf("Submitted notarization for acceptance: %s\n", txId.GetHex().c_str());
2245 // every "n" seconds, look for imports to include in our blocks from the Verus chain
2246 if ((GetAdjustedTime() - lastImportTime) >= 30 || lastHeight < (chainActive.LastTip() ? 0 : chainActive.LastTip()->GetHeight()))
2248 lastImportTime = GetAdjustedTime();
2249 lastHeight = (chainActive.LastTip() ? 0 : chainActive.LastTip()->GetHeight());
2251 // see if our notary has a confirmed notarization for us
2252 UniValue params(UniValue::VARR);
2255 params.push_back(thisChain.name);
2259 result = find_value(RPCCallRoot("getlastimportin", params), "result");
2260 } catch (exception e)
2262 result = NullUniValue;
2265 if (!result.isNull())
2267 auto txUniStr = find_value(result, "lastimporttransaction");
2268 auto txLastConfirmedStr = find_value(result, "lastconfirmednotarization");
2269 auto txTemplateStr = find_value(result, "importtxtemplate");
2270 CAmount nativeImportAvailable = uni_get_int64(find_value(result, "nativeimportavailable"));
2271 CCurrencyValueMap tokenImportAvailable(find_value(params[0], "tokenimportavailable"));
2273 CTransaction lastImportTx, lastConfirmedTx, templateTx;
2275 if (txUniStr.isStr() && txTemplateStr.isStr() &&
2276 DecodeHexTx(lastImportTx, txUniStr.get_str()) &&
2277 DecodeHexTx(lastConfirmedTx, txLastConfirmedStr.get_str()) &&
2278 DecodeHexTx(templateTx, txTemplateStr.get_str()))
2280 std::vector<CTransaction> importTxes;
2281 if (CreateLatestImports(notaryChain.chainDefinition, lastImportTx, templateTx, lastConfirmedTx, tokenImportAvailable, nativeImportAvailable, importTxes))
2283 for (auto importTx : importTxes)
2287 params.push_back(EncodeHexTx(importTx));
2291 txResult = find_value(RPCCallRoot("signrawtransaction", params), "result");
2292 if (txResult.isObject() && !(txResult = find_value(txResult, "hex")).isNull() && txResult.isStr() && txResult.get_str().size())
2295 params.push_back(txResult);
2296 txResult = find_value(RPCCallRoot("sendrawtransaction", params), "result");
2300 txResult = NullUniValue;
2303 } catch (exception e)
2305 txResult = NullUniValue;
2308 if (txResult.isStr())
2310 testId.SetHex(txResult.get_str());
2312 if (testId.IsNull())
2324 boost::this_thread::interruption_point();
2327 catch (const boost::thread_interrupted&)
2329 LogPrintf("Verus merge mining thread terminated\n");
2333 void CConnectedChains::SubmissionThreadStub()
2335 ConnectedChains.SubmissionThread();
2338 void CConnectedChains::QueueEarnedNotarization(CBlock &blk, int32_t txIndex, int32_t height)
2340 // called after winning a block that contains an earned notarization
2341 // the earned notarization and its height are queued for processing by the submission thread
2342 // when a new notarization is added, older notarizations are removed, but all notarizations in the current height are
2344 LOCK(cs_mergemining);
2346 // we only care about the last
2347 earnedNotarizationHeight = height;
2348 earnedNotarizationBlock = blk;
2349 earnedNotarizationIndex = txIndex;
2352 bool IsChainDefinitionInput(const CScript &scriptSig)
2355 return scriptSig.IsPayToCryptoCondition(&ecode) && ecode == EVAL_CURRENCY_DEFINITION;