From ccc86839b9774934882fec4cbf3428003cf75fd5 Mon Sep 17 00:00:00 2001 From: Duke Date: Fri, 5 Jan 2024 12:48:35 -0800 Subject: [PATCH 01/22] More details about p2p encryption --- doc/overview.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/overview.md b/doc/overview.md index 334cfe84b..531f17294 100644 --- a/doc/overview.md +++ b/doc/overview.md @@ -14,7 +14,15 @@ Equihash (200,9) (ASIC) ## P2P -TLS1.3 via WolfSSL is enforced for all network connections as of v3.6.1 +TLS1.3 via WolfSSL is enforced for all network connections as of v3.6.1 . +Many ciphersuites are technically supported by TLS1.3 but many of them +are ancient, proved to be less secure than intended or likely backdoored. + +Hush P2P connections are randomly choosen between these two ciphersuites each +time a new connection to a peer is created: + + * `TLS_AES_256_GCM_SHA384` + * `TLS_CHACHA20_POLY1305_SHA256` ## RPC From a358acab0b1a589cebc45846ab54f7fa751c4820 Mon Sep 17 00:00:00 2001 From: Duke Date: Fri, 5 Jan 2024 13:02:36 -0800 Subject: [PATCH 02/22] More info about ciphersuites --- doc/overview.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/overview.md b/doc/overview.md index 531f17294..7468a2622 100644 --- a/doc/overview.md +++ b/doc/overview.md @@ -17,8 +17,9 @@ Equihash (200,9) (ASIC) TLS1.3 via WolfSSL is enforced for all network connections as of v3.6.1 . Many ciphersuites are technically supported by TLS1.3 but many of them are ancient, proved to be less secure than intended or likely backdoored. +Hush only uses what are widely considered to be the most secure and [best ciphersuites](https://ciphersuite.info/cs/). -Hush P2P connections are randomly choosen between these two ciphersuites each +New Hush P2P connections randomly choose between these two ciphersuites each time a new connection to a peer is created: * `TLS_AES_256_GCM_SHA384` From 4ed576a7e256abb46e15d8f3606dc30ac276d461 Mon Sep 17 00:00:00 2001 From: Duke Date: Fri, 5 Jan 2024 13:06:21 -0800 Subject: [PATCH 03/22] Explain the importance of p2p encryption --- doc/overview.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/doc/overview.md b/doc/overview.md index 7468a2622..27d991754 100644 --- a/doc/overview.md +++ b/doc/overview.md @@ -25,6 +25,14 @@ time a new connection to a peer is created: * `TLS_AES_256_GCM_SHA384` * `TLS_CHACHA20_POLY1305_SHA256` +Encrypted P2P connections are important because it means passive network spies, +such as ISPs, cannot tell what nodes are communicating to each other and also +prevents certain attacks against privacy at the network level, such as looking +for which node was the first to relay a transaction. Bitcoin has no protection +against this which is why it's trivial for network spies to tell which node +(and hence which IP address) created a certain transaction and hence which +IP address owns which addresses. + ## RPC Inherited many RPC's from Bitcoin and Zcash with many new ones From 38dc994731fe9a5d9fd9730307ad4c1403d0d17a Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 21:49:17 -0500 Subject: [PATCH 04/22] Remove unused code --- src/cc/prices.cpp | 71 ----------------------------------------------- 1 file changed, 71 deletions(-) diff --git a/src/cc/prices.cpp b/src/cc/prices.cpp index 3c9bb2556..852ea5eb4 100644 --- a/src/cc/prices.cpp +++ b/src/cc/prices.cpp @@ -26,39 +26,6 @@ #define NVOUT_CCMARKER 1 #define NVOUT_NORMALMARKER 3 -typedef struct OneBetData { - int64_t positionsize; - int32_t firstheight; - int64_t costbasis; - int64_t profits; - - OneBetData() { positionsize = 0; firstheight = 0; costbasis = 0; profits = 0; } -} onebetdata; - -typedef struct BetInfo { - uint256 txid; - int64_t averageCostbasis, firstprice, lastprice, liquidationprice, equity; - int64_t exitfee; - int32_t lastheight; - int16_t leverage; - bool isOpen, isRekt; - uint256 tokenid; - - std::vector vecparsed; - std::vector bets; - CPubKey pk; - - bool isUp; - - BetInfo() { - averageCostbasis = firstprice = lastprice = liquidationprice = equity = 0; - lastheight = 0; - leverage = 0; - exitfee = 0; - isOpen = isRekt = isUp = false; - } -} BetInfo; - typedef struct MatchedBookTotal { int64_t diffLeveragedPosition; @@ -250,23 +217,12 @@ int32_t prices_syntheticprofits(int64_t &costbasis, int32_t firstheight, int32_t return 0; } -// makes result json object -void prices_betjson(UniValue &result, std::vector bets, int16_t leverage, int32_t endheight, int64_t lastprice) -{ -} - // retrieves costbasis from a tx spending bettx vout1 (deprecated) int64_t prices_costbasis(CTransaction bettx, uint256 &txidCostbasis) { return 0; } -// enumerates and retrieves added bets, returns the last baton txid -int64_t prices_enumaddedbets(uint256 &batontxid, std::vector &bets, uint256 bettxid) -{ - return 0; -} - // pricesbet rpc impl: make betting tx UniValue PricesBet(int64_t txfee, int64_t amount, int16_t leverage, std::vector synthetic) { @@ -281,11 +237,6 @@ UniValue PricesAddFunding(int64_t txfee, uint256 bettxid, int64_t amount) return(result); } -// scan chain from the initial bet's first position upto the chain tip and calculate bet's costbasises and profits, breaks if rekt detected -int32_t prices_scanchain(std::vector &bets, int16_t leverage, std::vector vec, int64_t &lastprice, int32_t &endheight) { - return 0; -} - // pricescostbasis rpc impl: set cost basis (open price) for the bet (deprecated) UniValue PricesSetcostbasis(int64_t txfee, uint256 bettxid) { @@ -302,11 +253,6 @@ UniValue PricesRefillFund(int64_t amount) } -int32_t prices_getbetinfo(uint256 bettxid, BetInfo &betinfo) -{ - return (-420); -} - // pricesrekt rpc: anyone can rekt a bet at some block where losses reached limit, collecting fee UniValue PricesRekt(int64_t txfee, uint256 bettxid, int32_t rektheight) { @@ -337,29 +283,12 @@ UniValue PricesList(uint32_t filter, CPubKey mypk) } -static bool prices_addbookentry(uint256 txid, std::vector &book) -{ - return false; -} - - static bool prices_ispositionup(const std::vector &vecparsed, int16_t leverage) { return false; } -static bool prices_isopposite(BetInfo p1, BetInfo p2) { - return false; -} - - - -static std::string findMatchedBook(const std::vector &vecparsed, const std::map > & bookmatched) { - return std::string(""); -} -void prices_getorderbook(std::map > & bookmatched, std::map &matchedTotals, TotalFund &fundTotals) { -} static bool prices_isacceptableamount(const std::vector &vecparsed, int64_t amount, int16_t leverage) { return false; From 21530ba15925933f8cbc0ca2fc5c6baf4a93cb9c Mon Sep 17 00:00:00 2001 From: Duke Leto Date: Sat, 6 Jan 2024 19:15:28 -0800 Subject: [PATCH 05/22] Remove unused code --- src/Makefile.am | 7 +- src/cc/CCcustom.cpp | 4 +- src/cc/pegs.cpp | 81 +-------- src/cc/prices.cpp | 307 ----------------------------------- src/rpc/testtransactions.cpp | 19 --- src/wallet/rpcwallet.cpp | 82 ---------- 6 files changed, 4 insertions(+), 496 deletions(-) delete mode 100644 src/cc/prices.cpp diff --git a/src/Makefile.am b/src/Makefile.am index 7869af310..021c53b1b 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -287,7 +287,6 @@ libbitcoin_server_a_SOURCES = \ cc/fsm.cpp \ cc/heir.cpp \ cc/oracles.cpp \ - cc/prices.cpp \ cc/pegs.cpp \ cc/payments.cpp \ cc/gateways.cpp \ @@ -471,10 +470,6 @@ if GLIBC_BACK_COMPAT libbitcoin_util_a_SOURCES += compat/glibc_compat.cpp endif -if ENABLE_TESTS -libbitcoin_server_a_SOURCES += rpc/testtransactions.cpp -endif - # cli libbitcoin_cli_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) @@ -721,7 +716,7 @@ endif $(AM_V_GEN) $(PROTOC) --cpp_out=$(@D) --proto_path=$(abspath $(normaladdr,PricesNormaladdr); strcpy(cp->CChexstr,PricesCChexstr); memcpy(cp->CCpriv,PricesCCpriv,32); - cp->validate = PricesValidate; - cp->ismyvin = IsPricesInput; + //cp->validate = PricesValidate; + //cp->ismyvin = IsPricesInput; break; case EVAL_PEGS: strcpy(cp->unspendableCCaddr,PegsCCaddr); diff --git a/src/cc/pegs.cpp b/src/cc/pegs.cpp index a9aa9e9ab..beb98bc82 100644 --- a/src/cc/pegs.cpp +++ b/src/cc/pegs.cpp @@ -21,74 +21,7 @@ #include "key_io.h" #include - -/* -pegs CC is able to create a coin backed (by any supported coin with gateways CC deposits) and pegged to any synthetic price that is able to be calculated based on prices CC - - First, the prices CC needs to be understood, so the extensive comments at the top of ~/src/cc/prices.cpp needs to be understood. - - The second aspect is the ability to import coins, as used by the crosschain burn/import and the -ac_import chains. - - - - OK, now we are ready to describe the pegs CC. Let us imagine an -ac_import sidechain with HUSH gateways CC. Now we have each native coin fungible with the real HUSH via the gateways deposit/withdraw mechanism. Let us start with that and make a pegged and backed USD chain. - - - - Here the native coin is HUSH, but we want USD, so there needs to be a way to convert the HUSH amounts into USD amounts. Something like "HUSHBTC, BTCUSD, *, 1" which is the prices CC syntax to calculate HUSH/USD, which is exactly what we need. So now we can assume that we have a block by block usable HUSH/USD price. implementationwise, there can be an -ac option like -ac_peg="HUSHBTC, BTCUSD, *, 1" and in conjunction with -ac_import=HUSH gateways CC sidechain, we now have a chain where deposit of HUSH issues the correct USD coins and redeem of USD coins releases the correct number of HUSH coins. - - Are we done yet? - - Not quite, as the prices of HUSH will be quite volatile relative to USD, which is good during bull markets, not so happy during bear markets. There are 2 halves to this problem, how to deal with massive price increase (easy to solve), how to solve 90% price drop (a lot harder). - - In order to solve both, what is needed is an "account" based tracking which updates based on both price change, coins issued, payments made. So let us create an account that is based on a specific pubkey, where all relevant deposits, issuances, withdraws are tracked via appropriate vin/vout markers. - - Let us modify the USD chain above so that only 80% of the possible USD is issued and 20% held in reserve. This 80% should be at least some easily changeable #define, or even an -ac parameter. We want the issued coins to be released without any encumberances, but the residual 20% value is still controlled (owned) but the depositor. This account has the amount of HUSH deposited and USD issued. At the moment of deposit, there will still be 20% equity left. Let us start with 1000 HUSH deposit, $1.5 per HUSH -> 800 HUSH converted to 1200 USD into depositor pubkey and the account of (1000 HUSH, -1200 USD) = 200 HUSH or $300 equity. - - Now it becomes easy for the bull market case, which is to allow (for a fee like 1%) issuance of more USD as the equity increases, so let us imagine HUSH at $10: - - (1000 HUSH, -1200 USD, 200HUSH reserve) -> $2000 equity, issue 80% -> $1600 using 160 HUSH - (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) - - we have $2800 USD in circulation, 40 HUSH reserve left against $10000 marketcap of the original deposit. It it easy to see that there are never any problems with lack of HUSH to redeem the issued USD in a world where prices only go up. Total USD issuance can be limited by using a decentralized account tracking based on each deposit. - - What is evident though is that with the constantly changing price and the various times that all the various deposits issue USD, the global reserves are something that will be hard to predict and in fact needs to be specifically tracked. Let us combine all accounts exposure in to a global reserves factor. This factor will control various max/min/ allowed and fee percentages. - - Now we are prepared to handle the price goes down scenario. We can rely on the global equity/reserve ratio to be changing relatively slowly as the reference price is the smooted trustless oracles price. This means there will be enough blocks to adjust the global reserves percentage. What we need to do is liquidate specific positions that have the least reserves. - - What does liquidation mean? It means a specific account will be purchased at below its current value and the HUSH withdrawn. Let us assume the price drops to $5: - - (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) 1000 HUSH with 2800 USD issued so $2200 reserves. Let us assume it can be liquidated at a 10% discount, so for $2000 in addition to the $2800, the 5000 HUSH is able to be withdrawn. This removes 4800 USD coins for 1000 HUSH, which is a very low reserve amount of 4%. If a low reserve amount is removed from the system, then the global reserve amount must be improved. - - In addition to the global reserves calculation, there needs to be a trigger percentage that enables positions to be liquidated. We also want to liquidate the worst positions, so in addition to the trigger percentage, there should be a liquidation threshold, and the liquidator would need to find 3 or more better positions that are beyond the liquidation threshold, to be able to liquidate. This will get us to at most 3 accounts that could be liquidated but are not able to, so some method to allow those to also be liquidated. The liquidating nodes are making instant profits, so they should be expected to do whatever blockchain scanning and proving to make things easy for the rest of the nodes. - - One last issue is the normal redemption case where we are not liquidating. In this case, it should be done at the current marketprice, should improve the global reserves metrics and not cause anybody whose position was modified to have cause for complaint. Ideally, there would be an account that has the identical to the global reserve percentage and also at the same price as current marketprice, but this is not realistic, so we need to identify classes of accounts and consider which ones can be fully or partially liquidated to satisfy the constraints. - - looking at our example account: - (1000 HUSH, -1200 USD, 200HUSH reserve, -160HUSH, issue $1600 USD, 40 HUSH reserve) - - what sort of non-liquidation withdraw would be acceptable? if the base amount 1000 HUSH is reduced along with USD owed, then the reserve status will go up for the account. but that would seem to allow extra USD to be able to be issued. there should be no disadvantage from funding a withdraw, but also not any large advantage. it needs to be a neutral event.... - - One solution is to allow for the chance for any account to be liquidated, but the equity compensated for with a premium based on the account reserves. So in the above case, a premium of 5% on the 40HUSH reserve is paid to liquidate its account. Instead of 5% premium, a lower 1% can be done if based on the MAX(correlated[daywindow],smoothed) so we get something that is close to the current marketprice. To prevent people taking advantage of the slowness of the smoothed price to adjust, there would need to be a one day delay in the withdraw. - - From a practical sense, it seems a day is a long time, so maybe having a way to pay a premium like 10%, or wait a day to get the MAX(correlated[daywindow],smoothed) price. This price "jumping" might also be taken advantage of in the deposit side, so similar to prices CC it seems good to have the MAX(correlated[daywindow],smoothed) method. - - Now, we have a decentralized mechanism to handle the price going lower! Combined with the fully decentralized method new USD coins are issued, makes this argubably the first decentralized blockchain that is both backed and pegged. There is the reliance on the gateways CC multisig signers, so there is a fundamental federated trust for chains without intrinsic value. - - Also, notice that the flexibly syntax of prices CC allows to define pegs easily for virtually any type of synthetic, and all the ECB fiats can easily get a backed and pegged coin. - - Let us now consider how to enforce a peg onto a specific gateways CC token. If this can also be achieved, then a full DEX for all the different gateways CC supported coins can be created onto a single fiat denominated chain. - - I think just having a pegscreate rpc call that binds an existing gateways create to a price CC syntax price will be almost enough to support this. Let us assume a USD stablechain and we have a BTC token, then pegscreate "BTCUSD, 1" - that will specify using the BTCUSD price, so now we need to create a based way to do tokenbid/tokenask. For a based price, the smoothed price is substituted. - - There is the issue of the one day delay, so it might make sense to allow specific bid/ask to be based on some simple combinations of the three possible prices. it might even be possible to go a bit overboard and make a forth like syntax to define the dynamic price for a bid, which maybe at times wont be valid, like it is only valid if the three prices are within 1% of each other. But all that seems over complex and for initial release it can just use the mined, correlated or smoothed price, with some specified percentage offset - - Implementation notes: - make sure that fees and markers that can be sent to an unspendable address are sent to: RNdqHx26GWy9bk8MtmH1UiXjQcXE4RKK2P, this is the address for BOTS - - - */ +//NOTE: in process of removal // start of consensus code #ifndef PEGS_THRESHOLDS @@ -105,8 +38,6 @@ extern uint64_t ASSETCHAINS_PEGSCCPARAMS[3]; extern uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2,uint8_t &wiftype); extern int64_t GetTokenBalance(CPubKey pk, uint256 tokenid); extern int32_t hush_currentheight(); -extern int32_t prices_syntheticvec(std::vector &vec, std::vector synthetic); -extern int64_t prices_syntheticprice(std::vector vec, int32_t height, int32_t minmax, int16_t leverage); CScript EncodePegsCreateOpRet(std::vector bindtxids) { @@ -522,16 +453,6 @@ char PegsFindAccount(struct CCcontract_info *cp,CPubKey pk,uint256 pegstxid, uin int64_t PegsGetTokenPrice(uint256 tokenid) { - int64_t price; CTransaction tokentx; uint256 hashBlock; std::vector exp; - std::string name,desc; std::vector vorigpubkey; int32_t numvouts; - - if (myGetTransaction(tokenid,tokentx,hashBlock)!=0 && (numvouts=tokentx.vout.size())>0 && DecodeTokenCreateOpRet(tokentx.vout[numvouts-1].scriptPubKey,vorigpubkey,name,desc)=='c') - { - std::vector vexpr; - SplitStr(desc, vexpr); - if (prices_syntheticvec(exp, vexpr)>=0 && (price = prices_syntheticprice(exp, hush_currentheight(), 0, 1))>=0) - return (price); - } return (0); } diff --git a/src/cc/prices.cpp b/src/cc/prices.cpp deleted file mode 100644 index 852ea5eb4..000000000 --- a/src/cc/prices.cpp +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright (c) 2016-2023 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/****************************************************************************** - * Copyright © 2014-2019 The SuperNET Developers. * - * * - * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * - * the top-level directory of this distribution for the individual copyright * - * holder information and the developer policies on copyright and licensing. * - * * - * Unless otherwise agreed in a custom licensing agreement, no part of the * - * SuperNET software, including this file may be copied, modified, propagated * - * or distributed except according to the terms contained in the LICENSE file * - * * - * Removal or modification of this copyright notice is prohibited. * - * * - *****************************************************************************/ -//TODO: Finish deleting all this jl777 garbage. This CC will never function - -#include "CCassets.h" -#include "CCPrices.h" -#include -#include - -#define IS_CHARINSTR(c, str) (std::string(str).find((char)(c)) != std::string::npos) -#define NVOUT_CCMARKER 1 -#define NVOUT_NORMALMARKER 3 - -typedef struct MatchedBookTotal { - - int64_t diffLeveragedPosition; - -} MatchedBookTotal; - -typedef struct TotalFund { - int64_t totalFund; - int64_t totalActiveBets; - int64_t totalCashout; - int64_t totalRekt; - int64_t totalEquity; - - TotalFund() { - totalFund = totalActiveBets = totalCashout = totalRekt = totalEquity = 0; - } - -} TotalFund; - -int32_t prices_syntheticprofits(int64_t &costbasis, int32_t firstheight, int32_t height, int16_t leverage, std::vector vec, int64_t positionsize, int64_t &profits, int64_t &outprice); -static bool prices_isacceptableamount(const std::vector &vecparsed, int64_t amount, int16_t leverage); - -// helpers: - -// returns true if there are only digits and no alphas or slashes in 's' -inline bool is_weight_str(std::string s) { - return false; -} - - -// start of consensus code - -CScript prices_betopret(CPubKey mypk,int32_t height,int64_t amount,int16_t leverage,int64_t firstprice,std::vector vec,uint256 tokenid) -{ - CScript opret; - opret << OP_RETURN << E_MARSHAL(ss << EVAL_PRICES << 'B' << mypk << height << amount << leverage << firstprice << vec << tokenid); - return(opret); -} - -uint8_t prices_betopretdecode(CScript scriptPubKey,CPubKey &pk,int32_t &height,int64_t &amount,int16_t &leverage,int64_t &firstprice,std::vector &vec,uint256 &tokenid) -{ - return(0); -} - -CScript prices_addopret(uint256 bettxid,CPubKey mypk,int64_t amount) -{ - CScript opret; - return(opret); -} - -uint8_t prices_addopretdecode(CScript scriptPubKey,uint256 &bettxid,CPubKey &pk,int64_t &amount) -{ - return(0); -} - -CScript prices_costbasisopret(uint256 bettxid,CPubKey mypk,int32_t height,int64_t costbasis) -{ - CScript opret; - return(opret); -} - -uint8_t prices_costbasisopretdecode(CScript scriptPubKey,uint256 &bettxid,CPubKey &pk,int32_t &height,int64_t &costbasis) -{ - return(0); -} - -CScript prices_finalopret(bool isRekt, uint256 bettxid, CPubKey pk, int32_t lastheight, int64_t costbasis, int64_t lastprice, int64_t liquidationprice, int64_t equity, int64_t exitfee, uint32_t nonce) -{ - CScript opret; - return(opret); -} - -uint8_t prices_finalopretdecode(CScript scriptPubKey, uint256 &bettxid, CPubKey &pk, int32_t &lastheight, int64_t &costbasis, int64_t &lastprice, int64_t &liquidationprice, int64_t &equity, int64_t &exitfee) -{ - return(0); -} - -// price opret basic validation and retrieval -static uint8_t PricesCheckOpret(const CTransaction & tx, vscript_t &opret) -{ - return (uint8_t)0; -} - -// validate bet tx helper -static bool ValidateBetTx(struct CCcontract_info *cp, Eval *eval, const CTransaction & bettx) -{ - return true; -} - -// validate add funding tx helper -static bool ValidateAddFundingTx(struct CCcontract_info *cp, Eval *eval, const CTransaction & addfundingtx, const CTransaction & vintx) -{ - return true; -} - - -// validate final tx helper -static bool ValidateFinalTx(struct CCcontract_info *cp, Eval *eval, const CTransaction & finaltx, const CTransaction & bettx) -{ - return true; -} - -bool PricesValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn) -{ - return true; -} -// helper functions for rpc calls in rpcwallet.cpp - -int64_t AddPricesInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, char *destaddr, int64_t total, int32_t maxinputs) -{ - int64_t totalinputs = 0; - return(totalinputs); -} - -double prices_minmarginpercent(int16_t leverage) -{ - return 0.0; -} - - -UniValue prices_rawtxresult(UniValue &result, std::string rawtx, int32_t broadcastflag) -{ - return(result); -} - -static std::string prices_getsourceexpression(const std::vector &vec) { - std::string expr; - return expr; -} - -// helper functions to get synthetic expression reduced: - -// return s true and needed operand count if string is opcode -static bool prices_isopcode(const std::string &s, int &need) -{ - return false; -} - -// split pair onto two quotes divided by "_" -static void prices_splitpair(const std::string &pair, std::string &upperquote, std::string &bottomquote) -{ -} - -// invert pair like BTS_USD -> USD_BTC -static std::string prices_invertpair(const std::string &pair) -{ - std::string s; - return s; -} - -// invert pairs in operation accordingly to "/" operator, convert operator to * or *** -static void prices_invertoperation(const std::vector &vexpr, int p, std::vector &voperation) -{ -} - -// reduce pairs in the operation, change or remove opcode if reduced -static int prices_reduceoperands(std::vector &voperation) -{ - return 0; -} - -// substitute reduced operation in vectored expr -static void prices_substitutereduced(std::vector &vexpr, int p, std::vector voperation) -{ -} - -// try to reduce synthetic expression by substituting "BTC_USD, BTC_EUR, 30, /" with "EUR_USD, 30" etc -static std::string prices_getreducedexpr(const std::string &expr) -{ - std::string reduced; - return reduced; -} - -// parse synthetic expression into vector of codes -int32_t prices_syntheticvec(std::vector &vec, std::vector synthetic) -{ - return(0); -} - -// calculates price for synthetic expression -int64_t prices_syntheticprice(std::vector vec, int32_t height, int32_t minmax, int16_t leverage) -{ - return 0; -} - -// calculates costbasis and profit/loss for the bet -int32_t prices_syntheticprofits(int64_t &costbasis, int32_t firstheight, int32_t height, int16_t leverage, std::vector vec, int64_t positionsize, int64_t &profits, int64_t &outprice) -{ - return 0; -} - -// retrieves costbasis from a tx spending bettx vout1 (deprecated) -int64_t prices_costbasis(CTransaction bettx, uint256 &txidCostbasis) -{ - return 0; -} - -// pricesbet rpc impl: make betting tx -UniValue PricesBet(int64_t txfee, int64_t amount, int16_t leverage, std::vector synthetic) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -// pricesaddfunding rpc impl: add yet another bet -UniValue PricesAddFunding(int64_t txfee, uint256 bettxid, int64_t amount) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -// pricescostbasis rpc impl: set cost basis (open price) for the bet (deprecated) -UniValue PricesSetcostbasis(int64_t txfee, uint256 bettxid) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - - -// pricesaddfunding rpc impl: add yet another bet -UniValue PricesRefillFund(int64_t amount) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - - -// pricesrekt rpc: anyone can rekt a bet at some block where losses reached limit, collecting fee -UniValue PricesRekt(int64_t txfee, uint256 bettxid, int32_t rektheight) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -// pricescashout rpc impl: bettor can cashout hit bet if it is not rekt -UniValue PricesCashout(int64_t txfee, uint256 bettxid) -{ - UniValue result(UniValue::VOBJ); - return result; -} - - -// pricesinfo rpc impl -UniValue PricesInfo(uint256 bettxid, int32_t refheight) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -// priceslist rpc impl -UniValue PricesList(uint32_t filter, CPubKey mypk) -{ - UniValue result(UniValue::VARR); - return(result); -} - - -static bool prices_ispositionup(const std::vector &vecparsed, int16_t leverage) { - return false; -} - - - - -static bool prices_isacceptableamount(const std::vector &vecparsed, int64_t amount, int16_t leverage) { - return false; -} - - -// walk through uxtos on the global address -// calculate the balance: -// + rekt positions -// = opposite positions -// - unbalanced positions -UniValue PricesGetOrderbook() -{ - UniValue result(UniValue::VOBJ); - return result; -} diff --git a/src/rpc/testtransactions.cpp b/src/rpc/testtransactions.cpp index 50f60af4e..a9c685c16 100644 --- a/src/rpc/testtransactions.cpp +++ b/src/rpc/testtransactions.cpp @@ -222,7 +222,6 @@ UniValue test_proof(const UniValue& params, bool fHelp, const CPubKey& mypk) return result; } -extern CScript prices_costbasisopret(uint256 bettxid, CPubKey mypk, int32_t height, int64_t costbasis); UniValue test_pricesmarker(const UniValue& params, bool fHelp, const CPubKey& mypk) { // make fake token tx: @@ -249,21 +248,3 @@ UniValue test_pricesmarker(const UniValue& params, bool fHelp, const CPubKey& my return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, prices_costbasisopret(bettxid, myPubkey, 100, 100))); } - -static const CRPCCommand commands[] = -{ // category name actor (function) okSafeMode - // --------------------- ------------------------ ----------------------- ---------- - - /* Not shown in help */ - { "hidden", "test_ac", &test_ac, true }, - { "hidden", "test_heirmarker", &test_heirmarker, true }, - { "hidden", "test_proof", &test_proof, true }, - { "hidden", "test_burntx", &test_burntx, true }, - { "hidden", "test_pricesmarker", &test_pricesmarker, true } -}; - -void RegisterTesttransactionsRPCCommands(CRPCTable &tableRPC) -{ - for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) - tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]); -} diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 491cab182..76aecf2b3 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6474,30 +6474,6 @@ UniValue oraclesaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) return(CCaddress(cp,(char *)"Oracles",pubkey)); } -UniValue pricesaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); struct CCcontract_info *cp,C,*assetscp,C2; std::vector pubkey; CPubKey pk,planpk,pricespk; char myaddr[64],houseaddr[64],exposureaddr[64]; - cp = CCinit(&C,EVAL_PRICES); - assetscp = CCinit(&C2,EVAL_PRICES); - if ( fHelp || params.size() > 1 ) - throw runtime_error("pricesaddress [pubkey]\n"); - if ( ensure_CCrequirements(cp->evalcode) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); - result = CCaddress(cp,(char *)"Prices",pubkey); - if (mypk.IsValid()) pk=mypk; - else pk = pubkey2pk(Mypubkey()); - pricespk = GetUnspendable(cp,0); - GetCCaddress(assetscp,myaddr,pk); - GetCCaddress1of2(assetscp,houseaddr,pricespk,planpk); - GetCCaddress1of2(assetscp,exposureaddr,pricespk,pricespk); - result.push_back(Pair("myaddr",myaddr)); // for holding my asssets - result.push_back(Pair("houseaddr",houseaddr)); // globally accessible house assets - result.push_back(Pair("exposureaddr",exposureaddr)); // tracking of exposure - return(result); -} - UniValue pegsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) { struct CCcontract_info *cp,C; std::vector pubkey; @@ -7534,64 +7510,6 @@ UniValue faucetget(const UniValue& params, bool fHelp, const CPubKey& mypk) return(result); } -uint32_t pricesGetParam(UniValue param) { - uint32_t filter = 0; - if (STR_TOLOWER(param.get_str()) == "all") - filter = 0; - else if (STR_TOLOWER(param.get_str()) == "open") - filter = 1; - else if (STR_TOLOWER(param.get_str()) == "closed") - filter = 2; - else - throw runtime_error("incorrect parameter\n"); - return filter; -} - -UniValue priceslist(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - if ( fHelp || params.size() != 0 && params.size() != 1) - throw runtime_error("priceslist [all|open|closed]\n"); - if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - uint32_t filter = 0; - if (params.size() == 1) - filter = pricesGetParam(params[0]); - - CPubKey emptypk; - - return(PricesList(filter, emptypk)); -} - -UniValue mypriceslist(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - if (fHelp || params.size() != 0 && params.size() != 1) - throw runtime_error("mypriceslist [all|open|closed]\n"); - if (ensure_CCrequirements(EVAL_PRICES) < 0) - throw runtime_error(CC_REQUIREMENTS_MSG); - - uint32_t filter = 0; - if (params.size() == 1) - filter = pricesGetParam(params[0]); - CPubKey pk; - if (mypk.IsValid()) pk=mypk; - else pk = pubkey2pk(Mypubkey()); - - return(PricesList(filter, pk)); -} - -UniValue pricesinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bettxid; int32_t height; - if ( fHelp || params.size() != 1 && params.size() != 2) - throw runtime_error("pricesinfo bettxid [height]\n"); - if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bettxid = Parseuint256((char *)params[0].get_str().c_str()); - height = 0; - if (params.size() == 2) - height = atoi(params[1].get_str().c_str()); - return(PricesInfo(bettxid, height)); -} UniValue dicefund(const UniValue& params, bool fHelp, const CPubKey& mypk) { From 0e0b1cca971874da26e0a629a1c4656b566c7ce4 Mon Sep 17 00:00:00 2001 From: Duke Leto Date: Sat, 6 Jan 2024 21:33:23 -0800 Subject: [PATCH 06/22] Attempt to try different randomx flags --- src/miner.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 5b0544200..2197cb533 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1099,11 +1099,19 @@ void static RandomXMiner() // flags |= RANDOMX_FLAG_LARGE_PAGES; flags |= RANDOMX_FLAG_FULL_MEM; //flags |= RANDOMX_FLAG_JIT; - randomx_cache *randomxCache = randomx_alloc_cache(flags); + randomx_cache *randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_LARGE_PAGES | RANDOMX_FLAG_JIT | RANDOMX_FLAG_HARD_AES); if (randomxCache == NULL) { - LogPrintf("RandomX cache is null, something is wrong, cannot mine!\n"); - return; + LogPrintf("RandomX cache is null, trying without large pages and without jit ...\n"); + randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_HARD_AES); + if (randomxCache == NULL) { + LogPrintf("RandomX cache is null, trying without hardware AES...\n"); + } + randomxCache = randomx_alloc_cache(flags); + if (randomxCache == NULL) { + LogPrintf("RandomX cache is null, cannot mine!\n"); + } } + rxdebug("%s: created randomx flags + cache\n"); randomx_dataset *randomxDataset = randomx_alloc_dataset(flags); rxdebug("%s: created dataset\n"); From 56ef56b13625616a5f82168fda8cb02feec6b526 Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 22:23:58 -0800 Subject: [PATCH 07/22] randomx_get_flags() automatically sets all flags except RANDOMX_FLAG_FULL_MEM, RANDOMX_FLAG_LARGE_PAGES and RANDOMX_FLAG_SECURE --- src/miner.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 2197cb533..4ba24ec29 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1095,16 +1095,13 @@ void static RandomXMiner() miningTimer.start(); randomx_flags flags = randomx_get_flags(); - // TODO: attempt to use large pages and fall back to no large pages - // flags |= RANDOMX_FLAG_LARGE_PAGES; flags |= RANDOMX_FLAG_FULL_MEM; - //flags |= RANDOMX_FLAG_JIT; - randomx_cache *randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_LARGE_PAGES | RANDOMX_FLAG_JIT | RANDOMX_FLAG_HARD_AES); + randomx_cache *randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_LARGE_PAGES | RANDOMX_FLAG_SECURE ); if (randomxCache == NULL) { - LogPrintf("RandomX cache is null, trying without large pages and without jit ...\n"); - randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_HARD_AES); + LogPrintf("RandomX cache is null, trying without large pages...\n"); + randomxCache = randomx_alloc_cache(flags | RANDOMX_FLAG_SECURE); if (randomxCache == NULL) { - LogPrintf("RandomX cache is null, trying without hardware AES...\n"); + LogPrintf("RandomX cache is null, trying without secure...\n"); } randomxCache = randomx_alloc_cache(flags); if (randomxCache == NULL) { From 1b5422eb2ddcedd9aabdf4f039144f9eef5c6f95 Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 22:54:14 -0800 Subject: [PATCH 08/22] Dynamically determine thread count for dataset init --- src/miner.cpp | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 4ba24ec29..6f5c1e971 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1201,14 +1201,27 @@ void static RandomXMiner() rxdebug("%s: initialized cache with keyHeight=%d, randomxBlockKey=%s\n", keyHeight, randomxBlockKey.ToString().c_str()); } - //TODO: this is hardcoded to use 2 threads instead of the number of mining threads - rxdebug("%s: initializing dataset with 2 threads\n"); - std::thread t1(&randomx_init_dataset, randomxDataset, randomxCache, 0, datasetItemCount / 2); - std::thread t2(&randomx_init_dataset, randomxDataset, randomxCache, datasetItemCount / 2, datasetItemCount - datasetItemCount / 2); - t1.join(); - t2.join(); - - // randomx_init_dataset(randomxDataset, randomxCache, 0, datasetItemCount); + int initThreadCount = std::thread::hardware_concurrency(); + if(initThreadCount > 1) { + rxdebug("%s: initializing dataset with %d threads\n", initThreadCount); + std::vector threads; + uint32_t startItem = 0; + auto perThread = datasetItemCount / initThreadCount; + auto remainder = datasetItemCount % initThreadCount; + for (int i = 0; i < initThreadCount; ++i) { + auto count = perThread + (i == initThreadCount - 1 ? remainder : 0); + threads.push_back(std::thread(&randomx_init_dataset, randomxDataset, randomxCache, startItem, count)); + startItem += count; + } + for (unsigned i = 0; i < threads.size(); ++i) { + threads[i].join(); + } + threads.clear(); + } else { + rxdebug("%s: initializing dataset with 1 thread\n"); + randomx_init_dataset(randomxDataset, randomxCache, 0, datasetItemCount); + } + rxdebug("%s: dataset initialized\n"); myVM = randomx_create_vm(flags, nullptr, randomxDataset); @@ -1463,8 +1476,8 @@ void static RandomXMiner() randomx_release_dataset(randomxDataset); rxdebug("%s: released dataset in normal exit\n"); - randomx_release_cache(randomxCache); - rxdebug("%s: released cache in normal exit\n"); + //randomx_release_cache(randomxCache); + //rxdebug("%s: released cache in normal exit\n"); miningTimer.stop(); c.disconnect(); } From 765487bb14856c3a6f3ed05941de4c861df5146f Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 23:30:19 -0800 Subject: [PATCH 09/22] Remove unused code --- src/rpc/server.cpp | 15 --- src/rpc/server.h | 11 --- src/wallet/rpcwallet.cpp | 200 --------------------------------------- 3 files changed, 226 deletions(-) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 9eb9076e7..c50d702a3 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -473,9 +473,6 @@ static const CRPCCommand vRPCCommands[] = { "oracles", "oraclessample", &oraclessample, true }, { "oracles", "oraclessamples", &oraclessamples, true }, - // Pegs - { "pegs", "pegsaddress", &pegsaddress, true }, - // Payments { "payments", "paymentsaddress", &paymentsaddress, true }, { "payments", "paymentstxidopret", &payments_txidopret, true }, @@ -539,18 +536,6 @@ static const CRPCCommand vRPCCommands[] = //{ "tokens", "tokenfillswap", &tokenfillswap, true }, { "tokens", "tokenconvert", &tokenconvert, true }, - // pegs - { "pegs", "pegscreate", &pegscreate, true }, - { "pegs", "pegsfund", &pegsfund, true }, - { "pegs", "pegsget", &pegsget, true }, - { "pegs", "pegsredeem", &pegsredeem, true }, - { "pegs", "pegsliquidate", &pegsliquidate, true }, - { "pegs", "pegsexchange", &pegsexchange, true }, - { "pegs", "pegsaccounthistory", &pegsaccounthistory, true }, - { "pegs", "pegsaccountinfo", &pegsaccountinfo, true }, - { "pegs", "pegsworstaccounts", &pegsworstaccounts, true }, - { "pegs", "pegsinfo", &pegsinfo, true }, - /* Address index */ { "addressindex", "getaddressmempool", &getaddressmempool, true }, { "addressindex", "getaddressutxos", &getaddressutxos, false }, diff --git a/src/rpc/server.h b/src/rpc/server.h index 8f88cb238..3b229d6f3 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -270,7 +270,6 @@ extern UniValue oraclessubscribe(const UniValue& params, bool fHelp, const CPubK extern UniValue oraclesdata(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue oraclessample(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue oraclessamples(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue paymentsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue payments_release(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue payments_fund(const UniValue& params, bool fHelp, const CPubKey& mypk); @@ -333,16 +332,6 @@ extern UniValue FSMcreate(const UniValue& params, bool fHelp, const CPubKey& myp extern UniValue FSMlist(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue FSMinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue auctionaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegscreate(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsfund(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsget(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsredeem(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsliquidate(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsexchange(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsaccounthistory(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsaccountinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsworstaccounts(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue pegsinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue getnewaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp //extern UniValue getnewaddress64(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcwallet.cpp diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 76aecf2b3..1dcc1525c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6102,7 +6102,6 @@ int32_t hush_notaryvin(CMutableTransaction &txNew,uint8_t *notarypub33, void *pT #include "../cc/CCPrices.h" #include "../cc/CCHeir.h" #include "../cc/CCPayments.h" -#include "../cc/CCPegs.h" int32_t ensure_CCrequirements(uint8_t evalcode) { CCerror = ""; @@ -6474,19 +6473,6 @@ UniValue oraclesaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) return(CCaddress(cp,(char *)"Oracles",pubkey)); } -UniValue pegsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - struct CCcontract_info *cp,C; std::vector pubkey; - cp = CCinit(&C,EVAL_PEGS); - if ( fHelp || params.size() > 1 ) - throw runtime_error("pegssaddress [pubkey]\n"); - if ( ensure_CCrequirements(cp->evalcode) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); - return(CCaddress(cp,(char *)"Pegs",pubkey)); -} - UniValue paymentsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) { struct CCcontract_info *cp,C; std::vector pubkey; @@ -8381,192 +8367,6 @@ UniValue heirlist(const UniValue& params, bool fHelp, const CPubKey& mypk) return (HeirList()); } -UniValue pegscreate(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); int32_t i; std::vector txids; - uint8_t N; uint256 txid; int64_t amount; - - if ( fHelp || params.size()<3) - throw runtime_error("pegscreate amount N bindtxid1 [bindtxid2 ...]\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - const CKeyStore& keystore = *pwalletMain; - Lock2NSPV(mypk); - amount = atof((char *)params[0].get_str().c_str()) * COIN + 0.00000000499999; - N = atoi((char *)params[1].get_str().c_str()); - if ( params.size() < N+1 ) - { - Unlock2NSPV(mypk); - throw runtime_error("not enough parameters for N pegscreate\n"); - } - for (i=0; i 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsfund(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 pegstxid,tokenid; int64_t amount; - - - if ( fHelp || params.size()!=3) - throw runtime_error("pegsfund pegstxid tokenid amount\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - const CKeyStore& keystore = *pwalletMain; - Lock2NSPV(mypk); - pegstxid = Parseuint256(params[0].get_str().c_str()); - tokenid = Parseuint256(params[1].get_str().c_str()); - amount = atof((char *)params[2].get_str().c_str()) * COIN + 0.00000000499999; - result = PegsFund(mypk,0,pegstxid,tokenid,amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsget(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 pegstxid,tokenid; int64_t amount; - - if ( fHelp || params.size()!=3) - throw runtime_error("pegsget pegstxid tokenid amount\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - pegstxid = Parseuint256(params[0].get_str().c_str()); - tokenid = Parseuint256(params[1].get_str().c_str()); - amount = atof((char *)params[2].get_str().c_str()) * COIN + 0.00000000499999; - result = PegsGet(mypk,0,pegstxid,tokenid,amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsredeem(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 pegstxid,tokenid; int64_t amount; - - if ( fHelp || params.size()!=2) - throw runtime_error("pegsredeem pegstxid tokenid\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - pegstxid = Parseuint256(params[0].get_str().c_str()); - tokenid = Parseuint256(params[1].get_str().c_str()); - result = PegsRedeem(mypk,0,pegstxid,tokenid); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsliquidate(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 pegstxid,tokenid,accounttxid; - - if ( fHelp || params.size()!=3) - throw runtime_error("pegsliquidate pegstxid tokenid accounttxid\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - pegstxid = Parseuint256(params[0].get_str().c_str()); - tokenid = Parseuint256(params[1].get_str().c_str()); - accounttxid = Parseuint256(params[2].get_str().c_str()); - result = PegsLiquidate(mypk,0,pegstxid,tokenid,accounttxid); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsexchange(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 pegstxid,tokenid,accounttxid; int64_t amount; - - if ( fHelp || params.size()!=3) - throw runtime_error("pegsexchange pegstxid tokenid amount\n"); - if ( ensure_CCrequirements(EVAL_PEGS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - pegstxid = Parseuint256(params[0].get_str().c_str()); - tokenid = Parseuint256(params[1].get_str().c_str()); - amount = atof((char *)params[2].get_str().c_str()) * COIN + 0.00000000499999; - result = PegsExchange(mypk,0,pegstxid,tokenid,amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue pegsaccounthistory(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 pegstxid; - - if ( fHelp || params.size() != 1 ) - throw runtime_error("pegsaccounthistory pegstxid\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - pegstxid = Parseuint256((char *)params[0].get_str().c_str()); - return(PegsAccountHistory(mypk,pegstxid)); -} - -UniValue pegsaccountinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 pegstxid; - - if ( fHelp || params.size() != 1 ) - throw runtime_error("pegsaccountinfo pegstxid\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - pegstxid = Parseuint256((char *)params[0].get_str().c_str()); - return(PegsAccountInfo(mypk,pegstxid)); -} - -UniValue pegsworstaccounts(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 pegstxid; - - if ( fHelp || params.size() != 1 ) - throw runtime_error("pegsworstaccounts pegstxid\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - pegstxid = Parseuint256((char *)params[0].get_str().c_str()); - return(PegsWorstAccounts(pegstxid)); -} - -UniValue pegsinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 pegstxid; - - if ( fHelp || params.size() != 1 ) - throw runtime_error("pegsinfo pegstxid\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - pegstxid = Parseuint256((char *)params[0].get_str().c_str()); - return(PegsInfo(pegstxid)); -} - extern UniValue dumpprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk); // in rpcdump.cpp extern UniValue convertpassphrase(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue importprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk); From b9937bc5d29007cc9f52b88ead1f26c4590eafe2 Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 23:37:48 -0800 Subject: [PATCH 10/22] Release randomx cache in normal exit --- src/miner.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 6f5c1e971..8b3ef9af8 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1476,8 +1476,8 @@ void static RandomXMiner() randomx_release_dataset(randomxDataset); rxdebug("%s: released dataset in normal exit\n"); - //randomx_release_cache(randomxCache); - //rxdebug("%s: released cache in normal exit\n"); + randomx_release_cache(randomxCache); + rxdebug("%s: released cache in normal exit\n"); miningTimer.stop(); c.disconnect(); } From 447f1f50f304758ca602fbb828b3a33bade68a30 Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 23:39:24 -0800 Subject: [PATCH 11/22] SMART_CHAIN_SYMBOL is always nonzero --- src/miner.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 8b3ef9af8..6749842ae 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1268,19 +1268,17 @@ void static RandomXMiner() return; } CBlock *pblock = &pblocktemplate->block; - if ( SMART_CHAIN_SYMBOL[0] != 0 ) + + if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) { - if ( ASSETCHAINS_REWARD[0] == 0 && !ASSETCHAINS_LASTERA ) + if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) { - if ( pblock->vtx.size() == 1 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) - { - static uint32_t counter; - if ( counter++ < 10 ) - fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",SMART_CHAIN_SYMBOL); - sleep(10); - continue; - } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",SMART_CHAIN_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); - } + static uint32_t counter; + if ( counter++ < 10 ) + fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",SMART_CHAIN_SYMBOL); + sleep(10); + continue; + } else fprintf(stderr,"%s vouts.%d mining.%d vs %d\n",SMART_CHAIN_SYMBOL,(int32_t)pblock->vtx[0].vout.size(),Mining_height,ASSETCHAINS_MINHEIGHT); } rxdebug("%s: incrementing extra nonce\n"); IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); From 4054140b2189d101ca35e79fb5843786c0738fe0 Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 23:47:00 -0800 Subject: [PATCH 12/22] RandomX interval and block lag are consensus changes and will never change at run-time, so they can be static --- src/miner.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 6749842ae..ff83e9e9c 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1058,6 +1058,9 @@ enum RandomXSolverCancelCheck Reason2 }; +int GetRandomXInterval() { return GetArg("-ac_randomx_interval",1024); } +int GetRandomXBlockLag() { return GetArg("-ac_randomx_lag", 64); } + #ifdef ENABLE_WALLET void static RandomXMiner(CWallet *pwallet) #else @@ -1131,9 +1134,9 @@ void static RandomXMiner() // With the defaults of 1024 and 64 // the key block will change every ~21.3 hours with a 75s block time // and every ~17 hours with the default 60s block time for HSCs - int randomxInterval = GetArg("-ac_randomx_interval",1024); + static int randomxInterval = GetRandomXInterval(); // This lag is 80 mins for 75s blocktime and 64 mins for 60s (default) blocktime for HSCs - int randomxBlockLag = GetArg("-ac_randomx_lag", 64); + static int randomxBlockLag = GetRandomXBlockLag(); randomx_vm *myVM = nullptr; try { From c1ab82a881674ec87b0fe325f09e22fe3e5920af Mon Sep 17 00:00:00 2001 From: Duke Date: Sat, 6 Jan 2024 23:57:39 -0800 Subject: [PATCH 13/22] Remove unused variables and add a const --- src/miner.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index ff83e9e9c..81fd936a6 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1079,7 +1079,7 @@ void static RandomXMiner() // Each thread has its own counter unsigned int nExtraNonce = 0; - uint8_t *script; uint64_t total; int32_t i,j,gpucount=HUSH_MAXGPUCOUNT,notaryid = -1; + int32_t gpucount=HUSH_MAXGPUCOUNT; while ( (ASSETCHAIN_INIT == 0 || HUSH_INITDONE == 0) ) { sleep(1); @@ -1204,7 +1204,7 @@ void static RandomXMiner() rxdebug("%s: initialized cache with keyHeight=%d, randomxBlockKey=%s\n", keyHeight, randomxBlockKey.ToString().c_str()); } - int initThreadCount = std::thread::hardware_concurrency(); + const int initThreadCount = std::thread::hardware_concurrency(); if(initThreadCount > 1) { rxdebug("%s: initializing dataset with %d threads\n", initThreadCount); std::vector threads; From 68427d0979fbcc70f074ff93da5b02d729ecd935 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 11:15:08 -0500 Subject: [PATCH 14/22] Remove unused code --- src/cc/CCPegs.h | 21 - src/cc/CCcustom.cpp | 4 +- src/cc/pegs.cpp | 1186 ------------------------------------------- 3 files changed, 2 insertions(+), 1209 deletions(-) diff --git a/src/cc/CCPegs.h b/src/cc/CCPegs.h index 197af430f..5cc2ce473 100644 --- a/src/cc/CCPegs.h +++ b/src/cc/CCPegs.h @@ -16,24 +16,3 @@ * * ******************************************************************************/ - -#ifndef CC_PEGS_H -#define CC_PEGS_H - -#include "CCinclude.h" - -bool PegsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn); - -// CCcustom -UniValue PegsCreate(const CPubKey& pk,uint64_t txfee,int64_t amount,std::vector bindtxids); -UniValue PegsFund(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, int64_t amount); -UniValue PegsGet(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, int64_t amount); -UniValue PegsRedeem(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid); -UniValue PegsLiquidate(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, uint256 liquidatetxid); -UniValue PegsExchange(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, int64_t amount); -UniValue PegsAccountHistory(const CPubKey& pk,uint256 pegstxid); -UniValue PegsAccountInfo(const CPubKey& pk,uint256 pegstxid); -UniValue PegsWorstAccounts(uint256 pegstxid); -UniValue PegsInfo(uint256 pegstxid); - -#endif diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 91622aff3..e8aa299ab 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -390,8 +390,8 @@ struct CCcontract_info *CCinit(struct CCcontract_info *cp, uint8_t evalcode) strcpy(cp->normaladdr,PegsNormaladdr); strcpy(cp->CChexstr,PegsCChexstr); memcpy(cp->CCpriv,PegsCCpriv,32); - cp->validate = PegsValidate; - cp->ismyvin = IsPegsInput; + //cp->validate = PegsValidate; + //cp->ismyvin = IsPegsInput; break; case EVAL_PAYMENTS: strcpy(cp->unspendableCCaddr,PaymentsCCaddr); diff --git a/src/cc/pegs.cpp b/src/cc/pegs.cpp index beb98bc82..2a14ca3cb 100644 --- a/src/cc/pegs.cpp +++ b/src/cc/pegs.cpp @@ -16,1193 +16,7 @@ * * ******************************************************************************/ -#include "CCPegs.h" #include "../importcoin.h" #include "key_io.h" #include -//NOTE: in process of removal - -// start of consensus code -#ifndef PEGS_THRESHOLDS -#define PEGS_THRESHOLDS -#define PEGS_ACCOUNT_MAX_DEBT 80 -#define PEGS_GLOBAL_RED_ZONE 60 -#define PEGS_ACCOUNT_YELLOW_ZONE 60 -#define PEGS_ACCOUNT_RED_ZONE 90 -#endif // PEGS_THRESHOLDS -#define CC_MARKER_VALUE 10000 - -extern uint64_t ASSETCHAINS_PEGSCCPARAMS[3]; - -extern uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2,uint8_t &wiftype); -extern int64_t GetTokenBalance(CPubKey pk, uint256 tokenid); -extern int32_t hush_currentheight(); - -CScript EncodePegsCreateOpRet(std::vector bindtxids) -{ - CScript opret; uint8_t evalcode = EVAL_PEGS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'C' << bindtxids); - return(opret); -} - -uint8_t DecodePegsCreateOpRet(const CScript &scriptPubKey,std::vector &bindtxids) -{ - std::vector vopret; uint8_t *script,e,f; - - GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_PEGS && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> bindtxids) != 0 ) - { - return(f); - } - return(0); -} - -CScript EncodePegsFundOpRet(uint256 tokenid,uint256 pegstxid,CPubKey srcpub,int64_t amount,std::pair account) -{ - CScript opret; uint8_t evalcode=EVAL_PEGS,funcid='F'; struct CCcontract_info *cp,C; CPubKey pegspk; - std::vector pubkeys; vscript_t vopret; - - cp = CCinit(&C,EVAL_PEGS); - pegspk = GetUnspendable(cp,0); - pubkeys.push_back(srcpub); - pubkeys.push_back(pegspk); - LOGSTREAM("pegscc", CCLOG_DEBUG1, stream << "EncodePegsFundOpRet [" << account.first << "," << account.second << "]" << std::endl); - vopret = E_MARSHAL(ss << evalcode << funcid << pegstxid << srcpub << amount << account); - return(EncodeTokenOpRet(tokenid,pubkeys,make_pair(OPRETID_PEGSDATA, vopret))); -} - -uint8_t DecodePegsFundOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &pegstxid,CPubKey &srcpub,int64_t &amount,std::pair &account) -{ - std::vector> oprets; - std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; - - if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys, oprets)!=0 && GetOpretBlob(oprets, OPRETID_PEGSDATA, vOpretExtra) && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) - { - vopret=vOpretExtra; - } - else GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_PEGS && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> pegstxid; ss >> srcpub; ss >> amount; ss >> account) != 0 ) - { - return(f); - } - return(0); -} - -uint8_t DecodePegsGetOpRet(const CTransaction tx,uint256& pegstxid,uint256 &tokenid,CPubKey &srcpub,int64_t &amount,std::pair &account) -{ - std::vector vopret; uint8_t *script; - ImportProof proof; CTransaction burntx; std::vector payouts; - - GetOpReturnData(tx.vout[tx.vout.size()-1].scriptPubKey, vopret); - - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_IMPORTCOIN && UnmarshalImportTx(tx,proof,burntx,payouts) && UnmarshalBurnTx(burntx,pegstxid,tokenid,srcpub,amount,account)) - { - return('G'); - } - return(0); -} - -CScript EncodePegsReedemOpRet(uint256 tokenid,uint256 pegstxid,CPubKey srcpub,int64_t amount,std::pair account) -{ - CScript opret; uint8_t evalcode=EVAL_PEGS,funcid='R'; struct CCcontract_info *cp,C; - std::vector pubkeys; vscript_t vopret; - - cp = CCinit(&C,EVAL_PEGS); - pubkeys.push_back(srcpub); - vopret = E_MARSHAL(ss << evalcode << funcid << pegstxid << srcpub << amount << account); - return(EncodeTokenOpRet(tokenid,pubkeys,make_pair(OPRETID_PEGSDATA, vopret))); -} - -uint8_t DecodePegsRedeemOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &pegstxid,CPubKey &srcpub,int64_t &amount,std::pair &account) -{ - std::vector> oprets; - std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; - - if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys, oprets)!=0 && GetOpretBlob(oprets, OPRETID_PEGSDATA, vOpretExtra) && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) - { - vopret=vOpretExtra; - } - else GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_PEGS && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> pegstxid; ss >> srcpub; ss >> amount; ss >> account) != 0 ) - { - return(f); - } - return(0); -} - -CScript EncodePegsExchangeOpRet(uint256 tokenid,uint256 pegstxid,CPubKey pk1,CPubKey pk2,int64_t amount,std::pair account) -{ - CScript opret; uint8_t evalcode=EVAL_PEGS,funcid='E'; struct CCcontract_info *cp,C; - std::vector pubkeys; vscript_t vopret; CPubKey pegspk; - - cp = CCinit(&C,EVAL_PEGS); - pegspk = GetUnspendable(cp,0); - pubkeys.push_back(pk1); - pubkeys.push_back(pk2); - vopret = E_MARSHAL(ss << evalcode << funcid << pegstxid << pk1 << amount << account); - return(EncodeTokenOpRet(tokenid,pubkeys,make_pair(OPRETID_PEGSDATA, vopret))); -} - -uint8_t DecodePegsExchangeOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &pegstxid,CPubKey &srcpub,int64_t &amount,std::pair &account) -{ - std::vector> oprets; - std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; - - if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys, oprets)!=0 && GetOpretBlob(oprets, OPRETID_PEGSDATA, vOpretExtra) && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) - { - vopret=vOpretExtra; - } - else GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_PEGS && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> pegstxid; ss >> srcpub; ss >> amount; ss >> account) != 0 ) - { - return(f); - } - return(0); -} - -CScript EncodePegsLiquidateOpRet(uint256 tokenid,uint256 pegstxid,CPubKey srcpub,int64_t amount,std::pair account) -{ - CScript opret; uint8_t evalcode=EVAL_PEGS,funcid='L'; struct CCcontract_info *cp,C; - std::vector pubkeys; vscript_t vopret; - - cp = CCinit(&C,EVAL_PEGS); - pubkeys.push_back(srcpub); - vopret = E_MARSHAL(ss << evalcode << funcid << pegstxid << srcpub << amount << account); - return(EncodeTokenOpRet(tokenid,pubkeys,make_pair(OPRETID_PEGSDATA, vopret))); -} - -uint8_t DecodePegsLiquidateOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &pegstxid,CPubKey &srcpub,int64_t &amount,std::pair &account) -{ - std::vector> oprets; - std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; - - if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys, oprets)!=0 && GetOpretBlob(oprets, OPRETID_PEGSDATA, vOpretExtra) && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) - { - vopret=vOpretExtra; - } - else GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && script[0] == EVAL_PEGS && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> pegstxid; ss >> srcpub; ss >> amount; ss >> account) != 0 ) - { - return(f); - } - return(0); -} - -uint8_t DecodePegsOpRet(CTransaction tx,uint256& pegstxid,uint256& tokenid) -{ - std::vector> oprets; int32_t numvouts=tx.vout.size(); - std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; - ImportProof proof; CTransaction burntx; std::vector payouts; uint256 tmppegstxid; CPubKey srcpub; int64_t amount; std::pair account; - - if (DecodeTokenOpRet(tx.vout[numvouts-1].scriptPubKey,tokenevalcode,tokenid,pubkeys, oprets)!=0 && GetOpretBlob(oprets, OPRETID_PEGSDATA, vOpretExtra) && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) - { - vopret=vOpretExtra; - } - else GetOpReturnData(tx.vout[numvouts-1].scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if (tx.IsPegsImport()) - return(DecodePegsGetOpRet(tx,pegstxid,tokenid,srcpub,amount,account)); - else if ( vopret.size() > 2 && script[0] == EVAL_PEGS) - { - E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> pegstxid); - return(f); - } - return(0); -} - -int64_t IsPegsvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v) -{ - char destaddr[64]; - if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 ) - { - if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 ) - return(tx.vout[v].nValue); - } - return(0); -} - -bool PegsExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx,int32_t minage,uint64_t txfee) -{ - static uint256 zerohash; - CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; int64_t inputs=0,outputs=0,assetoshis; - numvins = tx.vin.size(); - numvouts = tx.vout.size(); - for (i=0; iismyvin)(tx.vin[i].scriptSig) != 0 ) - { - //fprintf(stderr,"vini.%d check mempool\n",i); - if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 ) - return eval->Invalid("cant find vinTx"); - else - { - //fprintf(stderr,"vini.%d check hash and vout\n",i); - if ( hashBlock == zerohash ) - return eval->Invalid("cant Pegs from mempool"); - if ( (assetoshis= IsPegsvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 ) - inputs += assetoshis; - } - } - } - for (i=0; iInvalid("mismatched inputs != outputs + txfee"); - } - else return(true); -} - -bool PegsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn) -{ - int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks; bool retval; uint256 txid; uint8_t hash[32]; char str[65],destaddr[64]; - return (true); - std::vector > txids; - numvins = tx.vin.size(); - numvouts = tx.vout.size(); - preventCCvins = preventCCvouts = -1; - if ( numvouts < 1 ) - return eval->Invalid("no vouts"); - else - { - for (i=0; iInvalid("illegal normal vini"); - } - } - //fprintf(stderr,"check amounts\n"); - if ( PegsExactAmounts(cp,eval,tx,1,10000) == false ) - { - fprintf(stderr,"Pegsget invalid amount\n"); - return false; - } - else - { - txid = tx.GetHash(); - memcpy(hash,&txid,sizeof(hash)); - retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); - if ( retval != 0 ) - fprintf(stderr,"Pegsget validated\n"); - else fprintf(stderr,"Pegsget invalid\n"); - return(retval); - } - } -} -// end of consensus code - -// helper functions for rpc calls in rpcwallet.cpp - -int64_t AddPegsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk1,CPubKey pk2,int64_t total,int32_t maxinputs) -{ - // add threshold check - char coinaddr[64]; int64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t vout,n = 0; - std::vector > unspentOutputs; - - if (pk2.IsValid()) GetCCaddress1of2(cp,coinaddr,pk1,pk2); - else GetCCaddress(cp,coinaddr,pk1); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - // no need to prevent dup - if ( myGetTransaction(txid,vintx,hashBlock) != 0 ) - { - if (myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) - { - if ( total != 0 && maxinputs != 0 ) - mtx.vin.push_back(CTxIn(txid,vout,CScript())); - nValue = it->second.satoshis; - totalinputs += nValue; - n++; - if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) - break; - } - } - } - return(totalinputs); -} - -int64_t AddPegsTokenInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,uint256 pegstxid, uint256 tokenid, CPubKey pk1,CPubKey pk2, int64_t total,int32_t maxinputs) -{ - // add threshold check - char coinaddr[64]; int64_t nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t vout,n = 0; - std::vector > unspentOutputs; uint256 tmppegstxid,tmptokenid; CPubKey mypk; - - if (pk2.IsValid()) GetTokensCCaddress1of2(cp,coinaddr,pk1,pk2); - else GetTokensCCaddress(cp,coinaddr,pk1); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - // no need to prevent dup - if ( myGetTransaction(txid,vintx,hashBlock) != 0 ) - { - if (myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 && DecodePegsOpRet(vintx,tmppegstxid,tmptokenid)!=0 && tmppegstxid==pegstxid && tmptokenid==tokenid) - { - if ( total != 0 && maxinputs != 0 ) - mtx.vin.push_back(CTxIn(txid,vout,CScript())); - nValue = it->second.satoshis; - totalinputs += nValue; - n++; - if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) - break; - } - } - } - if (pk2.IsValid()) - { - mypk = pubkey2pk(Mypubkey()); - if (mypk!=pk1 && mypk!=pk2) - { - CCaddrTokens1of2set(cp,pk1,pk2,cp->CCpriv,coinaddr); - } - else - { - uint8_t mypriv[32]; - Myprivkey(mypriv); - CCaddrTokens1of2set(cp,pk1,pk2,mypriv,coinaddr); - memset(mypriv,0,sizeof(mypriv)); - } - } - return(totalinputs); -} - -std::string PegsDecodeAccountTx(CTransaction tx,CPubKey& pk,int64_t &amount,std::pair &account) -{ - uint256 hashBlock,tokenid,pegstxid; int32_t numvouts=tx.vout.size(); char funcid; - - if ((funcid=DecodePegsOpRet(tx,pegstxid,tokenid))!=0) - { - switch(funcid) - { - case 'F': if (DecodePegsFundOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,pegstxid,pk,amount,account)=='F') return("fund"); - break; - case 'G': if (DecodePegsGetOpRet(tx,pegstxid,tokenid,pk,amount,account)=='G') return("get"); - break; - case 'R': if (DecodePegsRedeemOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,pegstxid,pk,amount,account)=='R') return("redeem"); - break; - case 'E': if (DecodePegsExchangeOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,pegstxid,pk,amount,account)=='R') return("exchange"); - break; - case 'L': if (DecodePegsLiquidateOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,pegstxid,pk,amount,account)=='L') return("liquidate"); - break; - } - } - return (""); -} - -char PegsFindAccount(struct CCcontract_info *cp,CPubKey pk,uint256 pegstxid, uint256 tokenid, uint256 &accounttxid, std::pair &account) -{ - char coinaddr[64]; int64_t nValue,tmpamount; uint256 txid,spenttxid,hashBlock,tmptokenid,tmppegstxid; - CTransaction tx,acctx; int32_t numvouts,vout,ratio; char funcid,f; CPubKey pegspk,tmppk; - std::vector > unspentOutputs; - ImportProof proof; CTransaction burntx; std::vector payouts; - - accounttxid=zeroid; - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,pk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "txid=" << txid.GetHex() << ", vout=" << vout << ", nValue=" << nValue << std::endl); - if (vout == 1 && nValue == CC_MARKER_VALUE && myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (f=DecodePegsOpRet(tx,tmppegstxid,tmptokenid))!=0 && pegstxid==tmppegstxid && tokenid==tmptokenid) - { - accounttxid=txid; - funcid=f; - acctx=tx; - } - } - if (accounttxid!=zeroid && myIsutxo_spentinmempool(spenttxid,ignorevin,accounttxid,1) != 0) - { - accounttxid=zeroid; - if (myGetTransaction(spenttxid,tx,hashBlock)!=0 && (numvouts=tx.vout.size()) > 0 && - (f=DecodePegsOpRet(tx,tmppegstxid,tmptokenid))!=0 && pegstxid==tmppegstxid && tokenid==tmptokenid) - { - funcid=f; - accounttxid=spenttxid; - acctx=tx; - } - } - if (accounttxid!=zeroid) - { - PegsDecodeAccountTx(acctx,tmppk,tmpamount,account); - return(funcid); - } - else return(0); -} - -int64_t PegsGetTokenPrice(uint256 tokenid) -{ - return (0); -} - -std::string PegsGetTokenName(uint256 tokenid) -{ - CTransaction tokentx; uint256 hashBlock; std::string name,desc; std::vector vorigpubkey; int32_t numvouts; - - if (myGetTransaction(tokenid,tokentx,hashBlock)!=0 && (numvouts=tokentx.vout.size())>0 && DecodeTokenCreateOpRet(tokentx.vout[numvouts-1].scriptPubKey,vorigpubkey,name,desc)=='c') - { - return (name); - } - CCerror = strprintf("cant find token create or invalid tokenid %s",tokenid.GetHex()); - LOGSTREAM("pegscc",CCLOG_INFO, stream << CCerror << std::endl); - return(""); -} - -int64_t PegsGetTokensAmountPerPrice(int64_t amount,uint256 tokenid) -{ - mpz_t res,a,b; - mpz_init(res); - mpz_init(a); - mpz_init(b); - mpz_set_si(a, amount); - mpz_set_si(b, COIN); - mpz_mul(res, a, b); - mpz_set_si(a, PegsGetTokenPrice(tokenid)); - mpz_tdiv_q(res, res, a); - return (mpz_get_si(res)); -} - -double PegsGetRatio(uint256 tokenid,std::pair account) -{ - mpz_t res,a,b; - mpz_init(res); - mpz_init(a); - mpz_init(b); - mpz_set_si(a, account.first); - mpz_set_si(b, PegsGetTokenPrice(tokenid)); - mpz_mul(res, a, b); - mpz_set_si(a, COIN); - mpz_tdiv_q(res, res, a); - return ((double)account.second)*100/mpz_get_si(res); -} - -double PegsGetAccountRatio(uint256 pegstxid,uint256 tokenid,uint256 accounttxid) -{ - int64_t amount; uint256 hashBlock,tmptokenid,tmppegstxid; - CTransaction tx; int32_t numvouts; char funcid; CPubKey pk; - std::pair account; struct CCcontract_info *cp,C; - - cp = CCinit(&C,EVAL_PEGS); - if (myGetTransaction(accounttxid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tmptokenid))!=0 && pegstxid==tmppegstxid && tokenid==tmptokenid) - { - PegsDecodeAccountTx(tx,pk,amount,account); - return PegsGetRatio(tokenid,account); - } - return (0); -} - -double PegsGetGlobalRatio(uint256 pegstxid) -{ - char coinaddr[64]; int64_t nValue,amount,globaldebt=0; uint256 txid,accounttxid,hashBlock,tmppegstxid,tokenid; - CTransaction tx; int32_t numvouts,vout; char funcid; CPubKey mypk,pegspk,pk; - std::vector > unspentOutputs; std::pair account; - std::map> globalaccounts; - struct CCcontract_info *cp,C; - - cp = CCinit(&C,EVAL_PEGS); - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,pegspk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - if (vout == 0 && nValue == CC_MARKER_VALUE && myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tokenid))!=0 && pegstxid==tmppegstxid && (funcid=='F' || funcid=='G' || funcid=='E')) - { - PegsDecodeAccountTx(tx,pk,amount,account); - globalaccounts[tokenid].first+=account.first; - globalaccounts[tokenid].second+=account.second; - } - } - unspentOutputs.clear(); - GetTokensCCaddress(cp,coinaddr,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - if (myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && DecodePegsOpRet(tx,tmppegstxid,tokenid)!=0 && pegstxid==tmppegstxid) - { - globalaccounts[tokenid].first+=nValue; - } - } - mpz_t res,globaldeposit,a,b; - mpz_init(res); - mpz_init(globaldeposit); - mpz_init(a); - mpz_init(b); - mpz_set_si(globaldeposit, 0); - for (std::map>::iterator it = globalaccounts.begin(); it != globalaccounts.end(); ++it) - { - mpz_set_si(res, 0); - mpz_set_si(a, globalaccounts[it->first].first); - mpz_set_si(b, PegsGetTokenPrice(it->first)); - mpz_mul(res,a,b); - mpz_add(globaldeposit,globaldeposit,res); - globaldebt+=globalaccounts[it->first].second; - } - if (globaldebt>0) - { - mpz_set_si(res, 0); - mpz_set_si(a, COIN); - mpz_tdiv_q(res, globaldeposit, a); - printf("%lu %lu\n",globaldebt,mpz_get_si(res)); - return ((double)globaldebt)*100/mpz_get_si(res); - } - return (0); -} - -std::string PegsFindBestAccount(struct CCcontract_info *cp,uint256 pegstxid, uint256 tokenid, int64_t tokenamount,uint256 &accounttxid, std::pair &account) -{ - char coinaddr[64]; int64_t nValue,tmpamount; uint256 txid,hashBlock,tmptokenid,tmppegstxid; - CTransaction tx,acctx; int32_t numvouts,vout; char funcid,f; CPubKey pegspk,tmppk; - std::vector > unspentOutputs; - ImportProof proof; CTransaction burntx; std::vector payouts; double ratio,maxratio=0; - std::pair tmpaccount; - - accounttxid=zeroid; - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,pegspk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "txid=" << txid.GetHex() << ", vout=" << vout << ", nValue=" << nValue << std::endl); - if (vout == 0 && nValue == CC_MARKER_VALUE && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 && - (ratio=PegsGetAccountRatio(pegstxid,tokenid,txid))>(ASSETCHAINS_PEGSCCPARAMS[2]?ASSETCHAINS_PEGSCCPARAMS[2]:PEGS_ACCOUNT_YELLOW_ZONE) && ratio>maxratio) - { - if (myGetTransaction(txid,tx,hashBlock)!=0 && !PegsDecodeAccountTx(tx,tmppk,tmpamount,tmpaccount).empty() && tmpaccount.first>=tokenamount) - { - accounttxid=txid; - acctx=tx; - maxratio=ratio; - } - } - } - if (accounttxid!=zeroid) - { - return(PegsDecodeAccountTx(acctx,tmppk,tmpamount,account)); - } - else return(""); -} - -UniValue PegsCreate(const CPubKey& pk,uint64_t txfee,int64_t amount, std::vector bindtxids) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()); - CPubKey mypk,pegspk; struct CCcontract_info *cp,C; CTransaction tx; int32_t numvouts; int64_t totalsupply; std::string coin; - char depositaddr[64]; uint256 txid,hashBlock,tmptokenid,oracletxid; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; - - cp = CCinit(&C,EVAL_PEGS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - for(auto txid : bindtxids) - { - if (myGetTransaction(txid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find bindtxid " << txid.GetHex()); - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmptokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype)!='B') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid bindtxid " << txid.GetHex()); - } - if ( AddNormalinputs(mtx,mypk,amount,64,pk.IsValid()) >= amount ) - { - for (int i=0; i<100; i++) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,(amount-txfee)/100,pegspk)); - return(FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,EncodePegsCreateOpRet(bindtxids))); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "error adding normal inputs"); -} - -UniValue PegsFund(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid,int64_t amount) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()); std::string coin; - CTransaction pegstx,tx; int32_t numvouts; int64_t totalsupply,balance=0,funds=0,tokenfunds=0; uint256 accounttxid=zeroid,hashBlock,txid,tmptokenid,oracletxid; - CPubKey mypk,pegspk,tmppk; struct CCcontract_info *cp,*cpTokens,CTokens,C; char depositaddr[64],coinaddr[64]; std::pair account(0,0); - uint8_t M,N,taddr,prefix,prefix2,wiftype,mypriv[32]; std::vector pubkeys; bool found=false; std::vector bindtxids; - - cp = CCinit(&C,EVAL_PEGS); - cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - for(auto txid : bindtxids) - { - if (myGetTransaction(txid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find bindtxid " << txid.GetHex()); - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmptokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype)!='B') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid bindtxid " << txid.GetHex()); - if (tmptokenid==tokenid) - { - found=true; - break; - } - } - if (!found) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid tokenid " << tokenid.GetHex()); - if ((balance=GetTokenBalance(mypk,tokenid))>=amount) - { - PegsFindAccount(cp,mypk,pegstxid,tokenid,accounttxid,account); - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "current accounttxid=" << accounttxid.GetHex() << " [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - if (accounttxid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,accounttxid,1) != 0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "previous account tx not yet confirmed"); - if (accounttxid!=zeroid && (funds=AddPegsInputs(cp,mtx,pegspk,CPubKey(),txfee,1))>=txfee) - { - funds+=2*CC_MARKER_VALUE; - mtx.vin.push_back(CTxIn(accounttxid,0,CScript())); - Myprivkey(mypriv); - mtx.vin.push_back(CTxIn(accounttxid,1,CScript())); - GetCCaddress1of2(cp,coinaddr,mypk,pegspk); - CCaddr1of2set(cp,mypk,pegspk,mypriv,coinaddr); - memset(mypriv,0,sizeof(mypriv)); - } - else funds=AddPegsInputs(cp,mtx,pegspk,CPubKey(),txfee+2*CC_MARKER_VALUE,3); - if (funds>=txfee+2*CC_MARKER_VALUE) - { - if ((tokenfunds=AddTokenCCInputs(cpTokens,mtx,mypk,tokenid,amount,64))>=amount) - { - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,pegspk,pegspk)); - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,mypk,pegspk)); - mtx.vout.push_back(MakeTokensCC1of2vout(EVAL_PEGS,amount,mypk,pegspk)); - if (tokenfunds-amount>0) mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS,tokenfunds-amount,mypk)); - if (funds>txfee+2*CC_MARKER_VALUE) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,funds-(txfee+2*CC_MARKER_VALUE),pegspk)); - account.first+=amount; - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "new account [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - return(FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,EncodePegsFundOpRet(tokenid,pegstxid,mypk,amount,account))); - } - } - else - CCERR_RESULT("pegscc",CCLOG_INFO, stream <<"not enough balance in pegs global CC address"); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance (" << balance << ") for this amount of tokens " << amount); -} - -UniValue PegsGet(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, int64_t amount) -{ - CMutableTransaction burntx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()),mtx; - CTransaction pegstx,tx; int32_t numvouts; int64_t funds=0; uint256 accounttxid=zeroid,hashBlock,pricestxid; char coinaddr[64]; - CPubKey mypk,pegspk,tmppk; struct CCcontract_info *cp,C; std::pair account(0,0); uint8_t mypriv[32]; - std::vector dummyproof; std::vector vouts; std::vector bindtxids; CScript opret; - - cp = CCinit(&C,EVAL_PEGS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - if (PegsFindAccount(cp,mypk,pegstxid,tokenid,accounttxid,account)==0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cannot find account from which to issue coins, fund account first with pegsfund!"); - if (accounttxid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,accounttxid,1) != 0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "previous account tx not yet confirmed"); - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "current accounttxid=" << accounttxid.GetHex() << " [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - // spending markers - vouts.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,pegspk,pegspk)); - vouts.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,mypk,pegspk)); - // coin issue - vouts.push_back(CTxOut(amount,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); - account.second+=amount; - if (PegsGetRatio(tokenid,account)>PEGS_ACCOUNT_MAX_DEBT) - { - CCerror = strprintf("not possible to take more than %d%% of the deposit",PEGS_ACCOUNT_MAX_DEBT); - LOGSTREAM("pegscc",CCLOG_INFO, stream << CCerror << std::endl); - return(""); - } - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "new account [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - // burn tx does not exist in pegs method but it must be created in order for import validation to pass - // fictive burntx input of previous account state tx - burntx.vin.push_back(CTxIn(accounttxid,0,CScript())); - // fictive output of coins in burn tx - burntx.vout.push_back(MakeBurnOutput(amount,0xffffffff,"PEGSCC",vouts,dummyproof,pegstxid,tokenid,mypk,amount,account)); - std::vector leaftxids; - BitcoinGetProofMerkleRoot(dummyproof, leaftxids); - MerkleBranch newBranch(0, leaftxids); - TxProof txProof = std::make_pair(burntx.GetHash(), newBranch); - mtx=MakePegsImportCoinTransaction(txProof,burntx,vouts); - Myprivkey(mypriv); - GetCCaddress1of2(cp,coinaddr,mypk,pegspk); - CCaddr1of2set(cp,mypk,pegspk,mypriv,coinaddr); - UniValue retstr = FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,opret); - memset(mypriv,0,sizeof(mypriv)); - return(retstr); -} - -UniValue PegsRedeem(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()); std::string coin; - CTransaction pegstx,tx; int32_t numvouts; int64_t totalsupply,pegsfunds=0,funds=0,tokenfunds=0,amount; uint256 accounttxid=zeroid,hashBlock,txid,tmptokenid,oracletxid; - CPubKey mypk,pegspk,tmppk; struct CCcontract_info *cp,*cpTokens,CTokens,C; char depositaddr[64],coinaddr[64]; std::pair account(0,0); - uint8_t M,N,taddr,prefix,prefix2,wiftype,mypriv[32]; std::vector pubkeys; bool found=false; std::vector bindtxids; - - cp = CCinit(&C,EVAL_PEGS); - cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - for(auto txid : bindtxids) - { - if (myGetTransaction(txid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find bindtxid " << txid.GetHex()); - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmptokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype)!='B') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid bindtxid " << txid.GetHex()); - if (tmptokenid==tokenid) - { - found=true; - break; - } - } - if (!found) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid tokenid " << tokenid.GetHex()); - if (PegsFindAccount(cp,mypk,pegstxid,tokenid,accounttxid,account)==0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cannot find account from which to redeem tokens!"); - if (accounttxid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,accounttxid,1) != 0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "previous account tx not yet confirmed"); - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "current accounttxid=" << accounttxid.GetHex() << " [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - if ((funds=AddNormalinputs(mtx,mypk,account.second,64,pk.IsValid()))>=account.second ) - { - if (accounttxid!=zeroid && (pegsfunds=AddPegsInputs(cp,mtx,pegspk,CPubKey(),txfee,1))>=txfee) - { - pegsfunds+=2*CC_MARKER_VALUE; - mtx.vin.push_back(CTxIn(accounttxid,0,CScript())); - mtx.vin.push_back(CTxIn(accounttxid,1,CScript())); - Myprivkey(mypriv); - GetCCaddress1of2(cp,coinaddr,mypk,pegspk); - CCaddr1of2set(cp,mypk,pegspk,mypriv,coinaddr); - amount=account.first; - if ((tokenfunds=AddPegsTokenInputs(cp,mtx,pegstxid,tokenid,mypk,pegspk,amount,64))>=amount) - { - if (pegsfunds>=txfee+2*CC_MARKER_VALUE) - { - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,pegspk,pegspk)); - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,mypk,pegspk)); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS,amount,mypk)); - mtx.vout.push_back(CTxOut(account.second,CScript() << ParseHex(HexStr(CCtxidaddr(coinaddr,pegstxid))) << OP_CHECKSIG)); - if (pegsfunds>txfee+2*CC_MARKER_VALUE) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,pegsfunds-(txfee+2*CC_MARKER_VALUE),pegspk)); - account.first=0; - account.second=0; - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "new account [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - UniValue retstr = FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,EncodePegsReedemOpRet(tokenid,pegstxid,mypk,amount,account)); - memset(mypriv,0,32); - return(retstr); - } - else - { - memset(mypriv,0,32); - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - } - memset(mypriv,0,32); - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough tokens in pegs account (" << tokenfunds << ") to redeem this amount of tokens " << account.first); - } - else - { - memset(mypriv,0,32); - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - } - memset(mypriv,0,32); - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "to redeem from account and close it you must redeem full debt ammount " << account.second << " instead of " << funds); -} - - -UniValue PegsExchange(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, int64_t amount) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()); std::string coin; - CTransaction pegstx,tx; int32_t numvouts; int64_t totalsupply,pegsfunds=0,funds=0,tokenfunds=0,tokenamount,tmpamount; uint256 accounttxid=zeroid,hashBlock,txid,tmptokenid,oracletxid; - CPubKey mypk,pegspk,tmppk; struct CCcontract_info *cp,*cpTokens,CTokens,C; char depositaddr[64],coinaddr[64]; std::pair account(0,0); - uint8_t M,N,taddr,prefix,prefix2,wiftype,mypriv[32]; std::vector pubkeys; bool found=false; std::vector bindtxids; - - cp = CCinit(&C,EVAL_PEGS); - cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - for(auto txid : bindtxids) - { - if (myGetTransaction(txid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find bindtxid " << txid.GetHex()); - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmptokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype)!='B') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid bindtxid " << txid.GetHex()); - if (tmptokenid==tokenid) - { - found=true; - break; - } - } - if (!found) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid tokenid " << tokenid.GetHex()); - if (PegsFindAccount(cp,mypk,pegstxid,tokenid,accounttxid,account)!=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "you have active account, please close account first before exchanging other coins!"); - if ((funds=AddNormalinputs(mtx,mypk,amount,64,pk.IsValid()))>=amount ) - { - if ((pegsfunds=AddPegsInputs(cp,mtx,pegspk,CPubKey(),txfee,1))>=txfee) - { - tokenamount=PegsGetTokensAmountPerPrice(amount,tokenid); - tokenfunds=AddPegsTokenInputs(cp,mtx,pegstxid,tokenid,pegspk,CPubKey(),tokenamount,64); - if (tokenfundsCCpriv,coinaddr); - pegsfunds+=2*CC_MARKER_VALUE; - } - if (tokenfunds>=tokenamount) - { - if (accounttxid!=zeroid) - { - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,pegspk,pegspk)); - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,tmppk,pegspk)); - } - if ((accounttxid!=zeroid && pegsfunds>=txfee+2*CC_MARKER_VALUE) || pegsfunds>=txfee) - { - mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS,tokenamount,mypk)); - mtx.vout.push_back(CTxOut(amount,CScript() << ParseHex(HexStr(CCtxidaddr(coinaddr,pegstxid))) << OP_CHECKSIG)); - if (tokenfunds>tokenamount) mtx.vout.push_back(MakeTokensCC1of2vout(EVAL_PEGS,tokenfunds-tokenamount,tmppk,pegspk)); - if (accounttxid!=zeroid) - { - if (pegsfunds>txfee+2*CC_MARKER_VALUE) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,pegsfunds-(txfee+2*CC_MARKER_VALUE),pegspk)); - account.first=account.first-tokenamount; - account.second=account.second-amount; - } - else if (pegsfunds>txfee) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,pegsfunds-txfee,pegspk)); - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "modified account [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - return(FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,EncodePegsExchangeOpRet(tokenid,pegstxid,mypk,tmppk,amount,account))); - } - else - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough tokens in pegs account (" << tokenfunds << ") to exchange to this amount of tokens " << tokenamount); - } - else - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough funds to exchange " << amount << " coins to tokens - balance " << funds); -} - -UniValue PegsLiquidate(const CPubKey& pk,uint64_t txfee,uint256 pegstxid, uint256 tokenid, uint256 liquidatetxid) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), hush_nextheight()); std::string coin; - CTransaction pegstx,tx; int32_t numvouts; int64_t totalsupply,pegsfunds=0,funds=0,tokenfunds=0,amount,tmpamount,tokenamount,burnamount; - CPubKey mypk,pegspk,tmppk; struct CCcontract_info *cp,*cpTokens,CTokens,C; char depositaddr[64],coinaddr[64]; std::pair account(0,0),myaccount(0,0); - uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; bool found=false; std::vector bindtxids; - uint256 hashBlock,txid,tmptokenid,oracletxid,accounttxid; - - cp = CCinit(&C,EVAL_PEGS); - cpTokens = CCinit(&CTokens,EVAL_TOKENS); - if ( txfee == 0 ) - txfee = 10000; - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - for(auto txid : bindtxids) - { - if (myGetTransaction(txid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find bindtxid " << txid.GetHex()); - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmptokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype)!='B') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid bindtxid " << txid.GetHex()); - if (tmptokenid==tokenid) - { - found=true; - break; - } - } - if (!found) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid tokenid " << tokenid.GetHex()); - if (PegsFindAccount(cp,mypk,pegstxid,tokenid,accounttxid,myaccount)==0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cannot find account, you must have an account to liquidate another account!"); - if (accounttxid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,accounttxid,1) != 0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "previous account tx not yet confirmed"); - if (PegsGetAccountRatio(pegstxid,tokenid,liquidatetxid)<(ASSETCHAINS_PEGSCCPARAMS[0]?ASSETCHAINS_PEGSCCPARAMS[0]:PEGS_ACCOUNT_RED_ZONE) || PegsGetGlobalRatio(pegstxid)<(ASSETCHAINS_PEGSCCPARAMS[1]?ASSETCHAINS_PEGSCCPARAMS[1]:PEGS_ACCOUNT_RED_ZONE)) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not able to liquidate account until account ratio > " << (ASSETCHAINS_PEGSCCPARAMS[0]?ASSETCHAINS_PEGSCCPARAMS[0]:PEGS_ACCOUNT_RED_ZONE) << "% and global ratio > " << (ASSETCHAINS_PEGSCCPARAMS[1]?ASSETCHAINS_PEGSCCPARAMS[1]:PEGS_ACCOUNT_RED_ZONE) << "%"); - if (liquidatetxid!=zeroid && myGetTransaction(liquidatetxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0 || PegsDecodeAccountTx(tx,tmppk,amount,account).empty()) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cannot find account to liquidate or invalid tx " << liquidatetxid.GetHex()); - if (liquidatetxid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,liquidatetxid,1) != 0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "previous liquidate account tx not yet confirmed"); - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "current accounttxid=" << accounttxid.GetHex() << " [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - tokenamount=account.first; - burnamount=account.second; - tmpamount=PegsGetTokensAmountPerPrice(burnamount,tokenid)*105/100; - amount=tmpamount+((tokenamount-tmpamount)*10/100); - if ((funds=AddNormalinputs(mtx,mypk,account.second,64))>=burnamount) - { - if (liquidatetxid!=zeroid && (pegsfunds=AddPegsInputs(cp,mtx,pegspk,CPubKey(),txfee,1))>=txfee) - { - pegsfunds+=2*CC_MARKER_VALUE; - mtx.vin.push_back(CTxIn(liquidatetxid,0,CScript())); - mtx.vin.push_back(CTxIn(liquidatetxid,1,CScript())); - GetCCaddress1of2(cp,coinaddr,tmppk,pegspk); - CCaddr1of2set(cp,tmppk,pegspk,cp->CCpriv,coinaddr); - if ((tokenfunds=AddPegsTokenInputs(cp,mtx,pegstxid,tokenid,tmppk,pegspk,tokenamount,64))==tokenamount) - { - if (pegsfunds>=txfee+2*CC_MARKER_VALUE) - { - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,pegspk,pegspk)); - mtx.vout.push_back(MakeCC1of2vout(EVAL_PEGS,CC_MARKER_VALUE,tmppk,pegspk)); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS,amount,mypk)); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_PEGS,tokenamount-amount,pegspk)); - mtx.vout.push_back(CTxOut(burnamount,CScript() << ParseHex(HexStr(CCtxidaddr(coinaddr,pegstxid))) << OP_CHECKSIG)); - if (pegsfunds>txfee+2*CC_MARKER_VALUE) mtx.vout.push_back(MakeCC1vout(EVAL_PEGS,pegsfunds-(txfee+2*CC_MARKER_VALUE),pegspk)); - account.first=0; - account.second=0; - LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "new account [deposit=" << account.first << ",debt=" << account.second << "]" << std::endl); - return(FinalizeCCTxExt(pk.IsValid(),0,cp,mtx,mypk,txfee,EncodePegsLiquidateOpRet(tokenid,pegstxid,mypk,amount,account))); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "tokens amount in pegs account " << tokenfunds << " not matching amount in account " << account.first); // this shouldn't happen - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough balance in pegs global CC address"); - } - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "not enough funds to liquidate account, you must liquidate full debt ammount " << txfee+account.second << " instead of " << funds); -} - -UniValue PegsAccountHistory(const CPubKey& pk,uint256 pegstxid) -{ - char coinaddr[64]; int64_t nValue,amount; uint256 txid,accounttxid,hashBlock,tmptokenid,tmppegstxid; - CTransaction tx; int32_t numvouts,vout; char funcid; CPubKey mypk,pegspk,tmppk; std::map> accounts; - std::vector txids; std::pair account; std::vector bindtxids; - UniValue result(UniValue::VOBJ),acc(UniValue::VARR); struct CCcontract_info *cp,C; - - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","pegsaccounthistory")); - cp = CCinit(&C,EVAL_PEGS); - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,mypk,pegspk); - SetCCtxids(txids,coinaddr,true,EVAL_PEGS,pegstxid,0); - for (std::vector::const_iterator it=txids.begin(); it!=txids.end(); it++) - { - txid = *it; - if (myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tmptokenid))!=0 && pegstxid==tmppegstxid) - { - UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("action",PegsDecodeAccountTx(tx,tmppk,amount,account))); - obj.push_back(Pair("amount",amount)); - obj.push_back(Pair("accounttxid",txid.GetHex())); - obj.push_back(Pair("token",PegsGetTokenName(tmptokenid))); - obj.push_back(Pair("deposit",account.first)); - obj.push_back(Pair("debt",account.second)); - acc.push_back(obj); - } - } - result.push_back(Pair("account history",acc)); - return(result); -} - -UniValue PegsAccountInfo(const CPubKey& pk,uint256 pegstxid) -{ - char coinaddr[64]; int64_t nValue,amount; uint256 txid,accounttxid,hashBlock,tmptokenid,tmppegstxid; std::map> accounts; - CTransaction tx; int32_t numvouts,vout; char funcid; CPubKey mypk,pegspk,tmppk; std::vector bindtxids; - std::vector > unspentOutputs; std::pair account; - UniValue result(UniValue::VOBJ),acc(UniValue::VARR); struct CCcontract_info *cp,C; - - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","pegsaccountinfo")); - cp = CCinit(&C,EVAL_PEGS); - mypk = pk.IsValid()?pk:pubkey2pk(Mypubkey()); - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,mypk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - //LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "txid=" << txid.GetHex() << ", vout=" << vout << ", nValue=" << nValue << std::endl); - if (vout == 1 && nValue == CC_MARKER_VALUE && myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tmptokenid))!=0 && pegstxid==tmppegstxid) - { - //LOGSTREAM("pegscc",CCLOG_DEBUG2, stream << "txid=" << txid.GetHex() << ", vout=" << vout << ", nValue=" << nValue << ", tokenid=" << tmptokenid.GetHex() << std::endl); - PegsDecodeAccountTx(tx,tmppk,amount,account); - accounts[tmptokenid].first=account.first; - accounts[tmptokenid].second=account.second; - } - } - for (std::map>::iterator it = accounts.begin(); it != accounts.end(); ++it) - { - UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("token",PegsGetTokenName(it->first))); - obj.push_back(Pair("deposit",accounts[it->first].first)); - obj.push_back(Pair("debt",accounts[it->first].second)); - if (accounts[it->first].first==0 || accounts[it->first].second==0 || PegsGetTokenPrice(it->first)<=0) obj.push_back(Pair("ratio",0)); - else obj.push_back(Pair("ratio",strprintf("%.2f%%",PegsGetRatio(it->first,accounts[it->first])))); - acc.push_back(obj); - } - result.push_back(Pair("account info",acc)); - return(result); -} - -UniValue PegsWorstAccounts(uint256 pegstxid) -{ - char coinaddr[64]; int64_t nValue,amount; uint256 txid,accounttxid,hashBlock,tmppegstxid,tokenid,prev; - CTransaction tx; int32_t numvouts,vout; char funcid; CPubKey pegspk,pk; double ratio; std::vector bindtxids; - std::vector > unspentOutputs; std::pair account; - UniValue result(UniValue::VOBJ),acc(UniValue::VARR); struct CCcontract_info *cp,C; std::multimap map; - - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","pegsworstaccounts")); - cp = CCinit(&C,EVAL_PEGS); - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,pegspk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - if (vout == 0 && nValue == CC_MARKER_VALUE && myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tokenid))!=0 && pegstxid==tmppegstxid) - { - PegsDecodeAccountTx(tx,pk,amount,account); - if (account.first==0 || account.second==0 || PegsGetTokenPrice(tokenid)<=0) ratio=0; - else ratio=PegsGetRatio(tokenid,account); - if (ratio>PEGS_ACCOUNT_RED_ZONE) - { - UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("accounttxid",txid.GetHex())); - obj.push_back(Pair("deposit",account.first)); - obj.push_back(Pair("debt",account.second)); - obj.push_back(Pair("ratio",strprintf("%.2f%%",ratio))); - map.insert(std::pair(tokenid,obj)); - } - } - } - std::multimap::iterator it = map.begin(); - for (prev=it->first; it != map.end(); ++it) - { - if (it->first!=prev) - { - result.push_back(Pair(PegsGetTokenName(prev),acc)); - acc.clear(); - prev=it->first; - } - acc.push_back(it->second); - } - result.push_back(Pair(PegsGetTokenName(prev),acc)); - return(result); -} - -UniValue PegsInfo(uint256 pegstxid) -{ - char coinaddr[64]; int64_t nValue,amount; uint256 txid,accounttxid,hashBlock,tmppegstxid,tokenid; - CTransaction tx; int32_t numvouts,vout; char funcid; CPubKey pegspk,pk; std::vector bindtxids; - std::vector > unspentOutputs; std::pair account; - std::map> globalaccounts; double globaldeposit=0; - UniValue result(UniValue::VOBJ),acc(UniValue::VARR); struct CCcontract_info *cp,C; - - if (myGetTransaction(pegstxid,tx,hashBlock)==0 || (numvouts=tx.vout.size())<=0) - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "cant find pegstxid " << pegstxid.GetHex()); - if (DecodePegsCreateOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxids)!='C') - CCERR_RESULT("pegscc",CCLOG_INFO, stream << "invalid pegstxid " << pegstxid.GetHex()); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","pegsinfo")); - cp = CCinit(&C,EVAL_PEGS); - pegspk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,coinaddr,pegspk,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - if (vout == 0 && nValue == CC_MARKER_VALUE && myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && - (funcid=DecodePegsOpRet(tx,tmppegstxid,tokenid))!=0 && pegstxid==tmppegstxid) - { - PegsDecodeAccountTx(tx,pk,amount,account); - globalaccounts[tokenid].first+=account.first; - globalaccounts[tokenid].second+=account.second; - } - } - unspentOutputs.clear(); - GetTokensCCaddress(cp,coinaddr,pegspk); - SetCCunspents(unspentOutputs,coinaddr,true); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - nValue = (int64_t)it->second.satoshis; - if (myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size())>0 && DecodePegsOpRet(tx,tmppegstxid,tokenid)!=0 && pegstxid==tmppegstxid) - { - globalaccounts[tokenid].first+=nValue; - } - } - for (std::map>::iterator it = globalaccounts.begin(); it != globalaccounts.end(); ++it) - { - UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("token",PegsGetTokenName(it->first))); - obj.push_back(Pair("total deposit",globalaccounts[it->first].first)); - obj.push_back(Pair("total debt",globalaccounts[it->first].second)); - if (globalaccounts[it->first].first==0 || globalaccounts[it->first].second==0 || PegsGetTokenPrice(it->first)<=0) obj.push_back(Pair("total ratio",0)); - else obj.push_back(Pair("total ratio",strprintf("%.2f%%",PegsGetRatio(it->first,globalaccounts[it->first])))); - acc.push_back(obj); - } - result.push_back(Pair("info",acc)); - result.push_back(Pair("global ratio",strprintf("%.2f%%",PegsGetGlobalRatio(pegstxid)))); - return(result); -} From 196e00c78640c3133bc1e32f6d6b190b34f68b31 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 10:24:12 -0800 Subject: [PATCH 15/22] Remove unused variables --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 81fd936a6..edfd1742c 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -174,7 +174,7 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 } } else pk = _pk; - uint64_t deposits,voutsum=0; int32_t isrealtime,hushheight; uint32_t blocktime; const CChainParams& chainparams = Params(); + uint64_t voutsum=0; uint32_t blocktime; const CChainParams& chainparams = Params(); bool fNotarizationBlock = false; std::vector NotarizationNotaries; //fprintf(stderr,"%s: create new block with pubkey=%s\n", __func__, HexStr(pk).c_str()); From 7d73ebd7afe7acae18dff58b3e3b24d49aeb335c Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 10:25:36 -0800 Subject: [PATCH 16/22] Remove voutsum variable which is calculated but never used --- src/miner.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index edfd1742c..e258d8d38 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -174,7 +174,7 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 } } else pk = _pk; - uint64_t voutsum=0; uint32_t blocktime; const CChainParams& chainparams = Params(); + uint32_t blocktime; const CChainParams& chainparams = Params(); bool fNotarizationBlock = false; std::vector NotarizationNotaries; //fprintf(stderr,"%s: create new block with pubkey=%s\n", __func__, HexStr(pk).c_str()); @@ -241,9 +241,6 @@ CBlockTemplate* CreateNewBlock(CPubKey _pk,const CScript& _scriptPubKeyIn, int32 //fprintf(stderr,"%s: nHeight=%d, consensusBranchId=%u, proposedTime=%u\n", __func__, nHeight, consensusBranchId, proposedTime); - voutsum = GetBlockSubsidy(nHeight,consensusParams) + 10000*COIN; // approx fees - //fprintf(stderr,"%s: voutsum=%lu\n", __func__, voutsum); - if (proposedTime == nMedianTimePast) { // too fast or stuck, this addresses the too fast issue, while moving From d5c5c6008cc4d7ccda808dcb982c87be754f5939 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 13:05:31 -0800 Subject: [PATCH 17/22] Remove unused code --- src/Makefile.am | 1 - src/cc/pegs.cpp | 22 ---------------------- 2 files changed, 23 deletions(-) delete mode 100644 src/cc/pegs.cpp diff --git a/src/Makefile.am b/src/Makefile.am index 021c53b1b..98d0216b0 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -287,7 +287,6 @@ libbitcoin_server_a_SOURCES = \ cc/fsm.cpp \ cc/heir.cpp \ cc/oracles.cpp \ - cc/pegs.cpp \ cc/payments.cpp \ cc/gateways.cpp \ cc/channels.cpp \ diff --git a/src/cc/pegs.cpp b/src/cc/pegs.cpp deleted file mode 100644 index 2a14ca3cb..000000000 --- a/src/cc/pegs.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2016-2023 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/****************************************************************************** - * Copyright © 2014-2019 The SuperNET Developers. * - * * - * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * - * the top-level directory of this distribution for the individual copyright * - * holder information and the developer policies on copyright and licensing. * - * * - * Unless otherwise agreed in a custom licensing agreement, no part of the * - * SuperNET software, including this file may be copied, modified, propagated * - * or distributed except according to the terms contained in the LICENSE file * - * * - * Removal or modification of this copyright notice is prohibited. * - * * - ******************************************************************************/ - -#include "../importcoin.h" -#include "key_io.h" -#include - From a23ab58af6f4282e5c7f5d22f12f4b1ccad887c4 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 13:20:17 -0800 Subject: [PATCH 18/22] Start removing unused gateway code --- src/rpc/server.cpp | 30 ---- src/rpc/server.h | 15 -- src/wallet/rpcwallet.cpp | 316 --------------------------------------- 3 files changed, 361 deletions(-) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index c50d702a3..d764f392d 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -356,19 +356,6 @@ static const CRPCCommand vRPCCommands[] = { "crosschain", "migrate_createnotaryapprovaltransaction", &migrate_createnotaryapprovaltransaction, true }, { "crosschain", "selfimport", &selfimport, true }, { "crosschain", "importdual", &importdual, true }, - //ImportGateway - { "crosschain", "importgatewayddress", &importgatewayaddress, true }, - { "crosschain", "importgatewayinfo", &importgatewayinfo, true }, - { "crosschain", "importgatewaybind", &importgatewaybind, true }, - { "crosschain", "importgatewaydeposit", &importgatewaydeposit, true }, - { "crosschain", "importgatewaywithdraw", &importgatewaywithdraw, true }, - { "crosschain", "importgatewaypartialsign", &importgatewaypartialsign, true }, - { "crosschain", "importgatewaycompletesigning", &importgatewaycompletesigning, true }, - { "crosschain", "importgatewaymarkdone", &importgatewaymarkdone, true }, - { "crosschain", "importgatewaypendingwithdraws", &importgatewaypendingwithdraws, true }, - { "crosschain", "importgatewayprocessed", &importgatewayprocessed, true }, - - /* Mining */ { "mining", "getblocktemplate", &getblocktemplate, true }, @@ -489,23 +476,6 @@ static const CRPCCommand vRPCCommands[] = { "CClib", "cclibinfo", &cclibinfo, true }, { "CClib", "cclib", &cclib, true }, - // Gateways - { "gateways", "gatewaysaddress", &gatewaysaddress, true }, - { "gateways", "gatewayslist", &gatewayslist, true }, - { "gateways", "gatewaysexternaladdress", &gatewaysexternaladdress, true }, - { "gateways", "gatewaysdumpprivkey", &gatewaysdumpprivkey, true }, - { "gateways", "gatewaysinfo", &gatewaysinfo, true }, - { "gateways", "gatewaysbind", &gatewaysbind, true }, - { "gateways", "gatewaysdeposit", &gatewaysdeposit, true }, - { "gateways", "gatewaysclaim", &gatewaysclaim, true }, - { "gateways", "gatewayswithdraw", &gatewayswithdraw, true }, - { "gateways", "gatewayspartialsign", &gatewayspartialsign, true }, - { "gateways", "gatewayscompletesigning", &gatewayscompletesigning, true }, - { "gateways", "gatewaysmarkdone", &gatewaysmarkdone, true }, - { "gateways", "gatewayspendingdeposits", &gatewayspendingdeposits, true }, - { "gateways", "gatewayspendingwithdraws", &gatewayspendingwithdraws, true }, - { "gateways", "gatewaysprocessed", &gatewaysprocessed, true }, - // dice { "dice", "dicelist", &dicelist, true }, { "dice", "diceinfo", &diceinfo, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index 3b229d6f3..8f90627fe 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -284,21 +284,6 @@ extern UniValue payments_list(const UniValue& params, bool fHelp, const CPubKey& extern UniValue cclibaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue cclibinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue cclib(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysaddress(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayslist(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysdumpprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysexternaladdress(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysbind(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysdeposit(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysclaim(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayswithdraw(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayspartialsign(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayscompletesigning(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysmarkdone(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue gatewaysprocessed(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue channelslist(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue channelsinfo(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue channelsopen(const UniValue& params, bool fHelp, const CPubKey& mypk); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 1dcc1525c..630c9be13 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6486,19 +6486,6 @@ UniValue paymentsaddress(const UniValue& params, bool fHelp, const CPubKey& mypk return(CCaddress(cp,(char *)"Payments",pubkey)); } -UniValue gatewaysaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - struct CCcontract_info *cp,C; std::vector pubkey; - cp = CCinit(&C,EVAL_GATEWAYS); - if ( fHelp || params.size() > 1 ) - throw runtime_error("gatewaysaddress [pubkey]\n"); - if ( ensure_CCrequirements(cp->evalcode) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); - return(CCaddress(cp,(char *)"Gateways",pubkey)); -} - UniValue heiraddress(const UniValue& params, bool fHelp, const CPubKey& mypk) { struct CCcontract_info *cp,C; std::vector pubkey; @@ -6617,19 +6604,6 @@ UniValue tokenaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) return(CCaddress(cp,(char *)"Tokens", pubkey)); } -UniValue importgatewayaddress(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - struct CCcontract_info *cp,C; std::vector pubkey; - cp = CCinit(&C,EVAL_IMPORTGATEWAY); - if ( fHelp || params.size() > 1 ) - throw runtime_error("importgatewayddress [pubkey]\n"); - if ( ensure_CCrequirements(cp->evalcode) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); - return(CCaddress(cp,(char *)"ImportGateway", pubkey)); -} - UniValue channelslist(const UniValue& params, bool fHelp, const CPubKey& mypk) { if ( fHelp || params.size() > 0 ) @@ -6929,297 +6903,7 @@ UniValue rewardsinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) return(RewardsInfo(fundingtxid)); } -UniValue gatewayslist(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - if ( fHelp || params.size() > 0 ) - throw runtime_error("gatewayslist\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - const CKeyStore& keystore = *pwalletMain; - return(GatewaysList()); -} - -UniValue gatewaysexternaladdress(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bindtxid; CPubKey pubkey; - - if ( fHelp || params.size() != 2) - throw runtime_error("gatewaysexternaladdress bindtxid pubkey\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - pubkey = ParseHex(params[1].get_str().c_str()); - return(GatewaysExternalAddress(bindtxid,pubkey)); -} - -UniValue gatewaysdumpprivkey(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bindtxid; - - if ( fHelp || params.size() != 2) - throw runtime_error("gatewaysdumpprivkey bindtxid address\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - std::string strAddress = params[1].get_str(); - CTxDestination dest = DecodeDestination(strAddress); - if (!IsValidDestination(dest)) { - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid transparent address"); - } - const CKeyID *keyID = boost::get(&dest); - if (!keyID) { - throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); - } - CKey vchSecret; - if (!pwalletMain->GetKey(*keyID, vchSecret)) { - throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); - } - return(GatewaysDumpPrivKey(bindtxid,vchSecret)); -} -UniValue gatewaysinfo(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 txid; - if ( fHelp || params.size() != 1 ) - throw runtime_error("gatewaysinfo bindtxid\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - txid = Parseuint256((char *)params[0].get_str().c_str()); - return(GatewaysInfo(txid)); -} - -UniValue gatewaysbind(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; - uint8_t M,N,p1,p2,p3,p4=0; std::string coin; std::vector pubkey; - - if ( fHelp || params.size() < 10 ) - throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s) pubtype p2shtype wiftype [taddr]\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - tokenid = Parseuint256((char *)params[0].get_str().c_str()); - oracletxid = Parseuint256((char *)params[1].get_str().c_str()); - coin = params[2].get_str(); - totalsupply = atol((char *)params[3].get_str().c_str()); - M = atoi((char *)params[4].get_str().c_str()); - N = atoi((char *)params[5].get_str().c_str()); - if ( M > N || N == 0 || N > 15 || totalsupply < COIN/100 || tokenid == zeroid ) - { - Unlock2NSPV(mypk); - throw runtime_error("illegal M or N > 15 or tokensupply or invalid tokenid\n"); - } - if ( params.size() < 6+N+3 ) - { - Unlock2NSPV(mypk); - throw runtime_error("not enough parameters for N pubkeys\n"); - } - for (i=0; i 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewaysdeposit(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); int32_t i,claimvout,height; int64_t amount; std::string coin,deposithex; uint256 bindtxid,cointxid; std::vectorproof,destpub,pubkey; - if ( fHelp || params.size() != 9 ) - throw runtime_error("gatewaysdeposit bindtxid height coin cointxid claimvout deposithex proof destpub amount\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - height = atoi((char *)params[1].get_str().c_str()); - coin = params[2].get_str(); - cointxid = Parseuint256((char *)params[3].get_str().c_str()); - claimvout = atoi((char *)params[4].get_str().c_str()); - deposithex = params[5].get_str(); - proof = ParseHex(params[6].get_str()); - destpub = ParseHex(params[7].get_str()); - amount = atof((char *)params[8].get_str().c_str()) * COIN + 0.00000000499999; - if ( amount <= 0 || claimvout < 0 ) - { - Unlock2NSPV(mypk); - throw runtime_error("invalid param: amount, numpks or claimvout\n"); - } - if (destpub.size()!= 33) - { - Unlock2NSPV(mypk); - throw runtime_error("invalid destination pubkey"); - } - result = GatewaysDeposit(mypk,0,bindtxid,height,coin,cointxid,claimvout,deposithex,proof,pubkey2pk(destpub),amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewaysclaim(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); std::string coin; uint256 bindtxid,deposittxid; std::vectordestpub; int64_t amount; - if ( fHelp || params.size() != 5 ) - throw runtime_error("gatewaysclaim bindtxid coin deposittxid destpub amount\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - deposittxid = Parseuint256((char *)params[2].get_str().c_str()); - destpub = ParseHex(params[3].get_str()); - amount = atof((char *)params[4].get_str().c_str()) * COIN + 0.00000000499999; - if (destpub.size()!= 33) - { - Unlock2NSPV(mypk); - throw runtime_error("invalid destination pubkey"); - } - result = GatewaysClaim(mypk,0,bindtxid,coin,deposittxid,pubkey2pk(destpub),amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewayswithdraw(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 bindtxid; int64_t amount; std::string coin; std::vector withdrawpub; - if ( fHelp || params.size() != 4 ) - throw runtime_error("gatewayswithdraw bindtxid coin withdrawpub amount\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - withdrawpub = ParseHex(params[2].get_str()); - amount = atof((char *)params[3].get_str().c_str()) * COIN + 0.00000000499999; - if (withdrawpub.size()!= 33) - { - Unlock2NSPV(mypk); - throw runtime_error("invalid destination pubkey"); - } - result = GatewaysWithdraw(mypk,0,bindtxid,coin,pubkey2pk(withdrawpub),amount); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Lock2NSPV(mypk); - return(result); -} - -UniValue gatewayspartialsign(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); std::string coin,parthex; uint256 txid; - if ( fHelp || params.size() != 3 ) - throw runtime_error("gatewayspartialsign txidaddr refcoin hex\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - txid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - parthex = params[2].get_str(); - result = GatewaysPartialSign(mypk,0,txid,coin,parthex); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewayscompletesigning(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 withdrawtxid; std::string txhex,coin; - if ( fHelp || params.size() != 3 ) - throw runtime_error("gatewayscompletesigning withdrawtxid coin hex\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - withdrawtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - txhex = params[2].get_str(); - result = GatewaysCompleteSigning(mypk,0,withdrawtxid,coin,txhex); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewaysmarkdone(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue result(UniValue::VOBJ); uint256 completetxid; std::string coin; - if ( fHelp || params.size() != 2 ) - throw runtime_error("gatewaysmarkdone completesigningtx coin\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - Lock2NSPV(mypk); - completetxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - result = GatewaysMarkDone(mypk,0,completetxid,coin); - if ( result[JSON_HEXTX].getValStr().size() > 0 ) - { - result.push_back(Pair("result", "success")); - } - Unlock2NSPV(mypk); - return(result); -} - -UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bindtxid; std::string coin; - if ( fHelp || params.size() != 2 ) - throw runtime_error("gatewayspendingdeposits bindtxid coin\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - return(GatewaysPendingDeposits(mypk,bindtxid,coin)); -} - -UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bindtxid; std::string coin; - if ( fHelp || params.size() != 2 ) - throw runtime_error("gatewayspendingwithdraws bindtxid coin\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - return(GatewaysPendingWithdraws(mypk,bindtxid,coin)); -} - -UniValue gatewaysprocessed(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - uint256 bindtxid; std::string coin; - if ( fHelp || params.size() != 2 ) - throw runtime_error("gatewaysprocessed bindtxid coin\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) - throw runtime_error(CC_REQUIREMENTS_MSG); - bindtxid = Parseuint256((char *)params[0].get_str().c_str()); - coin = params[1].get_str(); - return(GatewaysProcessedWithdraws(mypk,bindtxid,coin)); -} UniValue oracleslist(const UniValue& params, bool fHelp, const CPubKey& mypk) { From c9f76406990dd4937b4b56cd7c26544c60afb185 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 23:25:35 -0500 Subject: [PATCH 19/22] Boost download has been broken for over a week, so we will host our own --- depends/packages/boost.mk | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 0062c0bdb..5b4804e14 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,9 +1,12 @@ package=boost $(package)_version=1_72_0 -$(package)_download_path=https://boostorg.jfrog.io/artifactory/main/release/$(subst _,.,$($(package)_version))/source/ +#$(package)_download_path=https://boostorg.jfrog.io/artifactory/main/release/$(subst _,.,$($(package)_version))/source/ +#$(package)_file_name=$(package)_$($(package)_version).tar.bz2 $(package)_sha256_hash=59c9b274bc451cf91a9ba1dd2c7fdcaf5d60b1b3aa83f2c9fa143417cc660722 -$(package)_file_name=$(package)_$($(package)_version).tar.bz2 +$(package)_download_path=https://git.hush.is/attachments +$(package)_file_name=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 +$(package)_download_file=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 $(package)_patches=fix-Solaris.patch define $(package)_set_vars From 31fce487d932afe3f67ddf03f037101bc690993c Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 23:32:11 -0500 Subject: [PATCH 20/22] Fix boost download link --- depends/packages/boost.mk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 5b4804e14..f7d34c253 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -5,8 +5,8 @@ $(package)_version=1_72_0 #$(package)_file_name=$(package)_$($(package)_version).tar.bz2 $(package)_sha256_hash=59c9b274bc451cf91a9ba1dd2c7fdcaf5d60b1b3aa83f2c9fa143417cc660722 $(package)_download_path=https://git.hush.is/attachments -$(package)_file_name=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 -$(package)_download_file=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 +$(package)_file_name=7b13759e-8623-4e48-ae08-f78502f4b6a5 +$(package)_download_file=7b13759e-8623-4e48-ae08-f78502f4b6a5 $(package)_patches=fix-Solaris.patch define $(package)_set_vars From 323d2134a1fcc119a4da82f9fc37e912b67e58c6 Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 23:25:35 -0500 Subject: [PATCH 21/22] Boost download has been broken for over a week, so we will host our own --- depends/packages/boost.mk | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 0062c0bdb..5b4804e14 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,9 +1,12 @@ package=boost $(package)_version=1_72_0 -$(package)_download_path=https://boostorg.jfrog.io/artifactory/main/release/$(subst _,.,$($(package)_version))/source/ +#$(package)_download_path=https://boostorg.jfrog.io/artifactory/main/release/$(subst _,.,$($(package)_version))/source/ +#$(package)_file_name=$(package)_$($(package)_version).tar.bz2 $(package)_sha256_hash=59c9b274bc451cf91a9ba1dd2c7fdcaf5d60b1b3aa83f2c9fa143417cc660722 -$(package)_file_name=$(package)_$($(package)_version).tar.bz2 +$(package)_download_path=https://git.hush.is/attachments +$(package)_file_name=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 +$(package)_download_file=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 $(package)_patches=fix-Solaris.patch define $(package)_set_vars From b70370123e0ad21fb83b93727e705feddf85fefe Mon Sep 17 00:00:00 2001 From: Duke Date: Sun, 7 Jan 2024 23:32:11 -0500 Subject: [PATCH 22/22] Fix boost download link --- depends/packages/boost.mk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 5b4804e14..f7d34c253 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -5,8 +5,8 @@ $(package)_version=1_72_0 #$(package)_file_name=$(package)_$($(package)_version).tar.bz2 $(package)_sha256_hash=59c9b274bc451cf91a9ba1dd2c7fdcaf5d60b1b3aa83f2c9fa143417cc660722 $(package)_download_path=https://git.hush.is/attachments -$(package)_file_name=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 -$(package)_download_file=94bfb5e0-7e29-4162-a066-bfd00e6b0db1 +$(package)_file_name=7b13759e-8623-4e48-ae08-f78502f4b6a5 +$(package)_download_file=7b13759e-8623-4e48-ae08-f78502f4b6a5 $(package)_patches=fix-Solaris.patch define $(package)_set_vars