text
stringlengths
5
1.04M
// Copyright (c) 2009-2014 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <llamacoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <llamacoinaddress>\n" "Reveals the private key corresponding to <llamacoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Llamacoin address"); CKeyID keyID; if (!address.GetKeyID(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 CBitcoinSecret(vchSecret).ToString(); }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); if (pwalletMain) { obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Poscoin address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Poscoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <poscoinaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Poscoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <poscoinaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Poscoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <poscoinaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Poscoin address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <poscoinaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <poscoinaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <poscoinaddress> [minconf=1]\n" "Returns the total amount received by <poscoinaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Poscoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsConfirmed()) continue; int64 allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toposcoinaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Poscoin address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Poscoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // // Used by addmultisigaddress / createmultisig: // static CScript _createmultisig(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Poscoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); return result; } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Poscoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n" "Creates a multi-signature address and returns a json object\n" "with keys:\n" "address : poscoin address\n" "redeemScript : hex-encoded redemption script"; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } struct tallyitem { int64 nAmount; int nConf; vector<uint256> txids; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); Array transactions; if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included\n" " \"txids\" : list of transactions with outputs to the address\n"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Poscoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <poscoinaddress>\n" "Return information about <poscoinaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value lockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock? [array-of-Objects]\n" "Updates list of temporarily unspendable outputs."); if (params.size() == 1) RPCTypeCheck(params, list_of(bool_type)); else RPCTypeCheck(params, list_of(bool_type)(array_type)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } Array outputs = params[1].get_array(); BOOST_FOREACH(Value& output, outputs) { if (output.type() != obj_type) throw JSONRPCError(-8, "Invalid parameter, expected object"); const Object& o = output.get_obj(); RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(-8, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(-8, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } Value listlockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "Returns list of temporarily unspendable outputs."); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); Array ret; BOOST_FOREACH(COutPoint &outpt, vOutpts) { Object o; o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; }
/********************************************************************** Copyright (c) 2020 MIPT Module Name: AstDump.h Abstract: Модуль, генерирующий изображение AST дерева Author: JulesIMF Last Edit: 20.12.2020 2:27 Edit Notes: **********************************************************************/ #include <cstdlib> #include <cassert> #include <cstdio> #include "../../inc/Vertex.h" void putVertex(FILE* file, Node::Vertex* vertex) { static int visited = 0; //printf("visit = %lu\n", visited++); using namespace Node; switch (vertex->type) { case Type::Id: fprintf(file, "v%p[label = \"%lu:%lu\\nId\\n\\\"%s\\\"\", shape = \"record\", style = \"bold\", fontsize = 15]; ", vertex, vertex->row, vertex->column, vertex->field.iter.get()); break; case Type::Var: fprintf(file, "v%p[label = \"%lu:%lu\\nVar\\n\\\"%s\\\"\", shape = \"record\", style = \"bold\", fontsize = 15]; ", vertex, vertex->row, vertex->column, vertex->field.fnc.iter.get()); break; case Type::Operator: fprintf(file, "v%p[label = \"%lu:%lu\\nOperator\\nopType = '%c'\", shape = \"octagon\", style = \"filled, bold\", fillcolor = \"yellow\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.opType); break; case Type::Statement: fprintf(file, "v%p[label = \"%lu:%lu\\nStatement\\nstType = '%c'\", shape = \"diamond\", style = \"filled, bold\", fillcolor = \"darkorchid1\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.stType); break; case Type::Call: fprintf(file, "v%p[label = \"%lu:%lu\\nCall\\nid = \\\"%s\\\", nArgs = %lu\", shape = \"octagon\", style = \"filled, bold\", fillcolor = \"yellow\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.fnc.iter.get(), vertex->field.fnc.nArgs); break; case Type::Const: fprintf(file, "v%p[label = \"%lu:%lu\\nConst\\nval = %lu, %s\", shape = \"record\", style = \"bold\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.lit.value, vertex->field.lit.isInt ? "int" : "float"); break; case Type::ArgList: fprintf(file, "v%p[label = \"%lu:%lu\\nArgList\", shape = \"parallelogram\", fillcolor = \"orange\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::IfElse: fprintf(file, "v%p[label = \"%lu:%lu\\nIf-Else\", shape = \"parallelogram\", fillcolor = \"orange\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::StmtLink: fprintf(file, "v%p[label = \"%lu:%lu\\nStmtLink\\nnewScope = %s\", shape = \"parallelogram\", fillcolor = \"mediumspringgreen\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.newScope ? "true" : "false"); break; case Type::FuncLink: fprintf(file, "v%p[label = \"%lu:%lu\\nFuncLink\", shape = \"parallelogram\", fillcolor = \"orange\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::Main: fprintf(file, "v%p[label = \"%lu:%lu\\nMain\", shape = \"parallelogram\", fillcolor = \"forestgreen\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::FuncDecl: fprintf(file, "v%p[label = \"%lu:%lu\\nFuncDecl\\nid = \\\"%s\\\", nArgs = %lu\", shape = \"parallelogram\", style = \"filled, bold\", fillcolor = \"forestgreen\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.fnc.iter.get(), vertex->field.fnc.nArgs); break; case Type::VarType: fprintf(file, "v%p[label = \"%lu:%lu\\VarType\\nid = \\\"%s\\\", nElements = %lu\", shape = \"parallelogram\", style = \"filled, bold\", fillcolor = \"forestgreen\", fontsize = 15];", vertex, vertex->row, vertex->column, vertex->field.varDecl.iter.get(), vertex->field.varDecl.nElements); break; case Type::PgmEnd: fprintf(file, "v%p[label = \"%lu:%lu\\nPgmEnd\", shape = \"parallelogram\", fillcolor = \"blue\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::In: fprintf(file, "v%p[label = \"%lu:%lu\\In\", shape = \"parallelogram\", fillcolor = \"blue\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; case Type::Out: fprintf(file, "v%p[label = \"%lu:%lu\\Out\", shape = \"parallelogram\", fillcolor = \"blue\", style = \"filled, bold\", fontsize = 15];", vertex, vertex->row, vertex->column); break; default: printf("%d\n", vertex->type); assert(!"Unknown type"); } fprintf(file, "\n"); if (vertex->left) { fprintf(file, "v%p->v%p [color = \"red\"]\n", vertex, vertex->left); putVertex(file, vertex->left); } if (vertex->right) { fprintf(file, "v%p->v%p [color = \"blue\"]\n", vertex, vertex->right); putVertex(file, vertex->right); } } void astDump(Node::Vertex* astTree) { FILE *file = fopen("ast.dot", "w"); assert(file); fprintf(file, "digraph\n{\ndpi = 300;\n"); putVertex(file, astTree); fprintf(file, "}"); fclose(file); system("dot -Tpng ast.dot -o ast.png > /dev/null"); //system("rm ast.dot"); // Следующий трюк работает только под Шиндовс //system("start ast.png"); }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_AUTOMATON_UTILS_H #define IRESEARCH_AUTOMATON_UTILS_H #include "formats/formats.hpp" #include "search/filter.hpp" #include "utils/automaton.hpp" #include "utils/fstext/fst_states_map.hpp" #include "utils/fstext/fst_table_matcher.hpp" #include "utils/fstext/fst_sorted_range_matcher.hpp" #include "utils/hash_utils.hpp" #include "utils/utf8_utils.hpp" #include "fst/closure.h" namespace iresearch { #ifdef IRESEARCH_DEBUG constexpr bool TEST_AUTOMATON_PROPS = true; #else constexpr bool TEST_AUTOMATON_PROPS = false; #endif struct filter_visitor; inline automaton_table_matcher make_automaton_matcher( const automaton& a, bool test_props = TEST_AUTOMATON_PROPS) { return automaton_table_matcher(a, test_props); } template<typename Char, typename Matcher> inline automaton::Weight match( Matcher& matcher, const basic_string_ref<Char>& target) { auto state = matcher.GetFst().Start(); matcher.SetState(state); auto begin = target.begin(); const auto end = target.end(); for (; begin < end && matcher.Find(*begin); ++begin) { state = matcher.Value().nextstate; matcher.SetState(state); } return begin == end ? matcher.Final(state) : automaton::Weight::Zero(); } template<typename Char> inline automaton::Weight accept(const automaton& a, const basic_string_ref<Char>& target) { using matcher_t = fst::SortedRangeExplicitMatcher<automaton, fst::MatchType::MATCH_INPUT>; matcher_t matcher(&a); return match(matcher, target); } class automaton_term_iterator final : public seek_term_iterator { public: automaton_term_iterator(const automaton& a, seek_term_iterator::ptr&& it) : a_(&a), matcher_(a_), it_(std::move(it)) { assert(it_); value_ = &it_->value(); } virtual const bytes_ref& value() const noexcept override { return *value_; } virtual doc_iterator::ptr postings(IndexFeatures features) const override { return it_->postings(features); } virtual void read() override { it_->read(); } virtual bool next() override { bool next = it_->next(); while (next && !accept()) { next = it_->next(); } return next; } virtual attribute* get_mutable(type_info::type_id type) noexcept override { return it_->get_mutable(type); } virtual SeekResult seek_ge(const bytes_ref& target) override { it_->seek_ge(target); if (accept()) { return SeekResult::FOUND; } return next() ? SeekResult::NOT_FOUND : SeekResult::END; } virtual bool seek(const bytes_ref& target) override { return SeekResult::FOUND == seek_ge(target); } virtual bool seek(const bytes_ref& target, const seek_cookie& cookie) override { return it_->seek(target, cookie); } virtual seek_cookie::ptr cookie() const override { return it_->cookie(); } private: bool accept() { return irs::match(matcher_, *value_); } const automaton* a_; fst::SortedRangeExplicitMatcher<automaton> matcher_; seek_term_iterator::ptr it_; const bytes_ref* value_; }; // automaton_term_iterator ////////////////////////////////////////////////////////////////////////////// /// @brief add a new transition to "to" state denoted by "label" or expands /// the last already existing one ////////////////////////////////////////////////////////////////////////////// inline void add_or_expand_arc( automaton& a, automaton::StateId from, range_label label, automaton::StateId to) { assert(fst::kILabelSorted == a.Properties(fst::kILabelSorted, true)); fst::ArcIteratorData<automaton::Arc> data; a.InitArcIterator(from, &data); if (data.narcs) { auto& prev = const_cast<automaton::Arc&>(data.arcs[data.narcs-1]); assert(prev < label); if (prev.nextstate == to && label.min - prev.max <= 1) { prev.ilabel = range_label{prev.min, label.max}; return; } } a.EmplaceArc(from, label, to); } ////////////////////////////////////////////////////////////////////////////// /// @class utf8_transitions_builder /// @brief helper class for building minimal acyclic binary automaton from /// a specified root, a default (rho) state and a set of arcs with /// UTF-8 encoded labels ////////////////////////////////////////////////////////////////////////////// class utf8_transitions_builder { public: utf8_transitions_builder() : states_map_(16, state_emplace(weight_)) { } template<typename Iterator> void insert(automaton& a, automaton::StateId from, automaton::StateId rho_state, Iterator begin, Iterator end) { last_ = bytes_ref::EMPTY; states_map_.reset(); // we inherit weight from 'from' node to all intermediate states // that were created by transitions builder weight_ = a.Final(from); // 'from' state is already a part of automaton states_[0].id = from; std::fill(std::begin(rho_states_), std::end(rho_states_), rho_state); if (rho_state != fst::kNoStateId) { // create intermediate default states if necessary a.SetFinal(rho_states_[1] = a.AddState(), weight_); a.SetFinal(rho_states_[2] = a.AddState(), weight_); a.SetFinal(rho_states_[3] = a.AddState(), weight_); } for (; begin != end; ++begin) { // we expect sorted input assert(last_ <= static_cast<bytes_ref>(std::get<0>(*begin))); const auto& label = std::get<0>(*begin); insert(a, label.c_str(), label.size(), std::get<1>(*begin)); last_ = static_cast<bytes_ref>(label); } finish(a, from); } private: struct state; struct arc : public range_label, private util::noncopyable { arc(automaton::Arc::Label label, state* target) noexcept : range_label{label}, target{target} { } arc(automaton::Arc::Label label, automaton::StateId target) noexcept : range_label{label}, id{target} { } bool operator==(const automaton::Arc& rhs) const noexcept { return ilabel == rhs.ilabel && id == rhs.nextstate; } bool operator!=(const automaton::Arc& rhs) const noexcept { return !(*this == rhs); } union { state* target; automaton::StateId id; }; }; // arc struct state : private util::noncopyable { void clear() noexcept { id = fst::kNoStateId; arcs.clear(); } void add_rho_arc(uint32_t min, uint32_t max, automaton::StateId rho) { if (fst::kNoStateId == rho) { return; } if (!arcs.empty()) { min = arcs.back().max + 1; } if (min < max) { arcs.emplace_back(range_label{min, max - 1}, rho); } } automaton::StateId id{fst::kNoStateId}; std::vector<arc> arcs; }; // state static_assert(std::is_nothrow_move_constructible_v<state>); struct state_hash { size_t operator()(const state& s, const automaton& fst) const noexcept { if (fst::kNoStateId != s.id) { return operator()(s.id, fst); } size_t hash = 0; auto& arcs = s.arcs; for (auto& arc: arcs) { hash = hash_combine(hash, arc.ilabel); // cppcheck-suppress redundantAssignment hash = hash_combine(hash, arc.id); } return hash; } size_t operator()(automaton::StateId id, const automaton& fst) const noexcept { fst::ArcIteratorData<automaton::Arc> arcs; fst.InitArcIterator(id, &arcs); const auto* begin = arcs.arcs; const auto* end = arcs.arcs + arcs.narcs; size_t hash = 0; for (; begin != end; ++begin) { hash = hash_combine(hash, begin->ilabel); // cppcheck-suppress redundantAssignment hash = hash_combine(hash, begin->nextstate); } return hash; } }; // state_hash struct state_equal { bool operator()(const state& lhs, automaton::StateId rhs, const automaton& fst) const noexcept { if (lhs.id != fst::kNoStateId) { // already a part of automaton return lhs.id == rhs; } fst::ArcIteratorData<automaton::Arc> rarcs; fst.InitArcIterator(rhs, &rarcs); if (lhs.arcs.size() != rarcs.narcs) { return false; } const auto* rarc = rarcs.arcs; for (const auto& larc : lhs.arcs) { if (larc != *rarc) { return false; } ++rarc; } return true; } }; // state_equal class state_emplace { public: explicit state_emplace(const automaton::Weight& weight) noexcept : weight_(&weight) { } automaton::StateId operator()(const state& s, automaton& fst) const { auto id = s.id; if (id == fst::kNoStateId) { id = fst.AddState(); fst.SetFinal(id, *weight_); } for (const auto& a : s.arcs) { fst.EmplaceArc(id, a.ilabel, a.id); } return id; } private: const automaton::Weight* weight_; }; // state_emplace using automaton_states_map = fst_states_map< automaton, state, state_emplace, state_hash, state_equal, fst::kNoStateId>; void minimize(automaton& a, size_t prefix); void insert(automaton& a, const byte_type* label_data, const size_t label_size, automaton::StateId target); void finish(automaton& a, automaton::StateId from); // FIXME use a memory pool for arcs automaton::Weight weight_; automaton::StateId rho_states_[4]; state states_[utf8_utils::MAX_CODE_POINT_SIZE + 1]; // +1 for root state automaton_states_map states_map_; bytes_ref last_; }; // utf8_automaton_builder ////////////////////////////////////////////////////////////////////////////// /// @brief validate a specified automaton and print message on error ////////////////////////////////////////////////////////////////////////////// inline bool validate(const automaton& a, bool test_props = TEST_AUTOMATON_PROPS) { if (fst::kError == a.Properties(automaton_table_matcher::FST_PROPERTIES, test_props)) { IR_FRMT_ERROR("Expected deterministic, epsilon-free acceptor, " "got the following properties " IR_UINT64_T_SPECIFIER "", a.Properties(automaton_table_matcher::FST_PROPERTIES, false)); return false; } return true; } ////////////////////////////////////////////////////////////////////////////// /// @brief generalized field visitation logic for automaton based filters /// @param segment segment reader /// @param field term reader /// @param matcher input matcher /// @param visitor visitor ////////////////////////////////////////////////////////////////////////////// template<typename Visitor> void visit( const sub_reader& segment, const term_reader& reader, automaton_table_matcher& matcher, Visitor& visitor) { assert(fst::kError != matcher.Properties(0)); auto terms = reader.iterator(matcher); if (IRS_UNLIKELY(!terms)) { return; } if (terms->next()) { visitor.prepare(segment, reader, *terms); do { terms->read(); visitor.visit(no_boost()); } while (terms->next()); } } ////////////////////////////////////////////////////////////////////////////// /// @brief establish UTF-8 labeled connection between specified source and /// target states ////////////////////////////////////////////////////////////////////////////// void utf8_emplace_arc( automaton& a, automaton::StateId from, bytes_ref label, automaton::StateId to); ////////////////////////////////////////////////////////////////////////////// /// @brief establish UTF-8 labeled connection between specified source (from) /// and target (to) states with the fallback to default (rho_state) /// state ////////////////////////////////////////////////////////////////////////////// void utf8_emplace_arc( automaton& a, automaton::StateId from, automaton::StateId rho_state, bytes_ref label, automaton::StateId to); ////////////////////////////////////////////////////////////////////////////// /// @brief establish default connnection between specified source (from) and /// and target (to) ////////////////////////////////////////////////////////////////////////////// void utf8_emplace_rho_arc( automaton& a, automaton::StateId from, automaton::StateId to); /* ////////////////////////////////////////////////////////////////////////////// /// @brief modifies a specified UTF-8 automaton to an equivalent one that is /// defined over the alphabet of { [0..255], fst::fsa::kRho } /// @returns fst::kNoStateId on success, otherwise first failed state id ////////////////////////////////////////////////////////////////////////////// automaton::StateId utf8_expand_labels(automaton& a); */ inline automaton make_char(const uint32_t c) { automaton a; a.AddStates(2); a.SetStart(0); a.SetFinal(1); a.EmplaceArc(0, range_label::fromRange(c), 1); return a; } inline automaton make_char(bytes_ref c) { automaton a; a.AddStates(2); a.SetStart(0); a.SetFinal(1); utf8_emplace_arc(a, 0, c, 1); return a; } inline automaton make_any() { automaton a; a.AddStates(2); a.SetStart(0); a.SetFinal(1); utf8_emplace_rho_arc(a, 0, 1); return a; } inline automaton make_all() { automaton a = make_any(); fst::Closure(&a, fst::ClosureType::CLOSURE_STAR); return a; }; ////////////////////////////////////////////////////////////////////////////// /// @brief instantiate compiled filter based on a specified automaton, field /// and other properties /// @param field field name /// @param matcher input matcher /// @param scored_terms_limit score as many terms /// @param index index reader /// @param order compiled order /// @param bool query boost /// @returns compiled filter ////////////////////////////////////////////////////////////////////////////// filter::prepared::ptr prepare_automaton_filter( string_ref field, const automaton& acceptor, size_t scored_terms_limit, const index_reader& index, const order::prepared& order, boost_t boost); } #endif
// Local-Hyperion includes #include "LedDeviceNanoleaf.h" // ssdp discover #include <ssdp/SSDPDiscover.h> // Qt includes #include <QEventLoop> #include <QNetworkReply> // Controller configuration settings const QString CONFIG_ADDRESS = "output"; const QString CONFIG_PORT = "port"; const QString CONFIG_AUTH_TOKEN ="token"; // Panel configuration settings const QString PANEL_LAYOUT = "layout"; const QString PANEL_NUM = "numPanels"; const QString PANEL_ID = "panelId"; const QString PANEL_POSITIONDATA = "positionData"; const QString PANEL_SHAPE_TYPE = "shapeType"; const QString PANEL_ORIENTATION = "0"; const QString PANEL_POS_X = "x"; const QString PANEL_POS_Y = "y"; // List of State Information const QString STATE_ON = "on"; const QString STATE_ONOFF_VALUE = "value"; const QString STATE_VALUE_TRUE = "true"; const QString STATE_VALUE_FALSE = "false"; //Device Data elements const QString DEV_DATA_NAME = "name"; const QString DEV_DATA_MODEL = "model"; const QString DEV_DATA_MANUFACTURER = "manufacturer"; const QString DEV_DATA_FIRMWAREVERSION = "firmwareVersion"; //Nanoleaf Stream Control elements const QString STREAM_CONTROL_IP = "streamControlIpAddr"; const QString STREAM_CONTROL_PORT = "streamControlPort"; const QString STREAM_CONTROL_PROTOCOL = "streamControlProtocol"; const quint16 STREAM_CONTROL_DEFAULT_PORT = 60222; //Fixed port for Canvas; // Nanoleaf OpenAPI URLs const QString API_DEFAULT_PORT = "16021"; const QString API_URL_FORMAT = "http://%1:%2/api/v1/%3/%4"; const QString API_ROOT = ""; const QString API_EXT_MODE_STRING_V1 = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\"}}"; const QString API_EXT_MODE_STRING_V2 = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\", \"extControlVersion\" : \"v2\"}}"; const QString API_STATE ="state"; const QString API_PANELLAYOUT = "panelLayout"; const QString API_EFFECT = "effects"; //Nanoleaf ssdp services const QString SSDP_CANVAS = "nanoleaf:nl29"; const QString SSDP_LIGHTPANELS = "nanoleaf_aurora:light"; const int SSDP_TIMEOUT = 5000; // timout in ms // Nanoleaf Panel Shapetypes enum SHAPETYPES { TRIANGLE, RHYTM, SQUARE, CONTROL_SQUARE_PRIMARY, CONTROL_SQUARE_PASSIVE, POWER_SUPPLY, }; // Nanoleaf external control versions enum EXTCONTROLVERSIONS { EXTCTRLVER_V1 = 1, EXTCTRLVER_V2 }; LedDevice* LedDeviceNanoleaf::construct(const QJsonObject &deviceConfig) { return new LedDeviceNanoleaf(deviceConfig); } LedDeviceNanoleaf::LedDeviceNanoleaf(const QJsonObject &deviceConfig) : ProviderUdp() { init(deviceConfig); } bool LedDeviceNanoleaf::init(const QJsonObject &deviceConfig) { LedDevice::init(deviceConfig); int configuredLedCount = this->getLedCount(); Debug(_log, "ActiveDevice : %s", QSTRING_CSTR( this->getActiveDevice() )); Debug(_log, "LedCount : %d", configuredLedCount); Debug(_log, "ColorOrder : %s", QSTRING_CSTR( this->getColorOrder() )); Debug(_log, "LatchTime : %d", this->getLatchTime()); //Set hostname as per configuration and default port _hostname = deviceConfig[ CONFIG_ADDRESS ].toString(); _api_port = API_DEFAULT_PORT; _auth_token = deviceConfig[ CONFIG_AUTH_TOKEN ].toString(); //If host not configured then discover device if ( _hostname.isEmpty() ) //Discover Nanoleaf device if ( !discoverNanoleafDevice() ) { throw std::runtime_error("No target IP defined nor Nanoleaf device discovered"); } //Get Nanoleaf device details and configuration _networkmanager = new QNetworkAccessManager(); // Read Panel count and panel Ids QString url = getUrl(_hostname, _api_port, _auth_token, API_ROOT ); QJsonDocument doc = getJson( url ); QJsonObject jsonAllPanelInfo = doc.object(); QString deviceName = jsonAllPanelInfo[DEV_DATA_NAME].toString(); _deviceModel = jsonAllPanelInfo[DEV_DATA_MODEL].toString(); QString deviceManufacturer = jsonAllPanelInfo[DEV_DATA_MANUFACTURER].toString(); _deviceFirmwareVersion = jsonAllPanelInfo[DEV_DATA_FIRMWAREVERSION].toString(); Debug(_log, "Name : %s", QSTRING_CSTR( deviceName )); Debug(_log, "Model : %s", QSTRING_CSTR( _deviceModel )); Debug(_log, "Manufacturer : %s", QSTRING_CSTR( deviceManufacturer )); Debug(_log, "FirmwareVersion: %s", QSTRING_CSTR( _deviceFirmwareVersion)); // Get panel details from /panelLayout/layout QJsonObject jsonPanelLayout = jsonAllPanelInfo[API_PANELLAYOUT].toObject(); QJsonObject jsonLayout = jsonPanelLayout[PANEL_LAYOUT].toObject(); int panelNum = jsonLayout[PANEL_NUM].toInt(); QJsonArray positionData = jsonLayout[PANEL_POSITIONDATA].toArray(); std::map<int, std::map<int, int>> panelMap; // Loop over all children. foreach (const QJsonValue & value, positionData) { QJsonObject panelObj = value.toObject(); int panelId = panelObj[PANEL_ID].toInt(); int panelX = panelObj[PANEL_POS_X].toInt(); int panelY = panelObj[PANEL_POS_Y].toInt(); int panelshapeType = panelObj[PANEL_SHAPE_TYPE].toInt(); //int panelOrientation = panelObj[PANEL_ORIENTATION].toInt(); //std::cout << "Panel [" << panelId << "]" << " (" << panelX << "," << panelY << ") - Type: [" << panelshapeType << "]" << std::endl; // Skip Rhythm panels if ( panelshapeType != RHYTM ) { panelMap[panelY][panelX] = panelId; } else { Info(_log, "Rhythm panel skipped."); } } // Sort panels top down, left right for(auto posY = panelMap.crbegin(); posY != panelMap.crend(); ++posY) { // posY.first is the first key for(auto const &posX : posY->second) { // posX.first is the second key, posX.second is the data //std::cout << "panelMap[" << posY->first << "][" << posX.first << "]=" << posX.second << std::endl; _panelIds.push_back(posX.second); } } this->_panelLedCount = _panelIds.size(); Debug(_log, "PanelsNum : %d", panelNum); Debug(_log, "PanelLedCount : %d", _panelLedCount); // Check. if enough panelds were found. if (_panelLedCount < configuredLedCount) { throw std::runtime_error ( (QString ("Not enough panels [%1] for configured LEDs [%2] found!").arg(_panelLedCount).arg(configuredLedCount)).toStdString() ); } else { if ( _panelLedCount > this->getLedCount() ) { Warning(_log, "Nanoleaf: More panels [%d] than configured LEDs [%d].", _panelLedCount, configuredLedCount ); } } switchOn(); // Set Nanoleaf to External Control (UDP) mode Debug(_log, "Set Nanoleaf to External Control (UDP) streaming mode"); QJsonDocument responseDoc = changeToExternalControlMode(); // Set UDP streaming port _port = STREAM_CONTROL_DEFAULT_PORT; // Resolve port for Ligh Panels QJsonObject jsonStreamControllInfo = responseDoc.object(); if ( ! jsonStreamControllInfo.isEmpty() ) { _port = jsonStreamControllInfo[STREAM_CONTROL_PORT].toInt(); } _defaultHost = _hostname; ProviderUdp::init(deviceConfig); Debug(_log, "Started successfully" ); return true; } bool LedDeviceNanoleaf::discoverNanoleafDevice() { bool isDeviceFound (false); // device searching by ssdp QString address; SSDPDiscover discover; // Discover Canvas device address = discover.getFirstService(STY_WEBSERVER, SSDP_CANVAS, SSDP_TIMEOUT); //No Canvas device not found if ( address.isEmpty() ) { // Discover Light Panels (Aurora) device address = discover.getFirstService(STY_WEBSERVER, SSDP_LIGHTPANELS, SSDP_TIMEOUT); if ( address.isEmpty() ) { Warning(_log, "No Nanoleaf device discovered"); } } // Canvas or Light Panels found if ( ! address.isEmpty() ) { Info(_log, "Nanoleaf device discovered at [%s]", QSTRING_CSTR( address )); isDeviceFound = true; QStringList addressparts = address.split(":", QString::SkipEmptyParts); _hostname = addressparts[0]; _api_port = addressparts[1]; } return isDeviceFound; } QJsonDocument LedDeviceNanoleaf::changeToExternalControlMode() { QString url = getUrl(_hostname, _api_port, _auth_token, API_EFFECT ); QJsonDocument jsonDoc; // If device model is Light Panels (Aurora) if ( _deviceModel == "NL22") { _extControlVersion = EXTCTRLVER_V1; //Enable UDP Mode v1 jsonDoc = putJson(url, API_EXT_MODE_STRING_V1); } else { _extControlVersion = EXTCTRLVER_V2; //Enable UDP Mode v2 jsonDoc= putJson(url, API_EXT_MODE_STRING_V2); } return jsonDoc; } QString LedDeviceNanoleaf::getUrl(QString host, QString port, QString auth_token, QString endpoint) const { return API_URL_FORMAT.arg(host).arg(port).arg(auth_token).arg(endpoint); } QJsonDocument LedDeviceNanoleaf::getJson(QString url) const { Debug(_log, "GET: [%s]", QSTRING_CSTR( url )); // Perfrom request QNetworkRequest request(url); QNetworkReply* reply = _networkmanager->get(request); // Connect requestFinished signal to quit slot of the loop. QEventLoop loop; loop.connect(reply, SIGNAL(finished()), SLOT(quit())); // Go into the loop until the request is finished. loop.exec(); QJsonDocument jsonDoc; if(reply->operation() == QNetworkAccessManager::GetOperation) { jsonDoc = handleReply( reply ); } // Free space. reply->deleteLater(); // Return response return jsonDoc; } QJsonDocument LedDeviceNanoleaf::putJson(QString url, QString json) const { Debug(_log, "PUT: [%s] [%s]", QSTRING_CSTR( url ), QSTRING_CSTR( json ) ); // Perfrom request QNetworkRequest request(url); QNetworkReply* reply = _networkmanager->put(request, json.toUtf8()); // Connect requestFinished signal to quit slot of the loop. QEventLoop loop; loop.connect(reply, SIGNAL(finished()), SLOT(quit())); // Go into the loop until the request is finished. loop.exec(); QJsonDocument jsonDoc; if(reply->operation() == QNetworkAccessManager::PutOperation) { jsonDoc = handleReply( reply ); } // Free space. reply->deleteLater(); // Return response return jsonDoc; } QJsonDocument LedDeviceNanoleaf::handleReply(QNetworkReply* const &reply ) const { QJsonDocument jsonDoc; int httpStatusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ).toInt(); if(reply->error() == QNetworkReply::NoError) { if ( httpStatusCode != 204 ){ QByteArray response = reply->readAll(); QJsonParseError error; jsonDoc = QJsonDocument::fromJson(response, &error); if (error.error != QJsonParseError::NoError) { Error (_log, "Got invalid response"); throw std::runtime_error(""); } else { //Debug // QString strJson(jsonDoc.toJson(QJsonDocument::Compact)); // std::cout << strJson.toUtf8().constData() << std::endl; } } } else { QString errorReason; if ( httpStatusCode > 0 ) { QString httpReason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString(); QString advise; switch ( httpStatusCode ) { case 400: advise = "Check Request Body"; break; case 401: advise = "Check Authentication Token (API Key)"; break; case 404: advise = "Check Resource given"; break; default: break; } errorReason = QString ("%1:%2 [%3 %4] - %5").arg(_hostname).arg(_api_port).arg(httpStatusCode).arg(httpReason).arg(advise); } else { errorReason = QString ("%1:%2 - %3").arg(_hostname).arg(_api_port).arg(reply->errorString()); } Error (_log, "%s", QSTRING_CSTR( errorReason )); throw std::runtime_error("Network Error"); } // Return response return jsonDoc; } LedDeviceNanoleaf::~LedDeviceNanoleaf() { delete _networkmanager; } int LedDeviceNanoleaf::write(const std::vector<ColorRgb> & ledValues) { int retVal = 0; uint udpBufferSize; //Light Panels // nPanels 1B // nFrames 1B // panelID 1B // <R> <G> <B> 3B // <W> 1B // tranitionTime 1B // //Canvas //In order to support the much larger number of panels on Canvas, the size of the nPanels, //panelId and tranitionTime fields have been been increased from 1B to 2B. //The nFrames field has been dropped as it was set to 1 in v1 anyway // // nPanels 2B // panelID 2B // <R> <G> <B> 3B // <W> 1B // tranitionTime 2B //udpBufferSize = _panelLedCount * 7 + 1; // Buffersize for LightPanels udpBufferSize = _panelLedCount * 8 + 2; uint8_t udpbuffer[udpBufferSize]; uchar lowByte; // lower byte uchar highByte; // upper byte uint i=0; // Set number of panels highByte = (uchar) (_panelLedCount >>8 ); lowByte = (uchar) (_panelLedCount & 0xFF); if ( _extControlVersion == EXTCTRLVER_V2 ) { udpbuffer[i++] = highByte; } udpbuffer[i++] = lowByte; ColorRgb color; for ( int panelCounter=0; panelCounter < _panelLedCount; panelCounter++ ) { uint panelID = _panelIds[panelCounter]; highByte = (uchar) (panelID >>8 ); lowByte = (uchar) (panelID & 0xFF); // Set panels configured if( panelCounter < this->getLedCount() ) { color = (ColorRgb) ledValues.at(panelCounter); } else { // Set panels not configed to black; color = ColorRgb::BLACK; //printf ("panelCounter [%d] >= panelLedCount [%d]\n", panelCounter, _panelLedCount ); } // Set panelID if ( _extControlVersion == EXTCTRLVER_V2 ) { udpbuffer[i++] = highByte; } udpbuffer[i++] = lowByte; // Set number of frames - V1 only if ( _extControlVersion == EXTCTRLVER_V1 ) { udpbuffer[i++] = 1; // No of Frames } // Set panel's color LEDs udpbuffer[i++] = color.red; udpbuffer[i++] = color.green; udpbuffer[i++] = color.blue; // Set white LED udpbuffer[i++] = 0; // W not set manually // Set transition time unsigned char tranitionTime = 1; // currently fixed at value 1 which corresponds to 100ms highByte = (uchar) (tranitionTime >>8 ); lowByte = (uchar) (tranitionTime & 0xFF); if ( _extControlVersion == EXTCTRLVER_V2 ) { udpbuffer[i++] = highByte; } udpbuffer[i++] = lowByte; //std::cout << "[" << panelCounter << "]" << " Color: " << color << std::endl; } // printf ("udpBufferSize[%d], Bytes to send [%d]\n", udpBufferSize, i); // for ( uint c= 0; c < udpBufferSize;c++ ) // { // printf ("%x ", (uchar) udpbuffer[c]); // } // printf("\n"); retVal &= writeBytes( i , udpbuffer); return retVal; } QString LedDeviceNanoleaf::getOnOffRequest (bool isOn ) const { QString state = isOn ? STATE_VALUE_TRUE : STATE_VALUE_FALSE; return QString( "{\"%1\":{\"%2\":%3}}" ).arg(STATE_ON).arg(STATE_ONOFF_VALUE).arg(state); } int LedDeviceNanoleaf::switchOn() { Debug(_log, "switchOn()"); //Switch on Nanoleaf device QString url = getUrl(_hostname, _api_port, _auth_token, API_STATE ); putJson(url, this->getOnOffRequest(true) ); return 0; } int LedDeviceNanoleaf::switchOff() { Debug(_log, "switchOff()"); //Set all LEDs to Black LedDevice::switchOff(); //Switch off Nanoleaf device physically QString url = getUrl(_hostname, _api_port, _auth_token, API_STATE ); putJson(url, getOnOffRequest(false) ); return _deviceReady ? write(std::vector<ColorRgb>(_ledCount, ColorRgb::BLACK )) : -1; return 0; }
// +------------------------------------------------------------------------- // | Copyright (C) 2017 Yunify, Inc. // +------------------------------------------------------------------------- // | Licensed under the Apache License, Version 2.0 (the "License"); // | You may not use this work except in compliance with the License. // | You may obtain a copy of the License in the LICENSE file, or at: // | // | http://www.apache.org/licenses/LICENSE-2.0 // | // | Unless required by applicable law or agreed to in writing, software // | distributed under the License is distributed on an "AS IS" BASIS, // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // | See the License for the specific language governing permissions and // | limitations under the License. // +------------------------------------------------------------------------- #include <string.h> #include <time.h> #include <sys/stat.h> #include <unistd.h> #include <iostream> #include <memory> #include <string> #include <utility> #include "gtest/gtest.h" #include "base/Logging.h" #include "base/Utils.h" #include "data/Directory.h" #include "data/FileMetaData.h" namespace { using QS::Data::Entry; using QS::Data::FileMetaData; using QS::Data::FileType; using QS::Data::Node; using std::make_shared; using std::ostream; using std::string; using std::shared_ptr; using std::unique_ptr; using ::testing::Test; using ::testing::Values; using ::testing::WithParamInterface; // default log dir static const char *defaultLogDir = "/tmp/qsfs.test.logs/"; void InitLog() { QS::Utils::CreateDirectoryIfNotExistsNoLog(defaultLogDir); QS::Logging::InitializeLogging(unique_ptr<QS::Logging::Log>( new QS::Logging::DefaultLog(defaultLogDir))); EXPECT_TRUE(QS::Logging::GetLogInstance() != nullptr) << "log instance is null"; } // default values for non interested attributes time_t mtime_ = time(NULL); uid_t uid_ = 1000U; gid_t gid_ = 1000U; mode_t fileMode_ = S_IRWXU | S_IRWXG | S_IROTH; struct MetaData { string filePath; uint64_t fileSize; FileType fileType; int numLink; bool isDir; bool isOperable; friend ostream &operator<<(ostream &os, const MetaData &meta) { return os << "FileName: " << meta.filePath << " FileSize: " << meta.fileSize << " FileType: " << QS::Data::GetFileTypeName(meta.fileType) << " NumLink: " << meta.numLink << " IsDir: " << meta.isDir << " IsOperable: " << meta.isOperable; } }; class EntryTest : public Test, public WithParamInterface<MetaData> { public: EntryTest() { InitLog(); auto meta = GetParam(); m_pFileMetaData.reset(new FileMetaData(meta.filePath, meta.fileSize, mtime_, mtime_, uid_, gid_, fileMode_, meta.fileType)); m_pEntry = new Entry(meta.filePath, meta.fileSize, mtime_, mtime_, uid_, gid_, fileMode_, meta.fileType); } protected: shared_ptr<FileMetaData> m_pFileMetaData; Entry *m_pEntry; }; class NodeTest : public Test { protected: static void SetUpTestCase() { InitLog(); pRootEntry = new Entry( "/", 0, mtime_, mtime_, uid_, gid_, fileMode_, FileType::Directory); pRootNode = make_shared<Node>(Entry(*pRootEntry), nullptr); pFileNode1 = make_shared<Node>( Entry("file1", 1024, mtime_, mtime_, uid_, gid_, fileMode_, FileType::File), pRootNode); pLinkNode = make_shared<Node>( Entry("linkToFile1", strlen(path), mtime_, mtime_, uid_, gid_, fileMode_, FileType::SymLink), pRootNode, path); pEmptyNode = unique_ptr<Node>(new Node); } static void TearDownTestCase() { delete pRootEntry; pRootEntry = nullptr; pRootNode = nullptr; pFileNode1 = nullptr; pLinkNode = nullptr; pEmptyNode = nullptr; } protected: static const char path[]; static Entry *pRootEntry; static shared_ptr<Node> pRootNode; static shared_ptr<Node> pFileNode1; static shared_ptr<Node> pLinkNode; static unique_ptr<Node> pEmptyNode; }; const char NodeTest::path[] = "pathLinkToFile1"; Entry *NodeTest::pRootEntry = nullptr; shared_ptr<Node> NodeTest::pRootNode(nullptr); shared_ptr<Node> NodeTest::pFileNode1(nullptr); shared_ptr<Node> NodeTest::pLinkNode(nullptr); unique_ptr<Node> NodeTest::pEmptyNode(nullptr); } // namespace TEST_P(EntryTest, CopyControl) { auto meta = GetParam(); Entry entry = Entry(m_pFileMetaData); EXPECT_EQ(*m_pEntry, entry); } TEST_P(EntryTest, PublicFunctions) { auto meta = GetParam(); EXPECT_EQ(m_pEntry->GetFilePath(), meta.filePath); EXPECT_EQ(m_pEntry->GetFileSize(), meta.fileSize); EXPECT_EQ(m_pEntry->GetFileType(), meta.fileType); EXPECT_EQ(m_pEntry->GetNumLink(), meta.numLink); EXPECT_EQ(m_pEntry->IsDirectory(), meta.isDir); EXPECT_EQ(m_pEntry->operator bool(), meta.isOperable); } INSTANTIATE_TEST_CASE_P( FSEntryTest, EntryTest, // filePath, fileSize, fileType, numLink, isDir, isOperable Values(MetaData{"/", 0, FileType::Directory, 2, true, true}, MetaData{"/file1", 0, FileType::File, 1, false, true}, MetaData{"/file2", 1024, FileType::File, 1, false, true})); TEST_F(NodeTest, DefaultCtor) { EXPECT_FALSE(pEmptyNode->operator bool()); EXPECT_TRUE(pEmptyNode->IsEmpty()); EXPECT_FALSE(const_cast<const Node*> (pEmptyNode.get())->GetEntry()); EXPECT_TRUE(pEmptyNode->GetFilePath().empty()); } TEST_F(NodeTest, CustomCtors) { EXPECT_TRUE(pRootNode->operator bool()); EXPECT_TRUE(pRootNode->IsEmpty()); EXPECT_EQ(pRootNode->GetFilePath(), "/"); EXPECT_EQ((const_cast<const Node*>(pRootNode.get())->GetEntry()), *pRootEntry); EXPECT_EQ(pRootNode->GetFilePath(), pRootEntry->GetFilePath()); EXPECT_EQ(*(pFileNode1->GetParent()), *pRootNode); EXPECT_EQ(pLinkNode->GetSymbolicLink(), string(path)); } TEST_F(NodeTest, PublicFunctions) { // When sharing resources between tests in test case of NodeTest, // as the test order is undefined, so we must restore the state // to its original value before passing control to the next test. EXPECT_FALSE(pRootNode->Find(pFileNode1->GetFilePath())); pRootNode->Insert(pFileNode1); EXPECT_EQ(pRootNode->Find(pFileNode1->GetFilePath()), pFileNode1); EXPECT_EQ(pRootNode->GetChildren().size(), 1U); EXPECT_FALSE(pRootNode->Find(pLinkNode->GetFilePath())); pRootNode->Insert(pLinkNode); EXPECT_EQ(pRootNode->Find(pLinkNode->GetFilePath()), pLinkNode); EXPECT_EQ(pRootNode->GetChildren().size(), 2U); string oldFilePath = pFileNode1->GetFilePath(); string newFilePath("myNewFile1"); pRootNode->RenameChild(oldFilePath, newFilePath); EXPECT_FALSE(pRootNode->Find(oldFilePath)); EXPECT_TRUE(pRootNode->Find(newFilePath)); EXPECT_EQ(pFileNode1->GetFilePath(), newFilePath); pRootNode->RenameChild(newFilePath, oldFilePath); pRootNode->Remove(pFileNode1); EXPECT_FALSE(pRootNode->Find(pFileNode1->GetFilePath())); pRootNode->Remove(pLinkNode); EXPECT_FALSE(pRootNode->Find(pLinkNode->GetFilePath())); EXPECT_TRUE(pRootNode->IsEmpty()); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); int code = RUN_ALL_TESTS(); return code; }
// Created on: 1993-01-14 // Created by: Remi LEQUETTE // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef TopTools_DataMapOfOrientedShapeInteger_HeaderFile #define TopTools_DataMapOfOrientedShapeInteger_HeaderFile #include <TopoDS_Shape.hxx> #include <Standard_Integer.hxx> #include <TopTools_OrientedShapeMapHasher.hxx> #include <NCollection_DataMap.hxx> typedef NCollection_DataMap<TopoDS_Shape,Standard_Integer,TopTools_OrientedShapeMapHasher> TopTools_DataMapOfOrientedShapeInteger; typedef NCollection_DataMap<TopoDS_Shape,Standard_Integer,TopTools_OrientedShapeMapHasher>::Iterator TopTools_DataMapIteratorOfDataMapOfOrientedShapeInteger; #endif
// Copyright © Amer Koleci and Contributors. // Licensed under the MIT License (MIT). See LICENSE in the repository root for more information. #include "Audio/AudioListener.h" #include "Audio/Audio.h" #include "Core/Log.h" namespace Alimer { AudioListener::AudioListener() { } }
#include "VerifiedAccount.h" #include <iostream> using namespace std; int main() { Account** arr = new Account*[2]; arr[0] = new VerifiedAccount("timi", 20, "timiimit", "pass123", Date(2018, 3, 29), VerificationType::email, "Verification successful", Date(2016, 4, 20)); arr[1] = new VerifiedAccount(*arr[0]); cout << arr[0]->toString() << endl; cout << arr[0]->toStringNV() << endl; system("pause"); return 0; }
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "call_stack.h" #include <shlwapi.h> #include <tlhelp32.h> #include "memory_hook.h" #include "base/string_util.h" // Typedefs for explicit dynamic linking with functions exported from // dbghelp.dll. typedef BOOL (__stdcall *t_StackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64); typedef PVOID (__stdcall *t_SymFunctionTableAccess64)(HANDLE, DWORD64); typedef DWORD64 (__stdcall *t_SymGetModuleBase64)(HANDLE, DWORD64); typedef BOOL (__stdcall *t_SymCleanup)(HANDLE); typedef BOOL (__stdcall *t_SymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64); typedef BOOL (__stdcall *t_SymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64); typedef BOOL (__stdcall *t_SymInitialize)(HANDLE, PCTSTR, BOOL); typedef DWORD (__stdcall *t_SymGetOptions)(void); typedef DWORD (__stdcall *t_SymSetOptions)(DWORD); typedef BOOL (__stdcall *t_SymGetSearchPath)(HANDLE, PTSTR, DWORD); typedef DWORD64 (__stdcall *t_SymLoadModule64)(HANDLE, HANDLE, PCSTR, PCSTR, DWORD64, DWORD); typedef BOOL (__stdcall *t_SymGetModuleInfo64)(HANDLE, DWORD64, PIMAGEHLP_MODULE64); // According to http://msdn2.microsoft.com/en-us/library/ms680650(VS.85).aspx // "All DbgHelp functions, such as this one, are single threaded. Therefore, // calls from more than one thread to this function will likely result in // unexpected behavior or memory corruption. To avoid this, you must // synchromize all concurrent calls from one thread to this function." // // dbghelp_lock_ is used to serialize access across all calls to the DbgHelp // library. This may be overly conservative (serializing them all together), // but does guarantee correctness. static Lock dbghelp_lock_; static t_StackWalk64 pStackWalk64 = NULL; static t_SymCleanup pSymCleanup = NULL; static t_SymGetSymFromAddr64 pSymGetSymFromAddr64 = NULL; static t_SymFunctionTableAccess64 pSymFunctionTableAccess64 = NULL; static t_SymGetModuleBase64 pSymGetModuleBase64 = NULL; static t_SymGetLineFromAddr64 pSymGetLineFromAddr64 = NULL; static t_SymInitialize pSymInitialize = NULL; static t_SymGetOptions pSymGetOptions = NULL; static t_SymSetOptions pSymSetOptions = NULL; static t_SymGetModuleInfo64 pSymGetModuleInfo64 = NULL; static t_SymGetSearchPath pSymGetSearchPath = NULL; static t_SymLoadModule64 pSymLoadModule64 = NULL; #define LOADPROC(module, name) do { \ p##name = reinterpret_cast<t_##name>(GetProcAddress(module, #name)); \ if (p##name == NULL) return false; \ } while (0) // Dynamically load the DbgHelp library and supporting routines that we // will use. static bool LoadDbgHelp() { static bool loaded = false; if (!loaded) { AutoLock Lock(dbghelp_lock_); // Re-check if we've loaded successfully now that we have the lock. if (loaded) return true; // Load dbghelp.dll, and obtain pointers to the exported functions that we // will be using. HMODULE dbghelp_module = LoadLibrary(L"dbghelp.dll"); if (dbghelp_module) { LOADPROC(dbghelp_module, StackWalk64); LOADPROC(dbghelp_module, SymFunctionTableAccess64); LOADPROC(dbghelp_module, SymGetModuleBase64); LOADPROC(dbghelp_module, SymCleanup); LOADPROC(dbghelp_module, SymGetSymFromAddr64); LOADPROC(dbghelp_module, SymGetLineFromAddr64); LOADPROC(dbghelp_module, SymInitialize); LOADPROC(dbghelp_module, SymGetOptions); LOADPROC(dbghelp_module, SymSetOptions); LOADPROC(dbghelp_module, SymGetModuleInfo64); LOADPROC(dbghelp_module, SymGetSearchPath); LOADPROC(dbghelp_module, SymLoadModule64); loaded = true; } else { return false; } } return loaded; } // Load the symbols for generating stack traces. static bool LoadSymbols(HANDLE process_handle) { static bool symbols_loaded = false; if (symbols_loaded) return true; BOOL ok; // Initialize the symbol engine. ok = pSymInitialize(process_handle, /* hProcess */ NULL, /* UserSearchPath */ FALSE); /* fInvadeProcess */ if (!ok) return false; DWORD options = pSymGetOptions(); options |= SYMOPT_LOAD_LINES; options |= SYMOPT_FAIL_CRITICAL_ERRORS; options |= SYMOPT_UNDNAME; options = pSymSetOptions(options); const DWORD kMaxSearchPath = 1024; TCHAR buf[kMaxSearchPath] = {0}; ok = pSymGetSearchPath(process_handle, buf, kMaxSearchPath); if (!ok) return false; HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if (snapshot == INVALID_HANDLE_VALUE) return false; MODULEENTRY32W module; module.dwSize = sizeof(module); // Set the size of the structure. BOOL cont = Module32FirstW(snapshot, &module); while (cont) { DWORD64 base; // NOTE the SymLoadModule64 function has the peculiarity of accepting a // both unicode and ASCII strings even though the parameter is PSTR. base = pSymLoadModule64(process_handle, 0, reinterpret_cast<PSTR>(module.szExePath), reinterpret_cast<PSTR>(module.szModule), reinterpret_cast<DWORD64>(module.modBaseAddr), module.modBaseSize); if (base == 0) { int err = GetLastError(); if (err != ERROR_MOD_NOT_FOUND && err != ERROR_INVALID_HANDLE) return false; } cont = Module32NextW(snapshot, &module); } CloseHandle(snapshot); symbols_loaded = true; return true; } CallStack::SymbolCache* CallStack::symbol_cache_; bool CallStack::Initialize() { // We need to delay load the symbol cache until after // the MemoryHook heap is alive. symbol_cache_ = new SymbolCache(); return LoadDbgHelp(); } CallStack::CallStack() { static LONG callstack_id = 0; frame_count_ = 0; hash_ = 0; id_ = InterlockedIncrement(&callstack_id); LoadDbgHelp(); CHECK(GetStackTrace()); } bool CallStack::IsEqual(const CallStack &target) { if (frame_count_ != target.frame_count_) return false; // They can't be equal if the sizes are different. // Walk the frames array until we // either find a mismatch, or until we reach the end of the call stacks. for (int index = 0; index < frame_count_; index++) { if (frames_[index] != target.frames_[index]) return false; // Found a mismatch. They are not equal. } // Reached the end of the call stacks. They are equal. return true; } void CallStack::AddFrame(DWORD_PTR pc) { DCHECK(frame_count_ < kMaxTraceFrames); frames_[frame_count_++] = pc; // Create a unique id for this CallStack. pc = pc + (frame_count_ * 13); // Alter the PC based on position in stack. hash_ = ~hash_ + (pc << 15); hash_ = hash_ ^ (pc >> 12); hash_ = hash_ + (pc << 2); hash_ = hash_ ^ (pc >> 4); hash_ = hash_ * 2057; hash_ = hash_ ^ (pc >> 16); } bool CallStack::GetStackTrace() { // Initialize the context record. CONTEXT context; memset(&context, 0, sizeof(context)); context.ContextFlags = CONTEXT_FULL; __asm call x __asm x: pop eax __asm mov context.Eip, eax __asm mov context.Ebp, ebp __asm mov context.Esp, esp STACKFRAME64 frame; memset(&frame, 0, sizeof(frame)); #ifdef _M_IX86 DWORD image_type = IMAGE_FILE_MACHINE_I386; frame.AddrPC.Offset = context.Eip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Ebp; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Offset = context.Esp; frame.AddrStack.Mode = AddrModeFlat; #elif NOT IMPLEMENTED! #endif HANDLE current_process = GetCurrentProcess(); HANDLE current_thread = GetCurrentThread(); // Walk the stack. unsigned int count = 0; { AutoLock lock(dbghelp_lock_); while (count < kMaxTraceFrames) { count++; if (!pStackWalk64(image_type, current_process, current_thread, &frame, &context, 0, pSymFunctionTableAccess64, pSymGetModuleBase64, NULL)) break; // Couldn't trace back through any more frames. if (frame.AddrFrame.Offset == 0) continue; // End of stack. // Push this frame's program counter onto the provided CallStack. AddFrame((DWORD_PTR)frame.AddrPC.Offset); } } return true; } void CallStack::ToString(std::string* output) { static const int kStackWalkMaxNameLen = MAX_SYM_NAME; HANDLE current_process = GetCurrentProcess(); if (!LoadSymbols(current_process)) { *output = "Error"; return; } AutoLock lock(dbghelp_lock_); // Iterate through each frame in the call stack. for (int32 index = 0; index < frame_count_; index++) { std::string line; DWORD_PTR intruction_pointer = frame(index); SymbolCache::iterator it; it = symbol_cache_->find( intruction_pointer ); if (it != symbol_cache_->end()) { line = it->second; } else { // Try to locate a symbol for this frame. DWORD64 symbol_displacement = 0; ULONG64 buffer[(sizeof(IMAGEHLP_SYMBOL64) + sizeof(TCHAR)*kStackWalkMaxNameLen + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(buffer); memset(buffer, 0, sizeof(buffer)); symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); symbol->MaxNameLength = kStackWalkMaxNameLen; BOOL ok = pSymGetSymFromAddr64(current_process, // hProcess intruction_pointer, // Address &symbol_displacement, // Displacement symbol); // Symbol if (ok) { // Try to locate more source information for the symbol. IMAGEHLP_LINE64 Line; memset(&Line, 0, sizeof(Line)); Line.SizeOfStruct = sizeof(Line); DWORD line_displacement; ok = pSymGetLineFromAddr64(current_process, intruction_pointer, &line_displacement, &Line); if (ok) { // Skip junk symbols from our internal stuff. if (strstr(symbol->Name, "CallStack::") || strstr(symbol->Name, "MemoryWatcher::") || strstr(symbol->Name, "Perftools_") || strstr(symbol->Name, "MemoryHook::") ) { // Just record a blank string. (*symbol_cache_)[intruction_pointer] = std::string(""); continue; } line += " "; line += static_cast<char*>(Line.FileName); line += " ("; line += IntToString(Line.LineNumber); line += "): "; line += symbol->Name; line += "\n"; } else { line += " unknown (0):"; line += symbol->Name; line += "\n"; } } else { // OK - couldn't get any info. Try for the module. IMAGEHLP_MODULE64 module_info; module_info.SizeOfStruct = sizeof(module_info); if (pSymGetModuleInfo64(current_process, intruction_pointer, &module_info)) { line += " ("; line += static_cast<char*>(module_info.ModuleName); line += ")\n"; } else { line += " ???\n"; } } } (*symbol_cache_)[intruction_pointer] = line; *output += line; } *output += "==================\n"; } Lock AllocationStack::freelist_lock_; AllocationStack* AllocationStack::freelist_ = NULL; void* AllocationStack::operator new(size_t size) { DCHECK(size == sizeof(AllocationStack)); { AutoLock lock(freelist_lock_); if (freelist_ != NULL) { AllocationStack* stack = freelist_; freelist_ = freelist_->next_; stack->next_ = NULL; return stack; } } return MemoryHook::Alloc(size); } void AllocationStack::operator delete(void* ptr) { AllocationStack *stack = reinterpret_cast<AllocationStack*>(ptr); AutoLock lock(freelist_lock_); DCHECK(stack->next_ == NULL); stack->next_ = freelist_; freelist_ = stack; }
/* * Copyright (C) 2015 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "pch.h" #include <gui/styles.hpp> #include <gui/node.hpp> namespace styles { bool selector::selects(const gui::node* node) const { if (!maySelect(node)) return false; switch (m_pseudoClass) { case pseudo::hover: if (!node->getHovered()) return false; break; case pseudo::active: if (!node->getActive()) return false; break; }; return true; } // same as selects, but doesn't take pseudo classes into account bool selector::maySelect(const gui::node* node) const { if (!node) return false; if (m_elemName != gui::elem::unspecified && m_elemName != node->getNodeName()) return false; for (auto& cl : m_classes) { if (!node->hasClass(cl)) return false; } return true; } };
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2020 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Aaron Young // ============================================================================= // // Class for an agent that wraps a Chrono::Vehicle wheeled vehicle. The // underlying dynamics are those of a wheeled vehicle, state data consists of // the position and orientation of the COM and the wheels of the vehicle // // ============================================================================= #include "chrono_synchrono/agent/SynWheeledVehicleAgent.h" #include "chrono_synchrono/utils/SynLog.h" #include "chrono_vehicle/utils/ChUtilsJSON.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_thirdparty/filesystem/path.h" #include "chrono_vehicle/chassis/ChRigidChassis.h" using namespace chrono::vehicle; namespace chrono { namespace synchrono { SynWheeledVehicleAgent::SynWheeledVehicleAgent(ChWheeledVehicle* vehicle, const std::string& filename) : SynAgent(), m_vehicle(vehicle) { m_state = chrono_types::make_shared<SynWheeledVehicleStateMessage>(AgentKey(), AgentKey()); m_description = chrono_types::make_shared<SynWheeledVehicleDescriptionMessage>(); if (!filename.empty()) { SetZombieVisualizationFilesFromJSON(filename); } else if (vehicle && std::dynamic_pointer_cast<ChRigidChassis>(vehicle->GetChassis())) { SetZombieVisualizationFiles(std::static_pointer_cast<ChRigidChassis>(vehicle->GetChassis())->GetMeshFilename(), vehicle->GetWheel(0, LEFT)->GetMeshFilename(), vehicle->GetWheel(0, LEFT)->GetTire()->GetMeshFilename()); int num_wheels = 0; for (auto axle : vehicle->GetAxles()) num_wheels += static_cast<int>(axle->GetWheels().size()); SetNumWheels(num_wheels); } } SynWheeledVehicleAgent::~SynWheeledVehicleAgent() {} void SynWheeledVehicleAgent::InitializeZombie(ChSystem* system) { m_zombie_body = CreateChassisZombieBody(m_description->chassis_vis_file, system); // For each wheel, create a tire mesh and wheel mesh. // If it is a right side wheel, a 180 degree rotation is made for (int i = 0; i < m_description->num_wheels; i++) { auto tire_trimesh = CreateMeshZombieComponent(m_description->tire_vis_file); auto wheel_trimesh = CreateMeshZombieComponent(m_description->wheel_vis_file); ChQuaternion<> rot = (i % 2 == 0) ? Q_from_AngZ(0) : Q_from_AngZ(CH_C_PI); wheel_trimesh->GetMesh()->Transform(ChVector<>(), ChMatrix33<>(rot)); tire_trimesh->GetMesh()->Transform(ChVector<>(), ChMatrix33<>(rot)); auto wheel = chrono_types::make_shared<ChBodyAuxRef>(); wheel->AddAsset(wheel_trimesh); wheel->AddAsset(tire_trimesh); wheel->SetCollide(false); wheel->SetBodyFixed(true); system->Add(wheel); m_wheel_list.push_back(wheel); } } void SynWheeledVehicleAgent::SynchronizeZombie(std::shared_ptr<SynMessage> message) { if (auto state = std::dynamic_pointer_cast<SynWheeledVehicleStateMessage>(message)) { m_zombie_body->SetFrame_REF_to_abs(state->chassis.GetFrame()); for (int i = 0; i < state->wheels.size(); i++) m_wheel_list[i]->SetFrame_REF_to_abs(state->wheels[i].GetFrame()); } } void SynWheeledVehicleAgent::Update() { if (!m_vehicle) return; auto chassis_abs = m_vehicle->GetChassisBody()->GetFrame_REF_to_abs(); SynPose chassis(chassis_abs.GetPos(), chassis_abs.GetRot()); chassis.GetFrame().SetPos_dt(chassis_abs.GetPos_dt()); chassis.GetFrame().SetPos_dtdt(chassis_abs.GetPos_dtdt()); chassis.GetFrame().SetRot_dt(chassis_abs.GetRot_dt()); chassis.GetFrame().SetRot_dtdt(chassis_abs.GetRot_dtdt()); std::vector<SynPose> wheels; for (auto axle : m_vehicle->GetAxles()) { for (auto wheel : axle->GetWheels()) { auto state = wheel->GetState(); auto wheel_abs = wheel->GetSpindle()->GetFrame_REF_to_abs(); SynPose frame(state.pos, state.rot); frame.GetFrame().SetPos_dt(wheel_abs.GetPos_dt()); frame.GetFrame().SetPos_dtdt(wheel_abs.GetPos_dtdt()); frame.GetFrame().SetRot_dt(wheel_abs.GetRot_dt()); frame.GetFrame().SetRot_dtdt(wheel_abs.GetRot_dtdt()); wheels.emplace_back(frame); } } auto time = m_vehicle->GetSystem()->GetChTime(); m_state->SetState(time, chassis, wheels); } // ------------------------------------------------------------------------ void SynWheeledVehicleAgent::SetZombieVisualizationFilesFromJSON(const std::string& filename) { m_description->SetZombieVisualizationFilesFromJSON(filename); } void SynWheeledVehicleAgent::SetKey(AgentKey agent_key) { m_description->SetSourceKey(agent_key); m_state->SetSourceKey(agent_key); m_agent_key = agent_key; } // ------------------------------------------------------------------------ std::shared_ptr<ChTriangleMeshShape> SynWheeledVehicleAgent::CreateMeshZombieComponent(const std::string& filename) { auto mesh = chrono_types::make_shared<geometry::ChTriangleMeshConnected>(); if (!filename.empty()) mesh->LoadWavefrontMesh(vehicle::GetDataFile(filename), false, false); auto trimesh = chrono_types::make_shared<ChTriangleMeshShape>(); trimesh->SetMesh(mesh); trimesh->SetStatic(true); trimesh->SetName(filesystem::path(filename).stem()); return trimesh; } std::shared_ptr<ChBodyAuxRef> SynWheeledVehicleAgent::CreateChassisZombieBody(const std::string& filename, ChSystem* system) { auto trimesh = CreateMeshZombieComponent(filename); auto zombie_body = chrono_types::make_shared<ChBodyAuxRef>(); zombie_body->AddAsset(trimesh); zombie_body->SetCollide(false); zombie_body->SetBodyFixed(true); zombie_body->SetFrame_COG_to_REF(ChFrame<>({0, 0, -0.2}, {1, 0, 0, 0})); system->Add(zombie_body); return zombie_body; } } // namespace synchrono } // namespace chrono
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.Timeline.RuntimeElement #include "UnityEngine/Timeline/RuntimeElement.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: UnityEngine.Timeline namespace UnityEngine::Timeline { // Size: 0x14 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Timeline.RuntimeClipBase class RuntimeClipBase : public UnityEngine::Timeline::RuntimeElement { public: // Creating value type constructor for type: RuntimeClipBase RuntimeClipBase() noexcept {} // public System.Double get_start() // Offset: 0xFFFFFFFF double get_start(); // public System.Double get_duration() // Offset: 0xFFFFFFFF double get_duration(); // public override System.Int64 get_intervalStart() // Offset: 0x17CCBC8 // Implemented from: UnityEngine.Timeline.RuntimeElement // Base method: System.Int64 RuntimeElement::get_intervalStart() int64_t get_intervalStart(); // public override System.Int64 get_intervalEnd() // Offset: 0x17CCC48 // Implemented from: UnityEngine.Timeline.RuntimeElement // Base method: System.Int64 RuntimeElement::get_intervalEnd() int64_t get_intervalEnd(); // protected System.Void .ctor() // Offset: 0x17CC5C8 // Implemented from: UnityEngine.Timeline.RuntimeElement // Base method: System.Void RuntimeElement::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeClipBase* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::Timeline::RuntimeClipBase::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeClipBase*, creationType>())); } }; // UnityEngine.Timeline.RuntimeClipBase #pragma pack(pop) } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Timeline::RuntimeClipBase*, "UnityEngine.Timeline", "RuntimeClipBase");
// http://turtle.sourceforge.net // // Copyright Mathieu Champlon 2014 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[ prerequisite #define BOOST_AUTO_TEST_MAIN #include <boost/test/auto_unit_test.hpp> #include <turtle/mock.hpp> //] #include "calculator.hpp" #include "mock_view.hpp" namespace phases { //[ phases BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; // create mock objects calculator c( v ); // create object under test MOCK_EXPECT( v.display ).once().with( 0 ); // configure mock objects c.add( 0, 0 ); // exercise object under test } // verify mock objects //] } namespace verify_reset { //[ verify_reset BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; calculator c( v ); MOCK_EXPECT( v.display ).once().with( 0 ); c.add( 0, 0 ); MOCK_VERIFY( v.display ); // verify all expectations are fulfilled for the 'display' method mock::verify( v ); // verify all expectations are fulfilled for all methods of 'v' mock::verify(); // verify all expectations are fulfilled for all existing mock objects MOCK_RESET( v.display ); // reset all expectations for the 'display' method mock::reset( v ); // reset all expectations for all methods of 'v' mock::reset(); // reset all expectations for all existing mock objects } // automatically verify all expectations are fulfilled for all mock objects going out of scope //] } namespace expectations { //[ expectations BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; calculator c( v ); MOCK_EXPECT( v.display ).once().with( 0 ); // this call must occur once (and only once) MOCK_EXPECT( v.display ).with( 1 ); // this call can occur any number of times (including never) c.add( 0, 0 ); } //] } namespace sequence { //[ sequence BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; calculator c( v ); mock::sequence s; MOCK_EXPECT( v.display ).once().with( 0 ).in( s ); // add this expectation to the sequence MOCK_EXPECT( v.display ).with( 1 ).in( s ); // add this expectation to the sequence after the previous call c.add( 0, 0 ); c.add( 1, 0 ); } //] } namespace several_sequences { //[ several_sequences BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; calculator c( v ); mock::sequence s1, s2; MOCK_EXPECT( v.display ).once().with( 0 ).in( s1 ); MOCK_EXPECT( v.display ).once().with( 1 ).in( s2 ); MOCK_EXPECT( v.display ).with( 2 ).in( s1, s2 ); // add this expectation to both sequences after the previous calls c.add( 0, 0 ); c.add( 1, 0 ); c.add( 1, 1 ); c.add( 2, 0 ); } //] } namespace action { //[ action_view class view { public: virtual bool display( int result ) = 0; // returns a boolean }; //] MOCK_BASE_CLASS( mock_view, view ) { MOCK_METHOD( display, 1 ) }; class calculator { public: calculator( view& v ); void add( int a, int b ); }; //[ action_test BOOST_AUTO_TEST_CASE( zero_plus_zero_is_zero ) { mock_view v; calculator c( v ); MOCK_EXPECT( v.display ).once().with( 0 ); // missing returns( true ) c.add( 0, 0 ); } //] }
class Solution { public: int largestAltitude(vector<int>& gain) { int maxAltitude = 0, prev = 0; for(int i = 0 ; i < gain.size(); i++) { int alt = gain[i] + prev; maxAltitude = max(maxAltitude, alt); prev = alt; } return maxAltitude; } };
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \file GLFBOTex.cpp \author Jens Krueger SCI Institute University of Utah Jens Schneider tum.3D, Muenchen \date August 2008 */ #include "GLFBOTex.h" #include <Controller/Controller.h> #ifdef WIN32 #ifndef DEBUG #pragma warning( disable : 4189 ) // disable unused var warning #endif #endif GLuint GLFBOTex::m_hFBO = 0; int GLFBOTex::m_iCount = 0; bool GLFBOTex::m_bInitialized = true; /** * Constructor: on first instantiation, generate an FBO. * In any case a new dummy texture according to the parameters is generated. */ GLFBOTex::GLFBOTex(MasterController* pMasterController, GLenum minfilter, GLenum magfilter, GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat, unsigned int iSizePerElement, bool bHaveDepth, int iNumBuffers) : m_pMasterController(pMasterController), m_iSizePerElement(iSizePerElement), m_iSizeX(width), m_iSizeY(height), m_LastDepthTextUnit(0), m_iNumBuffers(iNumBuffers) { if (width<1) width=1; if (height<1) height=1; if (!m_bInitialized) { if (GLEW_OK!=glewInit()) { T_ERROR("failed to initialize GLEW!"); return; } if (!glewGetExtension("GL_EXT_framebuffer_object")) { T_ERROR("GL_EXT_framebuffer_object not supported!"); return; } m_bInitialized=true; } glGetError(); assert(iNumBuffers>0); assert(iNumBuffers<5); m_hTexture=new GLuint[iNumBuffers]; m_LastTexUnit=new GLenum[iNumBuffers]; m_LastAttachment=new GLenum[iNumBuffers]; for (int i=0; i<m_iNumBuffers; i++) { m_LastTexUnit[i]=0; m_LastAttachment[i]=GL_COLOR_ATTACHMENT0_EXT+i; m_hTexture[i]=0; } if (m_hFBO==0) initFBO(); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during FBO creation!", static_cast<int>(glerr)); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; return; } } initTextures(minfilter,magfilter,wrapmode,width,height,intformat); { GLenum glerr = glGetError(); if(GL_NO_ERROR != glerr) { T_ERROR("Error '%d' during texture creation!", static_cast<int>(glerr)); glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; return; } } if (bHaveDepth) { #ifdef GLFBOTEX_DEPTH_RENDERBUFFER glGenRenderbuffersEXT(1,&m_hDepthBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24,width,height); #else glGenTextures(1,&m_hDepthBuffer); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT,width,height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); #endif } else m_hDepthBuffer=0; ++m_iCount; } /** * Destructor: Delete texture object. If no more instances of * GLFBOTex are around, the FBO is deleted as well. */ GLFBOTex::~GLFBOTex(void) { if (m_hTexture) { glDeleteTextures(m_iNumBuffers,m_hTexture); delete[] m_hTexture; m_hTexture=NULL; } if (m_LastTexUnit) { delete[] m_LastTexUnit; m_LastTexUnit=NULL; } if (m_LastAttachment) { delete[] m_LastAttachment; m_LastAttachment=NULL; } #ifdef GLFBOTEX_DEPTH_RENDERBUFFER if (m_hDepthBuffer) glDeleteRenderbuffersEXT(1,&m_hDepthBuffer); #else if (m_hDepthBuffer) glDeleteTextures(1,&m_hDepthBuffer); #endif m_hDepthBuffer=0; --m_iCount; if (m_iCount==0) { m_pMasterController->DebugOut()->Message(_func_, "FBO released via " "destructor call."); glDeleteFramebuffersEXT(1,&m_hFBO); m_hFBO=0; } } /** * Build a dummy texture according to the parameters. */ void GLFBOTex::initTextures(GLenum minfilter,GLenum magfilter,GLenum wrapmode, GLsizei width, GLsizei height, GLenum intformat) { MESSAGE("Initializing 2D texture of dimensions: %ux%u", static_cast<unsigned int>(width), static_cast<unsigned int>(height)); glDeleteTextures(m_iNumBuffers,m_hTexture); glGenTextures(m_iNumBuffers,m_hTexture); for (int i=0; i<m_iNumBuffers; i++) { glBindTexture(GL_TEXTURE_2D, m_hTexture[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapmode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapmode); int level=0; switch (minfilter) { case GL_NEAREST_MIPMAP_NEAREST: case GL_LINEAR_MIPMAP_NEAREST: case GL_NEAREST_MIPMAP_LINEAR: case GL_LINEAR_MIPMAP_LINEAR: do { glTexImage2D(GL_TEXTURE_2D, level, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); width/=2; height/=2; if (width==0 && height>0) width=1; if (width>0 && height==0) height=1; ++level; } while (width>=1 && height>=1); break; default: glTexImage2D(GL_TEXTURE_2D, 0, intformat, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); } } } /** * Build a new FBO. */ void GLFBOTex::initFBO(void) { MESSAGE("Initializing FBO..."); glGenFramebuffersEXT(1, &m_hFBO); } /** * Check the FBO for consistency. */ bool GLFBOTex::CheckFBO(const char* method) { GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: return true; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: T_ERROR("%s() - Unsupported Format!",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: T_ERROR("%s() - Incomplete missing attachment",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: T_ERROR("%s() - Incomplete dimensions",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: T_ERROR("%s() - Incomplete formats",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: T_ERROR("%s() - Incomplete draw buffer",method); return false; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: T_ERROR("%s() - Incomplete read buffer",method); return false; default: return false; } } /** * Lock texture for writing. Texture may not be bound any more! */ void GLFBOTex::Write(unsigned int iTargetBuffer, int iBuffer, bool bCheckBuffer) { GLenum target = GL_COLOR_ATTACHMENT0_EXT + iTargetBuffer; #ifdef _DEBUG if (!m_hFBO) { T_ERROR("FBO not initialized!"); return; } #endif glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,m_hFBO); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastAttachment[iBuffer]=target; glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, target, GL_TEXTURE_2D, m_hTexture[iBuffer], 0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D,m_hDepthBuffer,0); if (bCheckBuffer) { #ifdef _DEBUG if (!CheckFBO("Write")) return; #endif } } void GLFBOTex::FinishWrite(int iBuffer) { glGetError(); assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,m_LastAttachment[iBuffer],GL_TEXTURE_2D,0,0); if (m_hDepthBuffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D,0,0); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0); } void GLFBOTex::Read(unsigned int iTargetUnit, int iBuffer) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastTexUnit[iBuffer]!=0) { T_ERROR("Missing FinishRead()!"); } #endif assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); m_LastTexUnit[iBuffer]=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hTexture[iBuffer]); } void GLFBOTex::ReadDepth(unsigned int iTargetUnit) { GLenum texunit = GL_TEXTURE0 + iTargetUnit; #ifdef _DEBUG if (m_LastDepthTextUnit!=0) { T_ERROR("Missing FinishDepthRead()!"); } #endif m_LastDepthTextUnit=texunit; glActiveTextureARB(texunit); glBindTexture(GL_TEXTURE_2D,m_hDepthBuffer); } // Finish reading from the depth texture void GLFBOTex::FinishDepthRead() { glActiveTextureARB(m_LastDepthTextUnit); glBindTexture(GL_TEXTURE_2D,0); m_LastDepthTextUnit=0; } void GLFBOTex::NoDrawBuffer() { glDrawBuffer(GL_NONE); } void GLFBOTex::OneDrawBuffer() { glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); } void GLFBOTex::TwoDrawBuffers() { GLenum twobuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT }; glDrawBuffers(2, twobuffers); } void GLFBOTex::ThreeDrawBuffers() { GLenum threebuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT}; glDrawBuffers(3, threebuffers); } void GLFBOTex::FourDrawBuffers() { GLenum fourbuffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT}; glDrawBuffers(4, fourbuffers); } // Finish reading from this texture void GLFBOTex::FinishRead(int iBuffer) { assert(iBuffer>=0); assert(iBuffer<m_iNumBuffers); glActiveTextureARB(m_LastTexUnit[iBuffer]); glBindTexture(GL_TEXTURE_2D,0); m_LastTexUnit[iBuffer]=0; }
#include "dvlnet/loopback.h" #include "utils/stubs.h" #include "utils/language.h" namespace devilution::net { int loopback::create(std::string addrstr, std::string passwd) { return plr_single; } int loopback::join(std::string addrstr, std::string passwd) { ABORT(); } bool loopback::SNetReceiveMessage(int *sender, char **data, int *size) { if (message_queue.empty()) return false; message_last = message_queue.front(); message_queue.pop(); *sender = plr_single; *size = message_last.size(); *data = reinterpret_cast<char *>(message_last.data()); return true; } bool loopback::SNetSendMessage(int dest, void *data, unsigned int size) { if (dest == plr_single || dest == SNPLAYER_ALL) { auto *rawMessage = reinterpret_cast<unsigned char *>(data); buffer_t message(rawMessage, rawMessage + size); message_queue.push(message); } return true; } bool loopback::SNetReceiveTurns(char **data, unsigned int *size, DWORD *status) { for (auto i = 0; i < MAX_PLRS; ++i) { size[i] = 0; data[i] = nullptr; } return true; } bool loopback::SNetSendTurn(char *data, unsigned int size) { return true; } int loopback::SNetGetProviderCaps(struct _SNETCAPS *caps) { caps->size = 0; // engine writes only ?!? caps->flags = 0; // unused caps->maxmessagesize = 512; // capped to 512; underflow if < 24 caps->maxqueuesize = 0; // unused caps->maxplayers = MAX_PLRS; // capped to 4 caps->bytessec = 1000000; // ? caps->latencyms = 0; // unused caps->defaultturnssec = 10; // ? caps->defaultturnsintransit = 1; // maximum acceptable number // of turns in queue? return 1; } bool loopback::SNetRegisterEventHandler(event_type evtype, SEVTHANDLER func) { // not called in real singleplayer mode // not needed in pseudo multiplayer mode (?) return true; } bool loopback::SNetUnregisterEventHandler(event_type evtype, SEVTHANDLER func) { // not called in real singleplayer mode // not needed in pseudo multiplayer mode (?) return true; } bool loopback::SNetLeaveGame(int type) { return true; } bool loopback::SNetDropPlayer(int playerid, DWORD flags) { return true; } void loopback::setup_gameinfo(buffer_t info) { } bool loopback::SNetGetOwnerTurnsWaiting(DWORD *turns) { *turns = 0; return true; } bool loopback::SNetGetTurnsInTransit(DWORD *turns) { *turns = 0; return true; } std::string loopback::make_default_gamename() { return std::string(_("loopback")); } } // namespace devilution::net
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: implementation of the rcon client // //===========================================================================// // If we are going to include winsock.h then we need to disable protected_things.h // or else we get many warnings. #undef PROTECTED_THINGS_ENABLE #include "tier0/platform.h" #ifdef POSIX #include "net_ws_headers.h" #define WSAGetLastError() errno #else #if !defined( _X360 ) #include <winsock.h> #else #include "winsockx.h" #endif #undef SetPort // winsock screws with the SetPort string... *sigh*8 #endif #include <tier0/dbg.h> #include "utlbuffer.h" #include "cl_rcon.h" #include "vprof_engine.h" #include "proto_oob.h" // PORT_RCON define #include "cmd.h" #include "tier2/fileutils.h" #include "zip/XUnzip.h" #if defined( _X360 ) #include "xbox/xbox_win32stubs.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" static CRConClient g_RCONClient; CRConClient & RCONClient() { return g_RCONClient; } #ifdef ENABLE_RPT class CRPTClient : public CRConClient { typedef CRConClient BaseClass; public: virtual void OnSocketAccepted( SocketHandle_t hSocket, const netadr_t & netAdr, void** ppData ) { BaseClass::OnSocketAccepted( hSocket, netAdr, ppData ); // Immediately try to start vprofiling // Also, enable cheats on this client only Cmd_SetRptActive( true ); StartVProfData(); } virtual void OnSocketClosed( SocketHandle_t hSocket, const netadr_t & netAdr, void* pData ) { StopVProfData(); Cmd_SetRptActive( false ); BaseClass::OnSocketClosed( hSocket, netAdr, pData ); } }; static CRPTClient g_RPTClient; CRConClient & RPTClient() { return g_RPTClient; } #endif // ENABLE_RPT static void RconAddressChanged_f( IConVar *pConVar, const char *pOldString, float flOldValue ) { #ifndef SWDS ConVarRef var( pConVar ); netadr_t to; const char *cmdargs = var.GetString(); if ( ( !cmdargs || !cmdargs[ 0 ] ) && cl.m_NetChannel ) { to = cl.m_NetChannel->GetRemoteAddress(); } else if ( !NET_StringToAdr( cmdargs, &to ) ) { Msg( "Unable to resolve rcon address %s\n", var.GetString() ); return; } Msg( "Setting rcon_address: %s:%d\n", to.ToString( true ), to.GetPort() ); RCONClient().SetAddress( to ); #endif } static ConVar rcon_address( "rcon_address", "", FCVAR_SERVER_CANNOT_QUERY|FCVAR_DONTRECORD, "Address of remote server if sending unconnected rcon commands (format x.x.x.x:p) ", RconAddressChanged_f ); //----------------------------------------------------------------------------- // Implementation of remote vprof //----------------------------------------------------------------------------- CRConVProfExport::CRConVProfExport() { } void CRConVProfExport::AddListener() { } void CRConVProfExport::RemoveListener() { } void CRConVProfExport::SetBudgetFlagsFilter( int filter ) { } int CRConVProfExport::GetNumBudgetGroups() { return m_Info.Count(); } void CRConVProfExport::GetBudgetGroupInfos( CExportedBudgetGroupInfo *pInfos ) { memcpy( pInfos, m_Info.Base(), GetNumBudgetGroups() * sizeof(CExportedBudgetGroupInfo) ); } void CRConVProfExport::GetBudgetGroupTimes( float times[IVProfExport::MAX_BUDGETGROUP_TIMES] ) { int nGroups = min( m_Times.Count(), (int)IVProfExport::MAX_BUDGETGROUP_TIMES ); memset( times, 0, nGroups * sizeof(float) ); nGroups = min( GetNumBudgetGroups(), nGroups ); memcpy( times, m_Times.Base(), nGroups * sizeof(float) ); } void CRConVProfExport::PauseProfile() { // NOTE: This only has effect when testing on a listen server // it shouldn't do anything in the wild. When drawing the budget panel // this will cause the time spent doing so to not be counted VProfExport_Pause(); } void CRConVProfExport::ResumeProfile() { // NOTE: This only has effect when testing on a listen server // it shouldn't do anything in the wild VProfExport_Resume(); } void CRConVProfExport::CleanupGroupData() { int nCount = m_Info.Count(); for ( int i = 0; i < nCount; ++i ) { delete m_Info[i].m_pName; } m_Info.RemoveAll(); } void CRConVProfExport::OnRemoteGroupData( const void *data, int len ) { CUtlBuffer buf( data, len, CUtlBuffer::READ_ONLY ); int nFirstGroup = buf.GetInt(); if ( nFirstGroup == 0 ) { CleanupGroupData(); } else { Assert( nFirstGroup == m_Info.Count() ); } // NOTE: See WriteRemoteVProfGroupData in vprof_engine.cpp // to see the encoding of this data int nGroupCount = buf.GetInt(); int nBase = m_Info.AddMultipleToTail( nGroupCount ); char temp[1024]; for ( int i = 0; i < nGroupCount; ++i ) { CExportedBudgetGroupInfo *pInfo = &m_Info[nBase + i]; unsigned char red, green, blue, alpha; red = buf.GetUnsignedChar( ); green = buf.GetUnsignedChar( ); blue = buf.GetUnsignedChar( ); alpha = buf.GetUnsignedChar( ); buf.GetString( temp ); int nLen = Q_strlen( temp ); pInfo->m_Color.SetColor( red, green, blue, alpha ); char *pBuf = new char[ nLen + 1 ]; pInfo->m_pName = pBuf; memcpy( pBuf, temp, nLen+1 ); pInfo->m_BudgetFlags = 0; } } void CRConVProfExport::OnRemoteData( const void *data, int len ) { // NOTE: See WriteRemoteVProfData in vprof_engine.cpp // to see the encoding of this data int nCount = len / sizeof(float); Assert( nCount == m_Info.Count() ); CUtlBuffer buf( data, len, CUtlBuffer::READ_ONLY ); m_Times.SetCount( nCount ); memcpy( m_Times.Base(), data, nCount * sizeof(float) ); } CON_COMMAND( vprof_remote_start, "Request a VProf data stream from the remote server (requires authentication)" ) { // TODO: Make this work (it might already!) // RCONClient().StartVProfData(); } CON_COMMAND( vprof_remote_stop, "Stop an existing remote VProf data request" ) { // TODO: Make this work (it might already!) // RCONClient().StopVProfData(); } #ifdef ENABLE_RPT CON_COMMAND_F( rpt_screenshot, "", FCVAR_HIDDEN | FCVAR_DONTRECORD ) { RPTClient().TakeScreenshot(); } CON_COMMAND_F( rpt_download_log, "", FCVAR_HIDDEN | FCVAR_DONTRECORD ) { RPTClient().GrabConsoleLog(); } #endif // ENABLE_RPT //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- #pragma warning ( disable : 4355 ) CRConClient::CRConClient() : m_Socket( this ) { m_bAuthenticated = false; m_iAuthRequestID = 1; // must start at 1 m_iReqID = 0; m_nScreenShotIndex = 0; m_nConsoleLogIndex = 0; } #pragma warning ( default : 4355 ) //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CRConClient::~CRConClient() { } //----------------------------------------------------------------------------- // Changes the password //----------------------------------------------------------------------------- void CRConClient::SetPassword( const char *pPassword ) { m_Socket.CloseAllAcceptedSockets(); m_Password = pPassword; } void CRConClient::SetRemoteFileDirectory( const char *pDir ) { m_RemoteFileDir = pDir; m_nScreenShotIndex = 0; m_nConsoleLogIndex = 0; g_pFullFileSystem->CreateDirHierarchy( pDir, "MOD" ); } //----------------------------------------------------------------------------- // Purpose: set the addresss of the remote server //----------------------------------------------------------------------------- void CRConClient::SetAddress( const netadr_t &netAdr ) { m_Socket.CloseAllAcceptedSockets(); m_Address = netAdr; if ( m_Address.GetPort() == 0 ) { m_Address.SetPort( PORT_SERVER ); // override the port setting, by default rcon tries to bind to the same port as the server } } //----------------------------------------------------------------------------- // Inherited from ISocketCreatorListener //----------------------------------------------------------------------------- bool CRConClient::ShouldAcceptSocket( SocketHandle_t hSocket, const netadr_t & netAdr ) { // Can't connect if we're already connected return !IsConnected(); } void CRConClient::OnSocketAccepted( SocketHandle_t hSocket, const netadr_t & netAdr, void** ppData ) { } void CRConClient::OnSocketClosed( SocketHandle_t hSocket, const netadr_t & netAdr, void* pData ) { // reset state m_bAuthenticated = false; m_iReqID = 0; m_iAuthRequestID = 1; // must start at 1 m_SendBuffer.Purge(); m_RecvBuffer.Purge(); } //----------------------------------------------------------------------------- // Connects to the address specified by SetAddress //----------------------------------------------------------------------------- bool CRConClient::ConnectSocket() { if ( m_Socket.ConnectSocket( m_Address, true ) < 0 ) { Warning( "Unable to connect to remote server (%s)\n", m_Address.ToString() ); return false; } return true; } void CRConClient::CloseSocket() { m_Socket.CloseAllAcceptedSockets(); } //----------------------------------------------------------------------------- // Are we connected? //----------------------------------------------------------------------------- bool CRConClient::IsConnected() const { return m_Socket.GetAcceptedSocketCount() > 0; } //----------------------------------------------------------------------------- // Creates a listen server, connects to remote machines that connect to it //----------------------------------------------------------------------------- void CRConClient::CreateListenSocket( const netadr_t &netAdr ) { m_Socket.CreateListenSocket( netAdr ); } void CRConClient::CloseListenSocket() { m_Socket.CloseListenSocket( ); } //----------------------------------------------------------------------------- // Purpose: send queued messages //----------------------------------------------------------------------------- void CRConClient::SendQueuedData() { SocketHandle_t hSocket = GetSocketHandle(); while ( m_SendBuffer.TellMaxPut() - m_SendBuffer.TellGet() > sizeof(int) ) { size_t nSize = *(int*)m_SendBuffer.PeekGet(); Assert( nSize >= m_SendBuffer.TellMaxPut() - m_SendBuffer.TellGet() - sizeof( int ) ); int ret = send( hSocket, (const char *)m_SendBuffer.PeekGet(), nSize + sizeof( int ), 0 ); if ( ret != -1 ) { m_SendBuffer.SeekGet( CUtlBuffer::SEEK_CURRENT, nSize + sizeof( int ) ); continue; } if ( !SocketWouldBlock() ) { Warning( "Lost RCON connection, please retry command.\n"); CloseSocket(); } break; } int nSizeRemaining = m_SendBuffer.TellMaxPut() - m_SendBuffer.TellGet(); if ( nSizeRemaining <= sizeof(int) ) { m_SendBuffer.Purge(); return; } // In this case, we've still got queued messages to send // Keep the portion of the buffer we didn't process for next time CUtlBuffer tmpBuf; tmpBuf.Put( m_SendBuffer.PeekGet(), nSizeRemaining ); m_SendBuffer.Purge(); m_SendBuffer.Put( tmpBuf.Base(), tmpBuf.TellPut() ); } //----------------------------------------------------------------------------- // Purpose: parse received data //----------------------------------------------------------------------------- void CRConClient::ParseReceivedData() { m_RecvBuffer.SeekGet( CUtlBuffer::SEEK_HEAD, 0 ); int size = m_RecvBuffer.GetInt(); while ( size && size <= m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet() ) { //DevMsg( "RCON: got packet %i long\n", size ); int reqID = m_RecvBuffer.GetInt(); int cmdID = m_RecvBuffer.GetInt(); // ignore the cmd id // DevMsg( "RCON Cmd: <-- %i %i %i\n", reqID, cmdID, readLen ); switch( cmdID ) { case SERVERDATA_AUTH_RESPONSE: { if ( reqID == -1 ) // bad password { Msg( "Bad RCON password\n" ); m_bAuthenticated = false; } else { Assert( reqID == m_iAuthRequestID ); m_bAuthenticated = true; } char dummy[2]; m_RecvBuffer.GetString( dummy ); m_RecvBuffer.GetString( dummy ); } break; case SERVERDATA_SCREENSHOT_RESPONSE: { int nDataSize = m_RecvBuffer.GetInt(); SaveRemoteScreenshot( m_RecvBuffer.PeekGet(), nDataSize ); m_RecvBuffer.SeekGet( CUtlBuffer::SEEK_CURRENT, nDataSize ); } break; case SERVERDATA_CONSOLE_LOG_RESPONSE: { int nDataSize = m_RecvBuffer.GetInt(); SaveRemoteConsoleLog( m_RecvBuffer.PeekGet(), nDataSize ); m_RecvBuffer.SeekGet( CUtlBuffer::SEEK_CURRENT, nDataSize ); } break; case SERVERDATA_VPROF_DATA: { int nDataSize = m_RecvBuffer.GetInt(); m_VProfExport.OnRemoteData( m_RecvBuffer.PeekGet(), nDataSize ); m_RecvBuffer.SeekGet( CUtlBuffer::SEEK_CURRENT, nDataSize ); } break; case SERVERDATA_VPROF_GROUPS: { int nDataSize = m_RecvBuffer.GetInt(); m_VProfExport.OnRemoteGroupData( m_RecvBuffer.PeekGet(), nDataSize ); m_RecvBuffer.SeekGet( CUtlBuffer::SEEK_CURRENT, nDataSize ); } break; case SERVERDATA_RESPONSE_STRING: { char pBuf[2048]; m_RecvBuffer.GetString( pBuf ); Msg( "%s", pBuf ); } break; default: { // Displays a message from the server int strLen = m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet(); CUtlMemory<char> msg; msg.EnsureCapacity( strLen + 1 ); m_RecvBuffer.GetStringManualCharCount( msg.Base(), msg.Count() ); msg[ msg.Count() - 1 ] = '\0'; Msg( "%s", (const char *)msg.Base() ); m_RecvBuffer.GetStringManualCharCount( msg.Base(), msg.Count() ); // ignore the second string } break; } if ( m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet() >= sizeof(int) ) { size = m_RecvBuffer.GetInt(); // read how much is in this packet } else { size = 0; // finished the packet } } if ( size || (m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet() > 0) ) { // In this case, we've got a partial message; we didn't get it all. // Keep the portion of the buffer we didn't process for next time CUtlBuffer tmpBuf; if ( m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet() > 0 ) { tmpBuf.Put( m_RecvBuffer.PeekGet(), m_RecvBuffer.TellPut() - m_RecvBuffer.TellGet() ); } m_RecvBuffer.Purge(); if ( size > 0 ) { m_RecvBuffer.PutInt( size ); } if ( tmpBuf.TellPut() > 0 ) { m_RecvBuffer.Put( tmpBuf.Base(), tmpBuf.TellPut() ); } } else { m_RecvBuffer.Purge(); } } //----------------------------------------------------------------------------- // Purpose: check for any server responses //----------------------------------------------------------------------------- void CRConClient::RunFrame() { m_Socket.RunFrame(); if ( !IsConnected() ) return; SendQueuedData(); SocketHandle_t hSocket = GetSocketHandle(); char ch; int pendingLen = recv( hSocket, &ch, sizeof(ch), MSG_PEEK ); if ( pendingLen == -1 && SocketWouldBlock() ) return; if ( pendingLen == 0 ) // socket got closed { CloseSocket(); return; } if ( pendingLen < 0 ) { CloseSocket(); Warning( "Lost RCON connection, please retry command (%s)\n", NET_ErrorString( WSAGetLastError() ) ); return; } // find out how much we have to read unsigned long readLen = 0; ioctlsocket( hSocket, FIONREAD, &readLen ); if ( readLen <= sizeof(int) ) return; // we have a command to process // Read data into a utlbuffer m_RecvBuffer.EnsureCapacity( m_RecvBuffer.TellPut() + readLen + 1 ); char *recvbuffer = (char *)_alloca( min( 1024ul, readLen + 1 ) ); unsigned int len = 0; while ( len < readLen ) { int recvLen = recv( hSocket, recvbuffer , min( 1024ul, readLen - len ) , 0 ); if ( recvLen == 0 ) // socket was closed { CloseSocket(); break; } if ( recvLen < 0 && !SocketWouldBlock() ) { Warning( "RCON Cmd: recv error (%s)\n", NET_ErrorString( WSAGetLastError() ) ); break; } m_RecvBuffer.Put( recvbuffer, recvLen ); len += recvLen; } ParseReceivedData(); } //----------------------------------------------------------------------------- // Purpose: send a response to the server //----------------------------------------------------------------------------- void CRConClient::SendResponse( CUtlBuffer &response, bool bAutoAuthenticate ) { if ( bAutoAuthenticate && !IsAuthenticated() ) { Authenticate(); if ( IsConnected() ) { m_SendBuffer.Put( response.Base(), response.TellMaxPut() ); } return; } int ret = send( GetSocketHandle(), (const char *)response.Base(), response.TellMaxPut(), 0 ); if ( ret == -1 ) { if ( SocketWouldBlock() ) { m_SendBuffer.Put( response.Base(), response.TellMaxPut() ); } else { Warning( "Lost RCON connection, please retry command\n" ); CloseSocket(); } } } //----------------------------------------------------------------------------- // Purpose: builds a simple command to send to the server //----------------------------------------------------------------------------- void CRConClient::BuildResponse( CUtlBuffer &response, ServerDataRequestType_t msg, const char *pString1, const char *pString2 ) { // build the response response.PutInt(0); // the size, filled in below response.PutInt(m_iReqID++); response.PutInt(msg); response.PutString(pString1); response.PutString(pString2); int nSize = response.TellPut() - sizeof(int); response.SeekPut( CUtlBuffer::SEEK_HEAD, 0 ); response.PutInt( nSize ); // the size response.SeekPut( CUtlBuffer::SEEK_CURRENT, nSize ); } //----------------------------------------------------------------------------- // Purpose: authenticate ourselves //----------------------------------------------------------------------------- void CRConClient::Authenticate() { CUtlBuffer response; // build the response response.PutInt(0); // the size, filled in below response.PutInt(++m_iAuthRequestID); response.PutInt(SERVERDATA_AUTH); response.PutString( m_Password.Get() ); // Use the otherwise-empty second string for the userid. The server will use this to // exec "mp_disable_autokick <userid>" upon successful authentication. bool addedUserID = false; if ( cl.IsConnected() ) { if ( cl.m_nPlayerSlot < cl.m_nMaxClients && cl.m_nPlayerSlot >= 0 ) { Assert( cl.m_pUserInfoTable ); if ( cl.m_pUserInfoTable ) { player_info_t *pi = (player_info_t*) cl.m_pUserInfoTable->GetStringUserData( cl.m_nPlayerSlot, NULL ); if ( pi ) { addedUserID = true; // Fixup from network order (little endian) response.PutString( va( "%d", LittleLong( pi->userID ) ) ); } } } } if ( !addedUserID ) { response.PutString( "" ); } int size = response.TellPut() - sizeof(int); response.SeekPut( CUtlBuffer::SEEK_HEAD, 0 ); response.PutInt(size); // the size response.SeekPut( CUtlBuffer::SEEK_CURRENT, size ); SendResponse( response, false ); } //----------------------------------------------------------------------------- // Purpose: send an rcon command to a connected server //----------------------------------------------------------------------------- void CRConClient::SendCmd( const char *msg ) { if ( !IsConnected() ) { if ( !ConnectSocket() ) return; } CUtlBuffer response; BuildResponse( response, SERVERDATA_EXECCOMMAND, msg, "" ); SendResponse( response ); } //----------------------------------------------------------------------------- // Purpose: Start vprofiling //----------------------------------------------------------------------------- void CRConClient::StartVProfData() { if ( !IsConnected() ) { if ( !ConnectSocket() ) return; } // Override the vprof export to point to our local profiling data OverrideVProfExport( &m_VProfExport ); CUtlBuffer response; BuildResponse( response, SERVERDATA_VPROF, "", "" ); SendResponse( response ); } //----------------------------------------------------------------------------- // Purpose: Stop vprofiling //----------------------------------------------------------------------------- void CRConClient::StopVProfData() { // Reset the vprof export to point to the normal profiling data ResetVProfExport( &m_VProfExport ); // Don't bother restarting a connection to turn this off if ( !IsConnected() ) return; CUtlBuffer response; BuildResponse( response, SERVERDATA_REMOVE_VPROF, "", "" ); SendResponse( response ); } //----------------------------------------------------------------------------- // Purpose: get data from the server //----------------------------------------------------------------------------- void CRConClient::TakeScreenshot() { if ( !IsConnected() ) { if ( !ConnectSocket() ) return; } CUtlBuffer response; BuildResponse( response, SERVERDATA_TAKE_SCREENSHOT, "", "" ); SendResponse( response ); } void CRConClient::GrabConsoleLog() { if ( !IsConnected() ) { if ( !ConnectSocket() ) return; } CUtlBuffer response; BuildResponse( response, SERVERDATA_SEND_CONSOLE_LOG, "", "" ); SendResponse( response ); } //----------------------------------------------------------------------------- // We've got data from the server, save it //----------------------------------------------------------------------------- void CRConClient::SaveRemoteScreenshot( const void* pBuffer, int nBufLen ) { char pScreenshotPath[MAX_PATH]; do { Q_snprintf( pScreenshotPath, sizeof( pScreenshotPath ), "%s/screenshot%04d.jpg", m_RemoteFileDir.Get(), m_nScreenShotIndex++ ); } while ( g_pFullFileSystem->FileExists( pScreenshotPath, "MOD" ) ); char pFullPath[MAX_PATH]; GetModSubdirectory( pScreenshotPath, pFullPath, sizeof(pFullPath) ); HZIP hZip = OpenZip( (void*)pBuffer, nBufLen, ZIP_MEMORY ); int nIndex; ZIPENTRY zipInfo; FindZipItem( hZip, "screenshot.jpg", true, &nIndex, &zipInfo ); if ( nIndex >= 0 ) { UnzipItem( hZip, nIndex, pFullPath, 0, ZIP_FILENAME ); } CloseZip( hZip ); } void CRConClient::SaveRemoteConsoleLog( const void* pBuffer, int nBufLen ) { if ( nBufLen == 0 ) return; char pLogPath[MAX_PATH]; do { Q_snprintf( pLogPath, sizeof( pLogPath ), "%s/console%04d.log", m_RemoteFileDir.Get(), m_nConsoleLogIndex++ ); } while ( g_pFullFileSystem->FileExists( pLogPath, "MOD" ) ); char pFullPath[MAX_PATH]; GetModSubdirectory( pLogPath, pFullPath, sizeof(pFullPath) ); HZIP hZip = OpenZip( (void*)pBuffer, nBufLen, ZIP_MEMORY ); int nIndex; ZIPENTRY zipInfo; FindZipItem( hZip, "console.log", true, &nIndex, &zipInfo ); if ( nIndex >= 0 ) { UnzipItem( hZip, nIndex, pFullPath, 0, ZIP_FILENAME ); } CloseZip( hZip ); }
// Copyright (c) 2014-2018 The Proton Core developers // Copyright (c) 2018 The bwrgo Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "addrman.h" #include "darksend.h" #include "governance.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "netfulfilledman.h" #include "util.h" /** Masternode manager */ CMasternodeMan mnodeman; const std::string CMasternodeMan::SERIALIZATION_VERSION_STRING = "CMasternodeMan-Version-4"; struct CompareLastPaidBlock { bool operator()(const std::pair<int, CMasternode*>& t1, const std::pair<int, CMasternode*>& t2) const { return (t1.first != t2.first) ? (t1.first < t2.first) : (t1.second->vin < t2.second->vin); } }; struct CompareScoreMN { bool operator()(const std::pair<int64_t, CMasternode*>& t1, const std::pair<int64_t, CMasternode*>& t2) const { return (t1.first != t2.first) ? (t1.first < t2.first) : (t1.second->vin < t2.second->vin); } }; CMasternodeIndex::CMasternodeIndex() : nSize(0), mapIndex(), mapReverseIndex() {} bool CMasternodeIndex::Get(int nIndex, CTxIn& vinMasternode) const { rindex_m_cit it = mapReverseIndex.find(nIndex); if(it == mapReverseIndex.end()) { return false; } vinMasternode = it->second; return true; } int CMasternodeIndex::GetMasternodeIndex(const CTxIn& vinMasternode) const { index_m_cit it = mapIndex.find(vinMasternode); if(it == mapIndex.end()) { return -1; } return it->second; } void CMasternodeIndex::AddMasternodeVIN(const CTxIn& vinMasternode) { index_m_it it = mapIndex.find(vinMasternode); if(it != mapIndex.end()) { return; } int nNextIndex = nSize; mapIndex[vinMasternode] = nNextIndex; mapReverseIndex[nNextIndex] = vinMasternode; ++nSize; } void CMasternodeIndex::Clear() { mapIndex.clear(); mapReverseIndex.clear(); nSize = 0; } struct CompareByAddr { bool operator()(const CMasternode* t1, const CMasternode* t2) const { return t1->addr < t2->addr; } }; void CMasternodeIndex::RebuildIndex() { nSize = mapIndex.size(); for(index_m_it it = mapIndex.begin(); it != mapIndex.end(); ++it) { mapReverseIndex[it->second] = it->first; } } CMasternodeMan::CMasternodeMan() : cs(), vMasternodes(), mAskedUsForMasternodeList(), mWeAskedForMasternodeList(), mWeAskedForMasternodeListEntry(), mWeAskedForVerification(), mMnbRecoveryRequests(), mMnbRecoveryGoodReplies(), listScheduledMnbRequestConnections(), nLastIndexRebuildTime(0), indexMasternodes(), indexMasternodesOld(), fIndexRebuilt(false), fMasternodesAdded(false), fMasternodesRemoved(false), vecDirtyGovernanceObjectHashes(), nLastWatchdogVoteTime(0), mapSeenMasternodeBroadcast(), mapSeenMasternodePing(), nDsqCount(0) {} bool CMasternodeMan::Add(CMasternode &mn) { LOCK(cs); CMasternode *pmn = Find(mn.vin); if (pmn == NULL) { LogPrint("masternode", "CMasternodeMan::Add -- Adding new Masternode: addr=%s, %i now\n", mn.addr.ToString(), size() + 1); vMasternodes.push_back(mn); indexMasternodes.AddMasternodeVIN(mn.vin); fMasternodesAdded = true; return true; } return false; } void CMasternodeMan::AskForMN(CNode* pnode, const CTxIn &vin) { if(!pnode) return; LOCK(cs); std::map<COutPoint, std::map<CNetAddr, int64_t> >::iterator it1 = mWeAskedForMasternodeListEntry.find(vin.prevout); if (it1 != mWeAskedForMasternodeListEntry.end()) { std::map<CNetAddr, int64_t>::iterator it2 = it1->second.find(pnode->addr); if (it2 != it1->second.end()) { if (GetTime() < it2->second) { // we've asked recently, should not repeat too often or we could get banned return; } // we asked this node for this outpoint but it's ok to ask again already LogPrintf("CMasternodeMan::AskForMN -- Asking same peer %s for missing masternode entry again: %s\n", pnode->addr.ToString(), vin.prevout.ToStringShort()); } else { // we already asked for this outpoint but not this node LogPrintf("CMasternodeMan::AskForMN -- Asking new peer %s for missing masternode entry: %s\n", pnode->addr.ToString(), vin.prevout.ToStringShort()); } } else { // we never asked any node for this outpoint LogPrintf("CMasternodeMan::AskForMN -- Asking peer %s for missing masternode entry for the first time: %s\n", pnode->addr.ToString(), vin.prevout.ToStringShort()); } mWeAskedForMasternodeListEntry[vin.prevout][pnode->addr] = GetTime() + DSEG_UPDATE_SECONDS; pnode->PushMessage(NetMsgType::DSEG, vin); } void CMasternodeMan::Check() { LOCK(cs); LogPrint("masternode", "CMasternodeMan::Check -- nLastWatchdogVoteTime=%d, IsWatchdogActive()=%d\n", nLastWatchdogVoteTime, IsWatchdogActive()); BOOST_FOREACH(CMasternode& mn, vMasternodes) { mn.Check(); } } void CMasternodeMan::CheckAndRemove() { if(!masternodeSync.IsMasternodeListSynced()) return; LogPrintf("CMasternodeMan::CheckAndRemove\n"); { // Need LOCK2 here to ensure consistent locking order because code below locks cs_main // in CheckMnbAndUpdateMasternodeList() LOCK2(cs_main, cs); Check(); // Remove spent masternodes, prepare structures and make requests to reasure the state of inactive ones std::vector<CMasternode>::iterator it = vMasternodes.begin(); std::vector<std::pair<int, CMasternode> > vecMasternodeRanks; // ask for up to MNB_RECOVERY_MAX_ASK_ENTRIES masternode entries at a time int nAskForMnbRecovery = MNB_RECOVERY_MAX_ASK_ENTRIES; while(it != vMasternodes.end()) { CMasternodeBroadcast mnb = CMasternodeBroadcast(*it); uint256 hash = mnb.GetHash(); // If collateral was spent ... if ((*it).IsOutpointSpent()) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Removing Masternode: %s addr=%s %i now\n", (*it).GetStateString(), (*it).addr.ToString(), size() - 1); // erase all of the broadcasts we've seen from this txin, ... mapSeenMasternodeBroadcast.erase(hash); mWeAskedForMasternodeListEntry.erase((*it).vin.prevout); // and finally remove it from the list it->FlagGovernanceItemsAsDirty(); it = vMasternodes.erase(it); fMasternodesRemoved = true; } else { bool fAsk = pCurrentBlockIndex && (nAskForMnbRecovery > 0) && masternodeSync.IsSynced() && it->IsNewStartRequired() && !IsMnbRecoveryRequested(hash); if(fAsk) { // this mn is in a non-recoverable state and we haven't asked other nodes yet std::set<CNetAddr> setRequested; // calulate only once and only when it's needed if(vecMasternodeRanks.empty()) { int nRandomBlockHeight = GetRandInt(pCurrentBlockIndex->nHeight); vecMasternodeRanks = GetMasternodeRanks(nRandomBlockHeight); } bool fAskedForMnbRecovery = false; // ask first MNB_RECOVERY_QUORUM_TOTAL masternodes we can connect to and we haven't asked recently for(int i = 0; setRequested.size() < MNB_RECOVERY_QUORUM_TOTAL && i < (int)vecMasternodeRanks.size(); i++) { // avoid banning if(mWeAskedForMasternodeListEntry.count(it->vin.prevout) && mWeAskedForMasternodeListEntry[it->vin.prevout].count(vecMasternodeRanks[i].second.addr)) continue; // didn't ask recently, ok to ask now CService addr = vecMasternodeRanks[i].second.addr; setRequested.insert(addr); listScheduledMnbRequestConnections.push_back(std::make_pair(addr, hash)); fAskedForMnbRecovery = true; } if(fAskedForMnbRecovery) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Recovery initiated, masternode=%s\n", it->vin.prevout.ToStringShort()); nAskForMnbRecovery--; } // wait for mnb recovery replies for MNB_RECOVERY_WAIT_SECONDS seconds mMnbRecoveryRequests[hash] = std::make_pair(GetTime() + MNB_RECOVERY_WAIT_SECONDS, setRequested); } ++it; } } // proces replies for MASTERNODE_NEW_START_REQUIRED masternodes LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- mMnbRecoveryGoodReplies size=%d\n", (int)mMnbRecoveryGoodReplies.size()); std::map<uint256, std::vector<CMasternodeBroadcast> >::iterator itMnbReplies = mMnbRecoveryGoodReplies.begin(); while(itMnbReplies != mMnbRecoveryGoodReplies.end()){ if(mMnbRecoveryRequests[itMnbReplies->first].first < GetTime()) { // all nodes we asked should have replied now if(itMnbReplies->second.size() >= MNB_RECOVERY_QUORUM_REQUIRED) { // majority of nodes we asked agrees that this mn doesn't require new mnb, reprocess one of new mnbs LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- reprocessing mnb, masternode=%s\n", itMnbReplies->second[0].vin.prevout.ToStringShort()); // mapSeenMasternodeBroadcast.erase(itMnbReplies->first); int nDos; itMnbReplies->second[0].fRecovery = true; CheckMnbAndUpdateMasternodeList(NULL, itMnbReplies->second[0], nDos); } LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- removing mnb recovery reply, masternode=%s, size=%d\n", itMnbReplies->second[0].vin.prevout.ToStringShort(), (int)itMnbReplies->second.size()); mMnbRecoveryGoodReplies.erase(itMnbReplies++); } else { ++itMnbReplies; } } } { // no need for cm_main below LOCK(cs); std::map<uint256, std::pair< int64_t, std::set<CNetAddr> > >::iterator itMnbRequest = mMnbRecoveryRequests.begin(); while(itMnbRequest != mMnbRecoveryRequests.end()){ // Allow this mnb to be re-verified again after MNB_RECOVERY_RETRY_SECONDS seconds // if mn is still in MASTERNODE_NEW_START_REQUIRED state. if(GetTime() - itMnbRequest->second.first > MNB_RECOVERY_RETRY_SECONDS) { mMnbRecoveryRequests.erase(itMnbRequest++); } else { ++itMnbRequest; } } // check who's asked for the Masternode list std::map<CNetAddr, int64_t>::iterator it1 = mAskedUsForMasternodeList.begin(); while(it1 != mAskedUsForMasternodeList.end()){ if((*it1).second < GetTime()) { mAskedUsForMasternodeList.erase(it1++); } else { ++it1; } } // check who we asked for the Masternode list it1 = mWeAskedForMasternodeList.begin(); while(it1 != mWeAskedForMasternodeList.end()){ if((*it1).second < GetTime()){ mWeAskedForMasternodeList.erase(it1++); } else { ++it1; } } // check which Masternodes we've asked for std::map<COutPoint, std::map<CNetAddr, int64_t> >::iterator it2 = mWeAskedForMasternodeListEntry.begin(); while(it2 != mWeAskedForMasternodeListEntry.end()){ std::map<CNetAddr, int64_t>::iterator it3 = it2->second.begin(); while(it3 != it2->second.end()){ if(it3->second < GetTime()){ it2->second.erase(it3++); } else { ++it3; } } if(it2->second.empty()) { mWeAskedForMasternodeListEntry.erase(it2++); } else { ++it2; } } std::map<CNetAddr, CMasternodeVerification>::iterator it3 = mWeAskedForVerification.begin(); while(it3 != mWeAskedForVerification.end()){ if(it3->second.nBlockHeight < pCurrentBlockIndex->nHeight - MAX_POSE_BLOCKS) { mWeAskedForVerification.erase(it3++); } else { ++it3; } } // NOTE: do not expire mapSeenMasternodeBroadcast entries here, clean them on mnb updates! // remove expired mapSeenMasternodePing std::map<uint256, CMasternodePing>::iterator it4 = mapSeenMasternodePing.begin(); while(it4 != mapSeenMasternodePing.end()){ if((*it4).second.IsExpired()) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Removing expired Masternode ping: hash=%s\n", (*it4).second.GetHash().ToString()); mapSeenMasternodePing.erase(it4++); } else { ++it4; } } // remove expired mapSeenMasternodeVerification std::map<uint256, CMasternodeVerification>::iterator itv2 = mapSeenMasternodeVerification.begin(); while(itv2 != mapSeenMasternodeVerification.end()){ if((*itv2).second.nBlockHeight < pCurrentBlockIndex->nHeight - MAX_POSE_BLOCKS){ LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Removing expired Masternode verification: hash=%s\n", (*itv2).first.ToString()); mapSeenMasternodeVerification.erase(itv2++); } else { ++itv2; } } LogPrintf("CMasternodeMan::CheckAndRemove -- %s\n", ToString()); if(fMasternodesRemoved) { CheckAndRebuildMasternodeIndex(); } } if(fMasternodesRemoved) { NotifyMasternodeUpdates(); } } void CMasternodeMan::Clear() { LOCK(cs); vMasternodes.clear(); mAskedUsForMasternodeList.clear(); mWeAskedForMasternodeList.clear(); mWeAskedForMasternodeListEntry.clear(); mapSeenMasternodeBroadcast.clear(); mapSeenMasternodePing.clear(); nDsqCount = 0; nLastWatchdogVoteTime = 0; indexMasternodes.Clear(); indexMasternodesOld.Clear(); } int CMasternodeMan::CountMasternodes(int nProtocolVersion) { LOCK(cs); int nCount = 0; nProtocolVersion = nProtocolVersion == -1 ? mnpayments.GetMinMasternodePaymentsProto() : nProtocolVersion; BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.nProtocolVersion < nProtocolVersion) continue; nCount++; } return nCount; } int CMasternodeMan::CountEnabled(int nProtocolVersion) { LOCK(cs); int nCount = 0; nProtocolVersion = nProtocolVersion == -1 ? mnpayments.GetMinMasternodePaymentsProto() : nProtocolVersion; BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.nProtocolVersion < nProtocolVersion || !mn.IsEnabled()) continue; nCount++; } return nCount; } /* Only IPv4 masternodes are allowed in 12.1, saving this for later int CMasternodeMan::CountByIP(int nNetworkType) { LOCK(cs); int nNodeCount = 0; BOOST_FOREACH(CMasternode& mn, vMasternodes) if ((nNetworkType == NET_IPV4 && mn.addr.IsIPv4()) || (nNetworkType == NET_TOR && mn.addr.IsTor()) || (nNetworkType == NET_IPV6 && mn.addr.IsIPv6())) { nNodeCount++; } return nNodeCount; } */ void CMasternodeMan::DsegUpdate(CNode* pnode) { LOCK(cs); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(!(pnode->addr.IsRFC1918() || pnode->addr.IsLocal())) { std::map<CNetAddr, int64_t>::iterator it = mWeAskedForMasternodeList.find(pnode->addr); if(it != mWeAskedForMasternodeList.end() && GetTime() < (*it).second) { LogPrintf("CMasternodeMan::DsegUpdate -- we already asked %s for the list; skipping...\n", pnode->addr.ToString()); return; } } } pnode->PushMessage(NetMsgType::DSEG, CTxIn()); int64_t askAgain = GetTime() + DSEG_UPDATE_SECONDS; mWeAskedForMasternodeList[pnode->addr] = askAgain; LogPrint("masternode", "CMasternodeMan::DsegUpdate -- asked %s for the list\n", pnode->addr.ToString()); } CMasternode* CMasternodeMan::Find(const CScript &payee) { LOCK(cs); BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()) == payee) return &mn; } return NULL; } CMasternode* CMasternodeMan::Find(const CTxIn &vin) { LOCK(cs); BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.vin.prevout == vin.prevout) return &mn; } return NULL; } CMasternode* CMasternodeMan::Find(const CPubKey &pubKeyMasternode) { LOCK(cs); BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.pubKeyMasternode == pubKeyMasternode) return &mn; } return NULL; } bool CMasternodeMan::Get(const CPubKey& pubKeyMasternode, CMasternode& masternode) { // Theses mutexes are recursive so double locking by the same thread is safe. LOCK(cs); CMasternode* pMN = Find(pubKeyMasternode); if(!pMN) { return false; } masternode = *pMN; return true; } bool CMasternodeMan::Get(const CTxIn& vin, CMasternode& masternode) { // Theses mutexes are recursive so double locking by the same thread is safe. LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return false; } masternode = *pMN; return true; } masternode_info_t CMasternodeMan::GetMasternodeInfo(const CTxIn& vin) { masternode_info_t info; LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return info; } info = pMN->GetInfo(); return info; } masternode_info_t CMasternodeMan::GetMasternodeInfo(const CPubKey& pubKeyMasternode) { masternode_info_t info; LOCK(cs); CMasternode* pMN = Find(pubKeyMasternode); if(!pMN) { return info; } info = pMN->GetInfo(); return info; } bool CMasternodeMan::Has(const CTxIn& vin) { LOCK(cs); CMasternode* pMN = Find(vin); return (pMN != NULL); } // // Deterministically select the oldest/best masternode to pay on the network // CMasternode* CMasternodeMan::GetNextMasternodeInQueueForPayment(bool fFilterSigTime, int& nCount) { if(!pCurrentBlockIndex) { nCount = 0; return NULL; } return GetNextMasternodeInQueueForPayment(pCurrentBlockIndex->nHeight, fFilterSigTime, nCount); } CMasternode* CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool fFilterSigTime, int& nCount) { // Need LOCK2 here to ensure consistent locking order because the GetBlockHash call below locks cs_main LOCK2(cs_main,cs); CMasternode *pBestMasternode = NULL; std::vector<std::pair<int, CMasternode*> > vecMasternodeLastPaid; /* Make a vector with all of the last paid times */ int nMnCount = CountEnabled(); BOOST_FOREACH(CMasternode &mn, vMasternodes) { if(!mn.IsValidForPayment()) continue; // //check protocol version if(mn.nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; //it's in the list (up to 8 entries ahead of current block to allow propagation) -- so let's skip it if(mnpayments.IsScheduled(mn, nBlockHeight)) continue; //it's too new, wait for a cycle if(fFilterSigTime && mn.sigTime + (nMnCount*2.6*60) > GetAdjustedTime()) continue; //make sure it has at least as many confirmations as there are masternodes if(mn.GetCollateralAge() < nMnCount) continue; vecMasternodeLastPaid.push_back(std::make_pair(mn.GetLastPaidBlock(), &mn)); } nCount = (int)vecMasternodeLastPaid.size(); //when the network is in the process of upgrading, don't penalize nodes that recently restarted if(fFilterSigTime && nCount < nMnCount/3) return GetNextMasternodeInQueueForPayment(nBlockHeight, false, nCount); // Sort them low to high sort(vecMasternodeLastPaid.begin(), vecMasternodeLastPaid.end(), CompareLastPaidBlock()); uint256 blockHash; if(!GetBlockHash(blockHash, nBlockHeight - 101)) { LogPrintf("CMasternode::GetNextMasternodeInQueueForPayment -- ERROR: GetBlockHash() failed at nBlockHeight %d\n", nBlockHeight - 101); return NULL; } // Look at 1/10 of the oldest nodes (by last payment), calculate their scores and pay the best one // -- This doesn't look at who is being paid in the +8-10 blocks, allowing for double payments very rarely // -- 1/100 payments should be a double payment on mainnet - (1/(3000/10))*2 // -- (chance per block * chances before IsScheduled will fire) int nTenthNetwork = nMnCount/10; int nCountTenth = 0; arith_uint256 nHighest = 0; BOOST_FOREACH (PAIRTYPE(int, CMasternode*)& s, vecMasternodeLastPaid){ arith_uint256 nScore = s.second->CalculateScore(blockHash); if(nScore > nHighest){ nHighest = nScore; pBestMasternode = s.second; } nCountTenth++; if(nCountTenth >= nTenthNetwork) break; } return pBestMasternode; } CMasternode* CMasternodeMan::FindRandomNotInVec(const std::vector<CTxIn> &vecToExclude, int nProtocolVersion) { LOCK(cs); nProtocolVersion = nProtocolVersion == -1 ? mnpayments.GetMinMasternodePaymentsProto() : nProtocolVersion; int nCountEnabled = CountEnabled(nProtocolVersion); int nCountNotExcluded = nCountEnabled - vecToExclude.size(); LogPrintf("CMasternodeMan::FindRandomNotInVec -- %d enabled masternodes, %d masternodes to choose from\n", nCountEnabled, nCountNotExcluded); if(nCountNotExcluded < 1) return NULL; // fill a vector of pointers std::vector<CMasternode*> vpMasternodesShuffled; BOOST_FOREACH(CMasternode &mn, vMasternodes) { vpMasternodesShuffled.push_back(&mn); } InsecureRand insecureRand; // shuffle pointers std::random_shuffle(vpMasternodesShuffled.begin(), vpMasternodesShuffled.end(), insecureRand); bool fExclude; // loop through BOOST_FOREACH(CMasternode* pmn, vpMasternodesShuffled) { if(pmn->nProtocolVersion < nProtocolVersion || !pmn->IsEnabled()) continue; fExclude = false; BOOST_FOREACH(const CTxIn &txinToExclude, vecToExclude) { if(pmn->vin.prevout == txinToExclude.prevout) { fExclude = true; break; } } if(fExclude) continue; // found the one not in vecToExclude LogPrint("masternode", "CMasternodeMan::FindRandomNotInVec -- found, masternode=%s\n", pmn->vin.prevout.ToStringShort()); return pmn; } LogPrint("masternode", "CMasternodeMan::FindRandomNotInVec -- failed\n"); return NULL; } int CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int nBlockHeight, int nMinProtocol, bool fOnlyActive) { std::vector<std::pair<int64_t, CMasternode*> > vecMasternodeScores; //make sure we know about this block uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, nBlockHeight)) return -1; LOCK(cs); // scan for winner BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.nProtocolVersion < nMinProtocol) continue; if(fOnlyActive) { if(!mn.IsEnabled()) continue; } else { if(!mn.IsValidForPayment()) continue; } int64_t nScore = mn.CalculateScore(blockHash).GetCompact(false); vecMasternodeScores.push_back(std::make_pair(nScore, &mn)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreMN()); int nRank = 0; BOOST_FOREACH (PAIRTYPE(int64_t, CMasternode*)& scorePair, vecMasternodeScores) { nRank++; if(scorePair.second->vin.prevout == vin.prevout) return nRank; } return -1; } std::vector<std::pair<int, CMasternode> > CMasternodeMan::GetMasternodeRanks(int nBlockHeight, int nMinProtocol) { std::vector<std::pair<int64_t, CMasternode*> > vecMasternodeScores; std::vector<std::pair<int, CMasternode> > vecMasternodeRanks; //make sure we know about this block uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, nBlockHeight)) return vecMasternodeRanks; LOCK(cs); // scan for winner BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.nProtocolVersion < nMinProtocol || !mn.IsEnabled()) continue; int64_t nScore = mn.CalculateScore(blockHash).GetCompact(false); vecMasternodeScores.push_back(std::make_pair(nScore, &mn)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreMN()); int nRank = 0; BOOST_FOREACH (PAIRTYPE(int64_t, CMasternode*)& s, vecMasternodeScores) { nRank++; vecMasternodeRanks.push_back(std::make_pair(nRank, *s.second)); } return vecMasternodeRanks; } CMasternode* CMasternodeMan::GetMasternodeByRank(int nRank, int nBlockHeight, int nMinProtocol, bool fOnlyActive) { std::vector<std::pair<int64_t, CMasternode*> > vecMasternodeScores; LOCK(cs); uint256 blockHash; if(!GetBlockHash(blockHash, nBlockHeight)) { LogPrintf("CMasternode::GetMasternodeByRank -- ERROR: GetBlockHash() failed at nBlockHeight %d\n", nBlockHeight); return NULL; } // Fill scores BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.nProtocolVersion < nMinProtocol) continue; if(fOnlyActive && !mn.IsEnabled()) continue; int64_t nScore = mn.CalculateScore(blockHash).GetCompact(false); vecMasternodeScores.push_back(std::make_pair(nScore, &mn)); } sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareScoreMN()); int rank = 0; BOOST_FOREACH (PAIRTYPE(int64_t, CMasternode*)& s, vecMasternodeScores){ rank++; if(rank == nRank) { return s.second; } } return NULL; } void CMasternodeMan::ProcessMasternodeConnections() { //we don't care about this for regtest if(Params().NetworkIDString() == CBaseChainParams::REGTEST) return; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(pnode->fMasternode) { if(darkSendPool.pSubmittedToMasternode != NULL && pnode->addr == darkSendPool.pSubmittedToMasternode->addr) continue; LogPrintf("Closing Masternode connection: peer=%d, addr=%s\n", pnode->id, pnode->addr.ToString()); pnode->fDisconnect = true; } } } std::pair<CService, std::set<uint256> > CMasternodeMan::PopScheduledMnbRequestConnection() { LOCK(cs); if(listScheduledMnbRequestConnections.empty()) { return std::make_pair(CService(), std::set<uint256>()); } std::set<uint256> setResult; listScheduledMnbRequestConnections.sort(); std::pair<CService, uint256> pairFront = listScheduledMnbRequestConnections.front(); // squash hashes from requests with the same CService as the first one into setResult std::list< std::pair<CService, uint256> >::iterator it = listScheduledMnbRequestConnections.begin(); while(it != listScheduledMnbRequestConnections.end()) { if(pairFront.first == it->first) { setResult.insert(it->second); it = listScheduledMnbRequestConnections.erase(it); } else { // since list is sorted now, we can be sure that there is no more hashes left // to ask for from this addr break; } } return std::make_pair(pairFront.first, setResult); } void CMasternodeMan::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if(fLiteMode) return; // disable all bwrgo specific functionality if(!masternodeSync.IsBlockchainSynced()) return; if (strCommand == NetMsgType::MNANNOUNCE) { //Masternode Broadcast CMasternodeBroadcast mnb; vRecv >> mnb; pfrom->setAskFor.erase(mnb.GetHash()); LogPrint("masternode", "MNANNOUNCE -- Masternode announce, masternode=%s\n", mnb.vin.prevout.ToStringShort()); int nDos = 0; if (CheckMnbAndUpdateMasternodeList(pfrom, mnb, nDos)) { // use announced Masternode as a peer addrman.Add(CAddress(mnb.addr), pfrom->addr, 2*60*60); } else if(nDos > 0) { Misbehaving(pfrom->GetId(), nDos); } if(fMasternodesAdded) { NotifyMasternodeUpdates(); } } else if (strCommand == NetMsgType::MNPING) { //Masternode Ping CMasternodePing mnp; vRecv >> mnp; uint256 nHash = mnp.GetHash(); pfrom->setAskFor.erase(nHash); LogPrint("masternode", "MNPING -- Masternode ping, masternode=%s\n", mnp.vin.prevout.ToStringShort()); // Need LOCK2 here to ensure consistent locking order because the CheckAndUpdate call below locks cs_main LOCK2(cs_main, cs); if(mapSeenMasternodePing.count(nHash)) return; //seen mapSeenMasternodePing.insert(std::make_pair(nHash, mnp)); LogPrint("masternode", "MNPING -- Masternode ping, masternode=%s new\n", mnp.vin.prevout.ToStringShort()); // see if we have this Masternode CMasternode* pmn = mnodeman.Find(mnp.vin); // too late, new MNANNOUNCE is required if(pmn && pmn->IsNewStartRequired()) return; int nDos = 0; if(mnp.CheckAndUpdate(pmn, false, nDos)) return; if(nDos > 0) { // if anything significant failed, mark that node Misbehaving(pfrom->GetId(), nDos); } else if(pmn != NULL) { // nothing significant failed, mn is a known one too return; } // something significant is broken or mn is unknown, // we might have to ask for a masternode entry once AskForMN(pfrom, mnp.vin); } else if (strCommand == NetMsgType::DSEG) { //Get Masternode list or specific entry // Ignore such requests until we are fully synced. // We could start processing this after masternode list is synced // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; CTxIn vin; vRecv >> vin; LogPrint("masternode", "DSEG -- Masternode list, masternode=%s\n", vin.prevout.ToStringShort()); LOCK(cs); if(vin == CTxIn()) { //only should ask for this once //local network bool isLocal = (pfrom->addr.IsRFC1918() || pfrom->addr.IsLocal()); if(!isLocal && Params().NetworkIDString() == CBaseChainParams::MAIN) { std::map<CNetAddr, int64_t>::iterator i = mAskedUsForMasternodeList.find(pfrom->addr); if (i != mAskedUsForMasternodeList.end()){ int64_t t = (*i).second; if (GetTime() < t) { Misbehaving(pfrom->GetId(), 34); LogPrintf("DSEG -- peer already asked me for the list, peer=%d\n", pfrom->id); return; } } int64_t askAgain = GetTime() + DSEG_UPDATE_SECONDS; mAskedUsForMasternodeList[pfrom->addr] = askAgain; } } //else, asking for a specific node which is ok int nInvCount = 0; BOOST_FOREACH(CMasternode& mn, vMasternodes) { if (vin != CTxIn() && vin != mn.vin) continue; // asked for specific vin but we are not there yet if (mn.addr.IsRFC1918() || mn.addr.IsLocal()) continue; // do not send local network masternode if (mn.IsUpdateRequired()) continue; // do not send outdated masternodes LogPrint("masternode", "DSEG -- Sending Masternode entry: masternode=%s addr=%s\n", mn.vin.prevout.ToStringShort(), mn.addr.ToString()); CMasternodeBroadcast mnb = CMasternodeBroadcast(mn); uint256 hash = mnb.GetHash(); pfrom->PushInventory(CInv(MSG_MASTERNODE_ANNOUNCE, hash)); pfrom->PushInventory(CInv(MSG_MASTERNODE_PING, mn.lastPing.GetHash())); nInvCount++; if (!mapSeenMasternodeBroadcast.count(hash)) { mapSeenMasternodeBroadcast.insert(std::make_pair(hash, std::make_pair(GetTime(), mnb))); } if (vin == mn.vin) { LogPrintf("DSEG -- Sent 1 Masternode inv to peer %d\n", pfrom->id); return; } } if(vin == CTxIn()) { pfrom->PushMessage(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_LIST, nInvCount); LogPrintf("DSEG -- Sent %d Masternode invs to peer %d\n", nInvCount, pfrom->id); return; } // smth weird happen - someone asked us for vin we have no idea about? LogPrint("masternode", "DSEG -- No invs sent to peer %d\n", pfrom->id); } else if (strCommand == NetMsgType::MNVERIFY) { // Masternode Verify // Need LOCK2 here to ensure consistent locking order because the all functions below call GetBlockHash which locks cs_main LOCK2(cs_main, cs); CMasternodeVerification mnv; vRecv >> mnv; if(mnv.vchSig1.empty()) { // CASE 1: someone asked me to verify myself /IP we are using/ SendVerifyReply(pfrom, mnv); } else if (mnv.vchSig2.empty()) { // CASE 2: we _probably_ got verification we requested from some masternode ProcessVerifyReply(pfrom, mnv); } else { // CASE 3: we _probably_ got verification broadcast signed by some masternode which verified another one ProcessVerifyBroadcast(pfrom, mnv); } } } // Verification of masternodes via unique direct requests. void CMasternodeMan::DoFullVerificationStep() { if(activeMasternode.vin == CTxIn()) return; if(!masternodeSync.IsSynced()) return; std::vector<std::pair<int, CMasternode> > vecMasternodeRanks = GetMasternodeRanks(pCurrentBlockIndex->nHeight - 1, MIN_POSE_PROTO_VERSION); // Need LOCK2 here to ensure consistent locking order because the SendVerifyRequest call below locks cs_main // through GetHeight() signal in ConnectNode LOCK2(cs_main, cs); int nCount = 0; int nMyRank = -1; int nRanksTotal = (int)vecMasternodeRanks.size(); // send verify requests only if we are in top MAX_POSE_RANK std::vector<std::pair<int, CMasternode> >::iterator it = vecMasternodeRanks.begin(); while(it != vecMasternodeRanks.end()) { if(it->first > MAX_POSE_RANK) { LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Must be in top %d to send verify request\n", (int)MAX_POSE_RANK); return; } if(it->second.vin == activeMasternode.vin) { nMyRank = it->first; LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Found self at rank %d/%d, verifying up to %d masternodes\n", nMyRank, nRanksTotal, (int)MAX_POSE_CONNECTIONS); break; } ++it; } // edge case: list is too short and this masternode is not enabled if(nMyRank == -1) return; // send verify requests to up to MAX_POSE_CONNECTIONS masternodes // starting from MAX_POSE_RANK + nMyRank and using MAX_POSE_CONNECTIONS as a step int nOffset = MAX_POSE_RANK + nMyRank - 1; if(nOffset >= (int)vecMasternodeRanks.size()) return; std::vector<CMasternode*> vSortedByAddr; BOOST_FOREACH(CMasternode& mn, vMasternodes) { vSortedByAddr.push_back(&mn); } sort(vSortedByAddr.begin(), vSortedByAddr.end(), CompareByAddr()); it = vecMasternodeRanks.begin() + nOffset; while(it != vecMasternodeRanks.end()) { if(it->second.IsPoSeVerified() || it->second.IsPoSeBanned()) { LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Already %s%s%s masternode %s address %s, skipping...\n", it->second.IsPoSeVerified() ? "verified" : "", it->second.IsPoSeVerified() && it->second.IsPoSeBanned() ? " and " : "", it->second.IsPoSeBanned() ? "banned" : "", it->second.vin.prevout.ToStringShort(), it->second.addr.ToString()); nOffset += MAX_POSE_CONNECTIONS; if(nOffset >= (int)vecMasternodeRanks.size()) break; it += MAX_POSE_CONNECTIONS; continue; } LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Verifying masternode %s rank %d/%d address %s\n", it->second.vin.prevout.ToStringShort(), it->first, nRanksTotal, it->second.addr.ToString()); if(SendVerifyRequest((CAddress)it->second.addr, vSortedByAddr)) { nCount++; if(nCount >= MAX_POSE_CONNECTIONS) break; } nOffset += MAX_POSE_CONNECTIONS; if(nOffset >= (int)vecMasternodeRanks.size()) break; it += MAX_POSE_CONNECTIONS; } LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Sent verification requests to %d masternodes\n", nCount); } // This function tries to find masternodes with the same addr, // find a verified one and ban all the other. If there are many nodes // with the same addr but none of them is verified yet, then none of them are banned. // It could take many times to run this before most of the duplicate nodes are banned. void CMasternodeMan::CheckSameAddr() { if(!masternodeSync.IsSynced() || vMasternodes.empty()) return; std::vector<CMasternode*> vBan; std::vector<CMasternode*> vSortedByAddr; { LOCK(cs); CMasternode* pprevMasternode = NULL; CMasternode* pverifiedMasternode = NULL; BOOST_FOREACH(CMasternode& mn, vMasternodes) { vSortedByAddr.push_back(&mn); } sort(vSortedByAddr.begin(), vSortedByAddr.end(), CompareByAddr()); BOOST_FOREACH(CMasternode* pmn, vSortedByAddr) { // check only (pre)enabled masternodes if(!pmn->IsEnabled() && !pmn->IsPreEnabled()) continue; // initial step if(!pprevMasternode) { pprevMasternode = pmn; pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : NULL; continue; } // second+ step if(pmn->addr == pprevMasternode->addr) { if(pverifiedMasternode) { // another masternode with the same ip is verified, ban this one vBan.push_back(pmn); } else if(pmn->IsPoSeVerified()) { // this masternode with the same ip is verified, ban previous one vBan.push_back(pprevMasternode); // and keep a reference to be able to ban following masternodes with the same ip pverifiedMasternode = pmn; } } else { pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : NULL; } pprevMasternode = pmn; } } // ban duplicates BOOST_FOREACH(CMasternode* pmn, vBan) { LogPrintf("CMasternodeMan::CheckSameAddr -- increasing PoSe ban score for masternode %s\n", pmn->vin.prevout.ToStringShort()); pmn->IncreasePoSeBanScore(); } } bool CMasternodeMan::SendVerifyRequest(const CAddress& addr, const std::vector<CMasternode*>& vSortedByAddr) { if(netfulfilledman.HasFulfilledRequest(addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request")) { // we already asked for verification, not a good idea to do this too often, skip it LogPrint("masternode", "CMasternodeMan::SendVerifyRequest -- too many requests, skipping... addr=%s\n", addr.ToString()); return false; } CNode* pnode = ConnectNode(addr, NULL, true); if(pnode == NULL) { LogPrintf("CMasternodeMan::SendVerifyRequest -- can't connect to node to verify it, addr=%s\n", addr.ToString()); return false; } netfulfilledman.AddFulfilledRequest(addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request"); // use random nonce, store it and require node to reply with correct one later CMasternodeVerification mnv(addr, GetRandInt(999999), pCurrentBlockIndex->nHeight - 1); mWeAskedForVerification[addr] = mnv; LogPrintf("CMasternodeMan::SendVerifyRequest -- verifying node using nonce %d addr=%s\n", mnv.nonce, addr.ToString()); pnode->PushMessage(NetMsgType::MNVERIFY, mnv); return true; } void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv) { // only masternodes can sign this, why would someone ask regular node? if(!fMasterNode) { // do not ban, malicious node might be using my IP // and trying to confuse the node which tries to verify it return; } if(netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-reply")) { // peer should not ask us that often LogPrintf("MasternodeMan::SendVerifyReply -- ERROR: peer already asked me recently, peer=%d\n", pnode->id); Misbehaving(pnode->id, 20); return; } uint256 blockHash; if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { LogPrintf("MasternodeMan::SendVerifyReply -- can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; } std::string strMessage = strprintf("%s%d%s", activeMasternode.service.ToString(false), mnv.nonce, blockHash.ToString()); if(!darkSendSigner.SignMessage(strMessage, mnv.vchSig1, activeMasternode.keyMasternode)) { LogPrintf("MasternodeMan::SendVerifyReply -- SignMessage() failed\n"); return; } std::string strError; if(!darkSendSigner.VerifyMessage(activeMasternode.pubKeyMasternode, mnv.vchSig1, strMessage, strError)) { LogPrintf("MasternodeMan::SendVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } pnode->PushMessage(NetMsgType::MNVERIFY, mnv); netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-reply"); } void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& mnv) { std::string strError; // did we even ask for it? if that's the case we should have matching fulfilled request if(!netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request")) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: we didn't ask for verification of %s, peer=%d\n", pnode->addr.ToString(), pnode->id); Misbehaving(pnode->id, 20); return; } // Received nonce for a known address must match the one we sent if(mWeAskedForVerification[pnode->addr].nonce != mnv.nonce) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: wrong nounce: requested=%d, received=%d, peer=%d\n", mWeAskedForVerification[pnode->addr].nonce, mnv.nonce, pnode->id); Misbehaving(pnode->id, 20); return; } // Received nBlockHeight for a known address must match the one we sent if(mWeAskedForVerification[pnode->addr].nBlockHeight != mnv.nBlockHeight) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: wrong nBlockHeight: requested=%d, received=%d, peer=%d\n", mWeAskedForVerification[pnode->addr].nBlockHeight, mnv.nBlockHeight, pnode->id); Misbehaving(pnode->id, 20); return; } uint256 blockHash; if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { // this shouldn't happen... LogPrintf("MasternodeMan::ProcessVerifyReply -- can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; } // we already verified this address, why node is spamming? if(netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-done")) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: already verified %s recently\n", pnode->addr.ToString()); Misbehaving(pnode->id, 20); return; } { LOCK(cs); CMasternode* prealMasternode = NULL; std::vector<CMasternode*> vpMasternodesToBan; std::vector<CMasternode>::iterator it = vMasternodes.begin(); std::string strMessage1 = strprintf("%s%d%s", pnode->addr.ToString(false), mnv.nonce, blockHash.ToString()); while(it != vMasternodes.end()) { if((CAddress)it->addr == pnode->addr) { if(darkSendSigner.VerifyMessage(it->pubKeyMasternode, mnv.vchSig1, strMessage1, strError)) { // found it! prealMasternode = &(*it); if(!it->IsPoSeVerified()) { it->DecreasePoSeBanScore(); } netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-done"); // we can only broadcast it if we are an activated masternode if(activeMasternode.vin == CTxIn()) continue; // update ... mnv.addr = it->addr; mnv.vin1 = it->vin; mnv.vin2 = activeMasternode.vin; std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), mnv.vin1.prevout.ToStringShort(), mnv.vin2.prevout.ToStringShort()); // ... and sign it if(!darkSendSigner.SignMessage(strMessage2, mnv.vchSig2, activeMasternode.keyMasternode)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- SignMessage() failed\n"); return; } std::string strError; if(!darkSendSigner.VerifyMessage(activeMasternode.pubKeyMasternode, mnv.vchSig2, strMessage2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } mWeAskedForVerification[pnode->addr] = mnv; mnv.Relay(); } else { vpMasternodesToBan.push_back(&(*it)); } } ++it; } // no real masternode found?... if(!prealMasternode) { // this should never be the case normally, // only if someone is trying to game the system in some way or smth like that LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: no real masternode found for addr %s\n", pnode->addr.ToString()); Misbehaving(pnode->id, 20); return; } LogPrintf("CMasternodeMan::ProcessVerifyReply -- verified real masternode %s for addr %s\n", prealMasternode->vin.prevout.ToStringShort(), pnode->addr.ToString()); // increase ban score for everyone else BOOST_FOREACH(CMasternode* pmn, vpMasternodesToBan) { pmn->IncreasePoSeBanScore(); LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- increased PoSe ban score for %s addr %s, new score %d\n", prealMasternode->vin.prevout.ToStringShort(), pnode->addr.ToString(), pmn->nPoSeBanScore); } LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- PoSe score increased for %d fake masternodes, addr %s\n", (int)vpMasternodesToBan.size(), pnode->addr.ToString()); } } void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerification& mnv) { std::string strError; if(mapSeenMasternodeVerification.find(mnv.GetHash()) != mapSeenMasternodeVerification.end()) { // we already have one return; } mapSeenMasternodeVerification[mnv.GetHash()] = mnv; // we don't care about history if(mnv.nBlockHeight < pCurrentBlockIndex->nHeight - MAX_POSE_BLOCKS) { LogPrint("masternode", "MasternodeMan::ProcessVerifyBroadcast -- Outdated: current block %d, verification block %d, peer=%d\n", pCurrentBlockIndex->nHeight, mnv.nBlockHeight, pnode->id); return; } if(mnv.vin1.prevout == mnv.vin2.prevout) { LogPrint("masternode", "MasternodeMan::ProcessVerifyBroadcast -- ERROR: same vins %s, peer=%d\n", mnv.vin1.prevout.ToStringShort(), pnode->id); // that was NOT a good idea to cheat and verify itself, // ban the node we received such message from Misbehaving(pnode->id, 100); return; } uint256 blockHash; if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { // this shouldn't happen... LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- Can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; } int nRank = GetMasternodeRank(mnv.vin2, mnv.nBlockHeight, MIN_POSE_PROTO_VERSION); if (nRank == -1) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- Can't calculate rank for masternode %s\n", mnv.vin2.prevout.ToStringShort()); return; } if(nRank > MAX_POSE_RANK) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- Mastrernode %s is not in top %d, current rank %d, peer=%d\n", mnv.vin2.prevout.ToStringShort(), (int)MAX_POSE_RANK, nRank, pnode->id); return; } { LOCK(cs); std::string strMessage1 = strprintf("%s%d%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString()); std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), mnv.vin1.prevout.ToStringShort(), mnv.vin2.prevout.ToStringShort()); CMasternode* pmn1 = Find(mnv.vin1); if(!pmn1) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- can't find masternode1 %s\n", mnv.vin1.prevout.ToStringShort()); return; } CMasternode* pmn2 = Find(mnv.vin2); if(!pmn2) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- can't find masternode2 %s\n", mnv.vin2.prevout.ToStringShort()); return; } if(pmn1->addr != mnv.addr) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- addr %s do not match %s\n", mnv.addr.ToString(), pnode->addr.ToString()); return; } if(darkSendSigner.VerifyMessage(pmn1->pubKeyMasternode, mnv.vchSig1, strMessage1, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode1 failed, error: %s\n", strError); return; } if(darkSendSigner.VerifyMessage(pmn2->pubKeyMasternode, mnv.vchSig2, strMessage2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode2 failed, error: %s\n", strError); return; } if(!pmn1->IsPoSeVerified()) { pmn1->DecreasePoSeBanScore(); } mnv.Relay(); LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- verified masternode %s for addr %s\n", pmn1->vin.prevout.ToStringShort(), pnode->addr.ToString()); // increase ban score for everyone else with the same addr int nCount = 0; BOOST_FOREACH(CMasternode& mn, vMasternodes) { if(mn.addr != mnv.addr || mn.vin.prevout == mnv.vin1.prevout) continue; mn.IncreasePoSeBanScore(); nCount++; LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- increased PoSe ban score for %s addr %s, new score %d\n", mn.vin.prevout.ToStringShort(), mn.addr.ToString(), mn.nPoSeBanScore); } LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- PoSe score incresed for %d fake masternodes, addr %s\n", nCount, pnode->addr.ToString()); } } std::string CMasternodeMan::ToString() const { std::ostringstream info; info << "Masternodes: " << (int)vMasternodes.size() << ", peers who asked us for Masternode list: " << (int)mAskedUsForMasternodeList.size() << ", peers we asked for Masternode list: " << (int)mWeAskedForMasternodeList.size() << ", entries in Masternode list we asked for: " << (int)mWeAskedForMasternodeListEntry.size() << ", masternode index size: " << indexMasternodes.GetSize() << ", nDsqCount: " << (int)nDsqCount; return info.str(); } void CMasternodeMan::UpdateMasternodeList(CMasternodeBroadcast mnb) { LOCK(cs); mapSeenMasternodePing.insert(std::make_pair(mnb.lastPing.GetHash(), mnb.lastPing)); mapSeenMasternodeBroadcast.insert(std::make_pair(mnb.GetHash(), std::make_pair(GetTime(), mnb))); LogPrintf("CMasternodeMan::UpdateMasternodeList -- masternode=%s addr=%s\n", mnb.vin.prevout.ToStringShort(), mnb.addr.ToString()); CMasternode* pmn = Find(mnb.vin); if(pmn == NULL) { CMasternode mn(mnb); if(Add(mn)) { masternodeSync.AddedMasternodeList(); } } else { CMasternodeBroadcast mnbOld = mapSeenMasternodeBroadcast[CMasternodeBroadcast(*pmn).GetHash()].second; if(pmn->UpdateFromNewBroadcast(mnb)) { masternodeSync.AddedMasternodeList(); mapSeenMasternodeBroadcast.erase(mnbOld.GetHash()); } } } bool CMasternodeMan::CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBroadcast mnb, int& nDos) { // Need LOCK2 here to ensure consistent locking order because the SimpleCheck call below locks cs_main LOCK2(cs_main, cs); nDos = 0; LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s\n", mnb.vin.prevout.ToStringShort()); uint256 hash = mnb.GetHash(); if(mapSeenMasternodeBroadcast.count(hash) && !mnb.fRecovery) { //seen LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen\n", mnb.vin.prevout.ToStringShort()); // less then 2 pings left before this MN goes into non-recoverable state, bump sync timeout if(GetTime() - mapSeenMasternodeBroadcast[hash].first > MASTERNODE_NEW_START_REQUIRED_SECONDS - MASTERNODE_MIN_MNP_SECONDS * 2) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen update\n", mnb.vin.prevout.ToStringShort()); mapSeenMasternodeBroadcast[hash].first = GetTime(); masternodeSync.AddedMasternodeList(); } // did we ask this node for it? if(pfrom && IsMnbRecoveryRequested(hash) && GetTime() < mMnbRecoveryRequests[hash].first) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request\n", hash.ToString()); if(mMnbRecoveryRequests[hash].second.count(pfrom->addr)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request, addr=%s\n", hash.ToString(), pfrom->addr.ToString()); // do not allow node to send same mnb multiple times in recovery mode mMnbRecoveryRequests[hash].second.erase(pfrom->addr); // does it have newer lastPing? if(mnb.lastPing.sigTime > mapSeenMasternodeBroadcast[hash].second.lastPing.sigTime) { // simulate Check CMasternode mnTemp = CMasternode(mnb); mnTemp.Check(); LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request, addr=%s, better lastPing: %d min ago, projected mn state: %s\n", hash.ToString(), pfrom->addr.ToString(), (GetTime() - mnb.lastPing.sigTime)/60, mnTemp.GetStateString()); if(mnTemp.IsValidStateForAutoStart(mnTemp.nActiveState)) { // this node thinks it's a good one LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen good\n", mnb.vin.prevout.ToStringShort()); mMnbRecoveryGoodReplies[hash].push_back(mnb); } } } } return true; } mapSeenMasternodeBroadcast.insert(std::make_pair(hash, std::make_pair(GetTime(), mnb))); LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s new\n", mnb.vin.prevout.ToStringShort()); if(!mnb.SimpleCheck(nDos)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- SimpleCheck() failed, masternode=%s\n", mnb.vin.prevout.ToStringShort()); return false; } // search Masternode list CMasternode* pmn = Find(mnb.vin); if(pmn) { CMasternodeBroadcast mnbOld = mapSeenMasternodeBroadcast[CMasternodeBroadcast(*pmn).GetHash()].second; if(!mnb.Update(pmn, nDos)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Update() failed, masternode=%s\n", mnb.vin.prevout.ToStringShort()); return false; } if(hash != mnbOld.GetHash()) { mapSeenMasternodeBroadcast.erase(mnbOld.GetHash()); } } else { if(mnb.CheckOutpoint(nDos)) { Add(mnb); masternodeSync.AddedMasternodeList(); // if it matches our Masternode privkey... if(fMasterNode && mnb.pubKeyMasternode == activeMasternode.pubKeyMasternode) { mnb.nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE; if(mnb.nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... LogPrintf("CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Got NEW Masternode entry: masternode=%s sigTime=%lld addr=%s\n", mnb.vin.prevout.ToStringShort(), mnb.sigTime, mnb.addr.ToString()); activeMasternode.ManageState(); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay // but also do not ban the node we get this message from LogPrintf("CMasternodeMan::CheckMnbAndUpdateMasternodeList -- wrong PROTOCOL_VERSION, re-activate your MN: message nProtocolVersion=%d PROTOCOL_VERSION=%d\n", mnb.nProtocolVersion, PROTOCOL_VERSION); return false; } } mnb.Relay(); } else { LogPrintf("CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Rejected Masternode entry: %s addr=%s\n", mnb.vin.prevout.ToStringShort(), mnb.addr.ToString()); return false; } } return true; } void CMasternodeMan::UpdateLastPaid() { LOCK(cs); if(fLiteMode) return; if(!pCurrentBlockIndex) return; static bool IsFirstRun = true; // Do full scan on first run or if we are not a masternode // (MNs should update this info on every block, so limited scan should be enough for them) int nMaxBlocksToScanBack = (IsFirstRun || !fMasterNode) ? mnpayments.GetStorageLimit() : LAST_PAID_SCAN_BLOCKS; // LogPrint("mnpayments", "CMasternodeMan::UpdateLastPaid -- nHeight=%d, nMaxBlocksToScanBack=%d, IsFirstRun=%s\n", // pCurrentBlockIndex->nHeight, nMaxBlocksToScanBack, IsFirstRun ? "true" : "false"); BOOST_FOREACH(CMasternode& mn, vMasternodes) { mn.UpdateLastPaid(pCurrentBlockIndex, nMaxBlocksToScanBack); } // every time is like the first time if winners list is not synced IsFirstRun = !masternodeSync.IsWinnersListSynced(); } void CMasternodeMan::CheckAndRebuildMasternodeIndex() { LOCK(cs); if(GetTime() - nLastIndexRebuildTime < MIN_INDEX_REBUILD_TIME) { return; } if(indexMasternodes.GetSize() <= MAX_EXPECTED_INDEX_SIZE) { return; } if(indexMasternodes.GetSize() <= int(vMasternodes.size())) { return; } indexMasternodesOld = indexMasternodes; indexMasternodes.Clear(); for(size_t i = 0; i < vMasternodes.size(); ++i) { indexMasternodes.AddMasternodeVIN(vMasternodes[i].vin); } fIndexRebuilt = true; nLastIndexRebuildTime = GetTime(); } void CMasternodeMan::UpdateWatchdogVoteTime(const CTxIn& vin) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return; } pMN->UpdateWatchdogVoteTime(); nLastWatchdogVoteTime = GetTime(); } bool CMasternodeMan::IsWatchdogActive() { LOCK(cs); // Check if any masternodes have voted recently, otherwise return false // Changed behaviour to avoid WATCHDOG issues return false;//(GetTime() - nLastWatchdogVoteTime) <= MASTERNODE_WATCHDOG_MAX_SECONDS; } bool CMasternodeMan::AddGovernanceVote(const CTxIn& vin, uint256 nGovernanceObjectHash) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return false; } pMN->AddGovernanceVote(nGovernanceObjectHash); return true; } void CMasternodeMan::RemoveGovernanceObject(uint256 nGovernanceObjectHash) { LOCK(cs); BOOST_FOREACH(CMasternode& mn, vMasternodes) { mn.RemoveGovernanceObject(nGovernanceObjectHash); } } void CMasternodeMan::CheckMasternode(const CTxIn& vin, bool fForce) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return; } pMN->Check(fForce); } void CMasternodeMan::CheckMasternode(const CPubKey& pubKeyMasternode, bool fForce) { LOCK(cs); CMasternode* pMN = Find(pubKeyMasternode); if(!pMN) { return; } pMN->Check(fForce); } int CMasternodeMan::GetMasternodeState(const CTxIn& vin) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return CMasternode::MASTERNODE_NEW_START_REQUIRED; } return pMN->nActiveState; } int CMasternodeMan::GetMasternodeState(const CPubKey& pubKeyMasternode) { LOCK(cs); CMasternode* pMN = Find(pubKeyMasternode); if(!pMN) { return CMasternode::MASTERNODE_NEW_START_REQUIRED; } return pMN->nActiveState; } bool CMasternodeMan::IsMasternodePingedWithin(const CTxIn& vin, int nSeconds, int64_t nTimeToCheckAt) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return false; } return pMN->IsPingedWithin(nSeconds, nTimeToCheckAt); } void CMasternodeMan::SetMasternodeLastPing(const CTxIn& vin, const CMasternodePing& mnp) { LOCK(cs); CMasternode* pMN = Find(vin); if(!pMN) { return; } pMN->lastPing = mnp; mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); CMasternodeBroadcast mnb(*pMN); uint256 hash = mnb.GetHash(); if(mapSeenMasternodeBroadcast.count(hash)) { mapSeenMasternodeBroadcast[hash].second.lastPing = mnp; } } void CMasternodeMan::UpdatedBlockTip(const CBlockIndex *pindex) { pCurrentBlockIndex = pindex; LogPrint("masternode", "CMasternodeMan::UpdatedBlockTip -- pCurrentBlockIndex->nHeight=%d\n", pCurrentBlockIndex->nHeight); CheckSameAddr(); if(fMasterNode) { // normal wallet does not need to update this every block, doing update on rpc call should be enough UpdateLastPaid(); } } void CMasternodeMan::NotifyMasternodeUpdates() { // Avoid double locking bool fMasternodesAddedLocal = false; bool fMasternodesRemovedLocal = false; { LOCK(cs); fMasternodesAddedLocal = fMasternodesAdded; fMasternodesRemovedLocal = fMasternodesRemoved; } if(fMasternodesAddedLocal) { governance.CheckMasternodeOrphanObjects(); governance.CheckMasternodeOrphanVotes(); } if(fMasternodesRemovedLocal) { governance.UpdateCachesAndClean(); } LOCK(cs); fMasternodesAdded = false; fMasternodesRemoved = false; }
<<<<<<< HEAD // Copyright (c) 2012-2018, The CryptoNote developers, The Bytecoin developers, [ ] developers. // Licensed under the GNU Lesser General Public License. See LICENSE for details. #pragma once #include <deque> #include "CryptoNote.hpp" #include "Currency.hpp" #include "platform/DB.hpp" #include "platform/ExclusiveLock.hpp" #include "rpc_api.hpp" namespace cryptonote { enum class BroadcastAction { BROADCAST_ALL, NOTHING, BAN }; struct PreparedBlock { BinaryArray block_data; RawBlock raw_block; Block block; Hash bid; Hash base_transaction_hash; size_t coinbase_tx_size = 0; size_t parent_block_size = 0; Hash long_block_hash; // only if context != nullptr explicit PreparedBlock(BinaryArray &&ba, crypto::CryptoNightContext *context); explicit PreparedBlock(RawBlock &&rba, crypto::CryptoNightContext *context); // we get raw blocks from p2p PreparedBlock() {} }; class BlockChain { public: typedef platform::DB DB; explicit BlockChain(const Hash &genesis_bid, const std::string &coin_folder); virtual ~BlockChain() {} const std::string &get_coin_folder() const { return m_coin_folder; } const Hash &get_genesis_bid() const { return m_genesis_bid; } // Read blockchain state Hash get_tip_bid() const { return m_tip_bid; } Height get_tip_height() const { return m_tip_height; } const api::BlockHeader &get_tip() const; std::pair<std::deque<api::BlockHeader>::const_iterator, std::deque<api::BlockHeader>::const_iterator> get_tip_segment(Height height_delta, Height window, bool add_genesis) const; bool read_chain(Height height, Hash &bid) const; bool read_block(const Hash &bid, RawBlock &rb) const; bool has_block(const Hash &bid) const; bool read_header(const Hash &bid, api::BlockHeader &info) const; bool read_transaction(const Hash &tid, Transaction &tx, Height &height, size_t &index_in_block) const; // Modify blockchain state. cryptonote header does not contain enough info for consensus calcs, so we cannot have // header chain without block chain BroadcastAction add_block(const PreparedBlock &pb, api::BlockHeader &info); // Facilitate sync and download std::vector<Hash> get_sparse_chain() const; std::vector<api::BlockHeader> get_sync_headers(const std::vector<Hash> &sparse_chain, size_t max_count) const; std::vector<Hash> get_sync_headers_chain( const std::vector<Hash> &sparse_chain, Height &start_height, size_t max_count) const; Height find_blockchain_supplement(const std::vector<Hash> &remote_block_ids) const; Height get_timestamp_lower_bound_block_index(Timestamp) const; void test_undo_everything(); void test_print_structure() const; void test_prune_oldest(); void db_commit(); bool internal_import(); // import some existing blocks from inside DB Height internal_import_known_height() const { return m_internal_import_known_height; } protected: bool read_next_internal_block(Hash &bid) const; virtual bool check_standalone_consensus( const PreparedBlock &pb, api::BlockHeader &info, const api::BlockHeader &prev_info) const = 0; virtual bool redo_block(const Hash &bhash, const Block &block, const api::BlockHeader &info) = 0; virtual void undo_block(const Hash &bhash, const Block &block, Height height) = 0; bool redo_block(const Hash &bhash, const RawBlock &raw_block, const Block &block, const api::BlockHeader &info, const Hash &base_transaction_hash); void undo_block(const Hash &bhash, const RawBlock &raw_block, const Block &block, Height height); virtual void tip_changed() {} // Quick hack to allow BlockChainState to update next block params const Hash m_genesis_bid; const std::string m_coin_folder; Hash get_common_block( const Hash &bid1, const Hash &bid2, std::vector<Hash> *chain1, std::vector<Hash> *chain2) const; DB m_db; Hash read_chain(Height height) const; api::BlockHeader read_header(const Hash &bid) const; private: Hash m_tip_bid; Difficulty m_tip_cumulative_difficulty = 0; Height m_tip_height = -1; Height m_internal_import_known_height = 0; void read_tip(); void push_chain(Hash bid, Difficulty cumulative_difficulty); void pop_chain(); mutable std::deque<api::BlockHeader> m_tip_segment; // We cache recent headers for quick calculation in block windows void store_block(const Hash &bid, const BinaryArray &block_data); // bid->header, header is stored in DB only if previous block is stored void store_header(const Hash &bid, const api::BlockHeader &header); bool reorganize_blocks( const Hash &switch_to_chain, const PreparedBlock &recent_pb, const api::BlockHeader &recent_info); void check_children_counter(Difficulty cd, const Hash &bid, int value); void modify_children_counter(Difficulty cd, const Hash &bid, int delta); bool get_oldest_tip(Difficulty &cd, Hash &bid) const; bool prune_branch(Difficulty cd, Hash bid); }; } // namespace cryptonote ======= // Copyright (c) 2012-2018, The CryptoNote developers, The Bytecoin developers, [ ] developers. // Licensed under the GNU Lesser General Public License. See LICENSE for details. #pragma once #include <deque> #include "CryptoNote.hpp" #include "Currency.hpp" #include "platform/DB.hpp" #include "platform/ExclusiveLock.hpp" #include "rpc_api.hpp" namespace cryptonote { enum class BroadcastAction { BROADCAST_ALL, NOTHING, BAN }; struct PreparedBlock { BinaryArray block_data; RawBlock raw_block; Block block; Hash bid; Hash base_transaction_hash; size_t coinbase_tx_size = 0; size_t parent_block_size = 0; Hash long_block_hash; // only if context != nullptr explicit PreparedBlock(BinaryArray &&ba, crypto::CryptoNightContext *context); explicit PreparedBlock(RawBlock &&rba, crypto::CryptoNightContext *context); // we get raw blocks from p2p PreparedBlock() {} }; class BlockChain { public: typedef platform::DB DB; explicit BlockChain(const Hash &genesis_bid, const std::string &coin_folder); virtual ~BlockChain() {} const std::string &get_coin_folder() const { return m_coin_folder; } const Hash &get_genesis_bid() const { return m_genesis_bid; } // Read blockchain state Hash get_tip_bid() const { return m_tip_bid; } Height get_tip_height() const { return m_tip_height; } const api::BlockHeader &get_tip() const; std::pair<std::deque<api::BlockHeader>::const_iterator, std::deque<api::BlockHeader>::const_iterator> get_tip_segment(Height height_delta, Height window, bool add_genesis) const; bool read_chain(Height height, Hash &bid) const; bool read_block(const Hash &bid, RawBlock &rb) const; bool has_block(const Hash &bid) const; bool read_header(const Hash &bid, api::BlockHeader &info) const; bool read_transaction(const Hash &tid, Transaction &tx, Height &height, size_t &index_in_block) const; // Modify blockchain state. cryptonote header does not contain enough info for consensus calcs, so we cannot have // header chain without block chain BroadcastAction add_block(const PreparedBlock &pb, api::BlockHeader &info); // Facilitate sync and download std::vector<Hash> get_sparse_chain() const; std::vector<api::BlockHeader> get_sync_headers(const std::vector<Hash> &sparse_chain, size_t max_count) const; std::vector<Hash> get_sync_headers_chain( const std::vector<Hash> &sparse_chain, Height &start_height, size_t max_count) const; Height find_blockchain_supplement(const std::vector<Hash> &remote_block_ids) const; Height get_timestamp_lower_bound_block_index(Timestamp) const; void test_undo_everything(); void test_print_structure() const; void test_prune_oldest(); void db_commit(); bool internal_import(); // import some existing blocks from inside DB Height internal_import_known_height() const { return m_internal_import_known_height; } protected: bool read_next_internal_block(Hash &bid) const; virtual bool check_standalone_consensus( const PreparedBlock &pb, api::BlockHeader &info, const api::BlockHeader &prev_info) const = 0; virtual bool redo_block(const Hash &bhash, const Block &block, const api::BlockHeader &info) = 0; virtual void undo_block(const Hash &bhash, const Block &block, Height height) = 0; bool redo_block(const Hash &bhash, const RawBlock &raw_block, const Block &block, const api::BlockHeader &info, const Hash &base_transaction_hash); void undo_block(const Hash &bhash, const RawBlock &raw_block, const Block &block, Height height); virtual void tip_changed() {} // Quick hack to allow BlockChainState to update next block params const Hash m_genesis_bid; const std::string m_coin_folder; Hash get_common_block( const Hash &bid1, const Hash &bid2, std::vector<Hash> *chain1, std::vector<Hash> *chain2) const; DB m_db; Hash read_chain(Height height) const; api::BlockHeader read_header(const Hash &bid) const; private: Hash m_tip_bid; Difficulty m_tip_cumulative_difficulty = 0; Height m_tip_height = -1; Height m_internal_import_known_height = 0; void read_tip(); void push_chain(Hash bid, Difficulty cumulative_difficulty); void pop_chain(); mutable std::deque<api::BlockHeader> m_tip_segment; // We cache recent headers for quick calculation in block windows void store_block(const Hash &bid, const BinaryArray &block_data); // bid->header, header is stored in DB only if previous block is stored void store_header(const Hash &bid, const api::BlockHeader &header); bool reorganize_blocks( const Hash &switch_to_chain, const PreparedBlock &recent_pb, const api::BlockHeader &recent_info); void check_children_counter(Difficulty cd, const Hash &bid, int value); void modify_children_counter(Difficulty cd, const Hash &bid, int delta); bool get_oldest_tip(Difficulty &cd, Hash &bid) const; bool prune_branch(Difficulty cd, Hash bid); }; } // namespace cryptonote >>>>>>> 15c463360ec17ef10da96da016f30bce13467f24
/** * Murmure - Net-SNMP MIB Versatile Extender * Developed by Christian Visintin * * MIT License * Copyright (c) 2019 Christian Visintin * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. **/ #include <core/modules/rowstatus.hpp> #include <core/primitives/string.hpp> namespace murmure { /** * @function RowStatus * @description RowStatus class constructor * NOTE: set primitive to nullptr; set primitiveType to the primitive we'll use **/ RowStatus::RowStatus() { primitive = nullptr; primitiveType = PRIMITIVE_STRING; } /** * @function ~RowStatus * @description RowStatus class destructor **/ RowStatus::~RowStatus() { if (primitive != nullptr) { String<std::string>* primitivePtr = reinterpret_cast<String<std::string>*>(primitive); delete primitivePtr; } primitive = nullptr; } /** * @function setValue * @description initialize primitive and set its value * @param const std::string& * @returns bool * NOTE: must be called in initialization only **/ bool RowStatus::setValue(const std::string& value) { if (primitive == nullptr) { primitive = new String<std::string>(value); } return true; } /** * @function setValue * @description update primitive value associated to this module * @param const std::string& * @param const std::string& * @returns bool **/ bool RowStatus::setValue(const std::string& oid, const std::string& value) { //Check if primitive is initialized if (primitive == nullptr) { return false; } String<std::string>* primitivePtr = reinterpret_cast<String<std::string>*>(primitive); //Check syntax for rowStatus if (value != "active" && value != "notInService" && value != "notReady" && value != "createAndGo" && value != "createAndWait" && value != "destroy") { return false; } return primitivePtr->setValue(oid, value); } /** * @function getPrintableValue * @description get printable value from its primitive * @returns std::string **/ std::string RowStatus::getPrintableValue() { //Check if primitive is initialized if (primitive == nullptr) { return ""; } String<std::string>* primitivePtr = reinterpret_cast<String<std::string>*>(primitive); return primitivePtr->getPrintableValue(); } /** * @function getPrimitiveType * @description get primitive type name associated to this module * @returns std::string **/ std::string RowStatus::getPrimitiveType() { return primitiveType; } }
///////////////////////////////////////////////////////////////////////////// // Name: controls.cpp // Purpose: Controls wxWidgets sample // Author: Robert Roebling // Modified by: // Copyright: (c) Robert Roebling, Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/spinbutt.h" #include "wx/tglbtn.h" #include "wx/bookctrl.h" #include "wx/imaglist.h" #include "wx/artprov.h" #include "wx/cshelp.h" #include "wx/gbsizer.h" #if wxUSE_TOOLTIPS #include "wx/tooltip.h" #ifdef __WXMSW__ #include "wx/numdlg.h" #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS #ifndef __WXMSW__ #include "icons/choice.xpm" #include "icons/combo.xpm" #include "icons/list.xpm" #include "icons/radio.xpm" #include "icons/text.xpm" #include "icons/gauge.xpm" #endif #ifndef wxUSE_SPINBTN #define wxUSE_SPINBTN 1 #endif #include "wx/progdlg.h" #if wxUSE_SPINCTRL #include "wx/spinctrl.h" #endif // wxUSE_SPINCTRL #if !wxUSE_TOGGLEBTN #define wxToggleButton wxCheckBox #define EVT_TOGGLEBUTTON EVT_CHECKBOX #endif #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif //---------------------------------------------------------------------- // class definitions //---------------------------------------------------------------------- class MyApp: public wxApp { public: bool OnInit(); }; class MyPanel: public wxPanel { public: MyPanel(wxFrame *frame, int x, int y, int w, int h); virtual ~MyPanel(); #if wxUSE_TOOLTIPS void SetAllToolTips(); #endif // wxUSE_TOOLTIPS void OnIdle( wxIdleEvent &event ); void OnListBox( wxCommandEvent &event ); void OnListBoxDoubleClick( wxCommandEvent &event ); void OnListBoxButtons( wxCommandEvent &event ); #if wxUSE_CHOICE void OnChoice( wxCommandEvent &event ); void OnChoiceButtons( wxCommandEvent &event ); #endif void OnCombo( wxCommandEvent &event ); void OnComboTextChanged( wxCommandEvent &event ); void OnComboTextEnter( wxCommandEvent &event ); void OnComboButtons( wxCommandEvent &event ); void OnRadio( wxCommandEvent &event ); void OnRadioButtons( wxCommandEvent &event ); void OnRadioButton1( wxCommandEvent &event ); void OnRadioButton2( wxCommandEvent &event ); void OnSetFont( wxCommandEvent &event ); void OnPageChanged( wxBookCtrlEvent &event ); void OnPageChanging( wxBookCtrlEvent &event ); void OnSliderUpdate( wxCommandEvent &event ); void OnUpdateLabel( wxCommandEvent &event ); #if wxUSE_SPINBTN void OnSpinUp( wxSpinEvent &event ); void OnSpinDown( wxSpinEvent &event ); void OnSpinUpdate( wxSpinEvent &event ); #if wxUSE_PROGRESSDLG void OnUpdateShowProgress( wxUpdateUIEvent& event ); void OnShowProgress( wxCommandEvent &event ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void OnNewText( wxCommandEvent &event ); #if wxUSE_SPINCTRL void OnSpinCtrl(wxSpinEvent& event); void OnSpinCtrlUp(wxSpinEvent& event); void OnSpinCtrlDown(wxSpinEvent& event); void OnSpinCtrlText(wxCommandEvent& event); #endif // wxUSE_SPINCTRL void OnEnableAll(wxCommandEvent& event); void OnChangeColour(wxCommandEvent& event); void OnTestButton(wxCommandEvent& event); void OnBmpButton(wxCommandEvent& event); void OnBmpButtonToggle(wxCommandEvent& event); void OnSizerCheck (wxCommandEvent &event); wxListBox *m_listbox, *m_listboxSorted; #if wxUSE_CHOICE wxChoice *m_choice, *m_choiceSorted; #endif // wxUSE_CHOICE wxComboBox *m_combo; wxRadioBox *m_radio; #if wxUSE_GAUGE wxGauge *m_gauge, *m_gaugeVert; #endif // wxUSE_GAUGE #if wxUSE_SLIDER wxSlider *m_slider; #endif // wxUSE_SLIDER wxButton *m_fontButton; wxButton *m_lbSelectNum; wxButton *m_lbSelectThis; #if wxUSE_SPINBTN wxSpinButton *m_spinbutton; #if wxUSE_PROGRESSDLG wxButton *m_btnProgress; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxStaticText *m_wrappingText; wxStaticText *m_nonWrappingText; #if wxUSE_SPINCTRL wxSpinCtrl *m_spinctrl; #endif // wxUSE_SPINCTRL wxTextCtrl *m_spintext; wxCheckBox *m_checkbox; wxTextCtrl *m_text; wxBookCtrl *m_book; wxStaticText *m_label; wxBoxSizer *m_buttonSizer; wxButton *m_sizerBtn1; wxButton *m_sizerBtn2; wxButton *m_sizerBtn3; wxButton *m_sizerBtn4; wxBoxSizer *m_hsizer; wxButton *m_bigBtn; private: wxLog *m_logTargetOld; wxDECLARE_EVENT_TABLE(); }; class MyFrame: public wxFrame { public: MyFrame(const wxChar *title, int x, int y); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnClearLog(wxCommandEvent& event); #if wxUSE_TOOLTIPS void OnSetTooltipDelay(wxCommandEvent& event); void OnToggleTooltips(wxCommandEvent& event); #ifdef __WXMSW__ void OnSetMaxTooltipWidth(wxCommandEvent& event); #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void OnEnableAll(wxCommandEvent& event); void OnHideAll(wxCommandEvent& event); void OnHideList(wxCommandEvent& event); void OnContextHelp(wxCommandEvent& event); void OnIdle( wxIdleEvent& event ); void OnIconized( wxIconizeEvent& event ); void OnMaximized( wxMaximizeEvent& event ); void OnSize( wxSizeEvent& event ); void OnMove( wxMoveEvent& event ); MyPanel *GetPanel() const { return m_panel; } private: #if wxUSE_STATUSBAR void UpdateStatusBar(const wxPoint& pos, const wxSize& size) { if ( m_frameStatusBar ) { wxString msg; wxSize sizeAll = GetSize(), sizeCl = GetClientSize(); msg.Printf(_("pos=(%d, %d), size=%dx%d or %dx%d (client=%dx%d)"), pos.x, pos.y, size.x, size.y, sizeAll.x, sizeAll.y, sizeCl.x, sizeCl.y); SetStatusText(msg, 1); } } #endif // wxUSE_STATUSBAR MyPanel *m_panel; wxDECLARE_EVENT_TABLE(); }; // a button which intercepts double clicks (for testing...) class MyButton : public wxButton { public: MyButton(wxWindow *parent, wxWindowID id, const wxString& label = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize) : wxButton(parent, id, label, pos, size) { } void OnDClick(wxMouseEvent& event) { wxLogMessage(wxT("MyButton::OnDClick")); event.Skip(); } private: wxDECLARE_EVENT_TABLE(); }; // a combo which intercepts chars (to test Windows behaviour) class MyComboBox : public wxComboBox { public: MyComboBox(wxWindow *parent, wxWindowID id, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxComboBoxNameStr) : wxComboBox(parent, id, value, pos, size, n, choices, style, validator, name) { } protected: void OnChar(wxKeyEvent& event); void OnKeyDown(wxKeyEvent& event); void OnKeyUp(wxKeyEvent& event); void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyComboBox::OnFocusGot")); event.Skip(); } private: wxDECLARE_EVENT_TABLE(); }; // a radiobox which handles focus set/kill (for testing) class MyRadioBox : public wxRadioBox { public: MyRadioBox(wxWindow *parent, wxWindowID id, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, int majorDim = 1, long style = wxRA_SPECIFY_COLS, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxRadioBoxNameStr) : wxRadioBox(parent, id, title, pos, size, n, choices, majorDim, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusLost")); event.Skip(); } private: wxDECLARE_EVENT_TABLE(); }; // a choice which handles focus set/kill (for testing) class MyChoice : public wxChoice { public: MyChoice(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxChoiceNameStr ) : wxChoice(parent, id, pos, size, n, choices, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusLost")); event.Skip(); } private: wxDECLARE_EVENT_TABLE(); }; //---------------------------------------------------------------------- // other //---------------------------------------------------------------------- static void SetListboxClientData(const wxChar *name, wxListBox *control); #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control); #endif // wxUSE_CHOICE IMPLEMENT_APP(MyApp) //---------------------------------------------------------------------- // MyApp //---------------------------------------------------------------------- enum { CONTROLS_QUIT = wxID_EXIT, CONTROLS_ABOUT = wxID_ABOUT, CONTROLS_TEXT = 100, CONTROLS_CLEAR_LOG, // tooltip menu CONTROLS_SET_TOOLTIP_DELAY = 200, CONTROLS_ENABLE_TOOLTIPS, CONTROLS_SET_TOOLTIPS_MAX_WIDTH, // panel menu CONTROLS_ENABLE_ALL, CONTROLS_HIDE_ALL, CONTROLS_HIDE_LIST, CONTROLS_CONTEXT_HELP }; bool MyApp::OnInit() { // use standard command line handling: if ( !wxApp::OnInit() ) return false; // parse the cmd line int x = 50, y = 50; if ( argc == 3 ) { wxSscanf(wxString(argv[1]), wxT("%d"), &x); wxSscanf(wxString(argv[2]), wxT("%d"), &y); } #if wxUSE_HELP wxHelpProvider::Set( new wxSimpleHelpProvider ); #endif // wxUSE_HELP // Create the main frame window MyFrame *frame = new MyFrame(wxT("Controls wxWidgets App"), x, y); frame->Show(true); return true; } //---------------------------------------------------------------------- // MyPanel //---------------------------------------------------------------------- const int ID_BOOK = 1000; const int ID_LISTBOX = 130; const int ID_LISTBOX_SEL_NUM = 131; const int ID_LISTBOX_SEL_STR = 132; const int ID_LISTBOX_CLEAR = 133; const int ID_LISTBOX_APPEND = 134; const int ID_LISTBOX_DELETE = 135; const int ID_LISTBOX_FONT = 136; const int ID_LISTBOX_ENABLE = 137; const int ID_LISTBOX_SORTED = 138; const int ID_CHOICE = 120; const int ID_CHOICE_SEL_NUM = 121; const int ID_CHOICE_SEL_STR = 122; const int ID_CHOICE_CLEAR = 123; const int ID_CHOICE_APPEND = 124; const int ID_CHOICE_DELETE = 125; const int ID_CHOICE_FONT = 126; const int ID_CHOICE_ENABLE = 127; const int ID_CHOICE_SORTED = 128; const int ID_COMBO = 140; const int ID_COMBO_SEL_NUM = 141; const int ID_COMBO_SEL_STR = 142; const int ID_COMBO_CLEAR = 143; const int ID_COMBO_APPEND = 144; const int ID_COMBO_DELETE = 145; const int ID_COMBO_FONT = 146; const int ID_COMBO_ENABLE = 147; const int ID_COMBO_SET_TEXT = 148; const int ID_RADIOBOX = 160; const int ID_RADIOBOX_SEL_NUM = 161; const int ID_RADIOBOX_SEL_STR = 162; const int ID_RADIOBOX_FONT = 163; const int ID_RADIOBOX_ENABLE = 164; const int ID_RADIOBOX2 = 165; const int ID_RADIOBUTTON_1 = 166; const int ID_RADIOBUTTON_2 = 167; const int ID_SET_FONT = 170; #if wxUSE_GAUGE const int ID_GAUGE = 180; #endif // wxUSE_GAUGE #if wxUSE_SLIDER const int ID_SLIDER = 181; #endif // wxUSE_SLIDER const int ID_SPIN = 182; #if wxUSE_PROGRESSDLG const int ID_BTNPROGRESS = 183; #endif // wxUSE_PROGRESSDLG const int ID_BUTTON_LABEL = 184; const int ID_SPINCTRL = 185; const int ID_BTNNEWTEXT = 186; const int ID_BUTTON_TEST1 = 190; const int ID_BUTTON_TEST2 = 191; const int ID_BITMAP_BTN = 192; const int ID_BITMAP_BTN_ENABLE = 193; const int ID_CHANGE_COLOUR = 200; const int ID_SIZER_CHECK1 = 201; const int ID_SIZER_CHECK2 = 202; const int ID_SIZER_CHECK3 = 203; const int ID_SIZER_CHECK4 = 204; const int ID_SIZER_CHECK14 = 205; const int ID_SIZER_CHECKBIG = 206; const int ID_HYPERLINK = 300; wxBEGIN_EVENT_TABLE(MyPanel, wxPanel) EVT_IDLE ( MyPanel::OnIdle) EVT_BOOKCTRL_PAGE_CHANGING(ID_BOOK, MyPanel::OnPageChanging) EVT_BOOKCTRL_PAGE_CHANGED(ID_BOOK, MyPanel::OnPageChanged) EVT_LISTBOX (ID_LISTBOX, MyPanel::OnListBox) EVT_LISTBOX (ID_LISTBOX_SORTED, MyPanel::OnListBox) EVT_LISTBOX_DCLICK(ID_LISTBOX, MyPanel::OnListBoxDoubleClick) EVT_BUTTON (ID_LISTBOX_SEL_NUM, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_SEL_STR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_CLEAR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_APPEND, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_DELETE, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_FONT, MyPanel::OnListBoxButtons) EVT_CHECKBOX (ID_LISTBOX_ENABLE, MyPanel::OnListBoxButtons) #if wxUSE_CHOICE EVT_CHOICE (ID_CHOICE, MyPanel::OnChoice) EVT_CHOICE (ID_CHOICE_SORTED, MyPanel::OnChoice) EVT_BUTTON (ID_CHOICE_SEL_NUM, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_SEL_STR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_CLEAR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_APPEND, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_DELETE, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_FONT, MyPanel::OnChoiceButtons) EVT_CHECKBOX (ID_CHOICE_ENABLE, MyPanel::OnChoiceButtons) #endif EVT_COMBOBOX (ID_COMBO, MyPanel::OnCombo) EVT_TEXT (ID_COMBO, MyPanel::OnComboTextChanged) EVT_TEXT_ENTER(ID_COMBO, MyPanel::OnComboTextEnter) EVT_BUTTON (ID_COMBO_SEL_NUM, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SEL_STR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_CLEAR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_APPEND, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_DELETE, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_FONT, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SET_TEXT, MyPanel::OnComboButtons) EVT_CHECKBOX (ID_COMBO_ENABLE, MyPanel::OnComboButtons) EVT_RADIOBOX (ID_RADIOBOX, MyPanel::OnRadio) EVT_RADIOBOX (ID_RADIOBOX2, MyPanel::OnRadio) EVT_BUTTON (ID_RADIOBOX_SEL_NUM, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_SEL_STR, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_FONT, MyPanel::OnRadioButtons) EVT_CHECKBOX (ID_RADIOBOX_ENABLE, MyPanel::OnRadioButtons) EVT_RADIOBUTTON(ID_RADIOBUTTON_1, MyPanel::OnRadioButton1) EVT_RADIOBUTTON(ID_RADIOBUTTON_2, MyPanel::OnRadioButton2) EVT_BUTTON (ID_SET_FONT, MyPanel::OnSetFont) #if wxUSE_SLIDER EVT_SLIDER (ID_SLIDER, MyPanel::OnSliderUpdate) #endif // wxUSE_SLIDER #if wxUSE_SPINBTN EVT_SPIN (ID_SPIN, MyPanel::OnSpinUpdate) EVT_SPIN_UP (ID_SPIN, MyPanel::OnSpinUp) EVT_SPIN_DOWN (ID_SPIN, MyPanel::OnSpinDown) #if wxUSE_PROGRESSDLG EVT_UPDATE_UI (ID_BTNPROGRESS, MyPanel::OnUpdateShowProgress) EVT_BUTTON (ID_BTNPROGRESS, MyPanel::OnShowProgress) #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL EVT_SPINCTRL (ID_SPINCTRL, MyPanel::OnSpinCtrl) EVT_SPIN_UP (ID_SPINCTRL, MyPanel::OnSpinCtrlUp) EVT_SPIN_DOWN (ID_SPINCTRL, MyPanel::OnSpinCtrlDown) EVT_TEXT (ID_SPINCTRL, MyPanel::OnSpinCtrlText) #endif // wxUSE_SPINCTRL EVT_BUTTON (ID_BTNNEWTEXT, MyPanel::OnNewText) EVT_TOGGLEBUTTON(ID_BUTTON_LABEL, MyPanel::OnUpdateLabel) EVT_CHECKBOX (ID_CHANGE_COLOUR, MyPanel::OnChangeColour) EVT_BUTTON (ID_BUTTON_TEST1, MyPanel::OnTestButton) EVT_BUTTON (ID_BUTTON_TEST2, MyPanel::OnTestButton) EVT_BUTTON (ID_BITMAP_BTN, MyPanel::OnBmpButton) EVT_TOGGLEBUTTON(ID_BITMAP_BTN_ENABLE, MyPanel::OnBmpButtonToggle) EVT_CHECKBOX (ID_SIZER_CHECK1, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK2, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK3, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK4, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK14, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECKBIG, MyPanel::OnSizerCheck) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyButton, wxButton) EVT_LEFT_DCLICK(MyButton::OnDClick) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyComboBox, wxComboBox) EVT_CHAR(MyComboBox::OnChar) EVT_KEY_DOWN(MyComboBox::OnKeyDown) EVT_KEY_UP(MyComboBox::OnKeyUp) EVT_SET_FOCUS(MyComboBox::OnFocusGot) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyRadioBox, wxRadioBox) EVT_SET_FOCUS(MyRadioBox::OnFocusGot) EVT_KILL_FOCUS(MyRadioBox::OnFocusLost) wxEND_EVENT_TABLE() wxBEGIN_EVENT_TABLE(MyChoice, wxChoice) EVT_SET_FOCUS(MyChoice::OnFocusGot) EVT_KILL_FOCUS(MyChoice::OnFocusLost) wxEND_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ MyPanel::MyPanel( wxFrame *frame, int x, int y, int w, int h ) : wxPanel( frame, wxID_ANY, wxPoint(x, y), wxSize(w, h) ) { m_listbox = NULL; m_listboxSorted = NULL; #if wxUSE_CHOICE m_choice = NULL; m_choiceSorted = NULL; #endif // wxUSE_CHOICE m_combo = NULL; m_radio = NULL; #if wxUSE_GAUGE m_gauge = NULL; m_gaugeVert = NULL; #endif // wxUSE_GAUGE #if wxUSE_SLIDER m_slider = NULL; #endif // wxUSE_SLIDER m_fontButton = NULL; m_lbSelectNum = NULL; m_lbSelectThis = NULL; #if wxUSE_SPINBTN m_spinbutton = NULL; #if wxUSE_PROGRESSDLG m_btnProgress = NULL; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = NULL; #endif // wxUSE_SPINCTRL m_spintext = NULL; m_checkbox = NULL; m_text = NULL; m_book = NULL; m_label = NULL; m_text = new wxTextCtrl(this, wxID_ANY, wxT("This is the log window.\n"), wxPoint(0, 250), wxSize(100, 50), wxTE_MULTILINE); m_logTargetOld = wxLog::SetActiveTarget(new wxLogTextCtrl(m_text)); m_book = new wxBookCtrl(this, ID_BOOK); wxString choices[] = { wxT("This"), wxT("is"), wxT("one of my long and"), wxT("wonderful"), wxT("examples.") }; #ifndef __WXMSW__ // image ids enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; // fill the image list wxBitmap bmp(list_xpm); wxImageList *imagelist = new wxImageList(bmp.GetWidth(), bmp.GetHeight()); imagelist-> Add( bmp ); imagelist-> Add( wxBitmap( choice_xpm )); imagelist-> Add( wxBitmap( combo_xpm )); imagelist-> Add( wxBitmap( text_xpm )); imagelist-> Add( wxBitmap( radio_xpm )); #if wxUSE_GAUGE imagelist-> Add( wxBitmap( gauge_xpm )); #endif // wxUSE_GAUGE m_book->SetImageList(imagelist); #else // load images from resources enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; wxImageList *imagelist = new wxImageList(16, 16, false, Image_Max); static const wxChar *s_iconNames[Image_Max] = { wxT("list") , wxT("choice") , wxT("combo") , wxT("text") , wxT("radio") #if wxUSE_GAUGE , wxT("gauge") #endif // wxUSE_GAUGE }; for ( size_t n = 0; n < Image_Max; n++ ) { wxBitmap bmp(s_iconNames[n]); if ( !bmp.IsOk() || (imagelist->Add(bmp) == -1) ) { wxLogWarning(wxT("Couldn't load the image '%s' for the book control page %d."), s_iconNames[n], n); } } m_book->SetImageList(imagelist); #endif // ------------------------------------------------------------------------ // listbox page // ------------------------------------------------------------------------ wxPanel *panel = new wxPanel(m_book); m_listbox = new wxListBox( panel, ID_LISTBOX, wxPoint(10,10), wxSize(120,70), 5, choices, wxLB_MULTIPLE | wxLB_ALWAYS_SB | wxHSCROLL ); m_listboxSorted = new wxListBox( panel, ID_LISTBOX_SORTED, wxPoint(10,90), wxSize(120,70), 3, choices, wxLB_SORT ); SetListboxClientData(wxT("listbox"), m_listbox); SetListboxClientData(wxT("listbox"), m_listboxSorted); m_listbox->SetCursor(*wxCROSS_CURSOR); m_lbSelectNum = new wxButton( panel, ID_LISTBOX_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); m_lbSelectThis = new wxButton( panel, ID_LISTBOX_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new MyButton( panel, ID_LISTBOX_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); wxButton *button = new MyButton( panel, ID_LISTBOX_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); button->SetDefault(); m_checkbox = new wxCheckBox( panel, ID_LISTBOX_ENABLE, wxT("&Disable"), wxPoint(20,170) ); m_checkbox->SetValue(false); button->MoveAfterInTabOrder(m_checkbox); (void)new wxCheckBox( panel, ID_CHANGE_COLOUR, wxT("&Toggle colour"), wxPoint(110,170) ); panel->SetCursor(wxCursor(wxCURSOR_HAND)); m_book->AddPage(panel, wxT("wxListBox"), true, Image_List); // ------------------------------------------------------------------------ // choice page // ------------------------------------------------------------------------ #if wxUSE_CHOICE panel = new wxPanel(m_book); m_choice = new MyChoice( panel, ID_CHOICE, wxPoint(10,10), wxDefaultSize, 5, choices ); m_choiceSorted = new MyChoice( panel, ID_CHOICE_SORTED, wxPoint(10,70), wxSize(120,wxDefaultCoord), 5, choices, wxCB_SORT ); SetChoiceClientData(wxT("choice"), m_choice); SetChoiceClientData(wxT("choice"), m_choiceSorted); m_choice->SetSelection(2); (void)new wxButton( panel, ID_CHOICE_SEL_NUM, wxT("Select #&2"), wxPoint(220,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_SEL_STR, wxT("&Select 'This'"), wxPoint(380,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_CLEAR, wxT("&Clear"), wxPoint(220,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_APPEND, wxT("&Append 'Hi!'"), wxPoint(380,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_DELETE, wxT("D&elete selected item"), wxPoint(220,130), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_FONT, wxT("Set &Italic font"), wxPoint(380,130), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_CHOICE_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxChoice"), false, Image_Choice); #endif // wxUSE_CHOICE // ------------------------------------------------------------------------ // combo page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); m_combo = new MyComboBox( panel, ID_COMBO, wxT("This"), wxPoint(15,25), wxDefaultSize, 5, choices, wxTE_PROCESS_ENTER); wxSize combosize(m_combo->GetBestSize().x + 20, 100); (void)new wxStaticBox( panel, wxID_ANY, wxT("&Box around combobox"), wxPoint(5, 5), combosize); (void)new wxButton( panel, ID_COMBO_SEL_NUM, wxT("Select #&2"), wxPoint(220,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SEL_STR, wxT("&Select 'This'"), wxPoint(380,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_CLEAR, wxT("&Clear"), wxPoint(220,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_APPEND, wxT("&Append 'Hi!'"), wxPoint(380,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_DELETE, wxT("D&elete selected item"), wxPoint(220,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_FONT, wxT("Set &Italic font"), wxPoint(380,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SET_TEXT, wxT("Set 'Hi!' at #2"), wxPoint(380,180), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_COMBO_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxComboBox"), false, Image_Combo); // ------------------------------------------------------------------------ // radio box // ------------------------------------------------------------------------ wxString choices2[] = { wxT("First"), wxT("Second"), /* "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Nineth", "Tenth" */ }; panel = new wxPanel(m_book); wxGridBagSizer* radio_page_sizer = new wxGridBagSizer(5, 5); m_radio = new wxRadioBox(panel, ID_RADIOBOX, wxT("T&his"), wxPoint(10,10), wxDefaultSize, WXSIZEOF(choices), choices, 1, wxRA_SPECIFY_COLS ); MyRadioBox* mybox = new MyRadioBox(panel, ID_RADIOBOX2, wxT("&That"), wxPoint(10,160), wxDefaultSize, WXSIZEOF(choices2), choices2, 1, wxRA_SPECIFY_ROWS ); radio_page_sizer->Add( m_radio, wxGBPosition(0,0), wxGBSpan(2,1) ); radio_page_sizer->Add( mybox, wxGBPosition(2,0), wxGBSpan(2,1) ); #if wxUSE_HELP for (unsigned int item = 0; item < WXSIZEOF(choices); ++item) m_radio->SetItemHelpText( item, wxString::Format( wxT("Help text for \"%s\""), choices[item].c_str() ) ); // erase help text for the second item m_radio->SetItemHelpText( 1, wxT("") ); // set default help text for control m_radio->SetHelpText( wxT("Default helptext for wxRadioBox") ); #endif // wxUSE_HELP wxButton* select_two = new wxButton ( panel, ID_RADIOBOX_SEL_NUM, wxT("Select #&2") ); wxButton* select_this = new wxButton ( panel, ID_RADIOBOX_SEL_STR, wxT("&Select 'This'") ); m_fontButton = new wxButton ( panel, ID_SET_FONT, wxT("Set &more Italic font") ); wxButton* set_italic = new wxButton ( panel, ID_RADIOBOX_FONT, wxT("Set &Italic font") ); wxCheckBox* disable_cb = new wxCheckBox( panel, ID_RADIOBOX_ENABLE, wxT("&Disable") ); wxRadioButton *rb = new wxRadioButton( panel, ID_RADIOBUTTON_1, wxT("Radiobutton1"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); wxRadioButton *rb2 = new wxRadioButton( panel, ID_RADIOBUTTON_2, wxT("&Radiobutton2"), wxDefaultPosition, wxDefaultSize ); rb->SetValue( false ); radio_page_sizer->Add( select_two, wxGBPosition(0, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( select_this, wxGBPosition(1, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( m_fontButton, wxGBPosition(0, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( set_italic, wxGBPosition(1, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( disable_cb, wxGBPosition(2, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb, wxGBPosition(3, 1), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb2, wxGBPosition(3, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); panel->SetSizer( radio_page_sizer ); m_book->AddPage(panel, wxT("wxRadioBox"), false, Image_Radio); // ------------------------------------------------------------------------ // gauge and slider // ------------------------------------------------------------------------ #if wxUSE_SLIDER && wxUSE_GAUGE panel = new wxPanel(m_book); wxBoxSizer *gauge_page_vsizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer *gauge_page_first_row_sizer = new wxBoxSizer( wxHORIZONTAL ); wxStaticBoxSizer *gauge_sizer = new wxStaticBoxSizer( wxHORIZONTAL, panel, wxT("&wxGauge and wxSlider") ); gauge_page_first_row_sizer->Add( gauge_sizer, 0, wxALL, 5 ); wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL ); gauge_sizer->Add( sz ); m_gauge = new wxGauge( panel, wxID_ANY, 200, wxDefaultPosition, wxSize(155, 30), wxGA_HORIZONTAL|wxNO_BORDER ); sz->Add( m_gauge, 0, wxALL, 10 ); m_slider = new wxSlider( panel, ID_SLIDER, 0, 0, 200, wxDefaultPosition, wxSize(155,wxDefaultCoord), wxSL_AUTOTICKS | wxSL_LABELS); m_slider->SetTickFreq(40); sz->Add( m_slider, 0, wxALL, 10 ); m_gaugeVert = new wxGauge( panel, wxID_ANY, 100, wxDefaultPosition, wxSize(wxDefaultCoord, 90), wxGA_VERTICAL | wxGA_SMOOTH | wxNO_BORDER ); gauge_sizer->Add( m_gaugeVert, 0, wxALL, 10 ); wxStaticBox *sb = new wxStaticBox( panel, wxID_ANY, wxT("&Explanation"), wxDefaultPosition, wxDefaultSize ); //, wxALIGN_CENTER ); wxStaticBoxSizer *wrapping_sizer = new wxStaticBoxSizer( sb, wxVERTICAL ); gauge_page_first_row_sizer->Add( wrapping_sizer, 0, wxALL, 5 ); #ifdef __WXMOTIF__ // No wrapping text in wxStaticText yet :-( m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("Drag the slider!"), wxPoint(250,30), wxSize(240, wxDefaultCoord) ); #else m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("In order see the gauge (aka progress bar) ") wxT("control do something you have to drag the ") wxT("handle of the slider to the right.") wxT("\n\n") wxT("This is also supposed to demonstrate how ") wxT("to use static controls with line wrapping."), wxDefaultPosition, wxSize(240, wxDefaultCoord) ); #endif wrapping_sizer->Add( m_wrappingText ); wxStaticBoxSizer *non_wrapping_sizer = new wxStaticBoxSizer( wxVERTICAL, panel, wxT("Non-wrapping") ); gauge_page_first_row_sizer->Add( non_wrapping_sizer, 0, wxALL, 5 ); m_nonWrappingText = new wxStaticText( panel, wxID_ANY, wxT("This static text has two lines.\nThey do not wrap."), wxDefaultPosition, wxDefaultSize ); non_wrapping_sizer->Add( m_nonWrappingText ); gauge_page_vsizer->Add( gauge_page_first_row_sizer, 1 ); wxBoxSizer *gauge_page_second_row_sizer = new wxBoxSizer( wxHORIZONTAL ); int initialSpinValue = -5; wxString s; s << initialSpinValue; m_spintext = new wxTextCtrl( panel, wxID_ANY, s ); gauge_page_second_row_sizer->Add( m_spintext, 0, wxALL, 5 ); #if wxUSE_SPINBTN m_spinbutton = new wxSpinButton( panel, ID_SPIN ); m_spinbutton->SetRange(-40,30); m_spinbutton->SetValue(initialSpinValue); gauge_page_second_row_sizer->Add( m_spinbutton, 0, wxALL, 5 ); #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = new wxSpinCtrl( panel, ID_SPINCTRL, wxEmptyString ); m_spinctrl->SetRange(-10,30); m_spinctrl->SetValue(15); gauge_page_second_row_sizer->Add( m_spinctrl, 0, wxALL, 5 ); #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN #if wxUSE_PROGRESSDLG m_btnProgress = new wxButton( panel, ID_BTNPROGRESS, wxT("&Show progress dialog") ); gauge_page_second_row_sizer->Add( m_btnProgress, 0, wxALL, 5 ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxButton* newTextButton = new wxButton( panel, ID_BTNNEWTEXT, wxT("New text")); gauge_page_second_row_sizer->Add( newTextButton, 0, wxALL, 5 ); gauge_page_vsizer->Add(gauge_page_second_row_sizer, 1); panel->SetSizer( gauge_page_vsizer ); m_book->AddPage(panel, wxT("wxGauge"), false, Image_Gauge); #endif // wxUSE_SLIDER && wxUSE_GAUGE // ------------------------------------------------------------------------ // wxBitmapXXX // ------------------------------------------------------------------------ panel = new wxPanel(m_book); #if !defined(__WXMOTIF__) // wxStaticBitmap not working under Motif yet. wxIcon icon = wxArtProvider::GetIcon(wxART_INFORMATION); (void) new wxStaticBitmap( panel, wxID_ANY, icon, wxPoint(10, 10) ); // VZ: don't leak memory // bmpStatic = new wxStaticBitmap(panel, wxID_ANY, wxNullIcon, wxPoint(50, 10)); // bmpStatic->SetIcon(wxArtProvider::GetIcon(wxART_QUESTION)); #endif // !Motif wxBitmap bitmap( 100, 100 ); wxMemoryDC dc; dc.SelectObject( bitmap ); dc.SetBackground(*wxGREEN); dc.SetPen(*wxRED_PEN); dc.Clear(); dc.DrawEllipse(5, 5, 90, 90); dc.DrawText(wxT("Bitmap"), 30, 40); dc.SelectObject( wxNullBitmap ); wxPanel *panel2 = new wxPanel(panel, -1, wxPoint(100, 0), wxSize(100, 200)); (void)new wxBitmapButton(panel2, ID_BITMAP_BTN, bitmap, wxPoint(0, 20)); (void)new wxToggleButton(panel2, ID_BITMAP_BTN_ENABLE, wxT("Enable/disable &bitmap"), wxPoint(0, 140)); #if defined(__WXMSW__) || defined(__WXMOTIF__) // test for masked bitmap display bitmap = wxBitmap(wxT("test2.bmp"), wxBITMAP_TYPE_BMP); if (bitmap.IsOk()) { bitmap.SetMask(new wxMask(bitmap, *wxBLUE)); (void)new wxStaticBitmap(panel, wxID_ANY, bitmap, wxPoint(300, 120)); } #endif wxBitmap bmp1(wxArtProvider::GetBitmap(wxART_INFORMATION)), bmp2(wxArtProvider::GetBitmap(wxART_WARNING)), bmp3(wxArtProvider::GetBitmap(wxART_QUESTION)); wxBitmapButton *bmpBtn = new wxBitmapButton ( panel, wxID_ANY, bmp1, wxPoint(30, 70) ); bmpBtn->SetBitmapSelected(bmp2); bmpBtn->SetBitmapFocus(bmp3); (void)new wxToggleButton(panel, ID_BUTTON_LABEL, wxT("&Toggle label"), wxPoint(250, 20)); m_label = new wxStaticText(panel, wxID_ANY, wxT("Label with some long text"), wxPoint(250, 60), wxDefaultSize, wxALIGN_RIGHT /*| wxST_NO_AUTORESIZE*/); m_label->SetForegroundColour( *wxBLUE ); m_book->AddPage(panel, wxT("wxBitmapXXX")); // ------------------------------------------------------------------------ // sizer page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer *csizer = new wxStaticBoxSizer (new wxStaticBox (panel, wxID_ANY, wxT("Show Buttons")), wxHORIZONTAL ); wxCheckBox *check1, *check2, *check3, *check4, *check14, *checkBig; check1 = new wxCheckBox (panel, ID_SIZER_CHECK1, wxT("1")); check1->SetValue (true); csizer->Add (check1); check2 = new wxCheckBox (panel, ID_SIZER_CHECK2, wxT("2")); check2->SetValue (true); csizer->Add (check2); check3 = new wxCheckBox (panel, ID_SIZER_CHECK3, wxT("3")); check3->SetValue (true); csizer->Add (check3); check4 = new wxCheckBox (panel, ID_SIZER_CHECK4, wxT("4")); check4->SetValue (true); csizer->Add (check4); check14 = new wxCheckBox (panel, ID_SIZER_CHECK14, wxT("1-4")); check14->SetValue (true); csizer->Add (check14); checkBig = new wxCheckBox (panel, ID_SIZER_CHECKBIG, wxT("Big")); checkBig->SetValue (true); csizer->Add (checkBig); sizer->Add (csizer); m_hsizer = new wxBoxSizer( wxHORIZONTAL ); m_buttonSizer = new wxBoxSizer (wxVERTICAL); m_sizerBtn1 = new wxButton(panel, wxID_ANY, wxT("Test Button &1 (tab order 1)") ); m_buttonSizer->Add( m_sizerBtn1, 0, wxALL, 10 ); m_sizerBtn2 = new wxButton(panel, wxID_ANY, wxT("Test Button &2 (tab order 3)") ); m_buttonSizer->Add( m_sizerBtn2, 0, wxALL, 10 ); m_sizerBtn3 = new wxButton(panel, wxID_ANY, wxT("Test Button &3 (tab order 2)") ); m_buttonSizer->Add( m_sizerBtn3, 0, wxALL, 10 ); m_sizerBtn4 = new wxButton(panel, wxID_ANY, wxT("Test Button &4 (tab order 4)") ); m_buttonSizer->Add( m_sizerBtn4, 0, wxALL, 10 ); m_sizerBtn3->MoveBeforeInTabOrder(m_sizerBtn2); m_hsizer->Add (m_buttonSizer); m_hsizer->Add( 20,20, 1 ); m_bigBtn = new wxButton(panel, wxID_ANY, wxT("Multiline\nbutton") ); m_hsizer->Add( m_bigBtn , 3, wxGROW|wxALL, 10 ); sizer->Add (m_hsizer, 1, wxGROW); panel->SetSizer( sizer ); m_book->AddPage(panel, wxT("wxSizer")); // set the sizer for the panel itself sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(m_book, wxSizerFlags().Border().Expand()); sizer->Add(m_text, wxSizerFlags(1).Border().Expand()); SetSizer(sizer); #if wxUSE_TOOLTIPS SetAllToolTips(); #endif // wxUSE_TOOLTIPS } #if wxUSE_TOOLTIPS namespace { void ResetToolTip(wxWindow *win, const char *tip) { wxCHECK_RET( win, "NULL window?" ); win->UnsetToolTip(); win->SetToolTip(tip); } } void MyPanel::SetAllToolTips() { ResetToolTip(FindWindow(ID_LISTBOX_FONT), "Press here to set italic font"); ResetToolTip(m_checkbox, "Click here to disable the listbox"); ResetToolTip(m_listbox, "This is a list box"); ResetToolTip(m_combo, "This is a natural\ncombobox - can you believe me?"); ResetToolTip(m_slider, "This is a sliding slider"); ResetToolTip(FindWindow(ID_RADIOBOX2), "Ever seen a radiobox?"); //ResetToolTip(m_radio, "Tooltip for the entire radiobox"); for ( unsigned int nb = 0; nb < m_radio->GetCount(); nb++ ) { m_radio->SetItemToolTip(nb, ""); m_radio->SetItemToolTip(nb, "tooltip for\n" + m_radio->GetString(nb)); } // remove the tooltip for one of the items m_radio->SetItemToolTip(2, ""); } #endif // wxUSE_TOOLTIPS void MyPanel::OnIdle(wxIdleEvent& event) { static const int INVALID_SELECTION = -2; static int s_selCombo = INVALID_SELECTION; if (!m_combo || !m_choice) { event.Skip(); return; } int sel = m_combo->GetSelection(); if ( sel != s_selCombo ) { if ( s_selCombo != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: combobox selection changed from %d to %d"), s_selCombo, sel); } s_selCombo = sel; } static int s_selChoice = INVALID_SELECTION; sel = m_choice->GetSelection(); if ( sel != s_selChoice ) { if ( s_selChoice != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: choice selection changed from %d to %d"), s_selChoice, sel); } s_selChoice = sel; } event.Skip(); } void MyPanel::OnPageChanging( wxBookCtrlEvent &event ) { int selOld = event.GetOldSelection(); if ( selOld == 2 ) { if ( wxMessageBox(wxT("This demonstrates how a program may prevent the\n") wxT("page change from taking place - if you select\n") wxT("[No] the current page will stay the third one\n"), wxT("Control sample"), wxICON_QUESTION | wxYES_NO, this) != wxYES ) { event.Veto(); return; } } *m_text << wxT("Book selection is being changed from ") << selOld << wxT(" to ") << event.GetSelection() << wxT(" (current page from book is ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnPageChanged( wxBookCtrlEvent &event ) { *m_text << wxT("Book selection is now ") << event.GetSelection() << wxT(" (from book: ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnTestButton(wxCommandEvent& event) { wxLogMessage(wxT("Button %c clicked."), event.GetId() == ID_BUTTON_TEST1 ? wxT('1') : wxT('2')); } void MyPanel::OnBmpButton(wxCommandEvent& WXUNUSED(event)) { wxLogMessage(wxT("Bitmap button clicked.")); } void MyPanel::OnBmpButtonToggle(wxCommandEvent& event) { FindWindow(ID_BITMAP_BTN)->Enable(!event.IsChecked()); } void MyPanel::OnChangeColour(wxCommandEvent& WXUNUSED(event)) { static wxColour s_colOld; SetThemeEnabled(false); // test panel colour changing and propagation to the subcontrols if ( s_colOld.IsOk() ) { SetBackgroundColour(s_colOld); s_colOld = wxNullColour; m_lbSelectThis->SetForegroundColour(wxNullColour); m_lbSelectThis->SetBackgroundColour(wxNullColour); } else { s_colOld = *wxRED; SetBackgroundColour(*wxWHITE); m_lbSelectThis->SetForegroundColour(wxT("white")); m_lbSelectThis->SetBackgroundColour(wxT("red")); } m_lbSelectThis->Refresh(); Refresh(); } void MyPanel::OnListBox( wxCommandEvent &event ) { wxListBox *listbox = event.GetId() == ID_LISTBOX ? m_listbox : m_listboxSorted; bool deselect = false; if (listbox->HasFlag(wxLB_MULTIPLE) || listbox->HasFlag(wxLB_EXTENDED)) { deselect = !event.IsSelection(); if (deselect) m_text->AppendText( wxT("ListBox deselection event\n") ); } m_text->AppendText( wxT("ListBox event selection string is: '") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("'\n") ); // can't use GetStringSelection() with multiple selections, there could be // more than one of them if ( !listbox->HasFlag(wxLB_MULTIPLE) && !listbox->HasFlag(wxLB_EXTENDED) ) { m_text->AppendText( wxT("ListBox control selection string is: '") ); m_text->AppendText( listbox->GetStringSelection() ); m_text->AppendText( wxT("'\n") ); } wxStringClientData *obj = ((wxStringClientData *)event.GetClientObject()); m_text->AppendText( wxT("ListBox event client data string is: '") ); if (obj) // BC++ doesn't like use of '? .. : .. ' in this context m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); m_text->AppendText( wxT("ListBox control client data string is: '") ); obj = (wxStringClientData *)listbox->GetClientObject(event.GetInt()); if (obj) m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); } void MyPanel::OnListBoxDoubleClick( wxCommandEvent &event ) { m_text->AppendText( wxT("ListBox double click string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnListBoxButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_LISTBOX_ENABLE: { m_text->AppendText(wxT("Checkbox clicked.\n")); #if wxUSE_TOOLTIPS wxCheckBox *cb = (wxCheckBox*)event.GetEventObject(); if (event.GetInt()) cb->SetToolTip( wxT("Click to enable listbox") ); else cb->SetToolTip( wxT("Click to disable listbox") ); #endif // wxUSE_TOOLTIPS m_listbox->Enable( event.GetInt() == 0 ); m_lbSelectThis->Enable( event.GetInt() == 0 ); m_lbSelectNum->Enable( event.GetInt() == 0 ); m_listboxSorted->Enable( event.GetInt() == 0 ); FindWindow(ID_CHANGE_COLOUR)->Enable( event.GetInt() == 0 ); break; } case ID_LISTBOX_SEL_NUM: { if (m_listbox->GetCount() > 2) m_listbox->SetSelection( 2 ); if (m_listboxSorted->GetCount() > 2) m_listboxSorted->SetSelection( 2 ); m_lbSelectThis->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_SEL_STR: { if (m_listbox->FindString(wxT("This")) != wxNOT_FOUND) m_listbox->SetStringSelection( wxT("This") ); if (m_listboxSorted->FindString(wxT("This")) != wxNOT_FOUND) m_listboxSorted->SetStringSelection( wxT("This") ); m_lbSelectNum->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_CLEAR: { m_listbox->Clear(); m_listboxSorted->Clear(); break; } case ID_LISTBOX_APPEND: { m_listbox->Append( wxT("Hi kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!") ); m_listboxSorted->Append( wxT("Hi hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!") ); break; } case ID_LISTBOX_DELETE: { int idx; idx = m_listbox->GetSelection(); if ( idx != wxNOT_FOUND ) m_listbox->Delete( idx ); idx = m_listboxSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_listboxSorted->Delete( idx ); break; } case ID_LISTBOX_FONT: { m_listbox->SetFont( *wxITALIC_FONT ); m_listboxSorted->SetFont( *wxITALIC_FONT ); m_checkbox->SetFont( *wxITALIC_FONT ); break; } } } #if wxUSE_CHOICE static wxString GetDataString(wxClientData *data) { return data ? static_cast<wxStringClientData *>(data)->GetData() : wxString("none"); } void MyPanel::OnChoice( wxCommandEvent &event ) { wxChoice *choice = event.GetId() == ID_CHOICE ? m_choice : m_choiceSorted; const int sel = choice->GetSelection(); wxClientData *dataEvt = event.GetClientObject(), *dataCtrl = choice->GetClientObject(sel); wxLogMessage(wxT("EVT_CHOICE: item %d/%d (event/control), ") wxT("string \"%s\"/\"%s\", ") wxT("data \"%s\"/\"%s\""), (int)event.GetInt(), sel, event.GetString(), choice->GetStringSelection(), GetDataString(dataEvt), GetDataString(dataCtrl)); } void MyPanel::OnChoiceButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_CHOICE_ENABLE: { m_choice->Enable( event.GetInt() == 0 ); m_choiceSorted->Enable( event.GetInt() == 0 ); break; } case ID_CHOICE_SEL_NUM: { m_choice->SetSelection( 2 ); m_choiceSorted->SetSelection( 2 ); break; } case ID_CHOICE_SEL_STR: { m_choice->SetStringSelection( wxT("This") ); m_choiceSorted->SetStringSelection( wxT("This") ); break; } case ID_CHOICE_CLEAR: { m_choice->Clear(); m_choiceSorted->Clear(); break; } case ID_CHOICE_APPEND: { m_choice->Append( wxT("Hi!") ); m_choiceSorted->Append( wxT("Hi!") ); break; } case ID_CHOICE_DELETE: { int idx = m_choice->GetSelection(); if ( idx != wxNOT_FOUND ) m_choice->Delete( idx ); idx = m_choiceSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_choiceSorted->Delete( idx ); break; } case ID_CHOICE_FONT: { m_choice->SetFont( *wxITALIC_FONT ); m_choiceSorted->SetFont( *wxITALIC_FONT ); break; } } } #endif // wxUSE_CHOICE void MyPanel::OnCombo( wxCommandEvent &event ) { if (!m_combo) return; wxLogMessage(wxT("EVT_COMBOBOX: item %d/%d (event/control), string \"%s\"/\"%s\""), (int)event.GetInt(), m_combo->GetSelection(), event.GetString().c_str(), m_combo->GetStringSelection().c_str()); } void MyPanel::OnComboTextChanged(wxCommandEvent& event) { if (m_combo) { wxLogMessage(wxT("EVT_TEXT for the combobox: \"%s\" (event) or \"%s\" (control)."), event.GetString().c_str(), m_combo->GetValue().c_str()); } } void MyPanel::OnComboTextEnter(wxCommandEvent& WXUNUSED(event)) { if (m_combo) { wxLogMessage(wxT("Enter pressed in the combobox: value is '%s'."), m_combo->GetValue().c_str()); } } void MyPanel::OnComboButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_COMBO_ENABLE: { m_combo->Enable( event.GetInt() == 0 ); break; } case ID_COMBO_SEL_NUM: { m_combo->SetSelection( 2 ); break; } case ID_COMBO_SEL_STR: { m_combo->SetStringSelection( wxT("This") ); break; } case ID_COMBO_CLEAR: { m_combo->Clear(); break; } case ID_COMBO_APPEND: { m_combo->Append( wxT("Hi!") ); break; } case ID_COMBO_DELETE: { int idx = m_combo->GetSelection(); m_combo->Delete( idx ); break; } case ID_COMBO_FONT: { m_combo->SetFont( *wxITALIC_FONT ); break; } case ID_COMBO_SET_TEXT: { m_combo->SetString( 2, wxT("Hi!") ); break; } } } void MyPanel::OnRadio( wxCommandEvent &event ) { m_text->AppendText( wxT("RadioBox selection string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnRadioButton1( wxCommandEvent & WXUNUSED(event) ) { wxMessageBox(wxT("First wxRadioButton selected."), wxT("wxControl sample")); } void MyPanel::OnRadioButton2( wxCommandEvent & WXUNUSED(event) ) { m_text->AppendText(wxT("Second wxRadioButton selected.\n")); } void MyPanel::OnRadioButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_RADIOBOX_ENABLE: m_radio->Enable( event.GetInt() == 0 ); break; case ID_RADIOBOX_SEL_NUM: m_radio->SetSelection( 2 ); break; case ID_RADIOBOX_SEL_STR: m_radio->SetStringSelection( wxT("This") ); break; case ID_RADIOBOX_FONT: m_radio->SetFont( *wxITALIC_FONT ); break; } } void MyPanel::OnSetFont( wxCommandEvent &WXUNUSED(event) ) { m_fontButton->SetFont( *wxITALIC_FONT ); m_text->SetFont( *wxITALIC_FONT ); } void MyPanel::OnUpdateLabel( wxCommandEvent &event ) { m_label->SetLabel(event.GetInt() ? wxT("Very very very very very long text.") : wxT("Shorter text.")); } #if wxUSE_SLIDER void MyPanel::OnSliderUpdate( wxCommandEvent &WXUNUSED(event) ) { #if wxUSE_GAUGE m_gauge->SetValue( m_slider->GetValue() ); m_gaugeVert->SetValue( m_slider->GetValue() / 2 ); #endif // wxUSE_GAUGE } #endif // wxUSE_SLIDER #if wxUSE_SPINCTRL void MyPanel::OnSpinCtrlText(wxCommandEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl text changed: now %d (from event: %s)\n"), m_spinctrl->GetValue(), event.GetString().c_str() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrl(wxSpinEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl changed: now %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrlUp(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin up: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } void MyPanel::OnSpinCtrlDown(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin down: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN void MyPanel::OnSpinUp( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control up: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() > 17 ) { value += wxT("Preventing the spin button from going above 17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinDown( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control down: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() < -17 ) { value += wxT("Preventing the spin button from going below -17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinUpdate( wxSpinEvent &event ) { wxString value; value.Printf( wxT("%d"), event.GetPosition() ); m_spintext->SetValue( value ); value.Printf( wxT("Spin control range: (%d, %d), current = %d\n"), m_spinbutton->GetMin(), m_spinbutton->GetMax(), m_spinbutton->GetValue()); m_text->AppendText(value); } void MyPanel::OnNewText( wxCommandEvent& /* event */) { m_nonWrappingText->SetLabel( wxT("This text is short\nbut still spans\nover three lines.") ); m_wrappingText->SetLabel( wxT("This text is short but will still be wrapped if it is too long.") ); m_wrappingText->GetParent()->Layout(); } #if wxUSE_PROGRESSDLG void MyPanel::OnUpdateShowProgress( wxUpdateUIEvent& event ) { event.Enable( m_spinbutton->GetValue() > 0 ); } void MyPanel::OnShowProgress( wxCommandEvent& WXUNUSED(event) ) { int max = m_spinbutton->GetValue(); if ( max <= 0 ) { wxLogError(wxT("You must set positive range!")); return; } wxProgressDialog dialog(wxT("Progress dialog example"), wxT("An informative message"), max, // range this, // parent wxPD_CAN_ABORT | wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME); bool cont = true; for ( int i = 0; i <= max && cont; i++ ) { wxSleep(1); if ( i == max ) { cont = dialog.Update(i, wxT("That's all, folks!")); } else if ( i == max / 2 ) { cont = dialog.Update(i, wxT("Only a half left (very long message)!")); } else { cont = dialog.Update(i); } } if ( !cont ) { *m_text << wxT("Progress dialog aborted!\n"); } else { *m_text << wxT("Countdown from ") << max << wxT(" finished.\n"); } } #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void MyPanel::OnSizerCheck( wxCommandEvent &event) { switch (event.GetId ()) { case ID_SIZER_CHECK1: m_buttonSizer->Show (m_sizerBtn1, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK2: m_buttonSizer->Show (m_sizerBtn2, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK3: m_buttonSizer->Show (m_sizerBtn3, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK4: m_buttonSizer->Show (m_sizerBtn4, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK14: m_hsizer->Show (m_buttonSizer, event.IsChecked ()); m_hsizer->Layout (); break; case ID_SIZER_CHECKBIG: m_hsizer->Show (m_bigBtn, event.IsChecked ()); m_hsizer->Layout (); break; } } MyPanel::~MyPanel() { //wxLog::RemoveTraceMask(wxT("focus")); delete wxLog::SetActiveTarget(m_logTargetOld); delete m_book->GetImageList(); } //---------------------------------------------------------------------- // MyFrame //---------------------------------------------------------------------- wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(CONTROLS_QUIT, MyFrame::OnQuit) EVT_MENU(CONTROLS_ABOUT, MyFrame::OnAbout) EVT_MENU(CONTROLS_CLEAR_LOG, MyFrame::OnClearLog) #if wxUSE_TOOLTIPS EVT_MENU(CONTROLS_SET_TOOLTIP_DELAY, MyFrame::OnSetTooltipDelay) EVT_MENU(CONTROLS_ENABLE_TOOLTIPS, MyFrame::OnToggleTooltips) #ifdef __WXMSW__ EVT_MENU(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, MyFrame::OnSetMaxTooltipWidth) #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS EVT_MENU(CONTROLS_ENABLE_ALL, MyFrame::OnEnableAll) EVT_MENU(CONTROLS_HIDE_ALL, MyFrame::OnHideAll) EVT_MENU(CONTROLS_HIDE_LIST, MyFrame::OnHideList) EVT_MENU(CONTROLS_CONTEXT_HELP, MyFrame::OnContextHelp) EVT_ICONIZE(MyFrame::OnIconized) EVT_MAXIMIZE(MyFrame::OnMaximized) EVT_SIZE(MyFrame::OnSize) EVT_MOVE(MyFrame::OnMove) EVT_IDLE(MyFrame::OnIdle) wxEND_EVENT_TABLE() MyFrame::MyFrame(const wxChar *title, int x, int y) : wxFrame(NULL, wxID_ANY, title, wxPoint(x, y), wxSize(700, 450)) { SetHelpText( wxT("Controls sample demonstrating various widgets") ); // Give it an icon // The wxICON() macros loads an icon from a resource under Windows // and uses an #included XPM image under GTK+ and Motif SetIcon( wxICON(sample) ); wxMenu *file_menu = new wxMenu; file_menu->Append(CONTROLS_CLEAR_LOG, wxT("&Clear log\tCtrl-L")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_ABOUT, wxT("&About\tF1")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit controls sample")); wxMenuBar *menu_bar = new wxMenuBar; menu_bar->Append(file_menu, wxT("&File")); #if wxUSE_TOOLTIPS wxMenu *tooltip_menu = new wxMenu; tooltip_menu->Append(CONTROLS_SET_TOOLTIP_DELAY, wxT("Set &delay\tCtrl-D")); tooltip_menu->AppendSeparator(); tooltip_menu->Append(CONTROLS_ENABLE_TOOLTIPS, wxT("&Toggle tooltips\tCtrl-T"), wxT("enable/disable tooltips"), true); tooltip_menu->Check(CONTROLS_ENABLE_TOOLTIPS, true); #ifdef __WXMSW__ tooltip_menu->Append(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, "Set maximal &width"); #endif // __WXMSW__ menu_bar->Append(tooltip_menu, wxT("&Tooltips")); #endif // wxUSE_TOOLTIPS wxMenu *panel_menu = new wxMenu; panel_menu->Append(CONTROLS_ENABLE_ALL, wxT("&Disable all\tCtrl-E"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_HIDE_ALL, wxT("&Hide all\tCtrl-I"), wxT("Show/hide thoe whole panel controls"), true); panel_menu->Append(CONTROLS_HIDE_LIST, wxT("Hide &list ctrl\tCtrl-S"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_CONTEXT_HELP, wxT("&Context help...\tCtrl-H"), wxT("Get context help for a control")); menu_bar->Append(panel_menu, wxT("&Panel")); SetMenuBar(menu_bar); #if wxUSE_STATUSBAR CreateStatusBar(2); #endif // wxUSE_STATUSBAR m_panel = new MyPanel( this, 10, 10, 300, 100 ); } void MyFrame::OnQuit (wxCommandEvent& WXUNUSED(event) ) { Close(true); } void MyFrame::OnAbout( wxCommandEvent& WXUNUSED(event) ) { wxBusyCursor bc; wxMessageDialog dialog(this, wxT("This is a control sample"), wxT("About Controls"), wxOK ); dialog.ShowModal(); } void MyFrame::OnClearLog(wxCommandEvent& WXUNUSED(event)) { m_panel->m_text->Clear(); } #if wxUSE_TOOLTIPS void MyFrame::OnSetTooltipDelay(wxCommandEvent& WXUNUSED(event)) { static long s_delay = 5000; wxString delay; delay.Printf( wxT("%ld"), s_delay); delay = wxGetTextFromUser(wxT("Enter delay (in milliseconds)"), wxT("Set tooltip delay"), delay, this); if ( !delay ) return; // cancelled wxSscanf(delay, wxT("%ld"), &s_delay); wxToolTip::SetDelay(s_delay); wxLogStatus(this, wxT("Tooltip delay set to %ld milliseconds"), s_delay); } void MyFrame::OnToggleTooltips(wxCommandEvent& WXUNUSED(event)) { static bool s_enabled = true; s_enabled = !s_enabled; wxToolTip::Enable(s_enabled); wxLogStatus(this, wxT("Tooltips %sabled"), s_enabled ? wxT("en") : wxT("dis") ); } #ifdef __WXMSW__ void MyFrame::OnSetMaxTooltipWidth(wxCommandEvent& WXUNUSED(event)) { static int s_maxWidth = 0; wxNumberEntryDialog dlg ( this, "Change maximal tooltip width", "&Width in pixels:", GetTitle(), s_maxWidth, -1, 600 ); if ( dlg.ShowModal() == wxID_CANCEL ) return; s_maxWidth = dlg.GetValue(); wxToolTip::SetMaxWidth(s_maxWidth); // we need to set the tooltip again to test the new width m_panel->SetAllToolTips(); } #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void MyFrame::OnEnableAll(wxCommandEvent& WXUNUSED(event)) { static bool s_enable = true; s_enable = !s_enable; m_panel->Enable(s_enable); static bool s_enableCheckbox = true; if ( !s_enable ) { // this is a test for correct behaviour of either enabling or disabling // a child when its parent is disabled: the checkbox should have the // correct state when the parent is enabled back m_panel->m_checkbox->Enable(s_enableCheckbox); s_enableCheckbox = !s_enableCheckbox; } } void MyFrame::OnHideAll(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->Show(s_show); } void MyFrame::OnHideList(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->m_listbox->Show(s_show); } void MyFrame::OnContextHelp(wxCommandEvent& WXUNUSED(event)) { // starts a local event loop wxContextHelp chelp(this); } void MyFrame::OnMove( wxMoveEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(event.GetPosition(), GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIconized( wxIconizeEvent& event ) { wxLogMessage(wxT("Frame %s"), event.IsIconized() ? wxT("iconized") : wxT("restored")); event.Skip(); } void MyFrame::OnMaximized( wxMaximizeEvent& WXUNUSED(event) ) { wxLogMessage(wxT("Frame maximized")); } void MyFrame::OnSize( wxSizeEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(GetPosition(), event.GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIdle( wxIdleEvent& WXUNUSED(event) ) { // track the window which has the focus in the status bar static wxWindow *s_windowFocus = NULL; wxWindow *focus = wxWindow::FindFocus(); if ( focus != s_windowFocus ) { s_windowFocus = focus; wxString msg; if ( focus ) { msg.Printf( "Focus: %s" #ifdef __WXMSW__ ", HWND = %08x" #endif , s_windowFocus->GetName().c_str() #ifdef __WXMSW__ , (unsigned)wxPtrToUInt(s_windowFocus->GetHWND()) #endif ); } else { msg = wxT("No focus"); } #if wxUSE_STATUSBAR SetStatusText(msg); #endif // wxUSE_STATUSBAR } } void MyComboBox::OnChar(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnChar")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyDown(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyDown")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyUp(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyUp")); event.Skip(); } static void SetListboxClientData(const wxChar *name, wxListBox *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #endif // wxUSE_CHOICE
// // Created by xjdkc on 19-3-14. // #include <iostream> #include <algorithm> using namespace std; const int N = 1006; int f[N]; int main() { int n,ans=0; cin>>n; for (int i=0;i<n;i++) cin>>f[i]; for (int i=1;i<n-1;i++) { if (f[i]>f[i-1]&&f[i]>f[i+1]||f[i]<f[i-1]&&f[i]<f[i+1]) ans++; } cout<<ans<<endl; }
/* Qdiffle MIT License Copyright (c) 2016 Barry DeZonia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * floor_function.hpp * * Created on: Dec 8, 2015 * Author: bdezonia */ #ifndef SRC_FLOOR_FUNCTION_HPP_ #define SRC_FLOOR_FUNCTION_HPP_ #include "point_function.hpp" class FloorFunction : public PointFunction { public: FloorFunction(const std::shared_ptr<PointFunction>& other); ~FloorFunction(); double evaluate(const size_t dim, const double* point) const; bool acceptsDimensionality(const size_t d) const; private: std::shared_ptr<PointFunction> f; }; #endif /* SRC_FLOOR_FUNCTION_HPP_ */
/* projection scale factors */ #define PJ_LIB__ #include "proj.h" #include "proj_internal.h" #include <math.h> #include <errno.h> #ifndef DEFAULT_H #define DEFAULT_H 1e-5 /* radian default for numeric h */ #endif #define EPS 1.0e-12 int pj_factors(PJ_LP lp, const PJ *P, double h, struct FACTORS *fac) { double cosphi, t, n, r; int err; PJ_COORD coo = {{0, 0, 0, 0}}; coo.lp = lp; /* Failing the 3 initial checks will most likely be due to */ /* earlier errors, so we leave errno alone */ if (nullptr==fac) return 1; if (nullptr==P) return 1; if (HUGE_VAL==lp.lam) return 1; /* But from here, we're ready to make our own mistakes */ err = proj_errno_reset (P); /* Indicate that all factors are numerical approximations */ fac->code = 0; /* Check for latitude or longitude overange */ if ((fabs (lp.phi)-M_HALFPI) > EPS || fabs (lp.lam) > 10.) { proj_errno_set (P, PJD_ERR_LAT_OR_LON_EXCEED_LIMIT); return 1; } /* Set a reasonable step size for the numerical derivatives */ h = fabs (h); if (h < EPS) h = DEFAULT_H; /* If input latitudes are geocentric, convert to geographic */ if (P->geoc) lp = pj_geocentric_latitude (P, PJ_INV, coo).lp; /* If latitude + one step overshoots the pole, move it slightly inside, */ /* so the numerical derivative still exists */ if (fabs (lp.phi) > (M_HALFPI - h)) lp.phi = lp.phi < 0. ? -(M_HALFPI-h) : (M_HALFPI-h); /* Longitudinal distance from central meridian */ lp.lam -= P->lam0; if (!P->over) lp.lam = adjlon(lp.lam); /* Derivatives */ if (pj_deriv (lp, h, P, &(fac->der))) { proj_errno_set (P, PJD_ERR_LAT_OR_LON_EXCEED_LIMIT); return 1; } /* Scale factors */ cosphi = cos (lp.phi); fac->h = hypot (fac->der.x_p, fac->der.y_p); fac->k = hypot (fac->der.x_l, fac->der.y_l) / cosphi; if (P->es != 0.0) { t = sin(lp.phi); t = 1. - P->es * t * t; n = sqrt(t); fac->h *= t * n / P->one_es; fac->k *= n; r = t * t / P->one_es; } else r = 1.; /* Convergence */ fac->conv = -atan2 (fac->der.x_p, fac->der.y_p); /* Areal scale factor */ fac->s = (fac->der.y_p * fac->der.x_l - fac->der.x_p * fac->der.y_l) * r / cosphi; /* Meridian-parallel angle (theta prime) */ fac->thetap = aasin(P->ctx,fac->s / (fac->h * fac->k)); /* Tissot ellipse axis */ t = fac->k * fac->k + fac->h * fac->h; fac->a = sqrt(t + 2. * fac->s); t = t - 2. * fac->s; t = t > 0? sqrt(t): 0; fac->b = 0.5 * (fac->a - t); fac->a = 0.5 * (fac->a + t); /* Angular distortion */ fac->omega = 2. * aasin(P->ctx, (fac->a - fac->b) / (fac->a + fac->b) ); proj_errno_restore (P, err); return 0; }
/** * expection handling. * * @author Malik Umer Farooq <lablnet01@gmail.com> * @author-profile https://www.facebook.com/malikumerfarooq01/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT */ #include <map> #include "../str/str.h" namespace Lablnet { //Start namespace /** * Return the msgs. * * @since 1.0.0 * * @return array */ std::map<std::string,std::string> create_expection_errors() { std::map<std::string,std::string> e; e["fileNotExist"] = "Sorry, this file :r is not exists"; e["keyNotFound"] = "Sorry, there is no msg found regard this key :r"; return e; } /** * Store the assos array of expections errors. * * @since 1.0.0 * * @var array */ std::map<std::string,std::string> e = create_expection_errors(); /** * Get an msg from expection. * * @param (string) key valid key * * @since 1.0.0 * * @return string */ std::string getMsg(std::string key, std::string replacement = "") { if (e.count(key) == 1) return Lablnet::replace(e[key],":r",replacement); else return Lablnet::replace(e["keyNotFound"],":r",key); } } //End namespace Lablnet
#pragma once #include <mbgl/map/camera.hpp> #include <mbgl/renderer/renderer_frontend.hpp> #include <mbgl/gl/headless_backend.hpp> #include <mbgl/util/async_task.hpp> #include <mbgl/util/optional.hpp> #include <memory> namespace mbgl { class Scheduler; class Renderer; class Map; class TransformState; namespace gfx { class RendererBackend; } // namespace gfx class HeadlessFrontend : public RendererFrontend { public: HeadlessFrontend(float pixelRatio_, Scheduler&, const optional<std::string> programCacheDir = {}, gfx::ContextMode mode = gfx::ContextMode::Unique, const optional<std::string> localFontFamily = {}); HeadlessFrontend(Size, float pixelRatio_, Scheduler&, const optional<std::string> programCacheDir = {}, gfx::ContextMode mode = gfx::ContextMode::Unique, const optional<std::string> localFontFamily = {}); ~HeadlessFrontend() override; void reset() override; void update(std::shared_ptr<UpdateParameters>) override; void setObserver(RendererObserver&) override; Size getSize() const; void setSize(Size); Renderer* getRenderer(); gfx::RendererBackend* getBackend(); CameraOptions getCameraOptions(); bool hasImage(const std::string&); bool hasLayer(const std::string&); bool hasSource(const std::string&); ScreenCoordinate pixelForLatLng(const LatLng&); LatLng latLngForPixel(const ScreenCoordinate&); PremultipliedImage readStillImage(); PremultipliedImage render(Map&); optional<TransformState> getTransformState() const; private: Size size; float pixelRatio; gl::HeadlessBackend backend; util::AsyncTask asyncInvalidate; std::unique_ptr<Renderer> renderer; std::shared_ptr<UpdateParameters> updateParameters; }; } // namespace mbgl
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSE4_2_GSL_SF_GAMMA_INC_Q_HPP_INCLUDED #define NT2_TOOLBOX_GSL_SPECFUN_FUNCTION_SIMD_SSE_SSE4_2_GSL_SF_GAMMA_INC_Q_HPP_INCLUDED #include <nt2/toolbox/gsl_specfun/function/simd/sse/sse4_1/gsl_sf_gamma_inc_Q.hpp> #endif
#include "headers.hxx" #ifndef X_IMG_HXX_ #define X_IMG_HXX_ #include "img.hxx" #endif extern void x_DitherRow (BYTE HUGEP * from, BYTE HUGEP * to, PALETTEENTRY *pcolors, long row, long ncols, int transparent); //+------------------------------------------------------------------------ // Tags //------------------------------------------------------------------------- PerfDbgExtern(tagImgTaskIO); DeclareTag(tagImgTaskGif, "Dwn", "Img: Trace Gif optimizations") PerfDbgTag(tagImgTaskGifAbort, "Dwn", "Img: Zap invalid Gif scanlines") MtDefine(CImgTaskGif, Dwn, "CImgTaskGif") MtDefine(CImgTaskGifStack, CImgTaskGif, "CImgTaskGif Decode Stack") MtDefine(CImgTaskGifTable0, CImgTaskGif, "CImgTaskGif Decode Table 0") MtDefine(CImgTaskGifTable1, CImgTaskGif, "CImgTaskGif Decode Table 1") MtDefine(CImgTaskGifBits, CImgTaskGif, "CImgTaskGif Decode Image") MtDefine(CImgTaskGifFrame, CImgInfo, "CImgTaskGif GIFFRAME") #define XX_DMsg(x, y) #define PROG_INTERVAL 0x3 #define NUM_IMPORTANT_COLORS 256 #define MAXCOLORMAPSIZE 256 #define TRUE 1 #define FALSE 0 #define MAX_LWZ_BITS 12 #define INTERLACE 0x40 #define LOCALCOLORMAP 0x80 #define BitSet(byte, bit) (((byte) & (bit)) == (bit)) #define LM_to_uint(a,b) ((((unsigned int) b)<<8)|((unsigned int)a)) #define dwIndefiniteGIFThreshold 300 // 300 seconds == 5 minutes // If the GIF runs longer than // this, we will assume the author // intended an indefinite run. #define dwMaxGIFBits 13107200 // keep corrupted GIFs from causing // us to allocate _too_ big a buffer. // This one is 1280 X 1024 X 10. typedef struct _GIFSCREEN { unsigned long Width; unsigned long Height; unsigned long BitPixel; unsigned long ColorResolution; unsigned long Background; unsigned long AspectRatio; } GIFSCREEN; typedef struct _GIF89 { long transparent; long delayTime; long inputFlag; long disposal; } GIF89; #define MAX_STACK_SIZE ((1 << (MAX_LWZ_BITS)) * 2) #define MAX_TABLE_SIZE (1 << MAX_LWZ_BITS) typedef struct _GIFINFO { unsigned char *src; GIF89 Gif89; long lGifLoc; long ZeroDataBlock; /* ** Pulled out of nextCode */ long curbit, lastbit, get_done; long last_byte; long return_clear; /* ** Out of nextLWZ */ unsigned short *pstack, *sp; long stacksize; long code_size, set_code_size; long max_code, max_code_size; long clear_code, end_code; /* * Were statics in procedures */ unsigned char buf[280]; unsigned short *table[2]; long tablesize; long firstcode, oldcode; } GIFINFO; class CImgTaskGif : public CImgTask { typedef CImgTask super; public: DECLARE_MEMCLEAR_NEW_DELETE(Mt(CImgTaskGif)) CImgTaskGif(); virtual ~CImgTaskGif(); // CImgTask methods virtual void Decode(BOOL *pfNonProgressive); // CImgTaskGif methods void OnProg(BOOL fLast, ULONG ulCoversImg); BOOL Read(void * pv, ULONG cb); BOOL ReadByte(BYTE * pb); void ReadGIFMaster(); BOOL ReadColorMap(long number, PALETTEENTRY * ppe); long DoExtension(long label); long GetDataBlock(unsigned char *buf); BOOL initLWZ(long input_code_size); long nextCode(long code_size); unsigned short * growStack(); BOOL growTables(); long readLWZ(); long nextLWZ(); BOOL ReadScanline(unsigned char *pb, int cb); void CalculateUpdateRect(int logicalRow0, int logicalRowN, BOOL *pfInvalidateAll, LONG *pyBottom); void ProgressiveDithering(int logicalFill, int logicalRow); typedef BYTE HUGEP * HLPBYTE; CImgBitsDIB *ReadImage(long len, long height, BOOL fInterlace, BOOL fGIFFrame, int cpeColors, PALETTEENTRY * ppeColors, HLPBYTE * ppbBits, LONG lTrans); virtual void BltDib(HDC hdc, RECT * prcDst, RECT * prcSrc, DWORD dwRop, DWORD dwFlags); // Data members LONG _cbBuf; BYTE * _pbBuf; BYTE _abBuf[512]; BOOL _fEof; BOOL _fMustBeTransparent; BOOL _fDither; DWORD _cbImage; BOOL _fInterleaved; LONG _yLogRow; LONG _yLogRowDraw; LONG _yDithRow; void * _pvDithData; GIFINFO _gifinfo; PALETTEENTRY _apeFirst[256]; int _mapConstrained[256]; HLPBYTE _pbSrcAlloc; HLPBYTE _pbSrc; HLPBYTE _pbDst; }; CImgTaskGif::CImgTaskGif() { _yLogRow = -1; _yLogRowDraw = -1; } CImgTaskGif::~CImgTaskGif() { MemFree(_pbSrcAlloc); MemFree(_pvDithData); MemFree(_gifinfo.pstack); MemFree(_gifinfo.table[0]); MemFree(_gifinfo.table[1]); } void CImgTaskGif::Decode(BOOL *pfNonProgressive) { ReadGIFMaster(); if (_pImgBits && _gad.pgf && _yLogRowDraw >= 0) { if (_yLogRowDraw + 1 >= _gad.pgf->height) { _ySrcBot = -1; } else if (_fInterleaved) { _ySrcBot = (long)min((long)((_yLogRowDraw + 1) * 8), (long)_gad.pgf->height); if (_ySrcBot == _gad.pgf->height) _ySrcBot = -1; } else { _ySrcBot = _yLogRowDraw + 1; } _gad.pgf->pibd->SetValidLines(_ySrcBot); } } BOOL IsGifHdr(BYTE * pb) { return(pb[0] == 'G' && pb[1] == 'I' && pb[2] == 'F' && pb[3] == '8' && (pb[4] == '7' || pb[4] == '9') && pb[5] == 'a'); } CImgTask * NewImgTaskGif() { return(new CImgTaskGif); } BOOL CImgTaskGif::Read(void * pv, ULONG cb) { PerfDbgLog1(tagImgTaskIO, this, "+CImgTaskGif::Read (req %ld)", cb); LONG cbReq = (LONG)cb, cbGot, cbTot = 0; while (cbReq > 0) { cbGot = cbReq < _cbBuf ? cbReq : _cbBuf; if (cbGot > 0) { memcpy(pv, _pbBuf, cbGot); _pbBuf += cbGot; _cbBuf -= cbGot; cbTot += cbGot; if (cbTot == (LONG)cb) break; } if (_pDwnBindData->IsEof() || _fTerminate) break; if (cbGot > 0) { pv = (BYTE *)pv + cbGot; cbReq -= cbGot; } cbGot = 0; super::Read(_abBuf, ARRAY_SIZE(_abBuf), (ULONG *)&cbGot, cbReq); _pbBuf = _abBuf; _cbBuf = cbGot; } PerfDbgLog3(tagImgTaskIO, this, "-CImgTaskGif::Read (got %ld) %c%c", cbTot, _pDwnBindData->IsEof() ? 'E' : ' ', cbTot > 0 ? 'T' : 'F'); return(cbTot > 0); } inline BOOL CImgTaskGif::ReadByte(BYTE * pb) { if (--_cbBuf >= 0) { *pb = *_pbBuf++; return(TRUE); } else { return(Read(pb, 1)); } } void CImgTaskGif::ReadGIFMaster() { unsigned char buf[16]; unsigned char c; long useGlobalColormap; long imageCount = 0; long imageNumber = 1; GIFSCREEN GifScreen; long bitPixel; GIFFRAME * pgfLast = NULL; GIFFRAME * pgfNew = NULL; HLPBYTE pbBits; PALETTEENTRY apeLocal[MAXCOLORMAPSIZE]; PALETTEENTRY * ppeColors; int cpeColors; CImgBitsDIB *pibd = NULL; _gifinfo.ZeroDataBlock = 0; /* * Initialize GIF89 extensions */ _gifinfo.Gif89.transparent = -1; _gifinfo.Gif89.delayTime = 5; _gifinfo.Gif89.inputFlag = -1; // initialize our animation fields _gad.dwGIFVer = dwGIFVerUnknown; if (!Read(buf, 6)) { XX_DMsg(DBG_IMAGE, ("GIF: error reading magic number\n")); goto exitPoint; } if (!IsGifHdr(buf)) goto exitPoint; _gad.dwGIFVer = (buf[4] == '7') ? dwGIFVer87a : dwGIFVer89a; if (!Read(buf, 7)) { XX_DMsg(DBG_IMAGE, ("GIF: failed to read screen descriptor\n")); goto exitPoint; } GifScreen.Width = LM_to_uint(buf[0], buf[1]); GifScreen.Height = LM_to_uint(buf[2], buf[3]); GifScreen.BitPixel = 2 << (buf[4] & 0x07); GifScreen.ColorResolution = (((buf[4] & 0x70) >> 3) + 1); GifScreen.Background = buf[5]; GifScreen.AspectRatio = buf[6]; if (BitSet(buf[4], LOCALCOLORMAP)) { /* Global Colormap */ if (!ReadColorMap(GifScreen.BitPixel, _ape)) { XX_DMsg(DBG_IMAGE, ("error reading global colormap\n")); goto exitPoint; } } if (GifScreen.AspectRatio != 0 && GifScreen.AspectRatio != 49) { float r; r = ((float) (GifScreen.AspectRatio) + (float) 15.0) / (float) 64.0; XX_DMsg(DBG_IMAGE, ("Warning: non-square pixels!\n")); } for (;; ) // our appetite now knows no bounds save termination or error { if (!ReadByte(&c)) { XX_DMsg(DBG_IMAGE, ("EOF / read error on image data\n")); goto exitPoint; } if (c == ';') { /* GIF terminator */ if (imageCount < imageNumber) { XX_DMsg(DBG_IMAGE, ("No images found in file\n")); goto exitPoint; } break; } if (c == '!') { /* Extension */ if (!ReadByte(&c)) { XX_DMsg(DBG_IMAGE, ("EOF / read error on extension function code\n")); goto exitPoint; } DoExtension(c); continue; } if (c != ',') { /* Not a valid start character */ break; } ++imageCount; if (!Read(buf, 9)) { XX_DMsg(DBG_IMAGE, ("couldn't read left/top/width/height\n")); goto exitPoint; } useGlobalColormap = !BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1 << ((buf[8] & 0x07) + 1); /* * We only want to set width and height for the imageNumber * we are requesting. */ if (imageCount == imageNumber) { // Replicate some of Netscape's special cases: // Don't use the logical screen if it's a GIF87a and the topLeft of the first image is at the origin. // Don't use the logical screen if the first image spills out of the logical screen. // These are artifacts of primitive authoring tools falling into the hands of hapless users. RECT rectImage; // rect defining bounds of GIF RECT rectLS; // rect defining bounds of GIF logical screen. RECT rectSect; // intersection of image an logical screen BOOL fNoSpill; // True if the image doesn't spill out of the logical screen BOOL fGoofy87a; // TRUE if its one of the 87a pathologies that Netscape special cases rectImage.left = LM_to_uint(buf[0], buf[1]); rectImage.top = LM_to_uint(buf[2], buf[3]); rectImage.right = rectImage.left + LM_to_uint(buf[4], buf[5]); rectImage.bottom = rectImage.top + LM_to_uint(buf[6], buf[7]); rectLS.left = rectLS.top = 0; rectLS.right = GifScreen.Width; rectLS.bottom = GifScreen.Height; IntersectRect( &rectSect, &rectImage, &rectLS ); fNoSpill = EqualRect( &rectImage, &rectSect ); fGoofy87a = FALSE; if (_gad.dwGIFVer == dwGIFVer87a) { // netscape ignores the logical screen if the image is flush against // either the upper left or lower right corner fGoofy87a = (rectImage.top == 0 && rectImage.left == 0) || (rectImage.bottom == rectLS.bottom && rectImage.right == rectLS.right); } if (!fGoofy87a && fNoSpill) { _xWid = GifScreen.Width; _yHei = GifScreen.Height; } else { // Something is amiss. Fall back to the image's dimensions. // If the sizes match, but the image is offset, or we're ignoring // the logical screen cuz it's a goofy 87a, then pull it back to // to the origin if ((LM_to_uint(buf[4], buf[5]) == GifScreen.Width && LM_to_uint(buf[6], buf[7]) == GifScreen.Height) || fGoofy87a) { buf[0] = buf[1] = 0; // left corner to zero buf[2] = buf[3] = 0; // top to zero. } _xWid = LM_to_uint(buf[4], buf[5]); _yHei = LM_to_uint(buf[6], buf[7]); } _lTrans = _gifinfo.Gif89.transparent; // Post WHKNOWN OnSize(_xWid, _yHei, _lTrans); } if (!useGlobalColormap) { if (!ReadColorMap(bitPixel, apeLocal)) { XX_DMsg(DBG_IMAGE, ("error reading local colormap\n")); goto exitPoint; } } // We allocate a frame record for each imag in the GIF stream, including // the first/primary image. pgfNew = (GIFFRAME *) MemAllocClear(Mt(CImgTaskGifFrame), sizeof(GIFFRAME)); if ( pgfNew == NULL ) { XX_DMsg(DBG_IMAGE, ("not enough memory for GIF frame\n")); goto exitPoint; } if ( _gifinfo.Gif89.delayTime != -1 ) { // we have a fresh control extension for this block // convert to milliseconds pgfNew->uiDelayTime = _gifinfo.Gif89.delayTime * 10; //REVIEW(seanf): crude hack to cope with 'degenerate animations' whose timing is set to some // small value becaue of the delays imposed by Netscape's animation process if ( pgfNew->uiDelayTime <= 50 ) // assume these small values imply Netscape encoding delay pgfNew->uiDelayTime = 100; // pick a larger value s.t. the frame will be visible pgfNew->bDisposalMethod = _gifinfo.Gif89.disposal; if (_gifinfo.Gif89.transparent != -1) pgfNew->bTransFlags |= TRANSF_TRANSPARENT; } else { // fake one up s.t. GIFs that rely solely on Netscape's delay to time their animations will play // The spec says that the scope of one of these blocks is the image after the block. // Netscape says 'until further notice'. So we play it their way up to a point. We // propagate the disposal method and transparency. Since Netscape doesn't honor the timing // we use our default timing for these images. pgfNew->uiDelayTime = 100; pgfNew->bDisposalMethod = _gifinfo.Gif89.disposal; } pgfNew->top = LM_to_uint(buf[2], buf[3]); // bounds relative to the GIF logical screen pgfNew->left = LM_to_uint(buf[0], buf[1]); pgfNew->width = LM_to_uint(buf[4], buf[5]); pgfNew->height = LM_to_uint(buf[6], buf[7]); if (_gifinfo.Gif89.transparent != -1) pgfNew->bTransFlags |= TRANSF_TRANSPARENT; // Images that are offset, or do not cover the full logical screen are 'transparent' in the // sense that they require us to matte the frame onto the background. if (!_gad.fHasTransparency) { if (pgfNew->top != 0 || pgfNew->left != 0 || (UINT)pgfNew->width != (UINT)GifScreen.Width || (UINT)pgfNew->height != (UINT)GifScreen.Height) _fMustBeTransparent = TRUE; if ((pgfNew->bTransFlags & TRANSF_TRANSPARENT) || _fMustBeTransparent) { _gad.fHasTransparency = TRUE; if (_lTrans == -1) { _lTrans = 0; OnTrans(_lTrans); } } } // We don't need to allocate a handle for the simple region case. // FrancisH says Windows is too much of a cheapskate to allow us the simplicity // of allocating the region once and modifying as needed. Well, okay, he didn't // put it that way... pgfNew->hrgnVis = NULL; pgfNew->bRgnKind = NULLREGION; if (!useGlobalColormap) { cpeColors = bitPixel; ppeColors = apeLocal; } else { cpeColors = GifScreen.BitPixel; ppeColors = _ape; } // First frame: must be able to progressively render, so stick it in _gad now. if (_gad.pgf == NULL) { _gad.pgf = pgfNew; // Remember the color table for the first frame so that // progressive dithering can be done on it. memcpy(_apeFirst, ppeColors, cpeColors * sizeof(PALETTEENTRY)); } pibd = ReadImage(LM_to_uint(buf[4], buf[5]), // width LM_to_uint(buf[6], buf[7]), // height BitSet(buf[8], INTERLACE), imageCount != imageNumber, cpeColors, ppeColors, &pbBits, _gifinfo.Gif89.transparent); if (pibd != NULL) { if (pgfLast != NULL) { // Set up pgfNew if not the first frame int transparent = (pgfNew->bTransFlags & TRANSF_TRANSPARENT) ? _gifinfo.Gif89.transparent : -1; _gad.fAnimated = TRUE; // say multi-image == animated #ifdef _MAC pibd->ComputeTransMask(0, pgfNew->height, transparent, transparent); #else if (_colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) // palettized, use DIB_PAL_COLORS { // This will also dither the bits to the screen palette if (x_Dither(pbBits, ppeColors, pgfNew->width, pgfNew->height, transparent)) goto exitPoint; pibd->ComputeTransMask(0, pgfNew->height, g_wIdxTrans, 255); } #endif pgfNew->pibd = pibd; pibd = NULL; pgfLast->pgfNext = pgfNew; OnAnim(); } else { // first frame: already been set up Assert(_gad.pgf == pgfNew); Assert(_gad.pgf->pibd == pibd); pibd = NULL; } pgfLast = pgfNew; pgfNew = NULL; } // make the _gifinfo.Gif89.delayTime stale, so we know if we got a new // GCE for the next image _gifinfo.Gif89.delayTime = -1; } if ( imageCount > imageNumber ) _gad.fAnimated = TRUE; // say multi-image == animated exitPoint: if (pibd) delete pibd; if (pgfNew && _gad.pgf != pgfNew) MemFree(pgfNew); return; } BOOL CImgTaskGif::ReadColorMap(long number, PALETTEENTRY * ppe) { if (!Read(ppe, number * 3)) return(FALSE); if (number) { #ifdef _MAC DWORD UNALIGNED * pdwSrc = (DWORD *)((BYTE *)ppe + (number - 1) * 3); DWORD * pdwDst = (DWORD *)&ppe[number - 1]; for (; number > 0; --number) { *pdwDst-- = (*pdwSrc & 0xFFFFFF00); pdwSrc = (DWORD *)((BYTE *)pdwSrc - 3); } #else #ifndef UNIX DWORD UNALIGNED * pdwSrc = (DWORD *)((BYTE *)ppe + (number - 1) * 3); DWORD * pdwDst = (DWORD *)&ppe[number - 1]; for (; number > 0; --number) { *pdwDst-- = (*pdwSrc & 0xFFFFFF); pdwSrc = (DWORD *)((BYTE *)pdwSrc - 3); } #else BYTE * pdwSrc = (BYTE *)ppe + (number - 1) * 3; DWORD * pdwDst = (DWORD *)&ppe[number - 1]; for (; number > 0; --number) { *pdwDst-- = ((((DWORD)pdwSrc[2] << 8) | pdwSrc[1]) << 8) | pdwSrc[0]; pdwSrc -= 3; } #endif #endif // _MAC } return(TRUE); } long CImgTaskGif::DoExtension(long label) { unsigned char buf[256]; int count; switch (label) { case 0x01: /* Plain Text Extension */ break; case 0xff: /* Application Extension */ // Is it the Netscape looping extension count = GetDataBlock((unsigned char *) buf); if (count >= 11) { char *szNSExt = "NETSCAPE2.0"; if ( memcmp( buf, szNSExt, strlen( szNSExt ) ) == 0 ) { // if it has their signature, get the data subblock with the iter count count = GetDataBlock((unsigned char *) buf); if ( count >= 3 ) { _gad.fLooped = TRUE; _gad.cLoops = (buf[2] << 8) | buf[1]; } } } while (GetDataBlock((unsigned char *) buf) > 0) ; return FALSE; break; case 0xfe: /* Comment Extension */ while (GetDataBlock((unsigned char *) buf) > 0) { XX_DMsg(DBG_IMAGE, ("GIF comment: %s\n", buf)); } return FALSE; case 0xf9: /* Graphic Control Extension */ count = GetDataBlock((unsigned char *) buf); if (count >= 3) { _gifinfo.Gif89.disposal = (buf[0] >> 2) & 0x7; _gifinfo.Gif89.inputFlag = (buf[0] >> 1) & 0x1; _gifinfo.Gif89.delayTime = LM_to_uint(buf[1], buf[2]); if ((buf[0] & 0x1) != 0) _gifinfo.Gif89.transparent = buf[3]; else _gifinfo.Gif89.transparent = -1; } while (GetDataBlock((unsigned char *) buf) > 0) ; return FALSE; default: break; } while (GetDataBlock((unsigned char *) buf) > 0) ; return FALSE; } long CImgTaskGif::GetDataBlock(unsigned char *buf) { unsigned char count; count = 0; if (!ReadByte(&count)) { return -1; } _gifinfo.ZeroDataBlock = count == 0; if ((count != 0) && (!Read(buf, count))) { return -1; } return ((long) count); } #define MIN_CODE_BITS 5 #define MIN_STACK_SIZE 64 #define MINIMUM_CODE_SIZE 2 BOOL CImgTaskGif::initLWZ(long input_code_size) { if (input_code_size < MINIMUM_CODE_SIZE) return FALSE; _gifinfo.set_code_size = input_code_size; _gifinfo.code_size = _gifinfo.set_code_size + 1; _gifinfo.clear_code = 1 << _gifinfo.set_code_size; _gifinfo.end_code = _gifinfo.clear_code + 1; _gifinfo.max_code_size = 2 * _gifinfo.clear_code; _gifinfo.max_code = _gifinfo.clear_code + 2; _gifinfo.curbit = _gifinfo.lastbit = 0; _gifinfo.last_byte = 2; _gifinfo.get_done = FALSE; _gifinfo.return_clear = TRUE; if(input_code_size >= MIN_CODE_BITS) _gifinfo.stacksize = ((1 << (input_code_size)) * 2); else _gifinfo.stacksize = MIN_STACK_SIZE; if ( _gifinfo.pstack != NULL ) MemFree( _gifinfo.pstack ); if ( _gifinfo.table[0] != NULL ) MemFree( _gifinfo.table[0] ); if ( _gifinfo.table[1] != NULL ) MemFree( _gifinfo.table[1] ); _gifinfo.table[0] = 0; _gifinfo.table[1] = 0; _gifinfo.pstack = 0; _gifinfo.pstack = (unsigned short *)MemAlloc(Mt(CImgTaskGifStack), (_gifinfo.stacksize)*sizeof(unsigned short)); if(_gifinfo.pstack == 0){ goto ErrorExit; } _gifinfo.sp = _gifinfo.pstack; // Initialize the two tables. _gifinfo.tablesize = (_gifinfo.max_code_size); _gifinfo.table[0] = (unsigned short *)MemAlloc(Mt(CImgTaskGifTable0), (_gifinfo.tablesize)*sizeof(unsigned short)); _gifinfo.table[1] = (unsigned short *)MemAlloc(Mt(CImgTaskGifTable1), (_gifinfo.tablesize)*sizeof(unsigned short)); if((_gifinfo.table[0] == 0) || (_gifinfo.table[1] == 0)){ Assert(0); goto ErrorExit; } return TRUE; ErrorExit: if(_gifinfo.pstack){ MemFree(_gifinfo.pstack); _gifinfo.pstack = 0; } if(_gifinfo.table[0]){ MemFree(_gifinfo.table[0]); _gifinfo.table[0] = 0; } if(_gifinfo.table[1]){ MemFree(_gifinfo.table[1]); _gifinfo.table[1] = 0; } return FALSE; } long CImgTaskGif::nextCode(long code_size) { static const long maskTbl[16] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, }; long i, j, ret, end; unsigned char *buf = &_gifinfo.buf[0]; if (_gifinfo.return_clear) { _gifinfo.return_clear = FALSE; return _gifinfo.clear_code; } end = _gifinfo.curbit + code_size; if (end >= _gifinfo.lastbit) { long count; if (_gifinfo.get_done) { return -1; } buf[0] = buf[_gifinfo.last_byte - 2]; buf[1] = buf[_gifinfo.last_byte - 1]; if ((count = GetDataBlock(&buf[2])) == 0) _gifinfo.get_done = TRUE; if (count < 0) { return -1; } _gifinfo.last_byte = 2 + count; _gifinfo.curbit = (_gifinfo.curbit - _gifinfo.lastbit) + 16; _gifinfo.lastbit = (2 + count) * 8; end = _gifinfo.curbit + code_size; // Okay, bug 30784 time. It's possible that we only got 1 // measly byte in the last data block. Rare, but it does happen. // In that case, the additional byte may still not supply us with // enough bits for the next code, so, as Mars Needs Women, IE // Needs Data. if (end >= _gifinfo.lastbit && !_gifinfo.get_done) { // protect ourselve from the ( theoretically impossible ) // case where between the last data block, the 2 bytes from // the block preceding that, and the potential 0xFF bytes in // the next block, we overflow the buffer. // Since count should always be 1, Assert(count == 1); // there should be enough room in the buffer, so long as someone // doesn't shrink it. if (count + 0x101 >= sizeof(_gifinfo.buf)) { Assert(FALSE); return -1; } if ((count = GetDataBlock(&buf[2 + count])) == 0) _gifinfo.get_done = TRUE; if (count < 0) { return -1; } _gifinfo.last_byte += count; _gifinfo.lastbit = _gifinfo.last_byte * 8; end = _gifinfo.curbit + code_size; } } j = end / 8; i = _gifinfo.curbit / 8; if (i == j) ret = buf[i]; else if (i + 1 == j) ret = buf[i] | (((long) buf[i + 1]) << 8); else ret = buf[i] | (((long) buf[i + 1]) << 8) | (((long) buf[i + 2]) << 16); ret = (ret >> (_gifinfo.curbit % 8)) & maskTbl[code_size]; _gifinfo.curbit += code_size; return ret; } // Grows the stack and returns the top of the stack. unsigned short * CImgTaskGif::growStack() { long index; unsigned short *lp; if (_gifinfo.stacksize >= MAX_STACK_SIZE) return 0; index = (_gifinfo.sp - _gifinfo.pstack); if (MemRealloc(Mt(CImgTaskGifStack), (void **)&_gifinfo.pstack, (_gifinfo.stacksize)*2*sizeof(unsigned short))) return 0; _gifinfo.sp = &(_gifinfo.pstack[index]); _gifinfo.stacksize = (_gifinfo.stacksize)*2; lp = &(_gifinfo.pstack[_gifinfo.stacksize]); return lp; } BOOL CImgTaskGif::growTables() { if (MemRealloc(Mt(CImgTaskGifTable0), (void **)&_gifinfo.table[0], (_gifinfo.max_code_size)*sizeof(unsigned short))) return FALSE; if (MemRealloc(Mt(CImgTaskGifTable1), (void **)&_gifinfo.table[1], (_gifinfo.max_code_size)*sizeof(unsigned short))) return FALSE; return TRUE; } inline long CImgTaskGif::readLWZ() { return((_gifinfo.sp > _gifinfo.pstack) ? *--(_gifinfo.sp) : nextLWZ()); } #define CODE_MASK 0xffff long CImgTaskGif::nextLWZ() { long code, incode; unsigned short usi; unsigned short *table0 = _gifinfo.table[0]; unsigned short *table1 = _gifinfo.table[1]; unsigned short *pstacktop = &(_gifinfo.pstack[_gifinfo.stacksize]); while ((code = nextCode(_gifinfo.code_size)) >= 0) { if (code == _gifinfo.clear_code) { /* corrupt GIFs can make this happen */ if (_gifinfo.clear_code >= (1 << MAX_LWZ_BITS)) { return -2; } _gifinfo.code_size = _gifinfo.set_code_size + 1; _gifinfo.max_code_size = 2 * _gifinfo.clear_code; _gifinfo.max_code = _gifinfo.clear_code + 2; if(!growTables()) return -2; table0 = _gifinfo.table[0]; table1 = _gifinfo.table[1]; _gifinfo.tablesize = _gifinfo.max_code_size; for (usi = 0; usi < _gifinfo.clear_code; ++usi) { table1[usi] = usi; } memset(table0,0,sizeof(unsigned short )*(_gifinfo.tablesize)); memset(&table1[_gifinfo.clear_code],0,sizeof(unsigned short)*((_gifinfo.tablesize)-_gifinfo.clear_code)); _gifinfo.sp = _gifinfo.pstack; do { _gifinfo.firstcode = _gifinfo.oldcode = nextCode(_gifinfo.code_size); } while (_gifinfo.firstcode == _gifinfo.clear_code); return _gifinfo.firstcode; } if (code == _gifinfo.end_code) { long count; unsigned char buf[260]; if (_gifinfo.ZeroDataBlock) { return -2; } while ((count = GetDataBlock(buf)) > 0) ; if (count != 0) return -2; } incode = code; if (code >= MAX_TABLE_SIZE) return -2; if (code >= _gifinfo.max_code) { if (_gifinfo.sp >= pstacktop){ pstacktop = growStack(); if(pstacktop == 0) return -2; } *(_gifinfo.sp)++ = (unsigned short)((CODE_MASK ) & (_gifinfo.firstcode)); code = _gifinfo.oldcode; } while (code >= _gifinfo.clear_code) { if (_gifinfo.sp >= pstacktop){ pstacktop = growStack(); if(pstacktop == 0) return -2; } *(_gifinfo.sp)++ = table1[code]; if (code == (long)(table0[code])) { return (code); } code = (long)(table0[code]); } if (_gifinfo.sp >= pstacktop){ pstacktop = growStack(); if(pstacktop == 0) return -2; } _gifinfo.firstcode = (long)table1[code]; *(_gifinfo.sp)++ = table1[code]; if ((code = _gifinfo.max_code) < (1 << MAX_LWZ_BITS)) { table0[code] = (_gifinfo.oldcode) & CODE_MASK; table1[code] = (_gifinfo.firstcode) & CODE_MASK; ++_gifinfo.max_code; if ((_gifinfo.max_code >= _gifinfo.max_code_size) && (_gifinfo.max_code_size < ((1 << MAX_LWZ_BITS)))) { _gifinfo.max_code_size *= 2; ++_gifinfo.code_size; if(!growTables()) return -2; table0 = _gifinfo.table[0]; table1 = _gifinfo.table[1]; // Tables have been reallocated to the correct size but initialization // still remains to be done. This initialization is different from // the first time initialization of these tables. memset(&(table0[_gifinfo.tablesize]),0, sizeof(unsigned short )*(_gifinfo.max_code_size - _gifinfo.tablesize)); memset(&(table1[_gifinfo.tablesize]),0, sizeof(unsigned short )*(_gifinfo.max_code_size - _gifinfo.tablesize)); _gifinfo.tablesize = (_gifinfo.max_code_size); } } _gifinfo.oldcode = incode; if (_gifinfo.sp > _gifinfo.pstack) return ((long)(*--(_gifinfo.sp))); } return code; } void CImgTaskGif::OnProg(BOOL fLast, ULONG ulCoversImg) { BOOL fInvalAll; CalculateUpdateRect(_yLogRow - PROG_INTERVAL + 1, _yLogRow, &fInvalAll, &_yBot); if (fLast || (GetTickCount() - _dwTickProg > 1000)) { #ifndef _MAC ProgressiveDithering(_yLogRowDraw, _yLogRow); #endif _yLogRowDraw = _yLogRow; } super::OnProg(fLast, ulCoversImg, fInvalAll, _yBot); } #if DBG!=1 #pragma optimize(SPEED_OPTIMIZE_FLAGS, on) #endif BOOL CImgTaskGif::ReadScanline(unsigned char *pb, int cb) { int i; long b; for (i = cb; --i >= 0;) { b = readLWZ(); if (b < 0) return FALSE; *pb++ = (unsigned char)b; } return TRUE; } #pragma optimize("", on) #ifdef WIN16 #undef FillMemory #define FillMemory( _pv, _cb, ch) hmemset( (_pv), ch, (_cb) ) #endif CImgBitsDIB * CImgTaskGif::ReadImage(long len, long height, BOOL fInterlace, BOOL fGIFFrame, int cpeColors, PALETTEENTRY * ppeColors, HLPBYTE * ppbBits, long lTrans) { unsigned char c; long ypos = 0; long padlen = ((len + 3) / 4) * 4; char buf[256]; // need a buffer to read trailing blocks ( up to terminator ) into ULONG ulCoversImg = IMGBITS_PARTIAL; HLPBYTE pbBits; BOOL fAbort = FALSE; HRESULT hr; CImgBitsDIB *pibd = NULL; BOOL fColorTable; /* ** Initialize the Compression routines */ if (!ReadByte(&c)) { goto abort; } _cbImage = padlen * height * sizeof(char); if (_cbImage > dwMaxGIFBits) goto abort; pibd = new CImgBitsDIB(); if (!pibd) goto abort; // don't bother with allocating a color table if we're going to dither // to our standard palette fColorTable = (_colorMode != 8 || _pImgInfo->TstFlags(DWNF_RAWIMAGE)); if (!fColorTable) { hr = THR(pibd->AllocDIB(8, len, height, NULL, 0, -1, lTrans == -1)); if (hr) goto abort; } else { RGBQUAD argbTable[256]; if (cpeColors > 256) cpeColors = 256; CopyColorsFromPaletteEntries(argbTable, ppeColors, cpeColors); hr = THR(pibd->AllocDIB(8, len, height, argbTable, cpeColors, lTrans, lTrans == -1)); if (hr) goto abort; } pbBits = (BYTE *)pibd->GetBits(); if (!fGIFFrame) { _pImgBits = pibd; _gad.pgf->pibd = pibd; _pbDst = pbBits; if (fInterlace && _colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) { _pbSrcAlloc = (HLPBYTE) MemAlloc(Mt(CImgTaskGifBits), _cbImage); if (_pbSrcAlloc == NULL) goto abort; _pbSrc = _pbSrcAlloc; pbBits = _pbSrc; } else { _pbSrc = pbBits; } } #ifndef _MAC if (_colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) { int nDifferent; nDifferent = x_ComputeConstrainMap(cpeColors, ppeColors, lTrans, _mapConstrained); if (_pImgInfo->TstFlags(DWNF_FORCEDITHER) || (cpeColors > 16 && nDifferent > 15)) _fDither = TRUE; else TraceTag((tagImgTaskGif, "No dithering needed for '%ls'", GetUrl())); } #endif // _MAC if (c == 1) { // Netscape seems to field these bogus GIFs by filling treating them // as transparent. While not the optimal way to simulate this effect, // we'll fake it by pushing the initial code size up to a safe value, // consuming the input, and returning a buffer full of the transparent // color or zero, if no transparency is indicated. if (initLWZ(MINIMUM_CODE_SIZE)) while (readLWZ() >= 0); if (lTrans != -1) FillMemory(_pbSrc, _cbImage, lTrans); else // fall back on the background color FillMemory(_pbSrc, _cbImage, 0); if (!fGIFFrame) { _yLogRow = height - 1; OnProg(TRUE, IMGBITS_TOTAL); } goto done; } if (initLWZ(c) == FALSE) goto abort; if (fInterlace) { long i; long pass = 0, step = 8; if (!fGIFFrame && (height > 4)) _fInterleaved = TRUE; for (i = 0; i < height; i++) { // XX_DMsg(DBG_IMAGE, ("readimage, logical=%d, offset=%d\n", i, padlen * ((height-1) - ypos))); if ( fAbort #ifdef _MAC || !ReadScanline(&pbBits[padlen * ypos], len)) #else || !ReadScanline(&pbBits[padlen * ((height-1) - ypos)], len)) #endif { #if DBG==1 || defined(PERFTAGS) if (IsPerfDbgEnabled(tagImgTaskGifAbort)) { fAbort = TRUE; memset(&pbBits[padlen * ((height-1) - ypos)], 0, len); } else #endif break; } ypos += step; while (ypos >= height) { if (pass++ > 0) step /= 2; ypos = step / 2; if (!fGIFFrame && pass == 1) { ulCoversImg = IMGBITS_TOTAL; } } if (!fGIFFrame) { _yLogRow = i; if ((i & PROG_INTERVAL) == 0) { // Post ProgDraw (IE code has delay-logic) OnProg(FALSE, ulCoversImg); } } } if (!fGIFFrame) { OnProg(TRUE, IMGBITS_TOTAL); } } else { #ifdef _MAC for (ypos = 0; ypos < height; ypos++) #else for (ypos = height-1; ypos >= 0; ypos--) #endif { if (!ReadScanline(&pbBits[padlen * ypos], len)) break; if (!fGIFFrame) { _yLogRow++; // XX_DMsg(DBG_IMAGE, ("readimage, logical=%d, offset=%d\n", _yLogRow, padlen * ypos)); if ((_yLogRow & PROG_INTERVAL) == 0) { // Post ProgDraw (IE code has delay-logic) OnProg(FALSE, IMGBITS_PARTIAL); } } } if (!fGIFFrame) { OnProg(TRUE, IMGBITS_TOTAL); } } // consume blocks up to image block terminator so we can proceed to the next image while (GetDataBlock((unsigned char *) buf) > 0) ; done: *ppbBits = pbBits; return (pibd); abort: delete pibd; return NULL; } void CImgTaskGif::ProgressiveDithering(int logicalFill, int logicalRow) { BOOL bitbltNeeded = TRUE; int i; // Note: We only show the primary frame during prog draw, so we use the first GIFFRAME int padXSize; int row = logicalRow; int pass; int band; int band2; long offset; int passFill; int rowFill; int bandFill; int step; int j; if (logicalFill < 0) logicalFill = 0; if (_fDither && _pvDithData == NULL) { _pvDithData = pCreateDitherData(_gad.pgf->width); if (_pvDithData == NULL) return; } padXSize = ((_gad.pgf->width + 3) / 4) * 4; if (_fInterleaved) { getPassInfo(logicalFill,_gad.pgf->height,&passFill,&rowFill,&bandFill); getPassInfo(logicalRow,_gad.pgf->height,&pass,&row,&band); step = passFill == 0 ? 8 : bandFill*2; for (i = logicalFill; i <= logicalRow;i++) { offset = (long)padXSize*(long)(_gad.pgf->height - rowFill - 1) ; /* the DIB is stored upside down */ band2 = rowFill <= row ? band : band*2; if (band2 != 1) { if (_colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) { x_ColorConstrain(_pbSrc+offset, _pbDst+offset, _mapConstrained, _gad.pgf->width); } else hmemcpy(_pbDst+offset,_pbSrc+offset,padXSize); if (rowFill+band2 > _gad.pgf->height) band2 = _gad.pgf->height-rowFill; for (j = 1; j < band2; j++) hmemcpy(_pbDst+(offset-j*padXSize),_pbDst+offset,padXSize); if (_colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) { _gad.pgf->pibd->ComputeTransMask(rowFill, band2, g_wIdxTrans, 255); } } if ((rowFill += step) >= _gad.pgf->height) { if (passFill++ > 0) step /= 2; rowFill = step / 2; } } switch (pass) { case 0: band += row; break; case 3: band = _gad.pgf->height-row-1; break; default: band = _gad.pgf->height; break; } if (band > _gad.pgf->height) band = _gad.pgf->height; if (band > 0) { bitbltNeeded = (pass == 3); } if (bitbltNeeded) { if ((row >= _gad.pgf->height) || (logicalRow == _gad.pgf->height - 1)) row = _gad.pgf->height - 1; } } if (bitbltNeeded) { band = row + 1; if (_colorMode == 8 && !_pImgInfo->TstFlags(DWNF_RAWIMAGE)) { if (_yDithRow <= row) { if (_fDither) { x_DitherRelative(_pbSrc, _pbDst, _apeFirst, _gad.pgf->width, _gad.pgf->height, (_gad.pgf->bTransFlags & TRANSF_TRANSPARENT) ? _gifinfo.Gif89.transparent : -1, (int *)_pvDithData, _yDithRow, row); } else { ULONG cb = (long)padXSize * (long)(_gad.pgf->height - row - 1); x_ColorConstrain(_pbSrc + cb, _pbDst + cb, _mapConstrained, padXSize * (row - _yDithRow + 1)); } _gad.pgf->pibd->ComputeTransMask(_yDithRow, row - _yDithRow + 1, g_wIdxTrans, 255); _yDithRow = band; } } } } void CImgTaskGif::BltDib(HDC hdc, RECT * prcDst, RECT * prcSrc, DWORD dwRop, DWORD dwFlags) { int ySrcBot; if (_yLogRowDraw < 0 || _gad.pgf == NULL) return; if (_fInterleaved) ySrcBot = min(_yHei, (_yLogRowDraw + 1L) * 8L); else ySrcBot = _yLogRowDraw + 1; _gad.pgf->pibd->SetValidLines(ySrcBot); _gad.pgf->pibd->StretchBltOffset(hdc, prcDst, prcSrc, _gad.pgf->left, _gad.pgf->top, dwRop, dwFlags); } void CImgTaskGif::CalculateUpdateRect(int logicalRow0, int logicalRowN, BOOL *pfInvalidateAll, LONG *pyBottom) { *pfInvalidateAll = FALSE; if (logicalRowN == 0) { *pyBottom = 0; return; } if (_gad.pgf) { logicalRow0 += _gad.pgf->top; logicalRowN += _gad.pgf->top; } if (_fInterleaved) { int pass0, passN; int row0, rowN; int band0, bandN; getPassInfo(logicalRow0, _yHei, &pass0, &row0, &band0); getPassInfo(logicalRowN, _yHei, &passN, &rowN, &bandN); if (passN > pass0 + 1) *pfInvalidateAll = TRUE; *pyBottom = rowN + bandN; // We must special case the last row of last pass to deal with dithering // the possibly even numbered last row if (logicalRowN == _yHei - 1) *pyBottom = _yHei; } else *pyBottom = logicalRowN + 1; }
#include <NovelRT.h> #include <iostream> int main() { std::cout << "Hello, world!" << std::endl; }
#ifndef MAMMUT_MODULE_HPP_ #define MAMMUT_MODULE_HPP_ #include "./communicator.hpp" #include "./utils.hpp" #include "stdexcept" #include "string" #define MAMMUT_MODULE_DECL(ModuleType) friend class ::mammut::Servant; \ private: \ static std::string getModuleName(); \ public: \ static ModuleType* getInstance(Communicator* const communicator = NULL){ \ if(communicator){ \ return remote(communicator); \ }else{ \ return local(); \ } \ } \ static ModuleType* local(); \ static ModuleType* remote(mammut::Communicator* const communicator); \ static void release(ModuleType* module); \ namespace mammut{ class Module; class Mammut; class Servant; class Module: public utils::NonCopyable{ friend class ::mammut::Servant; public: virtual inline ~Module(){;} private: #ifdef MAMMUT_REMOTE virtual bool processMessage(const std::string& messageIdIn, const std::string& messageIn, std::string& messageIdOut, std::string& messageOut){ throw std::runtime_error("Remote module not implemented."); } #endif }; } #endif /* MAMMUT_MODULE_HPP_ */
#include <cgv/render/performance_monitor.h> #include <cgv/utils/file.h> #include <stack> #include <stdio.h> namespace cgv { namespace render { performance_monitor::frame_data& performance_monitor::current_frame() { return data.back(); } void performance_monitor::add_measurement(const performance_measurement& pm) { current_frame().push_back(pm); } performance_monitor::performance_monitor() : plot_color(0.3f,1,1) { enabled = true; frame_finished = true; placement.ref_min_pnt().set(10,10); placement.ref_max_pnt().set(310,110); nr_display_cycles = 2; bar_line_width = 5; frame_id = 0; init_tasks(); bar_config.push_back(PMB_MAX); bar_config.push_back(PMB_CUR); bar_config.push_back(PMB_MIN); } /// enable performance monitoring void performance_monitor::enable() { enabled = true; } /// disable performance monitoring void performance_monitor::disable() { enabled = false; } void performance_monitor::set_file_name(const std::string& _file_name) { file_name = _file_name; } /// initialize the list of tasks to one for the frame and one for each default rendering pass void performance_monitor::init_tasks() { tasks.clear(); add_task("frame", Col(0.5f,0.5f,0.5f)); add_task("main", Col(0.8f,0.2f,0.2f)); add_task("stereo", Col(0.2f,0.2f,0.8f)); add_task("shadow_map", Col(0.1f, 0.1f, 0.1f)); add_task("opaque_surface", Col(1,1,0)); add_task("transparent_surfaces", Col(0.9f,0.7f,0.5f)); add_task("pick", Col(0,0,1)); } /// removes all items of the bar config and hides the bar void performance_monitor::clear_bar() { bar_config.clear(); } /// add a bar item to the bar config void performance_monitor::add_bar_item(PerformanceMonitoringBar item) { bar_config.push_back(item); } /// place the performance monitor on screen in pixel coordinates void performance_monitor::set_placement(const Rec& rectangle) { placement = rectangle; } /// set the number of display cycles to by drawn for the performance monitor void performance_monitor::set_nr_display_cycles(unsigned _nr_cycles) { nr_display_cycles = _nr_cycles; } /// add a new to me monitored item int performance_monitor::add_task(const std::string& name, const cgv::media::color<float>& col) { performance_task pt(name,col); tasks.push_back(pt); return (int)tasks.size() - 1; } /// start performance measurement of a new frame void performance_monitor::start_frame() { if (!enabled) return; if (!frame_finished) finish_frame(); while (data.size() >= get_buffer_size()) data.pop_front(); data.push_back(frame_data()); watch.restart(); performance_measurement pm(watch.get_elapsed_time(), 0, true); add_measurement(pm); frame_finished = false; ++frame_id; } /// void performance_monitor::start_task(int task_id) { if (!enabled) return; performance_measurement pm(watch.get_elapsed_time(), task_id, true); add_measurement(pm); } void performance_monitor::finish_task(int task_id) { if (!enabled) return; performance_measurement pm(watch.get_elapsed_time(), task_id, false); add_measurement(pm); } /// finish measurement of a frame, if this is not called by hand, it is called automatically in the next call to start_frame. void performance_monitor::finish_frame() { if (!enabled) return; const char* start_or_finish[] = { "start", "finish" }; performance_measurement pm(watch.get_elapsed_time(), 0, false); add_measurement(pm); frame_finished = true; if (file_name.empty()) return; bool need_header = cgv::utils::file::exists(file_name); FILE* fp = fopen(file_name.c_str(), "wa"); if (!fp) return; int i; if (need_header) { const frame_data& cf = current_frame(); for (i=0; i<(int)cf.size(); ++i) { const performance_measurement& pm = cf[i]; fprintf(fp, i==0?"%s %s":",%s %s", start_or_finish[pm.start ? 0 : 1], tasks[pm.task_id].name.c_str()); } fprintf(fp, "\n"); } fprintf(fp, "%d", frame_id); for (i=0; i<(int)current_frame().size(); ++i) fprintf(fp, ", %f", current_frame()[i].time); fprintf(fp, "\n"); fclose(fp); } void performance_monitor::compute_colors(const frame_data& fdata) { colors.resize(2*fdata.size()-2); std::stack<int> task_stack; task_stack.push(0); for (unsigned t=0; t<fdata.size()-1; ++t) { int task_id = fdata[t].task_id; if (fdata[t].start) { colors[2*t+1] = colors[2*t] = tasks[task_id].col; task_stack.push(task_id); } else { task_stack.pop(); colors[2*t+1] = colors[2*t] = tasks[task_stack.top()].col; } } } void performance_monitor::compute_positions(int x0, int y0, int dx, int dy, const frame_data& fdata) { positions.resize(2*fdata.size()-2); double scale_x = 60.0*dx; double scale_y = 60.0*dy; int x = x0, y = y0; for (unsigned t=0; t < fdata.size()-1; ++t) { positions[2*t].set(x,y); x = x0 + (int)(fdata[t+1].time*scale_x+0.5); y = y0 + (int)(fdata[t+1].time*scale_y+0.5); positions[2*t+1].set(x,y); } } } }
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2018 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uritests.h" #include "guiutil.h" #include "walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?label=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString("Some Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=100&label=Some Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("lyra://D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?message=Some Example Address", &rv)); QVERIFY(rv.address == QString("D72dLgywmL73JyTwQBfuU29CADz9yCJ99v")); QVERIFY(rv.label == QString()); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?req-message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("lyra:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v?amount=1,000.0&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
#include <stdio.h> #include <string.h> int main() { int testcase; char s[10], s2[10], format[20] = "%0?d"; int A, B; scanf("%d", &testcase); while(testcase--) { scanf("%s %d %d", s, &A, &B); int len = strlen(s); int c = 1, i, j; for(i = 0; i < len; i++) c = c*10; format[2] = len+'0'; int ret = 0; for(i = c/10; i < c; i++) { sprintf(s2, format, i); int cnt[10] = {}, ta = 0, tb = 0; int err = 0; for(j = 0; j < len; j++) { cnt[s2[j]-'0']++; if(s2[j] == '0') err = 1; } if(err) continue; for(j = 0; j < len && ta <= A; j++) { if(s[j] == s2[j]) { ta++; cnt[s[j]-'0']--; } } if(ta != A) continue; for(j = 0; j < len && tb <= B; j++) { if(s[j] != s2[j]) { if(cnt[s[j]-'0']) { tb++; cnt[s[j]-'0']--; } } } if(ta == A && tb == B) ret++; } printf("%d\n", ret); } return 0; }
// // Created by zhanghui on 2022/3/20. // #ifndef SIMPLEST_CROSSPLATFORM_HELLOWORLD_LOGGER_HPP #define SIMPLEST_CROSSPLATFORM_HELLOWORLD_LOGGER_HPP #ifdef __cplusplus extern "C" { #endif #include <string.h> #define filename(x) strrchr(x,'/') ? strrchr(x,'/') + 1 : x void sch_log(const char* filename, int line, const char* format, ...); #define SCH_LOGI(format, ...) sch_log(filename(__FILE__), __LINE__, format, ##__VA_ARGS__) #ifdef __cplusplus } #endif #endif //SIMPLEST_CROSSPLATFORM_HELLOWORLD_LOGGER_HPP
#ifndef __ATTRIBUTES_HPP__ #define __ATTRIBUTES_HPP__ // C++ 11 dependencies #include <iterator> #include <string> // protobuf dependencies #include <mesos.pb.h> // stout dependencies #include <stout/option.hpp> namespace mesos { std::ostream& operator<<(std::ostream& stream, const Attribute& attribute); class Attributes { public: Attributes() {} /*implicit*/ Attributes(const google::protobuf::RepeatedPtrField<Attribute>& _attributes) { attributes.MergeFrom(_attributes); } /*implicit*/ Attributes(const Attributes& that) { attributes.MergeFrom(that.attributes); } Attributes& operator=(const Attributes& that) { if (this != &that) { attributes.Clear(); attributes.MergeFrom(that.attributes); } return *this; } bool operator==(const Attributes& that) const; bool operator!=(const Attributes& that) const { return !(*this == that); } size_t size() const { return attributes.size(); } // Using this operator makes it easy to copy an attributes object into // a protocol buffer field. operator const google::protobuf::RepeatedPtrField<Attribute>&() const { return attributes; } void add(const Attribute& attribute) { attributes.Add()->MergeFrom(attribute); } const Attribute get(int index) const { return attributes.Get(index); } const Option<Attribute> get(const Attribute& thatAttribute) const; template <typename T> T get(const std::string& name, const T& t) const; typedef google::protobuf::RepeatedPtrField<Attribute>::iterator iterator; typedef google::protobuf::RepeatedPtrField<Attribute>::const_iterator const_iterator; iterator begin() { return attributes.begin(); } iterator end() { return attributes.end(); } const_iterator begin() const { return attributes.begin(); } const_iterator end() const { return attributes.end(); } static Attribute parse(const std::string& name, const std::string& value); static Attributes parse(const std::string& s); static bool isValid(const Attribute& attribute); private: google::protobuf::RepeatedPtrField<Attribute> attributes; }; } // namespace mesos { #endif // __ATTRIBUTES_HPP__
// Example of parsing JSON to document by parts. // Using C++11 threads // Temporarily disable for clang (older version) due to incompatibility with libstdc++ #if (__cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1700)) && !defined(__clang__) #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/writer.h" #include "rapidjson/ostreamwrapper.h" #include <condition_variable> #include <iostream> #include <mutex> #include <thread> using namespace rapidjson; template<unsigned parseFlags = kParseDefaultFlags> class AsyncDocumentParser { public: AsyncDocumentParser(Document& d) : stream_(*this) , d_(d) , parseThread_() , mutex_() , notEmpty_() , finish_() , completed_() { // Create and execute thread after all member variables are initialized. parseThread_ = std::thread(&AsyncDocumentParser::Parse, this); } ~AsyncDocumentParser() { if (!parseThread_.joinable()) return; { std::unique_lock<std::mutex> lock(mutex_); // Wait until the buffer is read up (or parsing is completed) while (!stream_.Empty() && !completed_) finish_.wait(lock); // Automatically append '\0' as the terminator in the stream. static const char terminator[] = ""; stream_.src_ = terminator; stream_.end_ = terminator + 1; notEmpty_.notify_one(); // unblock the AsyncStringStream } parseThread_.join(); } void ParsePart(const char* buffer, size_t length) { std::unique_lock<std::mutex> lock(mutex_); // Wait until the buffer is read up (or parsing is completed) while (!stream_.Empty() && !completed_) finish_.wait(lock); // Stop further parsing if the parsing process is completed. if (completed_) return; // Set the buffer to stream and unblock the AsyncStringStream stream_.src_ = buffer; stream_.end_ = buffer + length; notEmpty_.notify_one(); } private: void Parse() { d_.ParseStream<parseFlags>(stream_); // The stream may not be fully read, notify finish anyway to unblock ParsePart() std::unique_lock<std::mutex> lock(mutex_); completed_ = true; // Parsing process is completed finish_.notify_one(); // Unblock ParsePart() or destructor if they are waiting. } struct AsyncStringStream { typedef char Ch; AsyncStringStream(AsyncDocumentParser& parser) : parser_(parser), src_(), end_(), count_() {} char Peek() const { std::unique_lock<std::mutex> lock(parser_.mutex_); // If nothing in stream, block to wait. while (Empty()) parser_.notEmpty_.wait(lock); return *src_; } char Take() { std::unique_lock<std::mutex> lock(parser_.mutex_); // If nothing in stream, block to wait. while (Empty()) parser_.notEmpty_.wait(lock); count_++; char c = *src_++; // If all stream is read up, notify that the stream is finish. if (Empty()) parser_.finish_.notify_one(); return c; } size_t Tell() const { return count_; } // Not implemented char* PutBegin() { return 0; } void Put(char) {} void Flush() {} size_t PutEnd(char*) { return 0; } bool Empty() const { return src_ == end_; } AsyncDocumentParser& parser_; const char* src_; //!< Current read position. const char* end_; //!< End of buffer size_t count_; //!< Number of characters taken so far. }; AsyncStringStream stream_; Document& d_; std::thread parseThread_; std::mutex mutex_; std::condition_variable notEmpty_; std::condition_variable finish_; bool completed_; }; int main() { Document d; { AsyncDocumentParser<> parser(d); const char json1[] = " { \"hello\" : \"world\", \"t\" : tr"; //const char json1[] = " { \"hello\" : \"world\", \"t\" : trX"; // For test parsing error const char json2[] = "ue, \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.14"; const char json3[] = "16, \"a\":[1, 2, 3, 4] } "; parser.ParsePart(json1, sizeof(json1) - 1); parser.ParsePart(json2, sizeof(json2) - 1); parser.ParsePart(json3, sizeof(json3) - 1); } if (d.HasParseError()) { std::cout << "Error at offset " << d.GetErrorOffset() << ": " << GetParseError_En(d.GetParseError()) << std::endl; return EXIT_FAILURE; } // Stringify the JSON to cout OStreamWrapper os(std::cout); Writer<OStreamWrapper> writer(os); d.Accept(writer); std::cout << std::endl; return EXIT_SUCCESS; } #else // Not supporting C++11 #include <iostream> int main() { std::cout << "This example requires C++11 compiler" << std::endl; } #endif
// (C) Copyright 2002-4 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. // (C) Copyright 2002-4 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. // binary_archive #include <archive/binary_oarchive.hpp> #include <archive/binary_iarchive.hpp> struct binary_archive_test_settings{ typedef icecube::archive::binary_oarchive test_oarchive; typedef std::ofstream test_ostream; typedef icecube::archive::binary_iarchive test_iarchive; typedef std::ifstream test_istream; static constexpr std::ios_base::openmode TEST_STREAM_FLAGS = (std::ios::binary); static constexpr std::ios_base::openmode TEST_ARCHIVE_FLAGS = (std::ios_base::openmode)0; }; #define test_settings binary_archive_test_settings
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/common/tasks/convolution_transposed.h" #include <string> #include <utility> #include <vector> #include "absl/strings/substitute.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/task/storage_type_util.h" #include "tensorflow/lite/delegates/gpu/common/task/weights_layout.h" #include "tensorflow/lite/delegates/gpu/common/task/work_group_picking.h" namespace tflite { namespace gpu { ConvolutionTransposed::ConvolutionTransposed( const OperationDef& definition, const ConvolutionTransposedAttributes& attr, const GpuInfo& gpu_info, bool weights_are_buffer) : GPUOperation(definition), stride_(attr.stride.w, attr.stride.h, 1, 1), block_size_(2, 2, 1, 2) { if (weights_are_buffer) { if (gpu_info.IsApple()) { weights_layout_ = WeightsLayout::kOSpatialIOGroupO4I4; } else { weights_layout_ = WeightsLayout::kOSpatialIOGroupI4O4; } } else { if (gpu_info.IsApple()) { weights_layout_ = WeightsLayout::k2DX4O4YIsSpatialIAndXIsOOGroupI4; } else { weights_layout_ = WeightsLayout::k2DX4I4YIsSpatialIAndXIsOOGroupO4; } } const bool is_f16 = definition.precision == CalculationsPrecision::F16; if (gpu_info.IsMali()) { if (gpu_info.mali_info.IsMidgard()) { block_size_ = is_f16 ? int4(2, 1, 1, 2) : int4(2, 1, 1, 1); } else { block_size_ = is_f16 ? int4(2, 2, 1, 2) : int4(2, 2, 1, 1); } compiler_options_.push_back(CompilerOptions::kClFastRelaxedMath); } const int dst_depth = DivideRoundUp(attr.weights.shape.o, 4); if (dst_depth == 1 || dst_depth == 3) { if (!gpu_info.IsMali()) { block_size_.y *= block_size_.w; } block_size_.w = 1; } args_.AddInt("stride_x", stride_.x); args_.AddInt("stride_y", stride_.y); args_.AddInt("padding_x", attr.padding.prepended.w); args_.AddInt("padding_y", attr.padding.prepended.h); args_.AddInt("kernel_size_x", attr.weights.shape.w); args_.AddInt("kernel_size_y", attr.weights.shape.h); code_ = GenerateConvolutionTransposedCode(definition_, gpu_info, weights_are_buffer, block_size_); } ConvolutionTransposed::ConvolutionTransposed( const OperationDef& definition, const ConvolutionTransposed3DAttributes& attr, const GpuInfo& gpu_info, bool weights_are_buffer) : GPUOperation(definition), stride_(attr.stride.w, attr.stride.h, attr.stride.d, 1), block_size_(2, 2, 1, 2) { if (weights_are_buffer) { if (gpu_info.IsApple()) { weights_layout_ = WeightsLayout::kOSpatialIOGroupO4I4; } else { weights_layout_ = WeightsLayout::kOSpatialIOGroupI4O4; } } else { if (gpu_info.IsApple()) { weights_layout_ = WeightsLayout::k2DX4O4YIsSpatialIAndXIsOOGroupI4; } else { weights_layout_ = WeightsLayout::k2DX4I4YIsSpatialIAndXIsOOGroupO4; } } const bool is_f16 = definition.precision == CalculationsPrecision::F16; if (gpu_info.IsMali()) { if (gpu_info.mali_info.IsMidgard()) { block_size_ = is_f16 ? int4(2, 1, 1, 2) : int4(2, 1, 1, 1); } else { block_size_ = is_f16 ? int4(2, 2, 1, 2) : int4(2, 2, 1, 1); } compiler_options_.push_back(CompilerOptions::kClFastRelaxedMath); } const int dst_depth = DivideRoundUp(attr.weights.shape.o, 4); if (dst_depth == 1 || dst_depth == 3) { if (!gpu_info.IsMali()) { block_size_.y *= block_size_.w; } block_size_.w = 1; } args_.AddInt("stride_x", stride_.x); args_.AddInt("stride_y", stride_.y); args_.AddInt("stride_z", stride_.z); args_.AddInt("padding_x", attr.padding.prepended.w); args_.AddInt("padding_y", attr.padding.prepended.h); args_.AddInt("padding_z", attr.padding.prepended.d); args_.AddInt("kernel_size_x", attr.weights.shape.w); args_.AddInt("kernel_size_y", attr.weights.shape.h); args_.AddInt("kernel_size_z", attr.weights.shape.d); args_.AddInt("grid_size_y"); code_ = GenerateConvolutionTransposedCode(definition_, gpu_info, weights_are_buffer, block_size_); } std::string ConvolutionTransposed::GenerateConvolutionTransposedCode( const OperationDef& op_def, const GpuInfo& gpu_info, bool weights_are_buffer, const int4& block_size) { auto src_desc = op_def.src_tensors[0]; src_desc.SetAddressMode(AddressMode::kZero); AddSrcTensor("src_tensor", src_desc); AddDstTensor("dst_tensor", op_def.dst_tensors[0]); if (op_def.src_tensors.size() != 1) { // dynamic weights if (weights_layout_ == WeightsLayout::kOSpatialIOGroupI4O4 || weights_layout_ == WeightsLayout::kOSpatialIOGroupO4I4) { BufferDescriptor desc; desc.element_type = op_def.src_tensors[1].data_type; desc.element_size = 16; desc.memory_type = MemoryType::GLOBAL; AddSrcBuffer("weights", desc); } else { for (int i = 0; i < 4; ++i) { Texture2DDescriptor desc; desc.element_type = op_def.src_tensors[1 + i].data_type; const std::string name = "weights" + std::to_string(i); AddSrcTexture2D("weights" + std::to_string(i), desc); } } } const auto& src_def = op_def.src_tensors[0]; std::string c; for (int s = 0; s < block_size.w; ++s) { std::string f0, f1, f2, f3; if (weights_are_buffer) { if (gpu_info.SupportsPointersInKernels()) { f0 = "FLT16_0123(weights_cache[" + std::to_string(s) + "])"; f1 = "FLT16_4567(weights_cache[" + std::to_string(s) + "])"; f2 = "FLT16_89ab(weights_cache[" + std::to_string(s) + "])"; f3 = "FLT16_cdef(weights_cache[" + std::to_string(s) + "])"; } else { f0 = "FLT16_0123(flt16val)"; f1 = "FLT16_4567(flt16val)"; f2 = "FLT16_89ab(flt16val)"; f3 = "FLT16_cdef(flt16val)"; } } else { f0 = "f" + std::to_string(s * 4 + 0); f1 = "f" + std::to_string(s * 4 + 1); f2 = "f" + std::to_string(s * 4 + 2); f3 = "f" + std::to_string(s * 4 + 3); } if (GetWeightsDescription().IsI4O4()) { switch (op_def.precision) { case CalculationsPrecision::F32: case CalculationsPrecision::F16: c += "#define CONV" + std::to_string(s) + "(R, S) \\\n"; c += "R += S.x * " + f0 + "; \\\n"; c += "R += S.y * " + f1 + "; \\\n"; c += "R += S.z * " + f2 + "; \\\n"; c += "R += S.w * " + f3 + "; \n"; break; case CalculationsPrecision::F32_F16: c += "#define CONV" + std::to_string(s) + "(R, S) \\\n"; c += "R += TO_ACCUM_TYPE(S.x * " + f0 + " + S.y * " + f1 + " + S.z * " + f2 + " + S.w * " + f3 + ");\n"; break; } } else { // O4I4 c += "#define CONV" + std::to_string(s) + "(R, S) \\\n"; c += "R.x += dot(S, " + f0 + "); \\\n"; c += "R.y += dot(S, " + f1 + "); \\\n"; c += "R.z += dot(S, " + f2 + "); \\\n"; c += "R.w += dot(S, " + f3 + "); \n"; } } auto generate_id = [&](const std::string& x, const std::string& y, const std::string& z) { std::string id; if (src_def.HasAxis(Axis::WIDTH)) { id += "_w" + x; } if (src_def.HasAxis(Axis::HEIGHT)) { id += "_h" + y; } if (src_def.HasAxis(Axis::DEPTH)) { id += "_d" + z; } return id; }; auto generate_id_full = [&](const std::string& x, const std::string& y, const std::string& z, const std::string& s) { return generate_id(x, y, z) + "_s" + s; }; auto generate_check = [&](const std::string& x, const std::string& y, const std::string& z) { std::string check; const std::vector<Axis> axes{Axis::WIDTH, Axis::HEIGHT, Axis::DEPTH}; const std::vector<std::string> names{"in_x", "in_y", "in_z"}; const std::vector<std::string> coords{x, y, z}; for (int i = 0; i < axes.size(); ++i) { const auto& axis = axes[i]; if (src_def.HasAxis(axis) && !src_def.SupportsZeroClamp(axis, gpu_info) && block_size[i] != 1) { if (!check.empty()) { check += " && "; } check += names[i] + coords[i]; } } return check; }; switch (op_def.precision) { case CalculationsPrecision::F32: c += "#define FLT16 float16\n"; break; case CalculationsPrecision::F32_F16: case CalculationsPrecision::F16: c += "#define FLT16 half16\n"; break; } c += "MAIN_FUNCTION($0) {\n"; if (op_def.IsBatchSupported()) { c += " int linear_id = GLOBAL_ID_0;\n"; c += " int dst_x = (linear_id / args.dst_tensor.Batch());\n"; c += " int B = linear_id % args.dst_tensor.Batch();\n"; c += " args.dst_tensor.SetBatchRef(B);\n"; c += " args.src_tensor.SetBatchRef(B);\n"; } else { c += " int dst_x = GLOBAL_ID_0;\n"; } c += " int rem_x = dst_x % args.stride_x;\n"; c += " int ceil_x = dst_x / args.stride_x;\n"; c += " dst_x = ceil_x * args.stride_x * " + std::to_string(block_size.x) + " + rem_x;\n"; if (src_def.HasAxis(Axis::DEPTH)) { c += " int linear_id_y = GLOBAL_ID_1;\n"; c += " int dst_y = linear_id_y % args.grid_size_y;\n"; c += " int dst_z = linear_id_y / args.grid_size_y;\n"; c += " int rem_z = dst_z % args.stride_z;\n"; c += " int ceil_z = dst_z / args.stride_z;\n"; c += " dst_z = ceil_z * args.stride_z * " + std::to_string(block_size.z) + " + rem_z;\n"; c += " if (dst_z >= args.dst_tensor.Depth()) return;\n"; } else { c += " int dst_y = GLOBAL_ID_1;\n"; } c += " int rem_y = dst_y % args.stride_y;\n"; c += " int ceil_y = dst_y / args.stride_y;\n"; c += " dst_y = ceil_y * args.stride_y * " + std::to_string(block_size.y) + " + rem_y;\n"; c += " int dst_s = GLOBAL_ID_2 * " + std::to_string(block_size.w) + ";\n"; c += " if (dst_x >= args.dst_tensor.Width() || dst_y >= " "args.dst_tensor.Height() || dst_s >= " "args.dst_tensor.Slices()) return;\n"; if (weights_are_buffer) { c += " int f_base = dst_s * args.src_tensor.Slices() * args.kernel_size_x " "* args.kernel_size_y"; if (src_def.HasAxis(Axis::DEPTH)) { c += " * args.kernel_size_z"; } c += ";\n"; } for (int s = 0; s < block_size.w; ++s) { const std::string sind = std::to_string(s); for (int z = 0; z < block_size.z; ++z) { const std::string zind = std::to_string(z); for (int y = 0; y < block_size.y; ++y) { const std::string yind = std::to_string(y); for (int x = 0; x < block_size.x; ++x) { const std::string xind = std::to_string(x); c += " ACCUM_FLT4 r" + generate_id_full(xind, yind, zind, sind) + " = INIT_ACCUM_FLT4(0.0f);\n"; } } } } c += " int kernel_first_dst_x = dst_x + args.padding_x;\n"; c += " int kernel_first_dst_y = dst_y + args.padding_y;\n"; c += " int kernel_last_dst_x = kernel_first_dst_x - args.kernel_size_x;\n"; c += " int kernel_last_dst_y = kernel_first_dst_y - args.kernel_size_y;\n"; c += " int offset_x = abs(args.padding_x);\n"; c += " int offset_x_strided = offset_x * args.stride_x;\n"; c += " int src_x = (kernel_first_dst_x + offset_x_strided) / args.stride_x - " "offset_x;\n"; c += " int offset_y = abs(args.padding_y);\n"; c += " int offset_y_strided = offset_y * args.stride_y;\n"; c += " int src_y = (kernel_first_dst_y + offset_y_strided) / args.stride_y - " "offset_y;\n"; if (src_def.HasAxis(Axis::DEPTH)) { c += " int kernel_first_dst_z = dst_z + args.padding_z;\n"; c += " int kernel_last_dst_z = kernel_first_dst_z - args.kernel_size_z;\n"; c += " int offset_z = abs(args.padding_z);\n"; c += " int offset_z_strided = offset_z * args.stride_z;\n"; c += " int src_z = (kernel_first_dst_z + offset_z_strided) / " "args.stride_z - offset_z;\n"; c += " int src_as_dst_z = src_z * args.stride_z;\n"; c += " for (;src_as_dst_z > kernel_last_dst_z; src_z -= 1, src_as_dst_z -= " "args.stride_z) {\n"; for (int z = 0; z < block_size.z; ++z) { const std::string zindex = std::to_string(z); c += " int sz" + zindex + " = src_z + " + zindex + ";\n"; if (!src_def.SupportsZeroClamp(Axis::DEPTH, gpu_info)) { c += " bool in_z" + zindex + " = sz" + zindex + " >= 0 && sz" + zindex + " < args.src_tensor.Depth();\n"; if (!src_def.CanReadOutOfBorder(Axis::DEPTH)) { c += " sz" + zindex + " = clamp(sz" + zindex + ", 0, args.src_tensor.Depth() - 1);\n"; } } } if (block_size.z == 1 && !src_def.SupportsZeroClamp(Axis::DEPTH, gpu_info)) { c += " if (!in_z0) continue;\n"; } c += " int kernel_z = kernel_first_dst_z - src_as_dst_z;\n"; c += " int src_as_dst_y = src_y * args.stride_y;\n"; c += " int src_y_copy = src_y;\n"; c += " for (;src_as_dst_y > kernel_last_dst_y; src_y_copy -= 1, " "src_as_dst_y -= args.stride_y) {\n"; } else { c += " int src_as_dst_y = src_y * args.stride_y;\n"; c += " for (;src_as_dst_y > kernel_last_dst_y; src_y -= 1, src_as_dst_y " "-= args.stride_y) {\n"; } for (int y = 0; y < block_size.y; ++y) { const std::string yindex = std::to_string(y); const std::string src_y = src_def.HasAxis(Axis::DEPTH) ? "src_y_copy" : "src_y"; c += " int sy" + yindex + " = " + src_y + " + " + yindex + ";\n"; if (!src_def.SupportsZeroClamp(Axis::HEIGHT, gpu_info)) { c += " bool in_y" + yindex + " = sy" + yindex + " >= 0 && sy" + yindex + " < args.src_tensor.Height();\n"; if (!src_def.CanReadOutOfBorder(Axis::HEIGHT)) { c += " sy" + yindex + " = clamp(sy" + yindex + ", 0, args.src_tensor.Height() - 1);\n"; } } } if (block_size.y == 1 && !src_def.SupportsZeroClamp(Axis::HEIGHT, gpu_info)) { c += " if (!in_y0) continue;\n"; } c += " int kernel_y = kernel_first_dst_y - src_as_dst_y;\n"; c += " int src_as_dst_x = src_x * args.stride_x;\n"; c += " int src_x_copy = src_x;\n"; c += " for (;src_as_dst_x > kernel_last_dst_x; src_x_copy -= 1, " "src_as_dst_x " "-= args.stride_x) {\n"; for (int x = 0; x < block_size.x; ++x) { const std::string xindex = std::to_string(x); c += " int sx" + xindex + " = src_x_copy + " + xindex + ";\n"; if (!src_def.SupportsZeroClamp(Axis::WIDTH, gpu_info)) { c += " bool in_x" + xindex + " = sx" + xindex + " >= 0 && sx" + xindex + " < args.src_tensor.Width();\n"; if (!src_def.CanReadOutOfBorder(Axis::WIDTH)) { c += " sx" + xindex + " = clamp(sx" + xindex + ", 0, args.src_tensor.Width() - 1);\n"; } } } if (block_size.x == 1 && !src_def.SupportsZeroClamp(Axis::WIDTH, gpu_info)) { c += " if (!in_x0) continue;\n"; } for (int z = 0; z < block_size.z; ++z) { const std::string zind = std::to_string(z); for (int y = 0; y < block_size.y; ++y) { const std::string yind = std::to_string(y); for (int x = 0; x < block_size.x; ++x) { const std::string xind = std::to_string(x); const std::string id = generate_id(xind, yind, zind); const std::string check = generate_check(xind, yind, zind); std::string coords = "sx" + xind + ", sy" + yind; if (src_def.HasAxis(Axis::DEPTH)) { coords += ", sz" + zind; } if (src_def.IsLinear()) { c += " args.src_tensor.GetAddress(addr" + id + ", " + coords + ", 0);\n"; if (src_def.ReturnsZeroForNegOneRead(gpu_info)) { c += " addr" + id + " = select(-1, addr" + id + ", (" + check + "));\n"; c += " int ds" + id + " = select(0, args.src_tensor.SliceStride(), (" + check + "));\n"; } } } } } if (src_def.IsLinear() && !src_def.ReturnsZeroForNegOneRead(gpu_info)) { c += " int ds = args.src_tensor.SliceStride();\n"; } c += " int kernel_x = kernel_first_dst_x - src_as_dst_x;\n"; if (src_def.HasAxis(Axis::DEPTH)) { c += " int kernel_index = (kernel_z * args.kernel_size_y + kernel_y) " "* args.kernel_size_x + kernel_x;\n"; } else { c += " int kernel_index = kernel_y * args.kernel_size_x + kernel_x;\n"; } if (weights_are_buffer) { c += " int f_offset = f_base + kernel_index * " "args.src_tensor.Slices() * " + std::to_string(block_size.w) + ";\n"; } else { c += " int x_c = kernel_index * args.src_tensor.Slices();\n"; } c += " for (int s = 0; s < args.src_tensor.Slices(); ++s) {\n"; const bool conditional_read = gpu_info.IsMali(); for (int z = 0; z < block_size.z; ++z) { const std::string zind = std::to_string(z); for (int y = 0; y < block_size.y; ++y) { const std::string yind = std::to_string(y); for (int x = 0; x < block_size.x; ++x) { const std::string xind = std::to_string(x); const std::string id = generate_id(xind, yind, zind); std::string address; if (src_def.IsLinear()) { address = "addr" + id; } else { address = "sx" + xind + ", sy" + yind; if (src_def.HasAxis(Axis::DEPTH)) { address += ", sz" + zind; } address += ", s"; } if (src_def.ReturnsZeroForNegOneRead(gpu_info)) { c += " FLT4 src" + id + " = args.src_tensor.Read(" + address + "); " + address + " += ds" + id + ";\n"; } else { const std::string check = generate_check(xind, yind, zind); if (!check.empty()) { if (conditional_read) { c += " FLT4 src" + id + " = " + check + " ? args.src_tensor.Read(" + address + ") : INIT_FLT4(0.0f);\n"; } else { c += " FLT4 src" + id + " = args.src_tensor.Read(" + address + ") * INIT_FLT(" + check + ");\n"; } } else { c += " FLT4 src" + id + " = args.src_tensor.Read(" + address + ");\n"; } if (src_def.IsLinear()) { c += " addr" + id + " += ds;\n"; } } } } } if (weights_are_buffer) { if (gpu_info.SupportsPointersInKernels()) { c += " __global FLT16* weights_cache = " "args.weights.GetPtr(f_offset);\n"; } } else { for (int s = 0; s < block_size.w; ++s) { c += absl::Substitute( R"( FLT4 f$1 = args.weights0.Read(dst_s + $0, x_c); FLT4 f$2 = args.weights1.Read(dst_s + $0, x_c); FLT4 f$3 = args.weights2.Read(dst_s + $0, x_c); FLT4 f$4 = args.weights3.Read(dst_s + $0, x_c); )", s, s * 4 + 0, s * 4 + 1, s * 4 + 2, s * 4 + 3); } c += " x_c++;\n"; } if (weights_are_buffer && !gpu_info.SupportsPointersInKernels()) { c += " FLT16 flt16val;\n"; } for (int s = 0; s < block_size.w; ++s) { if (weights_are_buffer && !gpu_info.SupportsPointersInKernels()) { c += " flt16val = args.weights.Read(f_offset + " + std::to_string(s) + ");\n"; } const std::string sind = std::to_string(s); for (int z = 0; z < block_size.z; ++z) { const std::string zind = std::to_string(z); for (int y = 0; y < block_size.y; ++y) { const std::string yind = std::to_string(y); for (int x = 0; x < block_size.x; ++x) { const std::string xind = std::to_string(x); const std::string id = generate_id(xind, yind, zind); const std::string full_id = generate_id_full(xind, yind, zind, sind); c += " CONV" + sind + "(r" + full_id + ", src" + id + ");\n"; } } } } if (weights_are_buffer) { c += " f_offset += " + std::to_string(block_size.w) + ";\n"; } c += " }\n"; c += " }\n"; c += " }\n"; if (src_def.HasAxis(Axis::DEPTH)) { c += " }\n"; } for (int s = 0; s < block_size.w; ++s) { const std::string sind = std::to_string(s); c += " if (dst_s < args.dst_tensor.Slices()) {\n"; c += " FLT4 bias_val = args.biases.Read(dst_s);\n"; for (int z = 0; z < block_size.z; ++z) { const std::string zind = std::to_string(z); for (int y = 0; y < block_size.y; ++y) { const std::string yind = std::to_string(y); for (int x = 0; x < block_size.x; ++x) { const std::string xind = std::to_string(x); const std::string id = generate_id_full(xind, yind, zind, sind); std::string checks = "xc < args.dst_tensor.Width() && yc < args.dst_tensor.Height()"; std::string coords = "xc, yc"; c += " {\n"; c += " int xc = dst_x + args.stride_x * " + xind + ";\n"; c += " int yc = dst_y + args.stride_y * " + yind + ";\n"; if (src_def.HasAxis(Axis::DEPTH)) { c += " int zc = dst_z + args.stride_z * " + zind + ";\n"; checks += " && zc < args.dst_tensor.Depth()"; coords += ", zc"; } c += " if (" + checks + ") {\n"; c += " FLT4 res = TO_FLT4(r" + id + ") + bias_val;\n"; c += " args.dst_tensor.Write(res, " + coords + ", dst_s);\n"; c += " }\n"; c += " }\n"; } } } c += " }\n"; c += " dst_s++;\n"; } c += "}\n"; return c; } absl::Status ConvolutionTransposed::BindArguments(ArgumentsBinder* args) { if (definition_.src_tensors[0].HasAxis(Axis::DEPTH)) { const int aligned_h = AlignByN(dst_[0]->Height(), stride_.y * block_size_.y); RETURN_IF_ERROR( args->SetInt("grid_size_y", DivideRoundUp(aligned_h, block_size_.y))); } return absl::OkStatus(); } int3 ConvolutionTransposed::GetGridSize() const { const int aligned_w = AlignByN(dst_[0]->Width(), stride_.x * block_size_.x); const int aligned_h = AlignByN(dst_[0]->Height(), stride_.y * block_size_.y); const int aligned_d = AlignByN(dst_[0]->Depth(), stride_.z * block_size_.z); const int grid_x = DivideRoundUp(aligned_w, block_size_.x) * dst_[0]->Batch(); const int grid_y = DivideRoundUp(aligned_h, block_size_.y) * DivideRoundUp(aligned_d, block_size_.z); const int grid_z = DivideRoundUp(dst_[0]->Slices(), block_size_.w); return int3(grid_x, grid_y, grid_z); } void ConvolutionTransposed::GetPossibleKernelWorkGroups( TuningType tuning_type, const GpuInfo& gpu_info, const KernelInfo& kernel_info, std::vector<int3>* work_groups) const { GetPossibleWorkGroupsConv(tuning_type, gpu_info, kernel_info, grid_size_, work_groups); } ConvolutionTransposed CreateConvolutionTransposed( const GpuInfo& gpu_info, const OperationDef& definition, const ConvolutionTransposedAttributes& attr) { const bool weights_are_buffer = gpu_info.IsMali() || gpu_info.IsApple(); ConvolutionTransposed result(definition, attr, gpu_info, weights_are_buffer); result.UploadWeights(attr.weights, weights_are_buffer); TensorLinearDescriptor desc; desc.storage_type = DeduceLinearStorageType(definition.GetPrimaryStorageType()); desc.element_type = definition.GetDataType(); desc.UploadLinearData(attr.bias); result.args_.AddObject( "biases", absl::make_unique<TensorLinearDescriptor>(std::move(desc))); return result; } ConvolutionTransposed CreateConvolutionTransposed3D( const GpuInfo& gpu_info, const OperationDef& definition, const ConvolutionTransposed3DAttributes& attr) { const bool weights_are_buffer = gpu_info.IsMali() || gpu_info.IsApple(); ConvolutionTransposed result(definition, attr, gpu_info, weights_are_buffer); result.UploadWeights(attr.weights, weights_are_buffer); TensorLinearDescriptor desc; desc.storage_type = DeduceLinearStorageType(definition.GetPrimaryStorageType()); desc.element_type = definition.GetDataType(); desc.UploadLinearData(attr.bias); result.args_.AddObject( "biases", absl::make_unique<TensorLinearDescriptor>(std::move(desc))); return result; } ConvolutionTransposed CreateConvolutionTransposedDynamicWeights( const GpuInfo& gpu_info, const OperationDef& definition, const ConvolutionTransposedAttributes& attr) { const bool weights_are_buffer = gpu_info.IsMali(); OperationDef new_def = definition; new_def.src_tensors = { definition.src_tensors[0]}; // leaving only src_tensor def, weights defs // will be added later const DataType weights_type = definition.GetDataType(); if (weights_are_buffer) { // add 1 src_tensor(buffer) for weights new_def.src_tensors.push_back( {weights_type, TensorStorageType::BUFFER, Layout::HWC}); } else { // add 4 src_tensors(4X textures 2d) for weights new_def.src_tensors.push_back( {weights_type, TensorStorageType::TEXTURE_2D, Layout::HWC}); new_def.src_tensors.push_back( {weights_type, TensorStorageType::TEXTURE_2D, Layout::HWC}); new_def.src_tensors.push_back( {weights_type, TensorStorageType::TEXTURE_2D, Layout::HWC}); new_def.src_tensors.push_back( {weights_type, TensorStorageType::TEXTURE_2D, Layout::HWC}); } ConvolutionTransposed result(new_def, attr, gpu_info, weights_are_buffer); TensorLinearDescriptor desc; desc.storage_type = DeduceLinearStorageType(new_def.GetPrimaryStorageType()); desc.element_type = new_def.GetDataType(); desc.UploadLinearData(attr.bias); result.args_.AddObject( "biases", absl::make_unique<TensorLinearDescriptor>(std::move(desc))); return result; } } // namespace gpu } // namespace tflite
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include "ob_serializable_function.h" #include "lib/utility/ob_macro_utils.h" #include "lib/utility/utility.h" #include "lib/hash_func/murmur_hash.h" #include "sql/engine/expr/ob_expr.h" namespace oceanbase { using namespace common; namespace sql { #define BOOL_EXTERN_DECLARE(id) CONCAT(extern bool g_reg_ser_func_, id) #define REG_UNUSED_SER_FUNC_ARRAY(id) CONCAT(bool g_reg_ser_func_, id) #define LIST_REGISTERED_FUNC_ARRAY(id) CONCAT(g_reg_ser_func_, id) LST_DO_CODE(BOOL_EXTERN_DECLARE, SER_FUNC_ARRAY_ID_ENUM); LST_DO_CODE(REG_UNUSED_SER_FUNC_ARRAY, UNUSED_SER_FUNC_ARRAY_ID_ENUM); bool check_all_ser_func_registered() { bool all_registered = true; bool all_reg_flags[] = {LST_DO(LIST_REGISTERED_FUNC_ARRAY, (, ), SER_FUNC_ARRAY_ID_ENUM)}; ObSerFuncArrayID unused_ids[] = {UNUSED_SER_FUNC_ARRAY_ID_ENUM}; for (int64_t i = 0; i < ARRAYSIZEOF(all_reg_flags); i++) { if (!all_reg_flags[i]) { bool found = false; for (int64_t j = 0; !found && j < ARRAYSIZEOF(unused_ids); j++) { if (i == unused_ids[j]) { found = true; } } if (!found) { LOG_ERROR("serialize function array not registered", "ObSerFuncArrayID", i); all_registered = false; } } } return all_registered; } #undef LIST_REGISTERED_FUNC_ARRAY #undef REG_UNUSED_SER_FUNC_ARRAY #undef BOOL_EXTERN_DECLARE ObFuncSerialization::FuncArray ObFuncSerialization::g_all_func_arrays[OB_SFA_MAX]; bool ObFuncSerialization::reg_func_array(const ObSerFuncArrayID id, void** array, const int64_t size) { bool succ = true; if (id < 0 || id >= OB_SFA_MAX || OB_ISNULL(array) || size < 0) { succ = false; } else { g_all_func_arrays[id].funcs_ = array; g_all_func_arrays[id].size_ = size; } return succ; } // All serializable functions should register here. void* g_all_misc_serializable_functions[] = { NULL // append only, only mark delete allowed. }; REG_SER_FUNC_ARRAY(OB_SFA_ALL_MISC, g_all_misc_serializable_functions, ARRAYSIZEOF(g_all_misc_serializable_functions)); static ObFuncSerialization::FuncIdx g_def_func_table_bucket; static ObFuncSerialization::FuncIdxTable g_def_func_table = {&g_def_func_table_bucket, 1, 0}; ObFuncSerialization::FuncIdxTable& ObFuncSerialization::create_hash_table() { if (!check_all_ser_func_registered()) { ob_abort(); } int64_t func_cnt = 1; for (int64_t i = 0; i < ARRAYSIZEOF(g_all_func_arrays); i++) { func_cnt += g_all_func_arrays[i].size_; } const int64_t bucket_size = next_pow2(func_cnt * 2); ObMemAttr attr(OB_SERVER_TENANT_ID, "SerFuncRegHT"); FuncIdxTable* ht = static_cast<FuncIdxTable*>(ob_malloc(sizeof(FuncIdxTable), attr)); FuncIdx* buckets = static_cast<FuncIdx*>(ob_malloc(sizeof(FuncIdx) * bucket_size, attr)); if (NULL == ht || NULL == buckets) { LOG_ERROR("allocate memory failed"); if (NULL != ht) { ob_free(ht); } if (NULL != buckets) { ob_free(buckets); } ht = &g_def_func_table; } else { int64_t conflicts = 0; int64_t size = 0; MEMSET(buckets, 0, sizeof(buckets[0]) * bucket_size); ht->buckets_ = buckets; ht->bucket_size_ = bucket_size; ht->bucket_size_mask_ = bucket_size - 1; for (uint64_t array_idx = 0; array_idx < ARRAYSIZEOF(g_all_func_arrays); array_idx++) { const FuncArray& array = g_all_func_arrays[array_idx]; for (uint64_t func_idx = 0; func_idx < array.size_; func_idx++) { void* func = array.funcs_[func_idx]; if (NULL == func) { continue; } // insert into hash table const uint64_t hash_val = hash(func); for (uint64_t i = 0; i < ht->bucket_size_; i++) { const uint64_t pos = (hash_val + i) & ht->bucket_size_mask_; if (NULL == ht->buckets_[pos].func_) { size += 1; ht->buckets_[pos].func_ = func; ht->buckets_[pos].idx_ = make_combine_idx(array_idx, func_idx); break; } else if (func == ht->buckets_[pos].func_) { // no overwrite break; } else { conflicts += 1; } if (i + 1 == ht->bucket_size_) { LOG_ERROR("hash table is full, impossible"); ob_abort(); } } } // end func loop } // end func array loop LOG_INFO("function serialization hash table created", K(func_cnt), K(bucket_size), K(size), K(conflicts)); } return *ht; } void ObFuncSerialization::check_hash_table_valid() { for (int64_t i = 0; i < ARRAYSIZEOF(g_all_func_arrays); i++) { for (int64_t j = 0; j < g_all_func_arrays[i].size_; j++) { void* func = g_all_func_arrays[i].funcs_[j]; if (NULL != func) { const uint64_t idx = get_serialize_index(func); OB_ASSERT(idx > 0 && OB_INVALID_INDEX != idx); OB_ASSERT(func == get_serialize_func(idx)); } } } } // define item[X][Y] offset in source array #define SRC_ITEM_OFF(X, Y) ((X)*n * row_size + (Y)*row_size) #define COPY_FUNCS bool ObFuncSerialization::convert_NxN_array(void** dst, void** src, const int64_t n, const int64_t row_size, // = 1 const int64_t copy_row_idx, // = 0 const int64_t copy_row_cnt) // = 1 { int ret = OB_SUCCESS; if (OB_ISNULL(dst) || OB_ISNULL(src) || n < 0 || row_size < 0 || copy_row_idx < 0 || copy_row_idx >= row_size || copy_row_cnt < 1 || copy_row_cnt > row_size) { ret = OB_INVALID_ARGUMENT; LOG_ERROR("invalid argument", K(ret), KP(dst), KP(src), K(n), K(row_size), K(copy_row_idx), K(copy_row_cnt)); } else { const int64_t mem_copy_size = copy_row_cnt * sizeof(void*); int64_t idx = 0; for (int64_t i = 0; i < n; i++) { for (int64_t j = 0; j < i; j++) { memcpy(&dst[idx], &src[SRC_ITEM_OFF(i, j) + copy_row_idx], mem_copy_size); idx += copy_row_cnt; memcpy(&dst[idx], &src[SRC_ITEM_OFF(j, i) + copy_row_idx], mem_copy_size); idx += copy_row_cnt; } memcpy(&dst[idx], &src[SRC_ITEM_OFF(i, i) + copy_row_idx], mem_copy_size); idx += copy_row_cnt; } } return OB_SUCCESS == ret; } } // end namespace sql } // end namespace oceanbase
#include "AsyncProducers.h" #include "ExprUsesVar.h" #include "Function.h" #include "IREquality.h" #include "IRMutator.h" #include "IROperator.h" namespace Halide { namespace Internal { using std::map; using std::pair; using std::set; using std::string; using std::vector; /** A mutator which eagerly folds no-op stmts */ class NoOpCollapsingMutator : public IRMutator { protected: using IRMutator::visit; Stmt visit(const LetStmt *op) override { Stmt body = mutate(op->body); if (is_no_op(body)) { return body; } else { return LetStmt::make(op->name, op->value, body); } } Stmt visit(const For *op) override { Stmt body = mutate(op->body); if (is_no_op(body)) { return body; } else { return For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body); } } Stmt visit(const Block *op) override { Stmt first = mutate(op->first); Stmt rest = mutate(op->rest); if (is_no_op(first)) { return rest; } else if (is_no_op(rest)) { return first; } else { return Block::make(first, rest); } } Stmt visit(const Fork *op) override { Stmt first = mutate(op->first); Stmt rest = mutate(op->rest); if (is_no_op(first)) { return rest; } else if (is_no_op(rest)) { return first; } else { return Fork::make(first, rest); } } Stmt visit(const Realize *op) override { Stmt body = mutate(op->body); if (is_no_op(body)) { return body; } else { return Realize::make(op->name, op->types, op->memory_type, op->bounds, op->condition, body); } } Stmt visit(const Allocate *op) override { Stmt body = mutate(op->body); if (is_no_op(body)) { return body; } else { return Allocate::make(op->name, op->type, op->memory_type, op->extents, op->condition, body, op->new_expr, op->free_function); } } Stmt visit(const IfThenElse *op) override { Stmt then_case = mutate(op->then_case); Stmt else_case = mutate(op->else_case); if (is_no_op(then_case) && is_no_op(else_case)) { return then_case; } else { return IfThenElse::make(op->condition, then_case, else_case); } } Stmt visit(const Atomic *op) override { Stmt body = mutate(op->body); if (is_no_op(body)) { return body; } else { return Atomic::make(op->producer_name, op->mutex_name, std::move(body)); } } }; class GenerateProducerBody : public NoOpCollapsingMutator { const string &func; vector<Expr> sema; using NoOpCollapsingMutator::visit; // Preserve produce nodes and add synchronization Stmt visit(const ProducerConsumer *op) override { if (op->name == func && op->is_producer) { // Add post-synchronization internal_assert(!sema.empty()) << "Duplicate produce node: " << op->name << "\n"; Stmt body = op->body; while (!sema.empty()) { Expr release = Call::make(Int(32), "halide_semaphore_release", {sema.back(), 1}, Call::Extern); body = Block::make(body, Evaluate::make(release)); sema.pop_back(); } return ProducerConsumer::make_produce(op->name, body); } else { Stmt body = mutate(op->body); if (is_no_op(body) || op->is_producer) { return body; } else { return ProducerConsumer::make(op->name, op->is_producer, body); } } } // Other stmt leaves get replaced with no-ops Stmt visit(const Evaluate *) override { return Evaluate::make(0); } Stmt visit(const Provide *) override { return Evaluate::make(0); } Stmt visit(const Store *op) override { if (starts_with(op->name, func + ".folding_semaphore.") && ends_with(op->name, ".head")) { // This is a counter associated with the producer side of a storage-folding semaphore. Keep it. return op; } else { return Evaluate::make(0); } } Stmt visit(const AssertStmt *) override { return Evaluate::make(0); } Stmt visit(const Prefetch *) override { return Evaluate::make(0); } Stmt visit(const Acquire *op) override { Stmt body = mutate(op->body); const Variable *var = op->semaphore.as<Variable>(); internal_assert(var); if (is_no_op(body)) { return body; } else if (starts_with(var->name, func + ".folding_semaphore.")) { // This is a storage-folding semaphore for the func we're producing. Keep it. return Acquire::make(op->semaphore, op->count, body); } else { // This semaphore will end up on both sides of the fork, // so we'd better duplicate it. string cloned_acquire = var->name + unique_name('_'); cloned_acquires[var->name] = cloned_acquire; return Acquire::make(Variable::make(type_of<halide_semaphore_t *>(), cloned_acquire), op->count, body); } } Stmt visit(const Atomic *op) override { return Evaluate::make(0); } Expr visit(const Call *op) override { if (op->name == "halide_semaphore_init") { internal_assert(op->args.size() == 2); const Variable *var = op->args[0].as<Variable>(); internal_assert(var); inner_semaphores.insert(var->name); } return op; } map<string, string> &cloned_acquires; set<string> inner_semaphores; public: GenerateProducerBody(const string &f, const vector<Expr> &s, map<string, string> &a) : func(f), sema(s), cloned_acquires(a) { } }; class GenerateConsumerBody : public NoOpCollapsingMutator { const string &func; vector<Expr> sema; using NoOpCollapsingMutator::visit; Stmt visit(const ProducerConsumer *op) override { if (op->name == func) { if (op->is_producer) { // Remove the work entirely return Evaluate::make(0); } else { // Synchronize on the work done by the producer before beginning consumption Expr acquire_sema = sema.back(); sema.pop_back(); return Acquire::make(acquire_sema, 1, op); } } else { return NoOpCollapsingMutator::visit(op); } } Stmt visit(const Allocate *op) override { // Don't want to keep the producer's storage-folding tracker - it's dead code on the consumer side if (starts_with(op->name, func + ".folding_semaphore.") && ends_with(op->name, ".head")) { return mutate(op->body); } else { return NoOpCollapsingMutator::visit(op); } } Stmt visit(const Store *op) override { if (starts_with(op->name, func + ".folding_semaphore.") && ends_with(op->name, ".head")) { return Evaluate::make(0); } else { return NoOpCollapsingMutator::visit(op); } } Stmt visit(const Acquire *op) override { // Don't want to duplicate any semaphore acquires. // Ones from folding should go to the producer side. const Variable *var = op->semaphore.as<Variable>(); internal_assert(var); if (starts_with(var->name, func + ".folding_semaphore.")) { return mutate(op->body); } else { return NoOpCollapsingMutator::visit(op); } } public: GenerateConsumerBody(const string &f, const vector<Expr> &s) : func(f), sema(s) { } }; class CloneAcquire : public IRMutator { using IRMutator::visit; const string &old_name; Expr new_var; Stmt visit(const Evaluate *op) override { const Call *call = op->value.as<Call>(); const Variable *var = ((call && !call->args.empty()) ? call->args[0].as<Variable>() : nullptr); if (var && var->name == old_name && (call->name == "halide_semaphore_release" || call->name == "halide_semaphore_init")) { vector<Expr> args = call->args; args[0] = new_var; Stmt new_stmt = Evaluate::make(Call::make(call->type, call->name, args, call->call_type)); return Block::make(op, new_stmt); } else { return op; } } public: CloneAcquire(const string &o, const string &new_name) : old_name(o) { new_var = Variable::make(type_of<halide_semaphore_t *>(), new_name); } }; class CountConsumeNodes : public IRVisitor { const string &func; using IRVisitor::visit; void visit(const ProducerConsumer *op) override { if (op->name == func && !op->is_producer) { count++; } IRVisitor::visit(op); } public: CountConsumeNodes(const string &f) : func(f) { } int count = 0; }; class ForkAsyncProducers : public IRMutator { using IRMutator::visit; const map<string, Function> &env; map<string, string> cloned_acquires; Stmt visit(const Realize *op) override { auto it = env.find(op->name); internal_assert(it != env.end()); Function f = it->second; if (f.schedule().async()) { Stmt body = op->body; // Make two copies of the body, one which only does the // producer, and one which only does the consumer. Inject // synchronization to preserve dependencies. Put them in a // task-parallel block. // Make a semaphore per consume node CountConsumeNodes consumes(op->name); body.accept(&consumes); vector<string> sema_names; vector<Expr> sema_vars; for (int i = 0; i < consumes.count; i++) { sema_names.push_back(op->name + ".semaphore_" + std::to_string(i)); sema_vars.push_back(Variable::make(Handle(), sema_names.back())); } Stmt producer = GenerateProducerBody(op->name, sema_vars, cloned_acquires).mutate(body); Stmt consumer = GenerateConsumerBody(op->name, sema_vars).mutate(body); // Recurse on both sides producer = mutate(producer); consumer = mutate(consumer); // Run them concurrently body = Fork::make(producer, consumer); for (const string &sema_name : sema_names) { // Make a semaphore on the stack Expr sema_space = Call::make(type_of<halide_semaphore_t *>(), "halide_make_semaphore", {0}, Call::Extern); // If there's a nested async producer, we may have // recursively cloned this semaphore inside the mutation // of the producer and consumer. auto it = cloned_acquires.find(sema_name); if (it != cloned_acquires.end()) { body = CloneAcquire(sema_name, it->second).mutate(body); body = LetStmt::make(it->second, sema_space, body); } body = LetStmt::make(sema_name, sema_space, body); } return Realize::make(op->name, op->types, op->memory_type, op->bounds, op->condition, body); } else { return IRMutator::visit(op); } } public: ForkAsyncProducers(const map<string, Function> &e) : env(e) { } }; // Lowers semaphore initialization from a call to // "halide_make_semaphore" to an alloca followed by a call into the // runtime to initialize. If something crashes before releasing a // semaphore, the task system is responsible for propagating the // failure to all branches of the fork. This depends on all semaphore // acquires happening as part of the halide_do_parallel_tasks logic, // not via explicit code in the closure. The current design for this // does not propagate failures downward to subtasks of a failed // fork. It assumes these will be able to reach completion in spite of // the failure, which remains to be proven. (There is a test for the // simple failure case, error_async_require_fail. One has not been // written for the complex nested case yet.) class InitializeSemaphores : public IRMutator { using IRMutator::visit; const Type sema_type = type_of<halide_semaphore_t *>(); Stmt visit(const LetStmt *op) override { vector<const LetStmt *> frames; // Find first op that is of sema_type while (op && op->value.type() != sema_type) { frames.push_back(op); op = op->body.as<LetStmt>(); } Stmt body; if (op) { body = mutate(op->body); // Peel off any enclosing let expressions from the value vector<pair<string, Expr>> lets; Expr value = op->value; while (const Let *l = value.as<Let>()) { lets.emplace_back(l->name, l->value); value = l->body; } const Call *call = value.as<Call>(); if (call && call->name == "halide_make_semaphore") { internal_assert(call->args.size() == 1); Expr sema_var = Variable::make(sema_type, op->name); Expr sema_init = Call::make(Int(32), "halide_semaphore_init", {sema_var, call->args[0]}, Call::Extern); Expr sema_allocate = Call::make(sema_type, Call::alloca, {(int)sizeof(halide_semaphore_t)}, Call::Intrinsic); body = Block::make(Evaluate::make(sema_init), std::move(body)); body = LetStmt::make(op->name, std::move(sema_allocate), std::move(body)); // Re-wrap any other lets for (auto it = lets.rbegin(); it != lets.rend(); it++) { body = LetStmt::make(it->first, it->second, std::move(body)); } } } else { body = mutate(frames.back()->body); } for (auto it = frames.rbegin(); it != frames.rend(); it++) { Expr value = mutate((*it)->value); if (value.same_as((*it)->value) && body.same_as((*it)->body)) { body = *it; } else { body = LetStmt::make((*it)->name, std::move(value), std::move(body)); } } return body; } Expr visit(const Call *op) override { internal_assert(op->name != "halide_make_semaphore") << "Call to halide_make_semaphore in unexpected place\n"; return op; } }; // Tighten the scope of consume nodes as much as possible to avoid needless synchronization. class TightenProducerConsumerNodes : public IRMutator { using IRMutator::visit; Stmt make_producer_consumer(const string &name, bool is_producer, Stmt body, const Scope<int> &scope) { if (const LetStmt *let = body.as<LetStmt>()) { if (expr_uses_vars(let->value, scope)) { return ProducerConsumer::make(name, is_producer, body); } else { return LetStmt::make(let->name, let->value, make_producer_consumer(name, is_producer, let->body, scope)); } } else if (const Block *block = body.as<Block>()) { // Check which sides it's used on bool first = stmt_uses_vars(block->first, scope); bool rest = stmt_uses_vars(block->rest, scope); if (is_producer) { return ProducerConsumer::make(name, is_producer, body); } else if (first && rest) { return Block::make(make_producer_consumer(name, is_producer, block->first, scope), make_producer_consumer(name, is_producer, block->rest, scope)); } else if (first) { return Block::make(make_producer_consumer(name, is_producer, block->first, scope), block->rest); } else if (rest) { return Block::make(block->first, make_producer_consumer(name, is_producer, block->rest, scope)); } else { // Used on neither side?! return body; } } else if (const ProducerConsumer *pc = body.as<ProducerConsumer>()) { return ProducerConsumer::make(pc->name, pc->is_producer, make_producer_consumer(name, is_producer, pc->body, scope)); } else if (const Realize *r = body.as<Realize>()) { return Realize::make(r->name, r->types, r->memory_type, r->bounds, r->condition, make_producer_consumer(name, is_producer, r->body, scope)); } else { return ProducerConsumer::make(name, is_producer, body); } } Stmt visit(const ProducerConsumer *op) override { Stmt body = mutate(op->body); Scope<int> scope; scope.push(op->name, 0); Function f = env.find(op->name)->second; if (f.outputs() == 1) { scope.push(op->name + ".buffer", 0); } else { for (int i = 0; i < f.outputs(); i++) { scope.push(op->name + "." + std::to_string(i) + ".buffer", 0); } } return make_producer_consumer(op->name, op->is_producer, body, scope); } const map<string, Function> &env; public: TightenProducerConsumerNodes(const map<string, Function> &e) : env(e) { } }; // Broaden the scope of acquire nodes to pack trailing work into the // same task and to potentially reduce the nesting depth of tasks. class ExpandAcquireNodes : public IRMutator { using IRMutator::visit; Stmt visit(const Block *op) override { // Do an entire sequence of blocks in a single visit method to conserve stack space. vector<Stmt> stmts; Stmt result; do { stmts.push_back(mutate(op->first)); result = op->rest; } while ((op = result.as<Block>())); result = mutate(result); vector<pair<Expr, Expr>> semaphores; for (auto it = stmts.rbegin(); it != stmts.rend(); it++) { Stmt s = *it; while (const Acquire *a = s.as<Acquire>()) { semaphores.emplace_back(a->semaphore, a->count); s = a->body; } result = Block::make(s, result); while (!semaphores.empty()) { result = Acquire::make(semaphores.back().first, semaphores.back().second, result); semaphores.pop_back(); } } return result; } Stmt visit(const Realize *op) override { Stmt body = mutate(op->body); if (const Acquire *a = body.as<Acquire>()) { // Don't do the allocation until we have the // semaphore. Reduces peak memory use. return Acquire::make(a->semaphore, a->count, mutate(Realize::make(op->name, op->types, op->memory_type, op->bounds, op->condition, a->body))); } else { return Realize::make(op->name, op->types, op->memory_type, op->bounds, op->condition, body); } } Stmt visit(const LetStmt *op) override { Stmt body = mutate(op->body); const Acquire *a = body.as<Acquire>(); if (a && !expr_uses_var(a->semaphore, op->name) && !expr_uses_var(a->count, op->name)) { return Acquire::make(a->semaphore, a->count, LetStmt::make(op->name, op->value, a->body)); } else { return LetStmt::make(op->name, op->value, body); } } Stmt visit(const ProducerConsumer *op) override { Stmt body = mutate(op->body); if (const Acquire *a = body.as<Acquire>()) { return Acquire::make(a->semaphore, a->count, mutate(ProducerConsumer::make(op->name, op->is_producer, a->body))); } else { return ProducerConsumer::make(op->name, op->is_producer, body); } } }; class TightenForkNodes : public IRMutator { using IRMutator::visit; Stmt make_fork(const Stmt &first, const Stmt &rest) { const LetStmt *lf = first.as<LetStmt>(); const LetStmt *lr = rest.as<LetStmt>(); const Realize *rf = first.as<Realize>(); const Realize *rr = rest.as<Realize>(); if (lf && lr && lf->name == lr->name && equal(lf->value, lr->value)) { return LetStmt::make(lf->name, lf->value, make_fork(lf->body, lr->body)); } else if (lf && !stmt_uses_var(rest, lf->name)) { return LetStmt::make(lf->name, lf->value, make_fork(lf->body, rest)); } else if (lr && !stmt_uses_var(first, lr->name)) { return LetStmt::make(lr->name, lr->value, make_fork(first, lr->body)); } else if (rf && !stmt_uses_var(rest, rf->name)) { return Realize::make(rf->name, rf->types, rf->memory_type, rf->bounds, rf->condition, make_fork(rf->body, rest)); } else if (rr && !stmt_uses_var(first, rr->name)) { return Realize::make(rr->name, rr->types, rr->memory_type, rr->bounds, rr->condition, make_fork(first, rr->body)); } else { return Fork::make(first, rest); } } Stmt visit(const Fork *op) override { Stmt first, rest; { ScopedValue<bool> old_in_fork(in_fork, true); first = mutate(op->first); rest = mutate(op->rest); } if (is_no_op(first)) { return rest; } else if (is_no_op(rest)) { return first; } else { return make_fork(first, rest); } } // This is also a good time to nuke any dangling allocations and lets in the fork children. Stmt visit(const Realize *op) override { Stmt body = mutate(op->body); if (in_fork && !stmt_uses_var(body, op->name) && !stmt_uses_var(body, op->name + ".buffer")) { return body; } else { return Realize::make(op->name, op->types, op->memory_type, op->bounds, op->condition, body); } } Stmt visit(const LetStmt *op) override { Stmt body = mutate(op->body); if (in_fork && !stmt_uses_var(body, op->name)) { return body; } else { return LetStmt::make(op->name, op->value, body); } } bool in_fork = false; }; // TODO: merge semaphores? Stmt fork_async_producers(Stmt s, const map<string, Function> &env) { s = TightenProducerConsumerNodes(env).mutate(s); s = ForkAsyncProducers(env).mutate(s); s = ExpandAcquireNodes().mutate(s); s = TightenForkNodes().mutate(s); s = InitializeSemaphores().mutate(s); return s; } } // namespace Internal } // namespace Halide
/** @file * @author Edouard DUPIN * @copyright 2014, Edouard DUPIN, all right reserved * @license APACHE v2.0 (see license file) */ #include <audio/blockEngine/core/audio.hpp>
#include "LUATreeLoaderTest.h" namespace { const char *TREE = "function init ()" "local example = AI.createTree(\"example\")" "local rootNodeExample1 = example:createRoot(\"PrioritySelector\", \"root1\")" "rootNodeExample1:addNode(\"Idle{3000}\", \"idle3000_1\"):setCondition(\"True\")" "local rootNodeExample2 = AI.createTree(\"example2\"):createRoot(\"PrioritySelector\", \"root2\")" "rootNodeExample2:addNode(\"Idle{3000}\", \"idle3000_2\"):setCondition(\"True\")" "rootNodeExample2:addNode(\"Steer{0.6,0.4}(GroupFlee{2},Wander{1})\", \"wander\")" "end"; } class LUATreeLoaderTest: public TestSuite { protected: ai::AIRegistry _registry; ai::LUATreeLoader _loader; public: LUATreeLoaderTest() : _loader(_registry) { } void SetUp() override { TestSuite::SetUp(); ASSERT_TRUE(_loader.init(TREE)) << _loader.getError(); } void TearDown() override { TestSuite::TearDown(); _loader.shutdown(); } }; TEST_F(LUATreeLoaderTest, testLoadExample) { const ai::TreeNodePtr& tree = _loader.load("example"); ASSERT_NE(nullptr, tree.get()) << "Could not find the expected behaviour"; ASSERT_EQ("root1", tree->getName()) << "unexpected root node name"; const ai::TreeNodes& children = tree->getChildren(); const int childrenAmount = children.size(); ASSERT_EQ(1, childrenAmount) << "expected amount of children"; ASSERT_EQ("idle3000_1", children[0]->getName()) << "unexpected child node name"; ASSERT_EQ("True", children[0]->getCondition()->getName()) << "unexpected condition name"; } TEST_F(LUATreeLoaderTest, testLoadExample2) { const ai::TreeNodePtr& tree = _loader.load("example2"); ASSERT_NE(nullptr, tree.get()) << "Could not find the expected behaviour"; ASSERT_EQ("root2", tree->getName()) << "unexpected root node name"; const ai::TreeNodes& children = tree->getChildren(); const int childrenAmount = children.size(); ASSERT_EQ(2, childrenAmount) << "expected amount of children"; ASSERT_EQ("idle3000_2", children[0]->getName()) << "unexpected child node name"; ASSERT_EQ("True", children[0]->getCondition()->getName()) << "unexpected condition name"; ASSERT_EQ("wander", children[1]->getName()) << "unexpected child node name"; ASSERT_EQ("True", children[0]->getCondition()->getName()) << "unexpected condition name"; }
// Copyright 2018 The Beam Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "node.h" #include "../core/serialization_adapters.h" #include "../core/proto.h" #include "../core/ecc_native.h" #include "../p2p/protocol.h" #include "../p2p/connection.h" #include "../utility/io/tcpserver.h" #include "../utility/logger.h" #include "../utility/logger_checkpoints.h" #include "pow/external_pow.h" namespace beam { bool Node::SyncStatus::operator == (const SyncStatus& x) const { return (m_Done == x.m_Done) && (m_Total == x.m_Total); } void Node::RefreshCongestions() { for (TaskSet::iterator it = m_setTasks.begin(); m_setTasks.end() != it; it++) it->m_bNeeded = false; m_Processor.EnumCongestions(); for (TaskList::iterator it = m_lstTasksUnassigned.begin(); m_lstTasksUnassigned.end() != it; ) { Task& t = *(it++); if (!t.m_bNeeded) DeleteUnassignedTask(t); } } void Node::UpdateSyncStatus() { SyncStatus stat = m_SyncStatus; UpdateSyncStatusRaw(); if (!(m_SyncStatus == stat) && m_UpdatedFromPeers) { if (!m_PostStartSynced && (m_SyncStatus.m_Done == m_SyncStatus.m_Total) && !m_Processor.IsFastSync()) { m_PostStartSynced = true; LOG_INFO() << "Tx replication is ON"; for (PeerList::iterator it = m_lstPeers.begin(); m_lstPeers.end() != it; it++) { Peer& peer = *it; if (Peer::Flags::Connected & peer.m_Flags) peer.SendLogin(); } } if (m_Cfg.m_Observer) m_Cfg.m_Observer->OnSyncProgress(); } } void Node::UpdateSyncStatusRaw() { Height hToCursor = m_Processor.m_Cursor.m_ID.m_Height * (SyncStatus::s_WeightHdr + SyncStatus::s_WeightBlock); m_SyncStatus.m_Total = hToCursor; m_SyncStatus.m_Done = hToCursor; if (m_Processor.IsFastSync()) { m_SyncStatus.m_Total += (m_Processor.m_SyncData.m_Target.m_Height - m_Processor.m_Cursor.m_ID.m_Height) * (SyncStatus::s_WeightHdr + SyncStatus::s_WeightBlock); m_SyncStatus.m_Done += (m_Processor.m_SyncData.m_Target.m_Height - m_Processor.m_Cursor.m_ID.m_Height) * SyncStatus::s_WeightHdr; TaskSet::iterator it = m_setTasks.begin(); if (m_setTasks.end() != it) { const Block::SystemState::ID& id = it->m_Key.first; if (id.m_Height > m_Processor.m_Cursor.m_ID.m_Height) m_SyncStatus.m_Done += (id.m_Height - m_Processor.m_Cursor.m_ID.m_Height) * SyncStatus::s_WeightBlock; } } bool bOnlyAssigned = (m_Processor.m_Cursor.m_ID.m_Height > 0); for (TaskSet::iterator it = m_setTasks.begin(); m_setTasks.end() != it; it++) { const Task& t = *it; if (!t.m_bNeeded) continue; if (m_Processor.m_Cursor.m_ID.m_Height >= t.m_sidTrg.m_Height) continue; if (bOnlyAssigned && !t.m_pOwner) continue; Height hVal = t.m_sidTrg.m_Height * (SyncStatus::s_WeightHdr + SyncStatus::s_WeightBlock); m_SyncStatus.m_Total = std::max(m_SyncStatus.m_Total, hVal); Height h = t.m_Key.first.m_Height; if (h > t.m_sidTrg.m_Height) continue; // ?! bool bBlock = t.m_Key.second; // If the request is the block - assume all the headers are received, as well as all the blocks up to cursor // If the request is the header - assume headers are requested in reverse order, up to current cursor (which isn't true in case of fork, but it's a coarse estimate) if (bBlock) h = m_Processor.m_Cursor.m_ID.m_Height; // the height down to which all the headers are already downloaded else if (h) h--; hVal = hToCursor + (t.m_sidTrg.m_Height - h) * SyncStatus::s_WeightHdr; m_SyncStatus.m_Done = std::max(m_SyncStatus.m_Done, hVal); } m_SyncStatus.m_Total = std::max(m_SyncStatus.m_Total, m_SyncStatus.m_Done); } void Node::DeleteUnassignedTask(Task& t) { assert(!t.m_pOwner && !t.m_bPack); m_lstTasksUnassigned.erase(TaskList::s_iterator_to(t)); m_setTasks.erase(TaskSet::s_iterator_to(t)); delete &t; } uint32_t Node::WantedTx::get_Timeout_ms() { return get_ParentObj().m_Cfg.m_Timeout.m_GetTx_ms; } void Node::WantedTx::OnExpired(const KeyType& key) { proto::GetTransaction msg; msg.m_ID = key; for (PeerList::iterator it = get_ParentObj().m_lstPeers.begin(); get_ParentObj().m_lstPeers.end() != it; it++) { Peer& peer = *it; if (peer.m_LoginFlags & proto::LoginFlags::SpreadingTransactions) peer.Send(msg); } } void Node::Bbs::CalcMsgKey(NodeDB::WalkerBbs::Data& d) { ECC::Hash::Processor() << d.m_Message << d.m_Channel >> d.m_Key; } uint32_t Node::Bbs::WantedMsg::get_Timeout_ms() { return get_ParentObj().get_ParentObj().m_Cfg.m_Timeout.m_GetBbsMsg_ms; } void Node::Bbs::WantedMsg::OnExpired(const KeyType& key) { proto::BbsGetMsg msg; msg.m_Key = key; for (PeerList::iterator it = get_ParentObj().get_ParentObj().m_lstPeers.begin(); get_ParentObj().get_ParentObj().m_lstPeers.end() != it; it++) { Peer& peer = *it; if (peer.m_LoginFlags & proto::LoginFlags::Bbs) peer.Send(msg); } get_ParentObj().MaybeCleanup(); } void Node::Wanted::Clear() { while (!m_lst.empty()) DeleteInternal(m_lst.back()); } void Node::Wanted::DeleteInternal(Item& n) { m_lst.erase(List::s_iterator_to(n)); m_set.erase(Set::s_iterator_to(n)); delete &n; } void Node::Wanted::Delete(Item& n) { bool bFront = (&m_lst.front() == &n); DeleteInternal(n); if (bFront) SetTimer(); } bool Node::Wanted::Delete(const KeyType& key) { Item n; n.m_Key = key; Set::iterator it = m_set.find(n); if (m_set.end() == it) return false; Delete(*it); return true; } bool Node::Wanted::Add(const KeyType& key) { Item n; n.m_Key = key; Set::iterator it = m_set.find(n); if (m_set.end() != it) return false; // already waiting for it bool bEmpty = m_lst.empty(); Item* p = new Item; p->m_Key = key; p->m_Advertised_ms = GetTime_ms(); m_set.insert(*p); m_lst.push_back(*p); if (bEmpty) SetTimer(); return true; } void Node::Wanted::SetTimer() { if (m_lst.empty()) { if (m_pTimer) m_pTimer->cancel(); } else { if (!m_pTimer) m_pTimer = io::Timer::create(io::Reactor::get_Current()); uint32_t dt = GetTime_ms() - m_lst.front().m_Advertised_ms; const uint32_t timeout_ms = get_Timeout_ms(); m_pTimer->start((timeout_ms > dt) ? (timeout_ms - dt) : 0, false, [this]() { OnTimer(); }); } } void Node::Wanted::OnTimer() { uint32_t t_ms = GetTime_ms(); const uint32_t timeout_ms = get_Timeout_ms(); while (!m_lst.empty()) { Item& n = m_lst.front(); if (t_ms - n.m_Advertised_ms < timeout_ms) break; OnExpired(n.m_Key); // should not invalidate our structure Delete(n); // will also reschedule the timer } } void Node::TryAssignTask(Task& t, const PeerID* pPeerID) { // prefer to request data from nodes supporting latest protocol for (uint32_t iCycle = 0; iCycle < 2; iCycle++) { if (pPeerID) { bool bCreate = false; PeerMan::PeerInfoPlus* pInfo = Cast::Up<PeerMan::PeerInfoPlus>(m_PeerMan.Find(*pPeerID, bCreate)); if (pInfo && pInfo->m_pLive && TryAssignTask(t, *pInfo->m_pLive, !iCycle)) return; } for (PeerList::iterator it = m_lstPeers.begin(); m_lstPeers.end() != it; it++) { Peer& p = *it; if (TryAssignTask(t, p, !iCycle)) return; } } } bool Node::TryAssignTask(Task& t, Peer& p, bool bMustSupportLatestProto) { if (bMustSupportLatestProto && !(proto::LoginFlags::Extension2 & p.m_LoginFlags)) return false; return TryAssignTask(t, p); } bool Node::TryAssignTask(Task& t, Peer& p) { uint32_t nPacks = t.m_Key.second ? m_nTasksPackBody : m_nTasksPackHdr; if (nPacks) return false; if (!p.ShouldAssignTasks()) return false; if (p.m_Tip.m_Height < t.m_Key.first.m_Height) return false; if (p.m_Tip.m_Height == t.m_Key.first.m_Height) { if (t.m_Key.first.m_Height) { Merkle::Hash hv; p.m_Tip.get_Hash(hv); if (hv != t.m_Key.first.m_Hash) return false; } else { // treasury if (!(Peer::Flags::HasTreasury & p.m_Flags)) return false; } } if (p.m_setRejected.end() != p.m_setRejected.find(t.m_Key)) return false; // check if the peer currently transfers a block uint32_t nBlocks = 0; for (TaskList::iterator it = p.m_lstTasks.begin(); p.m_lstTasks.end() != it; it++) if (it->m_Key.second) nBlocks++; // assign if (t.m_Key.second) { assert(!m_nTasksPackBody); Height hCountExtra = t.m_sidTrg.m_Height - t.m_Key.first.m_Height; if (proto::LoginFlags::Extension2 & p.m_LoginFlags) { proto::GetBodyPack msg; if (t.m_Key.first.m_Height <= m_Processor.m_SyncData.m_Target.m_Height) { // fast-sync mode, diluted blocks request. msg.m_Top.m_Height = m_Processor.m_SyncData.m_Target.m_Height; if (m_Processor.IsFastSync()) m_Processor.get_DB().get_StateHash(m_Processor.m_SyncData.m_Target.m_Row, msg.m_Top.m_Hash); else msg.m_Top.m_Hash = Zero; // treasury msg.m_CountExtra = m_Processor.m_SyncData.m_Target.m_Height - t.m_Key.first.m_Height; msg.m_Height0 = m_Processor.m_SyncData.m_h0; msg.m_HorizonLo1 = m_Processor.m_SyncData.m_TxoLo; msg.m_HorizonHi1 = m_Processor.m_SyncData.m_Target.m_Height; } else { // std blocks request msg.m_Top.m_Height = t.m_sidTrg.m_Height; m_Processor.get_DB().get_StateHash(t.m_sidTrg.m_Row, msg.m_Top.m_Hash); msg.m_CountExtra = hCountExtra; } p.Send(msg); t.m_bPack = true; m_nTasksPackBody++; } else { // old peer if (m_Processor.IsFastSync()) return false; // incompatible for (const uint64_t* pPtr = nullptr; ; ) { proto::GetBody msg; msg.m_ID = t.m_Key.first; p.Send(msg); if (++nBlocks >= m_Cfg.m_MaxConcurrentBlocksRequest) break; if (msg.m_ID.m_Height >= t.m_sidTrg.m_Height) break; // request more blocks, if applicable if (!pPtr) { pPtr = m_Processor.get_CachedRows(t.m_sidTrg, hCountExtra); if (!pPtr) break; } Task* pTask = new Task; pTask->m_Key = t.m_Key; m_setTasks.insert(*pTask); pTask->m_pOwner = &p; p.m_lstTasks.push_back(*pTask); pTask->m_sidTrg = t.m_sidTrg; pTask->m_bNeeded = false; pTask->m_bPack = false; t.m_Key.first.m_Height++; uint64_t rowid = pPtr[t.m_sidTrg.m_Height - t.m_Key.first.m_Height]; m_Processor.get_DB().get_StateHash(rowid, t.m_Key.first.m_Hash); m_setTasks.erase(TaskSet::s_iterator_to(t)); m_setTasks.insert(t); } } } else { assert(!m_nTasksPackHdr); if (nBlocks) return false; // don't requests headers from the peer that transfers a block uint32_t nPackSize = 0; if (t.m_Key.first.m_Height > m_Processor.m_Cursor.m_ID.m_Height) { Height dh = t.m_Key.first.m_Height - m_Processor.m_Cursor.m_ID.m_Height; if (dh > 1) { nPackSize = (proto::LoginFlags::Extension2 & p.m_LoginFlags) ? proto::g_HdrPackMaxSize : proto::g_HdrPackMaxSizeV0; if (nPackSize > dh) nPackSize = (uint32_t)dh; } } if (nPackSize) { proto::GetHdrPack msg; msg.m_Top = t.m_Key.first; msg.m_Count = nPackSize; p.Send(msg); t.m_bPack = true; m_nTasksPackHdr++; } else { proto::GetHdr msg; msg.m_ID = t.m_Key.first; p.Send(msg); } } bool bEmpty = p.m_lstTasks.empty(); assert(!t.m_pOwner); t.m_pOwner = &p; m_lstTasksUnassigned.erase(TaskList::s_iterator_to(t)); p.m_lstTasks.push_back(t); if (bEmpty) p.SetTimerWrtFirstTask(); return true; } void Node::Peer::SetTimerWrtFirstTask() { if (m_lstTasks.empty()) KillTimer(); else SetTimer(m_lstTasks.front().m_Key.second ? m_This.m_Cfg.m_Timeout.m_GetBlock_ms : m_This.m_Cfg.m_Timeout.m_GetState_ms); } void Node::Processor::RequestData(const Block::SystemState::ID& id, bool bBlock, const PeerID* pPreferredPeer, const NodeDB::StateID& sidTrg) { Node::Task tKey; tKey.m_Key.first = id; tKey.m_Key.second = bBlock; TaskSet::iterator it = get_ParentObj().m_setTasks.find(tKey); if (get_ParentObj().m_setTasks.end() == it) { LOG_INFO() << "Requesting " << (bBlock ? "block" : "header") << " " << id; Node::Task* pTask = new Node::Task; pTask->m_Key = tKey.m_Key; pTask->m_sidTrg = sidTrg; pTask->m_bNeeded = true; pTask->m_bPack = false; pTask->m_pOwner = NULL; get_ParentObj().m_setTasks.insert(*pTask); get_ParentObj().m_lstTasksUnassigned.push_back(*pTask); get_ParentObj().TryAssignTask(*pTask, pPreferredPeer); } else { Node::Task& t = *it; t.m_bNeeded = true; if (!t.m_pOwner && (t.m_sidTrg.m_Height < sidTrg.m_Height)) t.m_sidTrg = sidTrg; } } void Node::Processor::OnPeerInsane(const PeerID& peerID) { // Deleting the insane peer in-place is dangerous, because we may be invoked in its context. // Use "async-delete mechanism if (!m_pAsyncPeerInsane) { io::AsyncEvent::Callback cb = [this]() { FlushInsanePeers(); }; m_pAsyncPeerInsane = io::AsyncEvent::create(io::Reactor::get_Current(), std::move(cb)); } m_lstInsanePeers.push_back(peerID); m_pAsyncPeerInsane->get_trigger()(); } void Node::Processor::FlushInsanePeers() { for (; !m_lstInsanePeers.empty(); m_lstInsanePeers.pop_front()) { bool bCreate = false; PeerMan::PeerInfoPlus* pInfo = Cast::Up<PeerMan::PeerInfoPlus>(get_ParentObj().m_PeerMan.Find(m_lstInsanePeers.front(), bCreate)); if (pInfo) { Peer* pPeer = pInfo->m_pLive; if (pPeer) pPeer->DeleteSelf(true, proto::NodeConnection::ByeReason::Ban); else get_ParentObj().m_PeerMan.Ban(*pInfo); } } } void Node::Processor::OnNewState() { m_Cwp.Reset(); if (!IsTreasuryHandled()) return; LOG_INFO() << "My Tip: " << m_Cursor.m_ID << ", Work = " << Difficulty::ToFloat(m_Cursor.m_Full.m_ChainWork); if (IsFastSync()) return; //get_ParentObj().m_TxPool.DeleteOutOfBound(m_Cursor.m_Sid.m_Height + 1); get_ParentObj().m_Processor.DeleteOutdated(get_ParentObj().m_TxPool); // Better to delete all irrelevant txs explicitly, even if the node is supposed to mine // because in practice mining could be OFF (for instance, if miner key isn't defined, and owner wallet is offline). if (get_ParentObj().m_Miner.IsEnabled()) { get_ParentObj().m_Miner.HardAbortSafe(); get_ParentObj().m_Miner.SetTimer(0, true); // async start mining } proto::NewTip msg; msg.m_Description = m_Cursor.m_Full; for (PeerList::iterator it = get_ParentObj().m_lstPeers.begin(); get_ParentObj().m_lstPeers.end() != it; it++) { Peer& peer = *it; if (!(Peer::Flags::Connected & peer.m_Flags)) continue; if (msg.m_Description.m_Height >= Rules::HeightGenesis) { if (!NodeProcessor::IsRemoteTipNeeded(msg.m_Description, peer.m_Tip)) continue; } else { if (Peer::Flags::HasTreasury & peer.m_Flags) continue; } peer.Send(msg); } get_ParentObj().RefreshCongestions(); IObserver* pObserver = get_ParentObj().m_Cfg.m_Observer; if (pObserver) pObserver->OnStateChanged(); } void Node::Processor::OnRolledBack() { LOG_INFO() << "Rolled back to: " << m_Cursor.m_ID; IObserver* pObserver = get_ParentObj().m_Cfg.m_Observer; if (pObserver) pObserver->OnRolledBack(m_Cursor.m_ID); } uint32_t Node::Processor::TaskProcessor::get_Threads() { uint32_t nThreads = get_ParentObj().get_ParentObj().m_Cfg.m_VerificationThreads; return std::max(nThreads, 1U); } void Node::Processor::TaskProcessor::InitSafe() { if (!m_vThreads.empty()) return; m_Run = true; m_pCtl = nullptr; m_InProgress = 0; m_FlushTarget = static_cast<uint32_t>(-1); uint32_t nThreads = get_Threads(); m_vThreads.resize(nThreads); for (uint32_t i = 0; i < nThreads; i++) m_vThreads[i] = std::thread(&TaskProcessor::Thread, this, i); } void Node::Processor::TaskProcessor::Push(Task::Ptr&& pTask) { assert(pTask); InitSafe(); std::unique_lock<std::mutex> scope(m_Mutex); m_queTasks.push_back(std::move(pTask)); m_InProgress++; m_NewTask.notify_one(); } uint32_t Node::Processor::TaskProcessor::Flush(uint32_t nMaxTasks) { InitSafe(); std::unique_lock<std::mutex> scope(m_Mutex); FlushLocked(scope, nMaxTasks); return m_InProgress; } void Node::Processor::TaskProcessor::FlushLocked(std::unique_lock<std::mutex>& scope, uint32_t nMaxTasks) { m_FlushTarget = nMaxTasks; while (m_InProgress > nMaxTasks) m_Flushed.wait(scope); m_FlushTarget = static_cast<uint32_t>(-1); } void Node::Processor::TaskProcessor::ExecAll(Task& t) { InitSafe(); std::unique_lock<std::mutex> scope(m_Mutex); FlushLocked(scope, 0); assert(!m_pCtl && !m_InProgress); m_pCtl = &t; m_InProgress = get_Threads(); m_NewTask.notify_all(); FlushLocked(scope, 0); assert(!m_pCtl); } void Node::Processor::TaskProcessor::Stop() { if (m_vThreads.empty()) return; { std::unique_lock<std::mutex> scope(m_Mutex); m_Run = false; m_NewTask.notify_all(); } for (size_t i = 0; i < m_vThreads.size(); i++) if (m_vThreads[i].joinable()) m_vThreads[i].join(); m_vThreads.clear(); m_queTasks.clear(); } void Node::Processor::TaskProcessor::Thread(uint32_t) { std::unique_ptr<MyBatch> p(new MyBatch); p->m_bEnableBatch = true; MyBatch::Scope scopeBatch(*p); while (true) { Task::Ptr pGuard; Task* pTask; { std::unique_lock<std::mutex> scope(m_Mutex); while (true) { if (!m_Run) return; if (!m_queTasks.empty()) { pGuard = std::move(m_queTasks.front()); pTask = pGuard.get(); m_queTasks.pop_front(); break; } if (m_pCtl) { pTask = m_pCtl; break; } m_NewTask.wait(scope); } } assert(pTask && m_InProgress); pTask->Exec(); std::unique_lock<std::mutex> scope(m_Mutex); assert(m_InProgress); m_InProgress--; if (pGuard) { // standard task if (m_InProgress == m_FlushTarget) m_Flushed.notify_one(); } else { // control task if (m_InProgress) m_Flushed.wait(scope); // make sure we give other threads opportuinty to execute the control task else { m_pCtl = nullptr; m_Flushed.notify_all(); } } } } void Node::Processor::OnModified() { if (!m_bFlushPending) { if (!m_pFlushTimer) m_pFlushTimer = io::Timer::create(io::Reactor::get_Current()); m_pFlushTimer->start(50, false, [this]() { OnFlushTimer(); }); m_bFlushPending = true; } } void Node::Processor::TryGoUpAsync() { if (!m_bGoUpPending) { if (!m_pGoUpTimer) m_pGoUpTimer = io::Timer::create(io::Reactor::get_Current()); m_pGoUpTimer->start(0, false, [this]() { OnGoUpTimer(); }); m_bGoUpPending = true; } } void Node::Processor::OnGoUpTimer() { m_bGoUpPending = false; TryGoUp(); get_ParentObj().RefreshCongestions(); get_ParentObj().UpdateSyncStatus(); } bool Node::Processor::EnumViewerKeys(IKeyWalker& w) { const Keys& keys = get_ParentObj().m_Keys; // according to current design - a single master viewer key is enough if (keys.m_pOwner && !w.OnKey(*keys.m_pOwner, 0)) { // stupid compiler insists on parentheses here! return false; } if (keys.m_bRecoverViaDummyKey && !w.OnKey(*keys.m_pOwner, 1)) { // stupid compiler insists on parentheses here! return false; } return true; } void Node::Processor::OnUtxoEvent(const UtxoEvent::Value& evt) { if (get_ParentObj().m_Cfg.m_LogUtxos) { ECC::Key::IDV kidv; kidv = evt.m_Kidv; Height h; evt.m_Maturity.Export(h); LOG_INFO() << "Utxo " << kidv << ", Maturity=" << h << ", Added=" << static_cast<uint32_t>(evt.m_Added); } } void Node::Processor::OnDummy(const Key::ID& kid, Height) { NodeDB& db = get_DB(); if (db.GetDummyHeight(kid) != MaxHeight) return; // recovered Height h = get_ParentObj().SampleDummySpentHeight(); h += get_ParentObj().m_Cfg.m_Dandelion.m_DummyLifetimeHi * 2; // add some factor, to make sure the original creator node will spent it before us (if it's still running) db.InsertDummy(h, kid); } void Node::Processor::OnFlushTimer() { m_bFlushPending = false; CommitDB(); } void Node::Processor::FlushDB() { if (m_bFlushPending) { assert(m_pFlushTimer); m_pFlushTimer->cancel(); OnFlushTimer(); } } Node::Peer* Node::AllocPeer(const beam::io::Address& addr) { Peer* pPeer = new Peer(*this); m_lstPeers.push_back(*pPeer); pPeer->m_UnsentHiMark = m_Cfg.m_BandwidthCtl.m_Drown; pPeer->m_pInfo = NULL; pPeer->m_Flags = 0; pPeer->m_Port = 0; ZeroObject(pPeer->m_Tip); pPeer->m_RemoteAddr = addr; pPeer->m_LoginFlags = 0; pPeer->m_CursorBbs = std::numeric_limits<int64_t>::max(); pPeer->m_pCursorTx = nullptr; LOG_INFO() << "+Peer " << addr; return pPeer; } void Node::Keys::InitSingleKey(const ECC::uintBig& seed) { Key::IKdf::Ptr pKdf; ECC::HKdf::Create(pKdf, seed); SetSingleKey(pKdf); } void Node::Keys::SetSingleKey(const Key::IKdf::Ptr& pKdf) { m_nMinerSubIndex = 0; m_pMiner = pKdf; m_pGeneric = pKdf; m_pDummy = pKdf; m_pOwner = pKdf; } void Node::Initialize(IExternalPOW* externalPOW) { m_Processor.m_Horizon = m_Cfg.m_Horizon; //@@@ Processor初始化NodeProcessor::Initialize 文件node/processor.cpp m_Processor.Initialize(m_Cfg.m_sPathLocal.c_str(), m_Cfg.m_ProcessorParams); if (m_Cfg.m_VerificationThreads < 0) // use all the cores, don't subtract 'mining threads'. Verification has higher priority m_Cfg.m_VerificationThreads = std::thread::hardware_concurrency(); InitKeys(); InitIDs(); LOG_INFO() << "Node ID=" << m_MyPublicID; LOG_INFO() << "Initial Tip: " << m_Processor.m_Cursor.m_ID; LOG_INFO() << "Tx replication is OFF"; if (!m_Cfg.m_Treasury.empty() && !m_Processor.IsTreasuryHandled()) { // stupid compiler insists on parentheses here! LOG_INFO() << "@@@ OnTreasury..."; m_Processor.OnTreasury(Blob(m_Cfg.m_Treasury)); } RefreshOwnedUtxos(); ZeroObject(m_SyncStatus); RefreshCongestions(); if (m_Cfg.m_Listen.port()) { m_Server.Listen(m_Cfg.m_Listen); if (m_Cfg.m_BeaconPeriod_ms) m_Beacon.Start(); } m_PeerMan.Initialize(); m_Miner.Initialize(externalPOW); m_Bbs.Cleanup(); m_Bbs.m_HighestPosted_s = m_Processor.get_DB().get_BbsMaxTime(); m_Processor.OnHorizonChanged(); // invoke it once again, after the Compressor initialized and maybe deleted some of backlog, perhaps fossil height may go up } void Node::InitKeys() { if (!m_Keys.m_pOwner) m_Keys.m_pMiner = NULL; // can't mine without owner view key, because it's used for Tagging if (!m_Keys.m_pGeneric) { if (m_Keys.m_pMiner) m_Keys.m_pGeneric = m_Keys.m_pMiner; else { // use arbitrary, inited from system random. Needed for misc things, such as secure channel, decoys and etc. ECC::NoLeak<ECC::uintBig> seed; ECC::GenRandom(seed.V); ECC::HKdf::Create(m_Keys.m_pGeneric, seed.V); } } } void Node::InitIDs() { ECC::GenRandom(m_NonceLast.V); ECC::NoLeak<ECC::Scalar> s; Blob blob(s.V.m_Value); bool bNewID = !m_Processor.get_DB().ParamGet(NodeDB::ParamID::MyID, NULL, &blob); if (bNewID) { NextNonce(m_MyPrivateID); s.V = m_MyPrivateID; m_Processor.get_DB().ParamSet(NodeDB::ParamID::MyID, NULL, &blob); } else m_MyPrivateID = s.V; proto::Sk2Pk(m_MyPublicID, m_MyPrivateID); if (!m_Keys.m_pDummy) { // create it using Node-ID ECC::NoLeak<ECC::Hash::Value> hv; ECC::Hash::Processor() << m_MyPrivateID >> hv.V; std::shared_ptr<ECC::HKdf> pKdf = std::make_shared<ECC::HKdf>(); pKdf->Generate(hv.V); m_Keys.m_pDummy = std::move(pKdf); } } void Node::RefreshOwnedUtxos() { ECC::Hash::Processor hp; if (m_Keys.m_pDummy) { ECC::Scalar::Native sk; m_Keys.m_pDummy->DeriveKey(sk, Key::ID(0, Key::Type::Decoy)); hp << sk; } if (m_Keys.m_pOwner) { ECC::uintBig hv(Zero); ECC::Scalar::Native sk; m_Keys.m_pOwner->DerivePKey(sk, hv); hp << sk; } ECC::Hash::Value hv0, hv1(Zero); hp >> hv0; Blob blob(hv1); m_Processor.get_DB().ParamGet(NodeDB::ParamID::DummyID, NULL, &blob); if (hv0 == hv1) return; // unchaged if (m_Keys.m_pDummy && !(m_Keys.m_pOwner && m_Keys.m_pOwner->IsSame(*m_Keys.m_pDummy))) m_Keys.m_bRecoverViaDummyKey = true; m_Processor.RescanOwnedTxos(); m_Keys.m_bRecoverViaDummyKey = false; blob = Blob(hv0); m_Processor.get_DB().ParamSet(NodeDB::ParamID::DummyID, NULL, &blob); } void Node::Bbs::Cleanup() { get_ParentObj().m_Processor.get_DB().BbsDelOld(getTimestamp() - get_ParentObj().m_Cfg.m_Timeout.m_BbsMessageTimeout_s); } void Node::Bbs::MaybeCleanup() { uint32_t dt_ms = GetTime_ms() - m_LastCleanup_ms; if (dt_ms >= get_ParentObj().m_Cfg.m_Timeout.m_BbsCleanupPeriod_ms) Cleanup(); } Node::~Node() { LOG_INFO() << "Node stopping..."; m_Miner.HardAbortSafe(); if (m_Miner.m_External.m_pSolver) m_Miner.m_External.m_pSolver->stop(); for (size_t i = 0; i < m_Miner.m_vThreads.size(); i++) { PerThread& pt = m_Miner.m_vThreads[i]; if (pt.m_pReactor) pt.m_pReactor->stop(); if (pt.m_Thread.joinable()) pt.m_Thread.join(); } m_Miner.m_vThreads.clear(); for (PeerList::iterator it = m_lstPeers.begin(); m_lstPeers.end() != it; it++) it->m_LoginFlags = 0; // prevent re-assigning of tasks in the next loop while (!m_lstPeers.empty()) m_lstPeers.front().DeleteSelf(false, proto::NodeConnection::ByeReason::Stopping); while (!m_lstTasksUnassigned.empty()) DeleteUnassignedTask(m_lstTasksUnassigned.front()); assert(m_setTasks.empty()); m_Processor.m_TaskProcessor.Stop(); if (!std::uncaught_exceptions()) m_PeerMan.OnFlush(); LOG_INFO() << "Node stopped"; } void Node::Peer::SetTimer(uint32_t timeout_ms) { if (!m_pTimer) m_pTimer = io::Timer::create(io::Reactor::get_Current()); m_pTimer->start(timeout_ms, false, [this]() { OnTimer(); }); } void Node::Peer::KillTimer() { assert(m_pTimer); m_pTimer->cancel(); } void Node::Peer::OnTimer() { if (Flags::Connected & m_Flags) { assert(!m_lstTasks.empty()); LOG_WARNING() << "Peer " << m_RemoteAddr << " request timeout"; if (m_pInfo) m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::PenaltyTimeout, false); // task (request) wasn't handled in time. DeleteSelf(false, ByeReason::Timeout); } else // Connect didn't finish in time DeleteSelf(true, 0); } void Node::Peer::OnResendPeers() { PeerMan& pm = m_This.m_PeerMan; const PeerMan::RawRatingSet& rs = pm.get_Ratings(); uint32_t nRemaining = pm.m_Cfg.m_DesiredHighest; for (PeerMan::RawRatingSet::const_iterator it = rs.begin(); nRemaining && (rs.end() != it); it++) { const PeerMan::PeerInfo& pi = it->get_ParentObj(); if ((Flags::PiRcvd & m_Flags) && (&pi == m_pInfo)) continue; // skip if (!pi.m_RawRating.m_Value) continue; // banned if (!pi.m_LastSeen) continue; // recommend only verified peers proto::PeerInfo msg; msg.m_ID = pi.m_ID.m_Key; msg.m_LastAddr = pi.m_Addr.m_Value; Send(msg); nRemaining--; } } void Node::Peer::GenerateSChannelNonce(ECC::Scalar::Native& nonce) { m_This.NextNonce(nonce); } void Node::Peer::OnConnectedSecure() { LOG_INFO() << "Peer " << m_RemoteAddr << " Connected"; m_Flags |= Flags::Connected; if (m_Port && m_This.m_Cfg.m_Listen.port()) { // we've connected to the peer, let it now know our port proto::PeerInfoSelf msgPi; msgPi.m_Port = m_This.m_Cfg.m_Listen.port(); Send(msgPi); } ProveID(m_This.m_MyPrivateID, proto::IDType::Node); SendLogin(); if (m_This.m_Processor.IsTreasuryHandled() && !m_This.m_Processor.IsFastSync()) { proto::NewTip msg; msg.m_Description = m_This.m_Processor.m_Cursor.m_Full; Send(msg); } } void Node::Peer::SendLogin() { proto::Login msgLogin; msgLogin.m_CfgChecksum = Rules::get().Checksum; // checksum of all consesnsus related configuration msgLogin.m_Flags = proto::LoginFlags::Extension1 | proto::LoginFlags::Extension2 | proto::LoginFlags::SendPeers; // request a another node to periodically send a list of recommended peers if (m_This.m_PostStartSynced) msgLogin.m_Flags |= proto::LoginFlags::SpreadingTransactions; // indicate ability to receive and broadcast transactions if (m_This.m_Cfg.m_Bbs) msgLogin.m_Flags |= proto::LoginFlags::Bbs; // indicate ability to receive and broadcast BBS messages Send(msgLogin); } void Node::Peer::OnMsg(proto::Authentication&& msg) { proto::NodeConnection::OnMsg(std::move(msg)); LOG_INFO() << "Peer " << m_RemoteAddr << " Auth. Type=" << msg.m_IDType << ", ID=" << msg.m_ID; if (proto::IDType::Owner == msg.m_IDType) { bool b = ShouldFinalizeMining(); Key::IPKdf* pOwner = m_This.m_Keys.m_pOwner.get(); if (pOwner && IsKdfObscured(*pOwner, msg.m_ID)) { m_Flags |= Flags::Owner; ProvePKdfObscured(*pOwner, proto::IDType::Viewer); } if (!b && ShouldFinalizeMining()) m_This.m_Miner.OnFinalizerChanged(this); } if (proto::IDType::Node != msg.m_IDType) return; if ((Flags::PiRcvd & m_Flags) || (msg.m_ID == Zero)) ThrowUnexpected(); m_Flags |= Flags::PiRcvd; LOG_INFO() << m_RemoteAddr << " received PI"; PeerMan& pm = m_This.m_PeerMan; // alias if (m_pInfo) { // probably we connected by the address if (m_pInfo->m_ID.m_Key == msg.m_ID) { pm.OnSeen(*m_pInfo); TakeTasks(); return; // all settled (already) } // detach from it m_pInfo->m_pLive = NULL; if (m_pInfo->m_ID.m_Key == Zero) { LOG_INFO() << "deleted anonymous PI"; pm.Delete(*m_pInfo); // it's anonymous. } else { LOG_INFO() << "PeerID is different"; pm.OnActive(*m_pInfo, false); pm.RemoveAddr(*m_pInfo); // turned-out to be wrong } m_pInfo = NULL; } if (msg.m_ID == m_This.m_MyPublicID) { LOG_WARNING() << "Loopback connection"; DeleteSelf(false, ByeReason::Loopback); return; } io::Address addr; bool bAddrValid = (m_Port > 0); if (bAddrValid) { addr = m_RemoteAddr; addr.port(m_Port); } else LOG_INFO() << "No PI port"; // doesn't accept incoming connections? PeerMan::PeerInfoPlus* pPi = Cast::Up<PeerMan::PeerInfoPlus>(pm.OnPeer(msg.m_ID, addr, bAddrValid)); assert(pPi); if (pPi->m_pLive) { LOG_INFO() << "Duplicate connection with the same PI."; // Duplicate connection. In this case we have to choose wether to terminate this connection, or the previous. The best is to do it asymmetrically. // We decide this based on our Node IDs. // In addition, if the older connection isn't completed yet (i.e. it's our connect attempt) - it's prefered for deletion, because such a connection may be impossible (firewalls and friends). Peer* pDup = pPi->m_pLive; if (!pDup->IsSecureOut() || (m_This.m_MyPublicID > msg.m_ID)) { // detach from that peer assert(pPi == pDup->m_pInfo); pDup->m_pInfo = nullptr; pPi->m_pLive = nullptr; pDup->DeleteSelf(false, ByeReason::Duplicate); assert(!pPi->m_pLive); } else { DeleteSelf(false, ByeReason::Duplicate); return; } } if (!pPi->m_RawRating.m_Value) { LOG_INFO() << "Banned PI. Ignoring"; DeleteSelf(false, ByeReason::Ban); return; } // attach to it pPi->m_pLive = this; m_pInfo = pPi; pm.OnActive(*pPi, true); pm.OnSeen(*pPi); LOG_INFO() << *m_pInfo << " connected, info updated"; TakeTasks(); } bool Node::Peer::ShouldAssignTasks() { // Current design: don't ask anything from non-authenticated peers if (!((Peer::Flags::PiRcvd & m_Flags) && m_pInfo)) return false; return true; } bool Node::Peer::ShouldFinalizeMining() { return (Flags::Owner & m_Flags) && (proto::LoginFlags::MiningFinalization & m_LoginFlags); } void Node::Peer::OnMsg(proto::Bye&& msg) { LOG_INFO() << "Peer " << m_RemoteAddr << " Received Bye." << msg.m_Reason; NodeConnection::OnMsg(std::move(msg)); } void Node::Peer::OnDisconnect(const DisconnectReason& dr) { LOG_WARNING() << m_RemoteAddr << ": " << dr; bool bIsErr = true; uint8_t nByeReason = 0; switch (dr.m_Type) { default: assert(false); case DisconnectReason::Io: case DisconnectReason::Drown: break; case DisconnectReason::Bye: bIsErr = false; break; case DisconnectReason::ProcessingExc: case DisconnectReason::Protocol: nByeReason = ByeReason::Ban; break; } DeleteSelf(bIsErr, nByeReason); } void Node::Peer::ReleaseTasks() { while (!m_lstTasks.empty()) ReleaseTask(m_lstTasks.front()); } void Node::Peer::ReleaseTask(Task& t) { assert(this == t.m_pOwner); t.m_pOwner = NULL; if (t.m_bPack) { uint32_t& nCounter = t.m_Key.second ? m_This.m_nTasksPackBody : m_This.m_nTasksPackHdr; assert(nCounter); nCounter--; t.m_bPack = false; } m_lstTasks.erase(TaskList::s_iterator_to(t)); m_This.m_lstTasksUnassigned.push_back(t); if (t.m_bNeeded) m_This.TryAssignTask(t, NULL); else m_This.DeleteUnassignedTask(t); } void Node::Peer::DeleteSelf(bool bIsError, uint8_t nByeReason) { LOG_INFO() << "-Peer " << m_RemoteAddr; if (nByeReason && (Flags::Connected & m_Flags)) { proto::Bye msg; msg.m_Reason = nByeReason; Send(msg); } if (this == m_This.m_Miner.m_pFinalizer) { m_Flags &= ~Flags::Owner; m_LoginFlags &= proto::LoginFlags::MiningFinalization; assert(!ShouldFinalizeMining()); m_This.m_Miner.OnFinalizerChanged(NULL); } m_Tip.m_Height = 0; // prevent reassigning the tasks m_Flags &= ~Flags::HasTreasury; ReleaseTasks(); Unsubscribe(); if (m_pInfo) { // detach assert(this == m_pInfo->m_pLive); m_pInfo->m_pLive = NULL; m_This.m_PeerMan.OnActive(*m_pInfo, false); if (bIsError) m_This.m_PeerMan.OnRemoteError(*m_pInfo, ByeReason::Ban == nByeReason); if (m_This.m_PeerMan.get_Ratings().size() > m_This.m_PeerMan.m_Cfg.m_DesiredTotal) { bool bDelete = !m_pInfo->m_LastSeen || // never seen ((1 == m_pInfo->m_RawRating.m_Value) && m_This.m_PeerMan.IsOutdated(*m_pInfo)); // lowest rating, not seen for a while if (bDelete) { LOG_INFO() << *m_pInfo << " Deleted"; m_This.m_PeerMan.Delete(*m_pInfo); } } } SetTxCursor(nullptr); m_This.m_lstPeers.erase(PeerList::s_iterator_to(*this)); delete this; } void Node::Peer::Unsubscribe(Bbs::Subscription& s) { m_This.m_Bbs.m_Subscribed.erase(Bbs::Subscription::BbsSet::s_iterator_to(s.m_Bbs)); m_Subscriptions.erase(Bbs::Subscription::PeerSet::s_iterator_to(s.m_Peer)); delete &s; } void Node::Peer::Unsubscribe() { while (!m_Subscriptions.empty()) Unsubscribe(m_Subscriptions.begin()->get_ParentObj()); } void Node::Peer::TakeTasks() { if (!ShouldAssignTasks()) return; for (TaskList::iterator it = m_This.m_lstTasksUnassigned.begin(); m_This.m_lstTasksUnassigned.end() != it; ) m_This.TryAssignTask(*it++, *this); } void Node::Peer::OnMsg(proto::Pong&&) { if (!(Flags::Chocking & m_Flags)) ThrowUnexpected(); m_Flags &= ~Flags::Chocking; // not chocking - continue broadcast BroadcastTxs(); BroadcastBbs(); for (Bbs::Subscription::PeerSet::iterator it = m_Subscriptions.begin(); m_Subscriptions.end() != it; it++) BroadcastBbs(it->get_ParentObj()); } void Node::Peer::OnMsg(proto::NewTip&& msg) { if (msg.m_Description.m_ChainWork < m_Tip.m_ChainWork) ThrowUnexpected(); m_Tip = msg.m_Description; m_setRejected.clear(); m_Flags |= Flags::HasTreasury; Block::SystemState::ID id; m_Tip.get_ID(id); LOG_INFO() << "Peer " << m_RemoteAddr << " Tip: " << id; if (!m_pInfo) return; Processor& p = m_This.m_Processor; if (NodeProcessor::IsRemoteTipNeeded(m_Tip, p.m_Cursor.m_Full)) { switch (p.OnState(m_Tip, m_pInfo->m_ID.m_Key)) { case NodeProcessor::DataStatus::Invalid: ThrowUnexpected(); // no break; case NodeProcessor::DataStatus::Accepted: m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::RewardHeader, true); m_This.RefreshCongestions(); break; // since we made OnPeerInsane handling asynchronous - no need to return rapidly case NodeProcessor::DataStatus::Unreachable: LOG_WARNING() << id << " Tip unreachable!"; break; default: break; // suppress warning } } TakeTasks(); if (!m_This.m_UpdatedFromPeers) { m_This.m_UpdatedFromPeers = true; // at least 1 peer reported actual tip ZeroObject(m_This.m_SyncStatus); m_This.UpdateSyncStatus(); } } Node::Task& Node::Peer::get_FirstTask() { if (m_lstTasks.empty()) ThrowUnexpected(); return m_lstTasks.front(); } void Node::Peer::OnFirstTaskDone() { ReleaseTask(get_FirstTask()); SetTimerWrtFirstTask(); TakeTasks(); // maybe can take more } void Node::Peer::OnMsg(proto::DataMissing&&) { Task& t = get_FirstTask(); m_setRejected.insert(t.m_Key); OnFirstTaskDone(); } void Node::Peer::OnMsg(proto::GetHdr&& msg) { uint64_t rowid = m_This.m_Processor.get_DB().StateFindSafe(msg.m_ID); if (rowid) { proto::Hdr msgHdr; m_This.m_Processor.get_DB().get_State(rowid, msgHdr.m_Description); Send(msgHdr); } else { proto::DataMissing msgMiss(Zero); Send(msgMiss); } } void Node::Peer::OnMsg(proto::Hdr&& msg) { Task& t = get_FirstTask(); if (t.m_Key.second || t.m_bPack) ThrowUnexpected(); Block::SystemState::ID id; msg.m_Description.get_ID(id); if (id != t.m_Key.first) ThrowUnexpected(); assert((Flags::PiRcvd & m_Flags) && m_pInfo); m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::RewardHeader, true); NodeProcessor::DataStatus::Enum eStatus = m_This.m_Processor.OnState(msg.m_Description, m_pInfo->m_ID.m_Key); OnFirstTaskDone(eStatus); } void Node::Peer::OnMsg(proto::GetHdrPack&& msg) { proto::HdrPack msgOut; if (msg.m_Count) { // don't throw unexpected if pack size is bigger than max. In case it'll be increased in future versions - just truncate it. msg.m_Count = std::min(msg.m_Count, proto::g_HdrPackMaxSize); NodeDB& db = m_This.m_Processor.get_DB(); uint64_t rowid = db.StateFindSafe(msg.m_Top); if (rowid) { msgOut.m_vElements.reserve(msg.m_Count); Block::SystemState::Full s; for (uint32_t n = 0; ; ) { db.get_State(rowid, s); msgOut.m_vElements.push_back(s); if (++n == msg.m_Count) break; if (!db.get_Prev(rowid)) break; } msgOut.m_Prefix = s; } } if (msgOut.m_vElements.empty()) Send(proto::DataMissing(Zero)); else Send(msgOut); } void Node::Peer::OnMsg(proto::HdrPack&& msg) { Task& t = get_FirstTask(); if (t.m_Key.second || !t.m_bPack) ThrowUnexpected(); if (msg.m_vElements.empty() || (msg.m_vElements.size() > proto::g_HdrPackMaxSize)) ThrowUnexpected(); Block::SystemState::Full s; Cast::Down<Block::SystemState::Sequence::Prefix>(s) = msg.m_Prefix; Cast::Down<Block::SystemState::Sequence::Element>(s) = msg.m_vElements.back(); uint32_t nAccepted = 0; bool bInvalid = false; Block::SystemState::ID idLast; for (size_t i = msg.m_vElements.size(); ; ) { NodeProcessor::DataStatus::Enum eStatus = m_This.m_Processor.OnStateSilent(s, m_pInfo->m_ID.m_Key, idLast); switch (eStatus) { case NodeProcessor::DataStatus::Invalid: bInvalid = true; break; case NodeProcessor::DataStatus::Accepted: nAccepted++; default: break; // suppress warning } if (! --i) break; s.NextPrefix(); Cast::Down<Block::SystemState::Sequence::Element>(s) = msg.m_vElements[i - 1]; s.m_ChainWork += s.m_PoW.m_Difficulty; } // just to be pedantic if (idLast != t.m_Key.first) bInvalid = true; LOG_INFO() << "Hdr pack received " << msg.m_Prefix.m_Height << "-" << idLast; OnFirstTaskDone(NodeProcessor::DataStatus::Accepted); if (nAccepted) { assert((Flags::PiRcvd & m_Flags) && m_pInfo); m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::RewardHeader * nAccepted, true); m_This.RefreshCongestions(); // may delete us } else { if (bInvalid) ThrowUnexpected(); } m_This.UpdateSyncStatus(); } void Node::Peer::OnMsg(proto::GetBody&& msg) { proto::GetBodyPack msg2; msg2.m_Top = msg.m_ID; OnMsg(std::move(msg2)); } void Node::Peer::OnMsg(proto::GetBodyPack&& msg) { Processor& p = m_This.m_Processor; // alias if (msg.m_Top.m_Height) { NodeDB::StateID sid; sid.m_Row = p.get_DB().StateFindSafe(msg.m_Top); if (sid.m_Row) { sid.m_Height = msg.m_Top.m_Height; if (msg.m_CountExtra) { if (sid.m_Height - Rules::HeightGenesis < msg.m_CountExtra) ThrowUnexpected(); if (NodeDB::StateFlags::Active & p.get_DB().GetStateFlags(sid.m_Row)) { // functionality only supported for active states proto::BodyPack msgBody; size_t nSize = 0; sid.m_Height -= msg.m_CountExtra; Height hMax = std::min(msg.m_Top.m_Height, sid.m_Height + m_This.m_Cfg.m_BandwidthCtl.m_MaxBodyPackCount); for (; sid.m_Height <= hMax; sid.m_Height++) { sid.m_Row = p.FindActiveAtStrict(sid.m_Height); proto::BodyBuffers bb; if (!p.GetBlock(sid, msg.m_ExcludeE ? nullptr : &bb.m_Eternal, msg.m_ExcludeP ? nullptr : &bb.m_Perishable, msg.m_Height0, msg.m_HorizonLo1, msg.m_HorizonHi1)) break; nSize += bb.m_Eternal.size() + bb.m_Perishable.size(); msgBody.m_Bodies.push_back(std::move(bb)); if (nSize >= m_This.m_Cfg.m_BandwidthCtl.m_MaxBodyPackSize) break; } if (msgBody.m_Bodies.size()) { Send(msgBody); return; } } } else { proto::Body msgBody; if (p.GetBlock(sid, msg.m_ExcludeE ? nullptr : &msgBody.m_Body.m_Eternal, msg.m_ExcludeP ? nullptr : &msgBody.m_Body.m_Perishable, msg.m_Height0, msg.m_HorizonLo1, msg.m_HorizonHi1)) { Send(msgBody); return; } } } } else { if ((msg.m_Top.m_Hash == Zero) && p.IsTreasuryHandled()) { proto::Body msgBody; if (p.get_DB().ParamGet(NodeDB::ParamID::Treasury, NULL, NULL, &msgBody.m_Body.m_Eternal)) { Send(msgBody); return; } } } proto::DataMissing msgMiss(Zero); Send(msgMiss); } void Node::Peer::OnMsg(proto::Body&& msg) { Task& t = get_FirstTask(); if (!t.m_Key.second) ThrowUnexpected(); assert((Flags::PiRcvd & m_Flags) && m_pInfo); m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::RewardBlock, true); const Block::SystemState::ID& id = t.m_Key.first; Height h = id.m_Height; Processor& p = m_This.m_Processor; // alias NodeProcessor::DataStatus::Enum eStatus = h ? p.OnBlock(id, msg.m_Body.m_Perishable, msg.m_Body.m_Eternal, m_pInfo->m_ID.m_Key) : p.OnTreasury(msg.m_Body.m_Eternal); p.TryGoUpAsync(); OnFirstTaskDone(eStatus); } void Node::Peer::OnMsg(proto::BodyPack&& msg) { Task& t = get_FirstTask(); if (!t.m_Key.second || !t.m_bPack) ThrowUnexpected(); const Block::SystemState::ID& id = t.m_Key.first; Processor& p = m_This.m_Processor; assert(t.m_sidTrg.m_Height >= id.m_Height); Height hCountExtra = t.m_sidTrg.m_Height - id.m_Height; if (msg.m_Bodies.size() > hCountExtra + 1) ThrowUnexpected(); assert((Flags::PiRcvd & m_Flags) && m_pInfo); m_This.m_PeerMan.ModifyRating(*m_pInfo, PeerMan::Rating::RewardBlock, true); NodeProcessor::DataStatus::Enum eStatus = NodeProcessor::DataStatus::Rejected; if (!msg.m_Bodies.empty()) { const uint64_t* pPtr = p.get_CachedRows(t.m_sidTrg, hCountExtra); if (pPtr) { LOG_INFO() << id << " Block pack received " << id.m_Height << "-" << (id.m_Height + msg.m_Bodies.size() - 1); eStatus = NodeProcessor::DataStatus::Accepted; for (Height h = 0; h < msg.m_Bodies.size(); h++) { NodeDB::StateID sid; sid.m_Row = pPtr[hCountExtra - h]; sid.m_Height = id.m_Height + h; const proto::BodyBuffers& bb = msg.m_Bodies[h]; NodeProcessor::DataStatus::Enum es2 = p.OnBlock(sid, bb.m_Perishable, bb.m_Eternal, m_pInfo->m_ID.m_Key); if (NodeProcessor::DataStatus::Invalid == es2) { p.OnPeerInsane(m_pInfo->m_ID.m_Key); break; } } } } p.TryGoUpAsync(); OnFirstTaskDone(eStatus); } void Node::Peer::OnFirstTaskDone(NodeProcessor::DataStatus::Enum eStatus) { if (NodeProcessor::DataStatus::Invalid == eStatus) ThrowUnexpected(); get_FirstTask().m_bNeeded = false; OnFirstTaskDone(); if (NodeProcessor::DataStatus::Accepted == eStatus) m_This.RefreshCongestions(); } void Node::Peer::OnMsg(proto::NewTransaction&& msg) { if (!msg.m_Transaction) ThrowUnexpected(); // our deserialization permits NULL Ptrs. // However the transaction body must have already been checked for NULLs if (msg.m_Fluff) m_This.OnTransactionFluff(std::move(msg.m_Transaction), this, NULL); else { proto::Boolean msgOut; msgOut.m_Value = m_This.OnTransactionStem(std::move(msg.m_Transaction), this); Send(msgOut); } } bool Node::ValidateTx(Transaction::Context& ctx, const Transaction& tx) { return m_Processor.ValidateAndSummarize(ctx, tx, tx.get_Reader()) && ctx.IsValidTransaction() && m_Processor.ValidateTxContext(tx); } void Node::LogTx(const Transaction& tx, bool bValid, const Transaction::KeyType& key) { std::ostringstream os; os << "Tx " << key; for (size_t i = 0; i < tx.m_vInputs.size(); i++) os << "\n\tI: " << tx.m_vInputs[i]->m_Commitment; for (size_t i = 0; i < tx.m_vOutputs.size(); i++) { const Output& outp = *tx.m_vOutputs[i]; os << "\n\tO: " << outp.m_Commitment; if (outp.m_Incubation) os << ", Incubation +" << outp.m_Incubation; if (outp.m_pPublic) os << ", Sum=" << outp.m_pPublic->m_Value; } for (size_t i = 0; i < tx.m_vKernels.size(); i++) { const TxKernel& krn = *tx.m_vKernels[i]; Merkle::Hash hv; krn.get_ID(hv); char sz[Merkle::Hash::nTxtLen + 1]; hv.Print(sz); os << "\n\tK: " << sz << " Fee=" << krn.m_Fee; } os << "\n\tValid: " << bValid; LOG_INFO() << os.str(); } const ECC::uintBig& Node::NextNonce() { ECC::Scalar::Native sk; NextNonce(sk); return m_NonceLast.V; } void Node::NextNonce(ECC::Scalar::Native& sk) { m_Keys.m_pGeneric->DeriveKey(sk, m_NonceLast.V); ECC::Hash::Processor() << sk >> m_NonceLast.V; } uint32_t Node::RandomUInt32(uint32_t threshold) { if (threshold) { typedef uintBigFor<uint32_t>::Type Type; Type thr(threshold), val; Type::Threshold thrSel(thr); do { val = NextNonce(); } while (!thrSel.Accept(val)); val.Export(threshold); } return threshold; } void CmpTx(const Transaction& tx1, const Transaction& tx2, bool& b1Covers, bool& b2Covers) { } bool Node::OnTransactionStem(Transaction::Ptr&& ptx, const Peer* pPeer) { if (ptx->m_vInputs.empty() || ptx->m_vKernels.empty()) { // stupid compiler insists on parentheses here! return false; } Transaction::Context::Params pars; Transaction::Context ctx(pars); bool bTested = false; TxPool::Stem::Element* pDup = NULL; // find match by kernels for (size_t i = 0; i < ptx->m_vKernels.size(); i++) { const TxKernel& krn = *ptx->m_vKernels[i]; TxPool::Stem::Element::Kernel key; krn.get_ID(key.m_hv); TxPool::Stem::KrnSet::iterator it = m_Dandelion.m_setKrns.find(key); if (m_Dandelion.m_setKrns.end() == it) continue; TxPool::Stem::Element* pElem = it->m_pThis; bool bElemCovers = true, bNewCovers = true; pElem->m_pValue->get_Reader().Compare(std::move(ptx->get_Reader()), bElemCovers, bNewCovers); if (!bNewCovers) return false; // the new tx is reduced, drop it if (bElemCovers) { pDup = pElem; // exact match if (pDup->m_bAggregating) return true; // it shouldn't have been received, but nevermind, just ignore break; } if (!bTested && !ValidateTx(ctx, *ptx)) return false; bTested = true; m_Dandelion.Delete(*pElem); } if (!pDup) { if (!bTested && !ValidateTx(ctx, *ptx)) return false; AddDummyInputs(*ptx); std::unique_ptr<TxPool::Stem::Element> pGuard(new TxPool::Stem::Element); pGuard->m_bAggregating = false; pGuard->m_Time.m_Value = 0; pGuard->m_Profit.m_Fee = ctx.m_Fee; pGuard->m_Profit.SetSize(*ptx); pGuard->m_pValue.swap(ptx); m_Dandelion.InsertKrn(*pGuard); pDup = pGuard.release(); } assert(!pDup->m_bAggregating); if (pDup->m_pValue->m_vOutputs.size() > m_Cfg.m_Dandelion.m_OutputsMax) OnTransactionAggregated(*pDup); else { m_Dandelion.InsertAggr(*pDup); PerformAggregation(*pDup); } return true; } void Node::OnTransactionAggregated(TxPool::Stem::Element& x) { // must have at least 1 peer to continue the stem phase uint32_t nStemPeers = 0; for (PeerList::iterator it = m_lstPeers.begin(); m_lstPeers.end() != it; it++) if (it->m_LoginFlags & proto::LoginFlags::SpreadingTransactions) nStemPeers++; if (nStemPeers) { auto thr = uintBigFrom(m_Cfg.m_Dandelion.m_FluffProbability); // Compare two bytes of threshold with random nonce if (memcmp(thr.m_pData, NextNonce().m_pData, thr.nBytes) < 0) { // broadcast to random peer assert(nStemPeers); // Choose random peer index between 0 and nStemPeers - 1 uint32_t nRandomPeerIdx = RandomUInt32(nStemPeers); for (PeerList::iterator it = m_lstPeers.begin(); ; it++) if ((it->m_LoginFlags & proto::LoginFlags::SpreadingTransactions) && !nRandomPeerIdx--) { it->SendTx(x.m_pValue, false); break; } // set random timer uint32_t nTimeout_ms = m_Cfg.m_Dandelion.m_TimeoutMin_ms + RandomUInt32(m_Cfg.m_Dandelion.m_TimeoutMax_ms - m_Cfg.m_Dandelion.m_TimeoutMin_ms); m_Dandelion.SetTimer(nTimeout_ms, x); return; } } OnTransactionFluff(std::move(x.m_pValue), NULL, &x); } void Node::PerformAggregation(TxPool::Stem::Element& x) { assert(x.m_bAggregating); // Aggregation policiy: first select those with worse profit, than those with better TxPool::Stem::ProfitSet::iterator it = TxPool::Stem::ProfitSet::s_iterator_to(x.m_Profit); ++it; while (x.m_pValue->m_vOutputs.size() <= m_Cfg.m_Dandelion.m_OutputsMax) { if (m_Dandelion.m_setProfit.end() == it) break; TxPool::Stem::Element& src = it->get_ParentObj(); ++it; m_Dandelion.TryMerge(x, src); } it = TxPool::Stem::ProfitSet::s_iterator_to(x.m_Profit); if (m_Dandelion.m_setProfit.begin() != it) { --it; while (x.m_pValue->m_vOutputs.size() <= m_Cfg.m_Dandelion.m_OutputsMax) { TxPool::Stem::Element& src = it->get_ParentObj(); bool bEnd = (m_Dandelion.m_setProfit.begin() == it); if (!bEnd) --it; m_Dandelion.TryMerge(x, src); if (bEnd) break; } } if (x.m_pValue->m_vOutputs.size() >= m_Cfg.m_Dandelion.m_OutputsMin) { m_Dandelion.DeleteAggr(x); OnTransactionAggregated(x); } else m_Dandelion.SetTimer(m_Cfg.m_Dandelion.m_AggregationTime_ms, x); } void Node::AddDummyInputs(Transaction& tx) { bool bModified = false; while (tx.m_vInputs.size() < m_Cfg.m_Dandelion.m_OutputsMax) { Key::IDV kidv; Height h = m_Processor.get_DB().GetLowestDummy(kidv); if (h > m_Processor.m_Cursor.m_ID.m_Height) break; kidv.m_Value = 0; bModified = true; // ECC::Mode::Scope scope(ECC::Mode::Fast); ECC::Scalar::Native sk; // bounds UtxoTree::Key kMin, kMax; UtxoTree::Key::Data d; SwitchCommitment().Create(sk, d.m_Commitment, *m_Keys.m_pDummy, kidv); d.m_Maturity = 0; kMin = d; d.m_Maturity = m_Processor.m_Cursor.m_ID.m_Height; kMax = d; // check if it's still unspent struct Traveler :public UtxoTree::ITraveler { virtual bool OnLeaf(const RadixTree::Leaf& x) override { return false; } } t; UtxoTree::Cursor cu; t.m_pCu = &cu; t.m_pBound[0] = kMin.m_pArr; t.m_pBound[1] = kMax.m_pArr; if (m_Processor.get_Utxos().Traverse(t)) { // spent m_Processor.get_DB().DeleteDummy(kidv); } else { // unspent Input::Ptr pInp(new Input); pInp->m_Commitment = d.m_Commitment; tx.m_vInputs.push_back(std::move(pInp)); tx.m_Offset = ECC::Scalar::Native(tx.m_Offset) + ECC::Scalar::Native(sk); /// in the (unlikely) case the tx will be lost - we'll retry spending this UTXO after the following num of blocks m_Processor.get_DB().SetDummyHeight(kidv, m_Processor.m_Cursor.m_ID.m_Height + m_Cfg.m_Dandelion.m_DummyLifetimeLo + 1); } } if (bModified) { m_Processor.FlushDB(); // make sure they're not lost tx.Normalize(); } } void Node::AddDummyOutputs(Transaction& tx) { if (!m_Cfg.m_Dandelion.m_DummyLifetimeHi) return; // add dummy outputs bool bModified = false; NodeDB& db = m_Processor.get_DB(); while (tx.m_vOutputs.size() < m_Cfg.m_Dandelion.m_OutputsMin) { Key::IDV kidv(Zero); kidv.m_Type = Key::Type::Decoy; while (true) { NextNonce().ExportWord<0>(kidv.m_Idx); if (MaxHeight == db.GetDummyHeight(kidv)) break; } bModified = true; Output::Ptr pOutput(new Output); ECC::Scalar::Native sk; pOutput->Create(sk, *m_Keys.m_pDummy, kidv, *m_Keys.m_pDummy); Height h = SampleDummySpentHeight(); db.InsertDummy(h, kidv); tx.m_vOutputs.push_back(std::move(pOutput)); sk = -sk; tx.m_Offset = ECC::Scalar::Native(tx.m_Offset) + sk; } if (bModified) { m_Processor.FlushDB(); tx.Normalize(); } } Height Node::SampleDummySpentHeight() { const Config::Dandelion& d = m_Cfg.m_Dandelion; // alias Height h = m_Processor.m_Cursor.m_ID.m_Height + d.m_DummyLifetimeLo + 1; if (d.m_DummyLifetimeHi > d.m_DummyLifetimeLo) h += RandomUInt32(d.m_DummyLifetimeHi - d.m_DummyLifetimeLo); return h; } bool Node::OnTransactionFluff(Transaction::Ptr&& ptxArg, const Peer* pPeer, TxPool::Stem::Element* pElem) { Transaction::Ptr ptx; ptx.swap(ptxArg); Transaction::Context::Params pars; Transaction::Context ctx(pars); if (pElem) { ctx.m_Fee = pElem->m_Profit.m_Fee; m_Dandelion.Delete(*pElem); } else { for (size_t i = 0; i < ptx->m_vKernels.size(); i++) { TxPool::Stem::Element::Kernel key; ptx->m_vKernels[i]->get_ID(key.m_hv); TxPool::Stem::KrnSet::iterator it = m_Dandelion.m_setKrns.find(key); if (m_Dandelion.m_setKrns.end() != it) m_Dandelion.Delete(*it->m_pThis); } } TxPool::Fluff::Element::Tx key; ptx->get_Key(key.m_Key); TxPool::Fluff::TxSet::iterator it = m_TxPool.m_setTxs.find(key); if (m_TxPool.m_setTxs.end() != it) return true; const Transaction& tx = *ptx; m_Wtx.Delete(key.m_Key); // new transaction bool bValid = pElem ? true: ValidateTx(ctx, tx); LogTx(tx, bValid, key.m_Key); if (!bValid) { return false; // stupid compiler insists on parentheses here! } TxPool::Fluff::Element* pNewTxElem = m_TxPool.AddValidTx(std::move(ptx), ctx, key.m_Key); while (m_TxPool.m_setProfit.size() > m_Cfg.m_MaxPoolTransactions) { TxPool::Fluff::Element& txDel = m_TxPool.m_setProfit.rbegin()->get_ParentObj(); if (&txDel == pNewTxElem) pNewTxElem = nullptr; // Anti-spam protection: in case the maximum pool capacity is reached - ensure this tx is any better BEFORE broadcasting ti m_TxPool.Delete(txDel); } if (!pNewTxElem) return false; proto::HaveTransaction msgOut; msgOut.m_ID = key.m_Key; for (PeerList::iterator it2 = m_lstPeers.begin(); m_lstPeers.end() != it2; it2++) { Peer& peer = *it2; if (&peer == pPeer) continue; if (!(peer.m_LoginFlags & proto::LoginFlags::SpreadingTransactions) || peer.IsChocking()) continue; peer.Send(msgOut); peer.SetTxCursor(pNewTxElem); } if (m_Miner.IsEnabled() && !m_Miner.m_pTaskToFinalize) m_Miner.SetTimer(m_Cfg.m_Timeout.m_MiningSoftRestart_ms, false); return true; } void Node::Dandelion::OnTimedOut(Element& x) { if (x.m_bAggregating) { get_ParentObj().AddDummyOutputs(*x.m_pValue); get_ParentObj().OnTransactionAggregated(x); } else get_ParentObj().OnTransactionFluff(std::move(x.m_pValue), NULL, &x); } bool Node::Dandelion::ValidateTxContext(const Transaction& tx) { return get_ParentObj().m_Processor.ValidateTxContext(tx); } void Node::Peer::OnMsg(proto::Login&& msg) { VerifyCfg(msg); if ((m_LoginFlags ^ msg.m_Flags) & proto::LoginFlags::SendPeers) { if (msg.m_Flags & proto::LoginFlags::SendPeers) { if (!m_pTimerPeers) m_pTimerPeers = io::Timer::create(io::Reactor::get_Current()); m_pTimerPeers->start(m_This.m_Cfg.m_Timeout.m_TopPeersUpd_ms, true, [this]() { OnResendPeers(); }); OnResendPeers(); } else if (m_pTimerPeers) m_pTimerPeers->cancel(); } bool b = ShouldFinalizeMining(); if (m_This.m_Cfg.m_Bbs && !(proto::LoginFlags::Bbs & m_LoginFlags) && (proto::LoginFlags::Bbs & msg.m_Flags)) { proto::BbsResetSync msgOut; msgOut.m_TimeFrom = std::min(m_This.m_Bbs.m_HighestPosted_s, getTimestamp() - Rules::get().DA.MaxAhead_s); Send(msgOut); } m_LoginFlags = msg.m_Flags; if (b != ShouldFinalizeMining()) { // stupid compiler insists on parentheses! m_This.m_Miner.OnFinalizerChanged(b ? NULL : this); } BroadcastTxs(); BroadcastBbs(); } bool Node::Peer::IsChocking(size_t nExtra /* = 0 */) { if (Flags::Chocking & m_Flags) return true; if (get_Unsent() + nExtra <= m_This.m_Cfg.m_BandwidthCtl.m_Chocking) return false; OnChocking(); return true; } void Node::Peer::OnChocking() { if (!(Flags::Chocking & m_Flags)) { m_Flags |= Flags::Chocking; Send(proto::Ping(Zero)); } } void Node::Peer::SetTxCursor(TxPool::Fluff::Element* p) { if (m_pCursorTx) { assert(m_pCursorTx != p); m_This.m_TxPool.Release(*m_pCursorTx); } m_pCursorTx = p; if (m_pCursorTx) m_pCursorTx->m_Queue.m_Refs++; } void Node::Peer::BroadcastTxs() { if (!(proto::LoginFlags::SpreadingTransactions & m_LoginFlags)) return; if (IsChocking()) return; for (size_t nExtra = 0; ; ) { TxPool::Fluff::Queue::iterator itNext; if (m_pCursorTx) { itNext = TxPool::Fluff::Queue::s_iterator_to(m_pCursorTx->m_Queue); ++itNext; } else itNext = m_This.m_TxPool.m_Queue.begin(); if (m_This.m_TxPool.m_Queue.end() == itNext) break; // all sent SetTxCursor(&itNext->get_ParentObj()); if (!m_pCursorTx->m_pValue) continue; // already deleted proto::HaveTransaction msgOut; msgOut.m_ID = m_pCursorTx->m_Tx.m_Key; Send(msgOut); nExtra += m_pCursorTx->m_Profit.m_nSize; if (IsChocking(nExtra)) break; } } void Node::Peer::BroadcastBbs() { m_This.m_Bbs.MaybeCleanup(); if (!(proto::LoginFlags::Bbs & m_LoginFlags)) return; if (IsChocking()) return; size_t nExtra = 0; NodeDB& db = m_This.m_Processor.get_DB(); NodeDB::WalkerBbsLite wlk(db); wlk.m_ID = m_CursorBbs; for (db.EnumAllBbsSeq(wlk); wlk.MoveNext(); ) { proto::BbsHaveMsg msgOut; msgOut.m_Key = wlk.m_Key; Send(msgOut); nExtra += wlk.m_Size; if (IsChocking(nExtra)) break; } m_CursorBbs = wlk.m_ID; } void Node::Peer::OnMsg(proto::HaveTransaction&& msg) { TxPool::Fluff::Element::Tx key; key.m_Key = msg.m_ID; TxPool::Fluff::TxSet::iterator it = m_This.m_TxPool.m_setTxs.find(key); if (m_This.m_TxPool.m_setTxs.end() != it) return; // already have it if (!m_This.m_Wtx.Add(key.m_Key)) return; // already waiting for it proto::GetTransaction msgOut; msgOut.m_ID = msg.m_ID; Send(msgOut); } void Node::Peer::OnMsg(proto::GetTransaction&& msg) { TxPool::Fluff::Element::Tx key; key.m_Key = msg.m_ID; TxPool::Fluff::TxSet::iterator it = m_This.m_TxPool.m_setTxs.find(key); if (m_This.m_TxPool.m_setTxs.end() == it) return; // don't have it SendTx(it->get_ParentObj().m_pValue, true); } void Node::Peer::SendTx(Transaction::Ptr& ptx, bool bFluff) { proto::NewTransaction msg; msg.m_Fluff = bFluff; TemporarySwap scope(msg.m_Transaction, ptx); Send(msg); } void Node::Peer::OnMsg(proto::GetCommonState&& msg) { proto::ProofCommonState msgOut; Processor& p = m_This.m_Processor; // alias for (size_t i = 0; i < msg.m_IDs.size(); i++) { const Block::SystemState::ID& id = msg.m_IDs[i]; if (id.m_Height < Rules::HeightGenesis) ThrowUnexpected(); if ((id.m_Height < p.m_Cursor.m_ID.m_Height) && !p.IsFastSync()) { Merkle::Hash hv; p.get_DB().get_StateHash(p.FindActiveAtStrict(id.m_Height), hv); if ((hv == id.m_Hash) || (i + 1 == msg.m_IDs.size())) { msgOut.m_ID.m_Height = id.m_Height; msgOut.m_ID.m_Hash = hv; p.GenerateProofStateStrict(msgOut.m_Proof, id.m_Height); break; } } } Send(msgOut); } void Node::Peer::OnMsg(proto::GetProofState&& msg) { if (msg.m_Height < Rules::HeightGenesis) ThrowUnexpected(); proto::ProofState msgOut; Processor& p = m_This.m_Processor; const NodeDB::StateID& sid = p.m_Cursor.m_Sid; if ((msg.m_Height < sid.m_Height) && !p.IsFastSync()) p.GenerateProofStateStrict(msgOut.m_Proof, msg.m_Height); Send(msgOut); } void Node::Processor::GenerateProofStateStrict(Merkle::HardProof& proof, Height h) { assert(h < m_Cursor.m_Sid.m_Height); Merkle::ProofBuilderHard bld; get_DB().get_Proof(bld, m_Cursor.m_Sid, h); proof.swap(bld.m_Proof); proof.resize(proof.size() + 1); get_Utxos().get_Hash(proof.back()); } void Node::Peer::OnMsg(proto::GetProofKernel&& msg) { proto::ProofKernel msgOut; Processor& p = m_This.m_Processor; if (!p.IsFastSync()) { Height h = p.get_ProofKernel(msgOut.m_Proof.m_Inner, NULL, msg.m_ID); if (h) { uint64_t rowid = p.FindActiveAtStrict(h); p.get_DB().get_State(rowid, msgOut.m_Proof.m_State); if (h < p.m_Cursor.m_ID.m_Height) p.GenerateProofStateStrict(msgOut.m_Proof.m_Outer, h); } } Send(msgOut); } void Node::Peer::OnMsg(proto::GetProofKernel2&& msg) { proto::ProofKernel2 msgOut; Processor& p = m_This.m_Processor; if (!p.IsFastSync()) msgOut.m_Height = p.get_ProofKernel(msgOut.m_Proof, msg.m_Fetch ? &msgOut.m_Kernel : NULL, msg.m_ID); Send(msgOut); } void Node::Peer::OnMsg(proto::GetProofUtxo&& msg) { struct Traveler :public UtxoTree::ITraveler { proto::ProofUtxo m_Msg; UtxoTree* m_pTree; Merkle::Hash m_hvHistory; virtual bool OnLeaf(const RadixTree::Leaf& x) override { const UtxoTree::MyLeaf& v = Cast::Up<UtxoTree::MyLeaf>(x); UtxoTree::Key::Data d; d = v.m_Key; m_Msg.m_Proofs.resize(m_Msg.m_Proofs.size() + 1); Input::Proof& ret = m_Msg.m_Proofs.back(); ret.m_State.m_Count = v.get_Count(); ret.m_State.m_Maturity = d.m_Maturity; m_pTree->get_Proof(ret.m_Proof, *m_pCu); ret.m_Proof.resize(ret.m_Proof.size() + 1); ret.m_Proof.back().first = false; ret.m_Proof.back().second = m_hvHistory; return m_Msg.m_Proofs.size() < Input::Proof::s_EntriesMax; } } t; Processor& p = m_This.m_Processor; if (!p.IsFastSync()) { t.m_pTree = &p.get_Utxos(); t.m_hvHistory = p.m_Cursor.m_History; UtxoTree::Cursor cu; t.m_pCu = &cu; // bounds UtxoTree::Key kMin, kMax; UtxoTree::Key::Data d; d.m_Commitment = msg.m_Utxo; d.m_Maturity = msg.m_MaturityMin; kMin = d; d.m_Maturity = Height(-1); kMax = d; t.m_pBound[0] = kMin.m_pArr; t.m_pBound[1] = kMax.m_pArr; t.m_pTree->Traverse(t); } Send(t.m_Msg); } bool Node::Processor::BuildCwp() { if (!m_Cwp.IsEmpty()) return true; // already built if (m_Cursor.m_Full.m_Height < Rules::HeightGenesis) return false; struct Source :public Block::ChainWorkProof::ISource { Processor& m_Proc; Source(Processor& proc) :m_Proc(proc) {} virtual void get_StateAt(Block::SystemState::Full& s, const Difficulty::Raw& d) override { uint64_t rowid = m_Proc.get_DB().FindStateWorkGreater(d); m_Proc.get_DB().get_State(rowid, s); } virtual void get_Proof(Merkle::IProofBuilder& bld, Height h) override { const NodeDB::StateID& sid = m_Proc.m_Cursor.m_Sid; m_Proc.get_DB().get_Proof(bld, sid, h); } }; Source src(*this); m_Cwp.Create(src, m_Cursor.m_Full); get_Utxos().get_Hash(m_Cwp.m_hvRootLive); return true; } void Node::Peer::OnMsg(proto::GetProofChainWork&& msg) { proto::ProofChainWork msgOut; Processor& p = m_This.m_Processor; if (!p.IsFastSync() && p.BuildCwp()) { msgOut.m_Proof.m_LowerBound = msg.m_LowerBound; verify(msgOut.m_Proof.Crop(p.m_Cwp)); } Send(msgOut); } void Node::Peer::OnMsg(proto::PeerInfoSelf&& msg) { m_Port = msg.m_Port; } void Node::Peer::OnMsg(proto::PeerInfo&& msg) { if (msg.m_ID != m_This.m_MyPublicID) m_This.m_PeerMan.OnPeer(msg.m_ID, msg.m_LastAddr, false); } void Node::Peer::OnMsg(proto::GetExternalAddr&& msg) { proto::ExternalAddr msgOut; msgOut.m_Value = m_RemoteAddr.ip(); Send(msgOut); } void Node::Peer::OnMsg(proto::BbsMsgV0&& msg0) { if (!m_This.m_Cfg.m_BbsAllowV0) return; // drop proto::BbsMsg msg; msg.m_Channel = msg0.m_Channel; msg.m_TimePosted = msg0.m_TimePosted; msg.m_Message.swap(msg0.m_Message); OnMsg(msg, false); } void Node::Peer::OnMsg(proto::BbsMsg&& msg) { if (!m_This.m_Cfg.m_BbsAllowV0) { // test the hash ECC::Hash::Value hv; proto::Bbs::get_Hash(hv, msg); if (!proto::Bbs::IsHashValid(hv)) return; // drop } OnMsg(msg, true); } void Node::Peer::OnMsg(const proto::BbsMsg& msg, bool bNonceValid) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); if (msg.m_Message.size() > proto::Bbs::s_MaxMsgSize) ThrowUnexpected("Bbs msg too large"); // will also ban this peer Timestamp t = getTimestamp(); if (msg.m_TimePosted > t + Rules::get().DA.MaxAhead_s) return; // too much ahead of time if (msg.m_TimePosted + m_This.m_Cfg.m_Timeout.m_BbsMessageTimeout_s < t) return; // too old if (msg.m_TimePosted + Rules::get().DA.MaxAhead_s < m_This.m_Bbs.m_HighestPosted_s) return; // don't allow too much out-of-order messages NodeDB& db = m_This.m_Processor.get_DB(); NodeDB::WalkerBbs wlk(db); wlk.m_Data.m_Channel = msg.m_Channel; wlk.m_Data.m_TimePosted = msg.m_TimePosted; wlk.m_Data.m_Message = Blob(msg.m_Message); wlk.m_Data.m_bNonce = bNonceValid; msg.m_Nonce.Export(wlk.m_Data.m_Nonce); Bbs::CalcMsgKey(wlk.m_Data); if (db.BbsFind(wlk.m_Data.m_Key)) return; // already have it m_This.m_Bbs.MaybeCleanup(); uint64_t id = db.BbsIns(wlk.m_Data); m_This.m_Bbs.m_W.Delete(wlk.m_Data.m_Key); m_This.m_Bbs.m_HighestPosted_s = std::max(m_This.m_Bbs.m_HighestPosted_s, msg.m_TimePosted); // 1. Send to other BBS-es proto::BbsHaveMsg msgOut; msgOut.m_Key = wlk.m_Data.m_Key; for (PeerList::iterator it = m_This.m_lstPeers.begin(); m_This.m_lstPeers.end() != it; it++) { Peer& peer = *it; if (this == &peer) continue; if (!(peer.m_LoginFlags & proto::LoginFlags::Bbs) || peer.IsChocking()) continue; peer.Send(msgOut); } // 2. Send to subscribed typedef Bbs::Subscription::BbsSet::iterator It; Bbs::Subscription::InBbs key; key.m_Channel = msg.m_Channel; for (std::pair<It, It> range = m_This.m_Bbs.m_Subscribed.equal_range(key); range.first != range.second; range.first++) { Bbs::Subscription& s = range.first->get_ParentObj(); assert(s.m_Cursor < id); if ((this == s.m_pPeer) || s.m_pPeer->IsChocking()) continue; s.m_pPeer->SendBbsMsg(wlk.m_Data); s.m_Cursor = id; s.m_pPeer->IsChocking(); // in case it's chocking - for faster recovery recheck it ASAP } } void Node::Peer::OnMsg(proto::BbsHaveMsg&& msg) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); NodeDB& db = m_This.m_Processor.get_DB(); if (db.BbsFind(msg.m_Key)) { // stupid compiler insists on parentheses here! return; // already have it } if (!m_This.m_Bbs.m_W.Add(msg.m_Key)) { // stupid compiler insists on parentheses here! return; // already waiting for it } NodeDB::WalkerBbs wlk(db); wlk.m_Data.m_Key = msg.m_Key; proto::BbsGetMsg msgOut; msgOut.m_Key = msg.m_Key; Send(msgOut); } void Node::Peer::OnMsg(proto::BbsGetMsg&& msg) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); NodeDB& db = m_This.m_Processor.get_DB(); NodeDB::WalkerBbs wlk(db); wlk.m_Data.m_Key = msg.m_Key; if (!db.BbsFind(wlk)) return; // don't have it SendBbsMsg(wlk.m_Data); } void Node::Peer::SendBbsMsg(const NodeDB::WalkerBbs::Data& d) { if (d.m_bNonce && (proto::LoginFlags::Extension1 & m_LoginFlags)) { proto::BbsMsg msgOut; msgOut.m_Channel = d.m_Channel; msgOut.m_TimePosted = d.m_TimePosted; d.m_Message.Export(msgOut.m_Message); msgOut.m_Nonce = d.m_Nonce; Send(msgOut); } else { proto::BbsMsgV0 msgOut; msgOut.m_Channel = d.m_Channel; msgOut.m_TimePosted = d.m_TimePosted; d.m_Message.Export(msgOut.m_Message); Send(msgOut); } } void Node::Peer::OnMsg(proto::BbsSubscribe&& msg) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); Bbs::Subscription::InPeer key; key.m_Channel = msg.m_Channel; Bbs::Subscription::PeerSet::iterator it = m_Subscriptions.find(key); if ((m_Subscriptions.end() == it) != msg.m_On) return; if (msg.m_On) { Bbs::Subscription* pS = new Bbs::Subscription; pS->m_pPeer = this; pS->m_Bbs.m_Channel = msg.m_Channel; pS->m_Peer.m_Channel = msg.m_Channel; m_This.m_Bbs.m_Subscribed.insert(pS->m_Bbs); m_Subscriptions.insert(pS->m_Peer); pS->m_Cursor = m_This.m_Processor.get_DB().BbsFindCursor(msg.m_TimeFrom) - 1; BroadcastBbs(*pS); } else Unsubscribe(it->get_ParentObj()); } void Node::Peer::BroadcastBbs(Bbs::Subscription& s) { if (IsChocking()) return; NodeDB& db = m_This.m_Processor.get_DB(); NodeDB::WalkerBbs wlk(db); wlk.m_Data.m_Channel = s.m_Peer.m_Channel; wlk.m_ID = s.m_Cursor; for (db.EnumBbsCSeq(wlk); wlk.MoveNext(); ) { SendBbsMsg(wlk.m_Data); if (IsChocking()) break; } s.m_Cursor = wlk.m_ID; } void Node::Peer::OnMsg(proto::BbsResetSync&& msg) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); m_CursorBbs = m_This.m_Processor.get_DB().BbsFindCursor(msg.m_TimeFrom) - 1; BroadcastBbs(); } void Node::Peer::OnMsg(proto::BbsPickChannelV0&& msg) { if (!m_This.m_Cfg.m_Bbs) ThrowUnexpected(); if (proto::LoginFlags::Extension1 & m_LoginFlags) ThrowUnexpected(); // new client shouldn't ask for it proto::BbsPickChannelResV0 msgOut; msgOut.m_Channel = m_This.RandomUInt32(proto::Bbs::s_MaxChannels); Send(msgOut); } void Node::Peer::OnMsg(proto::MacroblockGet&& msg) { if (msg.m_Data >= Block::BodyBase::RW::Type::count) ThrowUnexpected(); Send(proto::Macroblock()); // deprecated } void Node::Peer::OnMsg(proto::GetUtxoEvents&& msg) { proto::UtxoEvents msgOut; if (Flags::Owner & m_Flags) { Processor& p = m_This.m_Processor; NodeDB& db = p.get_DB(); NodeDB::WalkerEvent wlk(db); Height hLast = 0; for (db.EnumEvents(wlk, msg.m_HeightMin); wlk.MoveNext(); hLast = wlk.m_Height) { typedef NodeProcessor::UtxoEvent UE; if ((msgOut.m_Events.size() >= proto::UtxoEvent::s_Max) && (wlk.m_Height != hLast)) break; if (p.IsFastSync() && (wlk.m_Height > p.m_SyncData.m_h0)) break; if (wlk.m_Body.n < sizeof(UE::Value) || (wlk.m_Key.n != sizeof(ECC::Point))) continue; // although shouldn't happen const UE::Value& evt = *reinterpret_cast<const UE::Value*>(wlk.m_Body.p); msgOut.m_Events.emplace_back(); proto::UtxoEvent& res = msgOut.m_Events.back(); res.m_Height = wlk.m_Height; res.m_Kidv = evt.m_Kidv; evt.m_Maturity.Export(res.m_Maturity); res.m_Commitment = *reinterpret_cast<const ECC::Point*>(wlk.m_Key.p); res.m_AssetID = evt.m_AssetID; res.m_Added = evt.m_Added; } } else LOG_WARNING() << "Peer " << m_RemoteAddr << " Unauthorized Utxo events request."; Send(msgOut); } void Node::Peer::OnMsg(proto::BlockFinalization&& msg) { if (!(Flags::Owner & m_Flags) || !(Flags::Finalizing & m_Flags)) ThrowUnexpected(); m_Flags &= ~Flags::Finalizing; if (!msg.m_Value) ThrowUnexpected(); Transaction& tx = *msg.m_Value; if (this != m_This.m_Miner.m_pFinalizer) return; // outdated if (!m_This.m_Miner.m_pTaskToFinalize) { m_This.m_Miner.Restart(); // time to restart return; } Miner::Task::Ptr pTask; pTask.swap(m_This.m_Miner.m_pTaskToFinalize); NodeProcessor::GeneratedBlock& x = *pTask; { ECC::Mode::Scope scope(ECC::Mode::Fast); // verify that all the outputs correspond to our viewer's Kdf (in case our comm was hacked this'd prevent mining for someone else) // and do the overall validation TxBase::Context::Params pars; pars.m_bBlockMode = true; TxBase::Context ctx(pars); if (!m_This.m_Processor.ValidateAndSummarize(ctx, *msg.m_Value, msg.m_Value->get_Reader())) ThrowUnexpected(); if (ctx.m_Coinbase != AmountBig::Type(Rules::get_Emission(m_This.m_Processor.m_Cursor.m_ID.m_Height + 1))) ThrowUnexpected(); ctx.m_Sigma = -ctx.m_Sigma; ctx.m_Coinbase += AmountBig::Type(x.m_Fees); AmountBig::AddTo(ctx.m_Sigma, ctx.m_Coinbase); if (!(ctx.m_Sigma == Zero)) ThrowUnexpected(); if (!tx.m_vInputs.empty()) ThrowUnexpected(); for (size_t i = 0; i < tx.m_vOutputs.size(); i++) { Key::IDV kidv; if (!tx.m_vOutputs[i]->Recover(*m_This.m_Keys.m_pOwner, kidv)) ThrowUnexpected(); } tx.MoveInto(x.m_Block); ECC::Scalar::Native offs = x.m_Block.m_Offset; offs += ECC::Scalar::Native(tx.m_Offset); x.m_Block.m_Offset = offs; } TxPool::Fluff txpEmpty; NodeProcessor::BlockContext bc(txpEmpty, 0, *m_This.m_Keys.m_pGeneric, *m_This.m_Keys.m_pGeneric); // the key isn't used anyway bc.m_Mode = NodeProcessor::BlockContext::Mode::Finalize; Cast::Down<NodeProcessor::GeneratedBlock>(bc) = std::move(x); bool bRes = m_This.m_Processor.GenerateNewBlock(bc); if (!bRes) { LOG_WARNING() << "Block finalization failed"; return; } Cast::Down<NodeProcessor::GeneratedBlock>(x) = std::move(bc); LOG_INFO() << "Block Finalized by owner"; m_This.m_Miner.StartMining(std::move(pTask)); } void Node::Server::OnAccepted(io::TcpStream::Ptr&& newStream, int errorCode) { if (newStream) { LOG_DEBUG() << "New peer connected: " << newStream->address(); Peer* p = get_ParentObj().AllocPeer(newStream->peer_address()); p->Accept(std::move(newStream)); p->SecureConnect(); } } void Node::Miner::Initialize(IExternalPOW* externalPOW) { const Config& cfg = get_ParentObj().m_Cfg; if (!cfg.m_MiningThreads && !externalPOW) return; m_pEvtMined = io::AsyncEvent::create(io::Reactor::get_Current(), [this]() { OnMined(); }); if (cfg.m_MiningThreads) { m_vThreads.resize(cfg.m_MiningThreads); for (uint32_t i = 0; i < cfg.m_MiningThreads; i++) { PerThread &pt = m_vThreads[i]; pt.m_pReactor = io::Reactor::create(); pt.m_pEvt = io::AsyncEvent::create(*pt.m_pReactor, [this, i]() { OnRefresh(i); }); pt.m_Thread = std::thread(&io::Reactor::run, pt.m_pReactor); } } m_External.m_pSolver = externalPOW; SetTimer(0, true); // async start mining } void Node::Miner::OnFinalizerChanged(Peer* p) { // always prefer newer (in case there are several ones) m_pFinalizer = p; if (!m_pFinalizer) { // try to find another one for (PeerList::iterator it = get_ParentObj().m_lstPeers.begin(); get_ParentObj().m_lstPeers.end() != it; it++) if (it->ShouldFinalizeMining()) { m_pFinalizer = &(*it); break; } } Restart(); } void Node::Miner::OnRefresh(uint32_t iIdx) { while (true) { Task::Ptr pTask; Block::SystemState::Full s; { std::scoped_lock<std::mutex> scope(m_Mutex); if (!m_pTask || *m_pTask->m_pStop) break; pTask = m_pTask; s = pTask->m_Hdr; // local copy } ECC::Hash::Value hv; // pick pseudo-random initial nonce for mining. ECC::Hash::Processor() << pTask->m_hvNonceSeed << iIdx >> hv; static_assert(s.m_PoW.m_Nonce.nBytes <= hv.nBytes); s.m_PoW.m_Nonce = hv; LOG_INFO() << "Mining nonce = " << s.m_PoW.m_Nonce; Block::PoW::Cancel fnCancel = [this, pTask](bool bRetrying) { if (*pTask->m_pStop) return true; if (bRetrying) { std::scoped_lock<std::mutex> scope(m_Mutex); if (pTask != m_pTask) return true; // soft restart triggered } return false; }; if (Rules::get().FakePoW) { uint32_t timeout_ms = get_ParentObj().m_Cfg.m_TestMode.m_FakePowSolveTime_ms; bool bSolved = false; for (uint32_t t0_ms = GetTime_ms(); ; ) { if (fnCancel(false)) break; std::this_thread::sleep_for(std::chrono::milliseconds(50)); uint32_t dt_ms = GetTime_ms() - t0_ms; if (dt_ms >= timeout_ms) { bSolved = true; break; } } if (!bSolved) continue; ZeroObject(s.m_PoW.m_Indices); // keep the difficulty intact } else { try { if (!s.GeneratePoW(fnCancel)) continue; } catch (const std::exception& ex) { LOG_DEBUG() << ex.what(); break; } } std::scoped_lock<std::mutex> scope(m_Mutex); if (*pTask->m_pStop) continue; // either aborted, or other thread was faster pTask->m_Hdr = s; // save the result *pTask->m_pStop = true; m_pTask = pTask; // In case there was a soft restart we restore the one that we mined. m_pEvtMined->post(); break; } } void Node::Miner::HardAbortSafe() { m_pTaskToFinalize.reset(); std::scoped_lock<std::mutex> scope(m_Mutex); if (m_pTask) { *m_pTask->m_pStop = true; m_pTask.reset(); } if (m_External.m_pSolver) { bool bHadTasks = false; for (size_t i = 0; i < _countof(m_External.m_ppTask); i++) { Task::Ptr& pTask = m_External.m_ppTask[i]; if (!pTask) continue; assert(*pTask->m_pStop); // should be the same stop inficator pTask.reset(); bHadTasks = true; } if (bHadTasks) m_External.m_pSolver->stop_current(); } } void Node::Miner::SetTimer(uint32_t timeout_ms, bool bHard) { if (!IsEnabled()) return; if (!m_pTimer) m_pTimer = io::Timer::create(io::Reactor::get_Current()); else if (m_bTimerPending && !bHard) return; m_pTimer->start(timeout_ms, false, [this]() { OnTimer(); }); m_bTimerPending = true; } void Node::Miner::OnTimer() { m_bTimerPending = false; Restart(); } bool Node::Miner::Restart() { if (!IsEnabled()) return false; // n/a if (!get_ParentObj().m_Processor.IsTreasuryHandled() || get_ParentObj().m_Processor.IsFastSync()) return false; m_pTaskToFinalize.reset(); const Keys& keys = get_ParentObj().m_Keys; if (m_pFinalizer) { if (Peer::Flags::Finalizing & m_pFinalizer->m_Flags) return false; // wait until we receive that outdated finalization } else if (!keys.m_pMiner) return false; // offline mining is disabled NodeProcessor::BlockContext bc( get_ParentObj().m_TxPool, keys.m_nMinerSubIndex, keys.m_pMiner ? *keys.m_pMiner : *keys.m_pGeneric, keys.m_pOwner ? *keys.m_pOwner : *keys.m_pGeneric); if (m_pFinalizer) bc.m_Mode = NodeProcessor::BlockContext::Mode::Assemble; bool bRes = get_ParentObj().m_Processor.GenerateNewBlock(bc); if (!bRes) { LOG_WARNING() << "Block generation failed, can't mine!"; return false; } Task::Ptr pTask(std::make_shared<Task>()); Cast::Down<NodeProcessor::GeneratedBlock>(*pTask) = std::move(bc); if (m_pFinalizer) { const NodeProcessor::GeneratedBlock& x = *pTask; LOG_INFO() << "Block generated: Height=" << x.m_Hdr.m_Height << ", Fee=" << x.m_Fees << ", Waiting for owner response..."; proto::GetBlockFinalization msg; msg.m_Height = pTask->m_Hdr.m_Height; msg.m_Fees = pTask->m_Fees; m_pFinalizer->Send(msg); assert(!(Peer::Flags::Finalizing & m_pFinalizer->m_Flags)); m_pFinalizer->m_Flags |= Peer::Flags::Finalizing; m_pTaskToFinalize = std::move(pTask); } else StartMining(std::move(pTask)); return true; } void Node::Miner::StartMining(Task::Ptr&& pTask) { assert(pTask && !m_pTaskToFinalize); const NodeProcessor::GeneratedBlock& x = *pTask; LOG_INFO() << "Block generated: Height=" << x.m_Hdr.m_Height << ", Fee=" << x.m_Fees << ", Difficulty=" << x.m_Hdr.m_PoW.m_Difficulty << ", Size=" << (x.m_BodyP.size() + x.m_BodyE.size()); pTask->m_hvNonceSeed = get_ParentObj().NextNonce(); // let's mine it. std::scoped_lock<std::mutex> scope(m_Mutex); if (m_pTask) { if (*m_pTask->m_pStop) return; // block already mined, probably notification to this thread on its way. Ignore the newly-constructed block pTask->m_pStop = m_pTask->m_pStop; // use the same soft-restart indicator } else { pTask->m_pStop.reset(new volatile bool); *pTask->m_pStop = false; } m_pTask = std::move(pTask); for (size_t i = 0; i < m_vThreads.size(); i++) m_vThreads[i].m_pEvt->post(); OnRefreshExternal(); } Node::Miner::Task::Ptr& Node::Miner::External::get_At(uint64_t jobID) { return m_ppTask[static_cast<size_t>(jobID % _countof(m_ppTask))]; } void Node::Miner::OnRefreshExternal() { if (!m_External.m_pSolver) return; // NOTE the mutex is locked here LOG_INFO() << "New job for external miner"; uint64_t jobID = ++m_External.m_jobID; m_External.get_At(jobID) = m_pTask; auto fnCancel = []() { return false; }; Merkle::Hash hv; m_pTask->m_Hdr.get_HashForPoW(hv); m_External.m_pSolver->new_job(std::to_string(jobID), hv, m_pTask->m_Hdr.m_PoW, m_pTask->m_Hdr.m_Height , BIND_THIS_MEMFN(OnMinedExternal), fnCancel); } void Node::Miner::OnMinedExternal() { std::string jobID_; Block::PoW POW; assert(m_External.m_pSolver); m_External.m_pSolver->get_last_found_block(jobID_, POW); char* szEnd = nullptr; uint64_t jobID = strtoul(jobID_.c_str(), &szEnd, 10); std::scoped_lock<std::mutex> scope(m_Mutex); bool bReject = (m_External.m_jobID - jobID >= _countof(m_External.m_ppTask)); LOG_INFO() << "Solution from external miner. jobID=" << jobID << ", Current.jobID=" << m_External.m_jobID << ", Accept=" << static_cast<uint32_t>(!bReject); if (bReject) { LOG_INFO() << "Solution is rejected due it is outdated."; return; // outdated } Task::Ptr& pTask = m_External.get_At(jobID); if (!pTask || *pTask->m_pStop) { LOG_INFO() << "Solution is rejected due block mining has been canceled."; return; // already cancelled } pTask->m_Hdr.m_PoW.m_Nonce = POW.m_Nonce; pTask->m_Hdr.m_PoW.m_Indices = POW.m_Indices; if (!pTask->m_Hdr.IsValidPoW()) { LOG_INFO() << "invalid solution from external miner"; return; } m_pTask = pTask; *m_pTask->m_pStop = true; m_pEvtMined->post(); } void Node::Miner::OnMined() { Task::Ptr pTask; { std::scoped_lock<std::mutex> scope(m_Mutex); if (!(m_pTask && *m_pTask->m_pStop)) return; //?! pTask.swap(m_pTask); } Block::SystemState::ID id; pTask->m_Hdr.get_ID(id); LOG_INFO() << "New block mined: " << id; Processor& p = get_ParentObj().m_Processor; // alias NodeProcessor::DataStatus::Enum eStatus = p.OnState(pTask->m_Hdr, get_ParentObj().m_MyPublicID); switch (eStatus) { default: case NodeProcessor::DataStatus::Invalid: // Some bug? LOG_WARNING() << "Mined block rejected as invalid!"; return; case NodeProcessor::DataStatus::Rejected: // Someone else mined exactly the same block! LOG_WARNING() << "Mined block duplicated"; return; case NodeProcessor::DataStatus::Accepted: break; // ok } assert(NodeProcessor::DataStatus::Accepted == eStatus); eStatus = p.OnBlock(id, pTask->m_BodyP, pTask->m_BodyE, get_ParentObj().m_MyPublicID); assert(NodeProcessor::DataStatus::Accepted == eStatus); p.FlushDB(); p.TryGoUpAsync(); // will likely trigger OnNewState(), and spread this block to the network } struct Node::Beacon::OutCtx { int m_Refs; OutCtx() :m_Refs(0) {} struct UvRequest :public uv_udp_send_t { IMPLEMENT_GET_PARENT_OBJ(OutCtx, m_Request) } m_Request; uv_buf_t m_BufDescr; #pragma pack (push, 1) struct Message { Merkle::Hash m_CfgChecksum; PeerID m_NodeID; uint16_t m_Port; // in network byte order }; #pragma pack (pop) Message m_Message; // the message broadcasted void Release() { assert(m_Refs > 0); if (!--m_Refs) delete this; } static void OnDone(uv_udp_send_t* req, int status); }; Node::Beacon::Beacon() :m_pUdp(NULL) ,m_pOut(NULL) { } Node::Beacon::~Beacon() { if (m_pUdp) uv_close((uv_handle_t*) m_pUdp, OnClosed); if (m_pOut) m_pOut->Release(); } uint16_t Node::Beacon::get_Port() { uint16_t nPort = get_ParentObj().m_Cfg.m_BeaconPort; return nPort ? nPort : get_ParentObj().m_Cfg.m_Listen.port(); } void Node::Beacon::Start() { assert(!m_pUdp); m_pUdp = new uv_udp_t; uv_udp_init(&io::Reactor::get_Current().get_UvLoop(), m_pUdp); m_pUdp->data = this; m_BufRcv.resize(sizeof(OutCtx::Message)); io::Address addr; addr.port(get_Port()); sockaddr_in sa; addr.fill_sockaddr_in(sa); if (uv_udp_bind(m_pUdp, (sockaddr*)&sa, UV_UDP_REUSEADDR)) // should allow multiple nodes on the same machine (for testing) std::ThrowLastError(); if (uv_udp_recv_start(m_pUdp, AllocBuf, OnRcv)) std::ThrowLastError(); if (uv_udp_set_broadcast(m_pUdp, 1)) std::ThrowLastError(); m_pTimer = io::Timer::create(io::Reactor::get_Current()); m_pTimer->start(get_ParentObj().m_Cfg.m_BeaconPeriod_ms, true, [this]() { OnTimer(); }); // periodic timer OnTimer(); } void Node::Beacon::OnTimer() { if (!m_pOut) { m_pOut = new OutCtx; m_pOut->m_Refs = 1; m_pOut->m_Message.m_CfgChecksum = Rules::get().Checksum; m_pOut->m_Message.m_NodeID = get_ParentObj().m_MyPublicID; m_pOut->m_Message.m_Port = htons(get_ParentObj().m_Cfg.m_Listen.port()); m_pOut->m_BufDescr.base = (char*) &m_pOut->m_Message; m_pOut->m_BufDescr.len = sizeof(m_pOut->m_Message); } else if (m_pOut->m_Refs > 1) return; // send still pending io::Address addr; addr.port(get_Port()); addr.ip(INADDR_BROADCAST); sockaddr_in sa; addr.fill_sockaddr_in(sa); m_pOut->m_Refs++; int nErr = uv_udp_send(&m_pOut->m_Request, m_pUdp, &m_pOut->m_BufDescr, 1, (sockaddr*) &sa, OutCtx::OnDone); if (nErr) m_pOut->Release(); } void Node::Beacon::OutCtx::OnDone(uv_udp_send_t* req, int /* status */) { UvRequest* pVal = (UvRequest*)req; assert(pVal); pVal->get_ParentObj().Release(); } void Node::Beacon::OnRcv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* pSa, unsigned flags) { OutCtx::Message msg; if (sizeof(msg) != nread) return; memcpy(&msg, buf->base, sizeof(msg)); // copy it to prevent (potential) datatype misallignment and etc. if (msg.m_CfgChecksum != Rules::get().Checksum) return; Beacon* pThis = (Beacon*)handle->data; if (pThis->get_ParentObj().m_MyPublicID == msg.m_NodeID) return; io::Address addr(*(sockaddr_in*)pSa); addr.port(ntohs(msg.m_Port)); pThis->get_ParentObj().m_PeerMan.OnPeer(msg.m_NodeID, addr, true); } void Node::Beacon::AllocBuf(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { Beacon* pThis = (Beacon*)handle->data; assert(pThis); buf->base = (char*) &pThis->m_BufRcv.at(0); buf->len = sizeof(OutCtx::Message); } void Node::Beacon::OnClosed(uv_handle_t* p) { assert(p); delete (uv_udp_t*) p; } void Node::PeerMan::Initialize() { const Config& cfg = get_ParentObj().m_Cfg; for (uint32_t i = 0; i < cfg.m_Connect.size(); i++) { PeerID id0(Zero); OnPeer(id0, cfg.m_Connect[i], true); } // peers m_pTimerUpd = io::Timer::create(io::Reactor::get_Current()); m_pTimerUpd->start(cfg.m_Timeout.m_PeersUpdate_ms, true, [this]() { Update(); }); m_pTimerFlush = io::Timer::create(io::Reactor::get_Current()); m_pTimerFlush->start(cfg.m_Timeout.m_PeersDbFlush_ms, true, [this]() { OnFlush(); }); { NodeDB::WalkerPeer wlk(get_ParentObj().m_Processor.get_DB()); for (get_ParentObj().m_Processor.get_DB().EnumPeers(wlk); wlk.MoveNext(); ) { if (wlk.m_Data.m_ID == get_ParentObj().m_MyPublicID) continue; // could be left from previous run? PeerMan::PeerInfo* pPi = OnPeer(wlk.m_Data.m_ID, io::Address::from_u64(wlk.m_Data.m_Address), false); if (!pPi) continue; // set rating (akward, TODO - fix this) uint32_t r = wlk.m_Data.m_Rating; if (!r) Ban(*pPi); else if (r > pPi->m_RawRating.m_Value) ModifyRating(*pPi, r - pPi->m_RawRating.m_Value, true); else ModifyRating(*pPi, pPi->m_RawRating.m_Value - r, false); pPi->m_LastSeen = wlk.m_Data.m_LastSeen; } } } void Node::PeerMan::OnFlush() { NodeDB& db = get_ParentObj().m_Processor.get_DB(); db.PeersDel(); const PeerMan::RawRatingSet& rs = get_Ratings(); for (PeerMan::RawRatingSet::const_iterator it = rs.begin(); rs.end() != it; it++) { const PeerMan::PeerInfo& pi = it->get_ParentObj(); NodeDB::WalkerPeer::Data d; d.m_ID = pi.m_ID.m_Key; d.m_Rating = pi.m_RawRating.m_Value; d.m_Address = pi.m_Addr.m_Value.u64(); d.m_LastSeen = pi.m_LastSeen; db.PeerIns(d); } } void Node::PeerMan::ActivatePeer(PeerInfo& pi) { PeerInfoPlus& pip = (PeerInfoPlus&)pi; if (pip.m_pLive) return; //? Peer* p = get_ParentObj().AllocPeer(pip.m_Addr.m_Value); p->m_pInfo = &pip; pip.m_pLive = p; p->Connect(pip.m_Addr.m_Value); p->m_Port = pip.m_Addr.m_Value.port(); } void Node::PeerMan::DeactivatePeer(PeerInfo& pi) { PeerInfoPlus& pip = (PeerInfoPlus&)pi; if (!pip.m_pLive) return; //? pip.m_pLive->DeleteSelf(false, proto::NodeConnection::ByeReason::Other); } PeerManager::PeerInfo* Node::PeerMan::AllocPeer() { PeerInfoPlus* p = new PeerInfoPlus; p->m_pLive = NULL; return p; } void Node::PeerMan::DeletePeer(PeerInfo& pi) { delete (PeerInfoPlus*)&pi; } } // namespace beam
//===- unittest/Tooling/TransformerTest.cpp -------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "clang/Tooling/Transformer/Transformer.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Tooling/Tooling.h" #include "clang/Tooling/Transformer/RangeSelector.h" #include "clang/Tooling/Transformer/RewriteRule.h" #include "clang/Tooling/Transformer/Stencil.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using namespace clang; using namespace tooling; using namespace ast_matchers; namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; using transformer::cat; using transformer::changeTo; using transformer::rewriteDescendants; using transformer::RewriteRule; constexpr char KHeaderContents[] = R"cc( struct string { string(const char*); char* c_str(); int size(); }; int strlen(const char*); namespace proto { struct PCFProto { int foo(); }; struct ProtoCommandLineFlag : PCFProto { PCFProto& GetProto(); }; } // namespace proto class Logger {}; void operator<<(Logger& l, string msg); Logger& log(int level); )cc"; static ast_matchers::internal::Matcher<clang::QualType> isOrPointsTo(const clang::ast_matchers::DeclarationMatcher &TypeMatcher) { return anyOf(hasDeclaration(TypeMatcher), pointsTo(TypeMatcher)); } static std::string format(StringRef Code) { const std::vector<Range> Ranges(1, Range(0, Code.size())); auto Style = format::getLLVMStyle(); const auto Replacements = format::reformat(Style, Code, Ranges); auto Formatted = applyAllReplacements(Code, Replacements); if (!Formatted) { ADD_FAILURE() << "Could not format code: " << llvm::toString(Formatted.takeError()); return std::string(); } return *Formatted; } static void compareSnippets(StringRef Expected, const llvm::Optional<std::string> &MaybeActual) { ASSERT_TRUE(MaybeActual) << "Rewrite failed. Expecting: " << Expected; auto Actual = *MaybeActual; std::string HL = "#include \"header.h\"\n"; auto I = Actual.find(HL); if (I != std::string::npos) Actual.erase(I, HL.size()); EXPECT_EQ(format(Expected), format(Actual)); } // FIXME: consider separating this class into its own file(s). class ClangRefactoringTestBase : public testing::Test { protected: void appendToHeader(StringRef S) { FileContents[0].second += S; } void addFile(StringRef Filename, StringRef Content) { FileContents.emplace_back(std::string(Filename), std::string(Content)); } llvm::Optional<std::string> rewrite(StringRef Input) { std::string Code = ("#include \"header.h\"\n" + Input).str(); auto Factory = newFrontendActionFactory(&MatchFinder); if (!runToolOnCodeWithArgs( Factory->create(), Code, std::vector<std::string>(), "input.cc", "clang-tool", std::make_shared<PCHContainerOperations>(), FileContents)) { llvm::errs() << "Running tool failed.\n"; return None; } if (ErrorCount != 0) { llvm::errs() << "Generating changes failed.\n"; return None; } auto ChangedCode = applyAtomicChanges("input.cc", Code, Changes, ApplyChangesSpec()); if (!ChangedCode) { llvm::errs() << "Applying changes failed: " << llvm::toString(ChangedCode.takeError()) << "\n"; return None; } return *ChangedCode; } Transformer::ChangeConsumer consumer() { return [this](Expected<AtomicChange> C) { if (C) { Changes.push_back(std::move(*C)); } else { // FIXME: stash this error rather then printing. llvm::errs() << "Error generating changes: " << llvm::toString(C.takeError()) << "\n"; ++ErrorCount; } }; } template <typename R> void testRule(R Rule, StringRef Input, StringRef Expected) { Transformer T(std::move(Rule), consumer()); T.registerMatchers(&MatchFinder); compareSnippets(Expected, rewrite(Input)); } clang::ast_matchers::MatchFinder MatchFinder; // Records whether any errors occurred in individual changes. int ErrorCount = 0; AtomicChanges Changes; private: FileContentMappings FileContents = {{"header.h", ""}}; }; class TransformerTest : public ClangRefactoringTestBase { protected: TransformerTest() { appendToHeader(KHeaderContents); } }; // Given string s, change strlen($s.c_str()) to REPLACED. static RewriteRule ruleStrlenSize() { StringRef StringExpr = "strexpr"; auto StringType = namedDecl(hasAnyName("::basic_string", "::string")); auto R = makeRule( callExpr(callee(functionDecl(hasName("strlen"))), hasArgument(0, cxxMemberCallExpr( on(expr(hasType(isOrPointsTo(StringType))) .bind(StringExpr)), callee(cxxMethodDecl(hasName("c_str")))))), changeTo(cat("REPLACED")), cat("Use size() method directly on string.")); return R; } TEST_F(TransformerTest, StrlenSize) { std::string Input = "int f(string s) { return strlen(s.c_str()); }"; std::string Expected = "int f(string s) { return REPLACED; }"; testRule(ruleStrlenSize(), Input, Expected); } // Tests that no change is applied when a match is not expected. TEST_F(TransformerTest, NoMatch) { std::string Input = "int f(string s) { return s.size(); }"; testRule(ruleStrlenSize(), Input, Input); } // Tests replacing an expression. TEST_F(TransformerTest, Flag) { StringRef Flag = "flag"; RewriteRule Rule = makeRule( cxxMemberCallExpr(on(expr(hasType(cxxRecordDecl( hasName("proto::ProtoCommandLineFlag")))) .bind(Flag)), unless(callee(cxxMethodDecl(hasName("GetProto"))))), changeTo(node(std::string(Flag)), cat("EXPR"))); std::string Input = R"cc( proto::ProtoCommandLineFlag flag; int x = flag.foo(); int y = flag.GetProto().foo(); )cc"; std::string Expected = R"cc( proto::ProtoCommandLineFlag flag; int x = EXPR.foo(); int y = flag.GetProto().foo(); )cc"; testRule(std::move(Rule), Input, Expected); } TEST_F(TransformerTest, AddIncludeQuoted) { RewriteRule Rule = makeRule(callExpr(callee(functionDecl(hasName("f")))), {addInclude("clang/OtherLib.h"), changeTo(cat("other()"))}); std::string Input = R"cc( int f(int x); int h(int x) { return f(x); } )cc"; std::string Expected = R"cc(#include "clang/OtherLib.h" int f(int x); int h(int x) { return other(); } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, AddIncludeAngled) { RewriteRule Rule = makeRule( callExpr(callee(functionDecl(hasName("f")))), {addInclude("clang/OtherLib.h", transformer::IncludeFormat::Angled), changeTo(cat("other()"))}); std::string Input = R"cc( int f(int x); int h(int x) { return f(x); } )cc"; std::string Expected = R"cc(#include <clang/OtherLib.h> int f(int x); int h(int x) { return other(); } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, AddIncludeQuotedForRule) { RewriteRule Rule = makeRule(callExpr(callee(functionDecl(hasName("f")))), changeTo(cat("other()"))); addInclude(Rule, "clang/OtherLib.h"); std::string Input = R"cc( int f(int x); int h(int x) { return f(x); } )cc"; std::string Expected = R"cc(#include "clang/OtherLib.h" int f(int x); int h(int x) { return other(); } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, AddIncludeAngledForRule) { RewriteRule Rule = makeRule(callExpr(callee(functionDecl(hasName("f")))), changeTo(cat("other()"))); addInclude(Rule, "clang/OtherLib.h", transformer::IncludeFormat::Angled); std::string Input = R"cc( int f(int x); int h(int x) { return f(x); } )cc"; std::string Expected = R"cc(#include <clang/OtherLib.h> int f(int x); int h(int x) { return other(); } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, NodePartNameNamedDecl) { StringRef Fun = "fun"; RewriteRule Rule = makeRule(functionDecl(hasName("bad")).bind(Fun), changeTo(name(std::string(Fun)), cat("good"))); std::string Input = R"cc( int bad(int x); int bad(int x) { return x * x; } )cc"; std::string Expected = R"cc( int good(int x); int good(int x) { return x * x; } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, NodePartNameDeclRef) { std::string Input = R"cc( template <typename T> T bad(T x) { return x; } int neutral(int x) { return bad<int>(x) * x; } )cc"; std::string Expected = R"cc( template <typename T> T bad(T x) { return x; } int neutral(int x) { return good<int>(x) * x; } )cc"; StringRef Ref = "ref"; testRule(makeRule(declRefExpr(to(functionDecl(hasName("bad")))).bind(Ref), changeTo(name(std::string(Ref)), cat("good"))), Input, Expected); } TEST_F(TransformerTest, NodePartNameDeclRefFailure) { std::string Input = R"cc( struct Y { int operator*(); }; int neutral(int x) { Y y; int (Y::*ptr)() = &Y::operator*; return *y + x; } )cc"; StringRef Ref = "ref"; Transformer T(makeRule(declRefExpr(to(functionDecl())).bind(Ref), changeTo(name(std::string(Ref)), cat("good"))), consumer()); T.registerMatchers(&MatchFinder); EXPECT_FALSE(rewrite(Input)); } TEST_F(TransformerTest, NodePartMember) { StringRef E = "expr"; RewriteRule Rule = makeRule(memberExpr(member(hasName("bad"))).bind(E), changeTo(member(std::string(E)), cat("good"))); std::string Input = R"cc( struct S { int bad; }; int g() { S s; return s.bad; } )cc"; std::string Expected = R"cc( struct S { int bad; }; int g() { S s; return s.good; } )cc"; testRule(Rule, Input, Expected); } TEST_F(TransformerTest, NodePartMemberQualified) { std::string Input = R"cc( struct S { int bad; int good; }; struct T : public S { int bad; }; int g() { T t; return t.S::bad; } )cc"; std::string Expected = R"cc( struct S { int bad; int good; }; struct T : public S { int bad; }; int g() { T t; return t.S::good; } )cc"; StringRef E = "expr"; testRule(makeRule(memberExpr().bind(E), changeTo(member(std::string(E)), cat("good"))), Input, Expected); } TEST_F(TransformerTest, NodePartMemberMultiToken) { std::string Input = R"cc( struct Y { int operator*(); int good(); template <typename T> void foo(T t); }; int neutral(int x) { Y y; y.template foo<int>(3); return y.operator *(); } )cc"; std::string Expected = R"cc( struct Y { int operator*(); int good(); template <typename T> void foo(T t); }; int neutral(int x) { Y y; y.template good<int>(3); return y.good(); } )cc"; StringRef MemExpr = "member"; testRule(makeRule(memberExpr().bind(MemExpr), changeTo(member(std::string(MemExpr)), cat("good"))), Input, Expected); } TEST_F(TransformerTest, NoEdits) { using transformer::noEdits; std::string Input = "int f(int x) { return x; }"; testRule(makeRule(returnStmt().bind("return"), noEdits()), Input, Input); } TEST_F(TransformerTest, NoopEdit) { using transformer::node; using transformer::noopEdit; std::string Input = "int f(int x) { return x; }"; testRule(makeRule(returnStmt().bind("return"), noopEdit(node("return"))), Input, Input); } TEST_F(TransformerTest, IfBound2Args) { using transformer::ifBound; std::string Input = "int f(int x) { return x; }"; std::string Expected = "int f(int x) { CHANGE; }"; testRule(makeRule(returnStmt().bind("return"), ifBound("return", changeTo(cat("CHANGE;")))), Input, Expected); } TEST_F(TransformerTest, IfBound3Args) { using transformer::ifBound; std::string Input = "int f(int x) { return x; }"; std::string Expected = "int f(int x) { CHANGE; }"; testRule(makeRule(returnStmt().bind("return"), ifBound("nothing", changeTo(cat("ERROR")), changeTo(cat("CHANGE;")))), Input, Expected); } TEST_F(TransformerTest, ShrinkTo) { using transformer::shrinkTo; std::string Input = "int f(int x) { return x; }"; std::string Expected = "return x;"; testRule(makeRule(functionDecl(hasDescendant(returnStmt().bind("return"))) .bind("function"), shrinkTo(node("function"), node("return"))), Input, Expected); } // Rewrite various Stmts inside a Decl. TEST_F(TransformerTest, RewriteDescendantsDeclChangeStmt) { std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int f(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule(makeRule(functionDecl(hasName("f")).bind("fun"), rewriteDescendants("fun", InlineX)), Input, Expected); } // Rewrite various TypeLocs inside a Decl. TEST_F(TransformerTest, RewriteDescendantsDeclChangeTypeLoc) { std::string Input = "int f(int *x) { return *x; }"; std::string Expected = "char f(char *x) { return *x; }"; auto IntToChar = makeRule(typeLoc(loc(qualType(isInteger(), builtinType()))), changeTo(cat("char"))); testRule(makeRule(functionDecl(hasName("f")).bind("fun"), rewriteDescendants("fun", IntToChar)), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsStmt) { // Add an unrelated definition to the header that also has a variable named // "x", to test that the rewrite is limited to the scope we intend. appendToHeader(R"cc(int g(int x) { return x; })cc"); std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int f(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule(makeRule(functionDecl(hasName("f"), hasBody(stmt().bind("body"))), rewriteDescendants("body", InlineX)), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsStmtWithAdditionalChange) { std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int newName(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule( makeRule( functionDecl(hasName("f"), hasBody(stmt().bind("body"))).bind("f"), flatten(changeTo(name("f"), cat("newName")), rewriteDescendants("body", InlineX))), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsTypeLoc) { std::string Input = "int f(int *x) { return *x; }"; std::string Expected = "int f(char *x) { return *x; }"; auto IntToChar = makeRule(typeLoc(loc(qualType(isInteger(), builtinType()))).bind("loc"), changeTo(cat("char"))); testRule( makeRule(functionDecl(hasName("f"), hasParameter(0, varDecl(hasTypeLoc( typeLoc().bind("parmType"))))), rewriteDescendants("parmType", IntToChar)), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsReferToParentBinding) { std::string Input = "int f(int p) { int y = p; { int z = p * p; } return p; }"; std::string Expected = "int f(int p) { int y = 3; { int z = 3 * 3; } return 3; }"; std::string VarId = "var"; auto InlineVar = makeRule(declRefExpr(to(varDecl(equalsBoundNode(VarId)))), changeTo(cat("3"))); testRule(makeRule(functionDecl(hasName("f"), hasParameter(0, varDecl().bind(VarId))) .bind("fun"), rewriteDescendants("fun", InlineVar)), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsUnboundNode) { std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); Transformer T(makeRule(functionDecl(hasName("f")), rewriteDescendants("UNBOUND", InlineX)), consumer()); T.registerMatchers(&MatchFinder); EXPECT_FALSE(rewrite(Input)); EXPECT_THAT(Changes, IsEmpty()); EXPECT_EQ(ErrorCount, 1); } TEST_F(TransformerTest, RewriteDescendantsInvalidNodeType) { std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; auto IntToChar = makeRule(qualType(isInteger(), builtinType()), changeTo(cat("char"))); Transformer T( makeRule(functionDecl( hasName("f"), hasParameter(0, varDecl(hasType(qualType().bind("type"))))), rewriteDescendants("type", IntToChar)), consumer()); T.registerMatchers(&MatchFinder); EXPECT_FALSE(rewrite(Input)); EXPECT_THAT(Changes, IsEmpty()); EXPECT_EQ(ErrorCount, 1); } // // We include one test per typed overload. We don't test extensively since that // is already covered by the tests above. // TEST_F(TransformerTest, RewriteDescendantsTypedStmt) { // Add an unrelated definition to the header that also has a variable named // "x", to test that the rewrite is limited to the scope we intend. appendToHeader(R"cc(int g(int x) { return x; })cc"); std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int f(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule(makeRule(functionDecl(hasName("f"), hasBody(stmt().bind("body"))), [&InlineX](const MatchFinder::MatchResult &R) { const auto *Node = R.Nodes.getNodeAs<Stmt>("body"); assert(Node != nullptr && "body must be bound"); return transformer::detail::rewriteDescendants( *Node, InlineX, R); }), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsTypedDecl) { std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int f(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule(makeRule(functionDecl(hasName("f")).bind("fun"), [&InlineX](const MatchFinder::MatchResult &R) { const auto *Node = R.Nodes.getNodeAs<Decl>("fun"); assert(Node != nullptr && "fun must be bound"); return transformer::detail::rewriteDescendants( *Node, InlineX, R); }), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsTypedTypeLoc) { std::string Input = "int f(int *x) { return *x; }"; std::string Expected = "int f(char *x) { return *x; }"; auto IntToChar = makeRule(typeLoc(loc(qualType(isInteger(), builtinType()))).bind("loc"), changeTo(cat("char"))); testRule( makeRule( functionDecl( hasName("f"), hasParameter(0, varDecl(hasTypeLoc(typeLoc().bind("parmType"))))), [&IntToChar](const MatchFinder::MatchResult &R) { const auto *Node = R.Nodes.getNodeAs<TypeLoc>("parmType"); assert(Node != nullptr && "parmType must be bound"); return transformer::detail::rewriteDescendants(*Node, IntToChar, R); }), Input, Expected); } TEST_F(TransformerTest, RewriteDescendantsTypedDynTyped) { // Add an unrelated definition to the header that also has a variable named // "x", to test that the rewrite is limited to the scope we intend. appendToHeader(R"cc(int g(int x) { return x; })cc"); std::string Input = "int f(int x) { int y = x; { int z = x * x; } return x; }"; std::string Expected = "int f(int x) { int y = 3; { int z = 3 * 3; } return 3; }"; auto InlineX = makeRule(declRefExpr(to(varDecl(hasName("x")))), changeTo(cat("3"))); testRule( makeRule(functionDecl(hasName("f"), hasBody(stmt().bind("body"))), [&InlineX](const MatchFinder::MatchResult &R) { auto It = R.Nodes.getMap().find("body"); assert(It != R.Nodes.getMap().end() && "body must be bound"); return transformer::detail::rewriteDescendants(It->second, InlineX, R); }), Input, Expected); } TEST_F(TransformerTest, InsertBeforeEdit) { std::string Input = R"cc( int f() { return 7; } )cc"; std::string Expected = R"cc( int f() { int y = 3; return 7; } )cc"; StringRef Ret = "return"; testRule( makeRule(returnStmt().bind(Ret), insertBefore(statement(std::string(Ret)), cat("int y = 3;"))), Input, Expected); } TEST_F(TransformerTest, InsertAfterEdit) { std::string Input = R"cc( int f() { int x = 5; return 7; } )cc"; std::string Expected = R"cc( int f() { int x = 5; int y = 3; return 7; } )cc"; StringRef Decl = "decl"; testRule( makeRule(declStmt().bind(Decl), insertAfter(statement(std::string(Decl)), cat("int y = 3;"))), Input, Expected); } TEST_F(TransformerTest, RemoveEdit) { std::string Input = R"cc( int f() { int x = 5; return 7; } )cc"; std::string Expected = R"cc( int f() { return 7; } )cc"; StringRef Decl = "decl"; testRule( makeRule(declStmt().bind(Decl), remove(statement(std::string(Decl)))), Input, Expected); } TEST_F(TransformerTest, WithMetadata) { auto makeMetadata = [](const MatchFinder::MatchResult &R) -> llvm::Any { int N = R.Nodes.getNodeAs<IntegerLiteral>("int")->getValue().getLimitedValue(); return N; }; std::string Input = R"cc( int f() { int x = 5; return 7; } )cc"; Transformer T( makeRule( declStmt(containsDeclaration(0, varDecl(hasInitializer( integerLiteral().bind("int"))))) .bind("decl"), withMetadata(remove(statement(std::string("decl"))), makeMetadata)), consumer()); T.registerMatchers(&MatchFinder); auto Factory = newFrontendActionFactory(&MatchFinder); EXPECT_TRUE(runToolOnCodeWithArgs( Factory->create(), Input, std::vector<std::string>(), "input.cc", "clang-tool", std::make_shared<PCHContainerOperations>(), {})); ASSERT_EQ(Changes.size(), 1u); const llvm::Any &Metadata = Changes[0].getMetadata(); ASSERT_TRUE(llvm::any_isa<int>(Metadata)); EXPECT_THAT(llvm::any_cast<int>(Metadata), 5); } TEST_F(TransformerTest, MultiChange) { std::string Input = R"cc( void foo() { if (10 > 1.0) log(1) << "oh no!"; else log(0) << "ok"; } )cc"; std::string Expected = R"( void foo() { if (true) { /* then */ } else { /* else */ } } )"; StringRef C = "C", T = "T", E = "E"; testRule( makeRule(ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)), hasElse(stmt().bind(E))), {changeTo(node(std::string(C)), cat("true")), changeTo(statement(std::string(T)), cat("{ /* then */ }")), changeTo(statement(std::string(E)), cat("{ /* else */ }"))}), Input, Expected); } TEST_F(TransformerTest, EditList) { using clang::transformer::editList; std::string Input = R"cc( void foo() { if (10 > 1.0) log(1) << "oh no!"; else log(0) << "ok"; } )cc"; std::string Expected = R"( void foo() { if (true) { /* then */ } else { /* else */ } } )"; StringRef C = "C", T = "T", E = "E"; testRule(makeRule(ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)), hasElse(stmt().bind(E))), editList({changeTo(node(std::string(C)), cat("true")), changeTo(statement(std::string(T)), cat("{ /* then */ }")), changeTo(statement(std::string(E)), cat("{ /* else */ }"))})), Input, Expected); } TEST_F(TransformerTest, Flatten) { using clang::transformer::editList; std::string Input = R"cc( void foo() { if (10 > 1.0) log(1) << "oh no!"; else log(0) << "ok"; } )cc"; std::string Expected = R"( void foo() { if (true) { /* then */ } else { /* else */ } } )"; StringRef C = "C", T = "T", E = "E"; testRule( makeRule( ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)), hasElse(stmt().bind(E))), flatten(changeTo(node(std::string(C)), cat("true")), changeTo(statement(std::string(T)), cat("{ /* then */ }")), changeTo(statement(std::string(E)), cat("{ /* else */ }")))), Input, Expected); } TEST_F(TransformerTest, FlattenWithMixedArgs) { using clang::transformer::editList; std::string Input = R"cc( void foo() { if (10 > 1.0) log(1) << "oh no!"; else log(0) << "ok"; } )cc"; std::string Expected = R"( void foo() { if (true) { /* then */ } else { /* else */ } } )"; StringRef C = "C", T = "T", E = "E"; testRule(makeRule(ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)), hasElse(stmt().bind(E))), flatten(changeTo(node(std::string(C)), cat("true")), edit(changeTo(statement(std::string(T)), cat("{ /* then */ }"))), editList({changeTo(statement(std::string(E)), cat("{ /* else */ }"))}))), Input, Expected); } TEST_F(TransformerTest, OrderedRuleUnrelated) { StringRef Flag = "flag"; RewriteRule FlagRule = makeRule( cxxMemberCallExpr(on(expr(hasType(cxxRecordDecl( hasName("proto::ProtoCommandLineFlag")))) .bind(Flag)), unless(callee(cxxMethodDecl(hasName("GetProto"))))), changeTo(node(std::string(Flag)), cat("PROTO"))); std::string Input = R"cc( proto::ProtoCommandLineFlag flag; int x = flag.foo(); int y = flag.GetProto().foo(); int f(string s) { return strlen(s.c_str()); } )cc"; std::string Expected = R"cc( proto::ProtoCommandLineFlag flag; int x = PROTO.foo(); int y = flag.GetProto().foo(); int f(string s) { return REPLACED; } )cc"; testRule(applyFirst({ruleStrlenSize(), FlagRule}), Input, Expected); } TEST_F(TransformerTest, OrderedRuleRelated) { std::string Input = R"cc( void f1(); void f2(); void call_f1() { f1(); } void call_f2() { f2(); } )cc"; std::string Expected = R"cc( void f1(); void f2(); void call_f1() { REPLACE_F1; } void call_f2() { REPLACE_F1_OR_F2; } )cc"; RewriteRule ReplaceF1 = makeRule(callExpr(callee(functionDecl(hasName("f1")))), changeTo(cat("REPLACE_F1"))); RewriteRule ReplaceF1OrF2 = makeRule(callExpr(callee(functionDecl(hasAnyName("f1", "f2")))), changeTo(cat("REPLACE_F1_OR_F2"))); testRule(applyFirst({ReplaceF1, ReplaceF1OrF2}), Input, Expected); } // Change the order of the rules to get a different result. When `ReplaceF1OrF2` // comes first, it applies for both uses, so `ReplaceF1` never applies. TEST_F(TransformerTest, OrderedRuleRelatedSwapped) { std::string Input = R"cc( void f1(); void f2(); void call_f1() { f1(); } void call_f2() { f2(); } )cc"; std::string Expected = R"cc( void f1(); void f2(); void call_f1() { REPLACE_F1_OR_F2; } void call_f2() { REPLACE_F1_OR_F2; } )cc"; RewriteRule ReplaceF1 = makeRule(callExpr(callee(functionDecl(hasName("f1")))), changeTo(cat("REPLACE_F1"))); RewriteRule ReplaceF1OrF2 = makeRule(callExpr(callee(functionDecl(hasAnyName("f1", "f2")))), changeTo(cat("REPLACE_F1_OR_F2"))); testRule(applyFirst({ReplaceF1OrF2, ReplaceF1}), Input, Expected); } // Verify that a set of rules whose matchers have different base kinds works // properly, including that `applyFirst` produces multiple matchers. We test // two different kinds of rules: Expr and Decl. We place the Decl rule in the // middle to test that `buildMatchers` works even when the kinds aren't grouped // together. TEST_F(TransformerTest, OrderedRuleMultipleKinds) { std::string Input = R"cc( void f1(); void f2(); void call_f1() { f1(); } void call_f2() { f2(); } )cc"; std::string Expected = R"cc( void f1(); void DECL_RULE(); void call_f1() { REPLACE_F1; } void call_f2() { REPLACE_F1_OR_F2; } )cc"; RewriteRule ReplaceF1 = makeRule(callExpr(callee(functionDecl(hasName("f1")))), changeTo(cat("REPLACE_F1"))); RewriteRule ReplaceF1OrF2 = makeRule(callExpr(callee(functionDecl(hasAnyName("f1", "f2")))), changeTo(cat("REPLACE_F1_OR_F2"))); RewriteRule DeclRule = makeRule(functionDecl(hasName("f2")).bind("fun"), changeTo(name("fun"), cat("DECL_RULE"))); RewriteRule Rule = applyFirst({ReplaceF1, DeclRule, ReplaceF1OrF2}); EXPECT_EQ(transformer::detail::buildMatchers(Rule).size(), 2UL); testRule(Rule, Input, Expected); } // Verifies that a rule with a top-level matcher for an implicit node (like // `implicitCastExpr`) works correctly -- the implicit nodes are not skipped. TEST_F(TransformerTest, OrderedRuleImplicitMatched) { std::string Input = R"cc( void f1(); int f2(); void call_f1() { f1(); } float call_f2() { return f2(); } )cc"; std::string Expected = R"cc( void f1(); int f2(); void call_f1() { REPLACE_F1; } float call_f2() { return REPLACE_F2; } )cc"; RewriteRule ReplaceF1 = makeRule(callExpr(callee(functionDecl(hasName("f1")))), changeTo(cat("REPLACE_F1"))); RewriteRule ReplaceF2 = makeRule(implicitCastExpr(hasSourceExpression(callExpr())), changeTo(cat("REPLACE_F2"))); testRule(applyFirst({ReplaceF1, ReplaceF2}), Input, Expected); } // // Negative tests (where we expect no transformation to occur). // // Tests for a conflict in edits from a single match for a rule. TEST_F(TransformerTest, TextGeneratorFailure) { std::string Input = "int conflictOneRule() { return 3 + 7; }"; // Try to change the whole binary-operator expression AND one its operands: StringRef O = "O"; class AlwaysFail : public transformer::MatchComputation<std::string> { llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &, std::string *) const override { return llvm::createStringError(llvm::errc::invalid_argument, "ERROR"); } std::string toString() const override { return "AlwaysFail"; } }; Transformer T( makeRule(binaryOperator().bind(O), changeTo(node(std::string(O)), std::make_shared<AlwaysFail>())), consumer()); T.registerMatchers(&MatchFinder); EXPECT_FALSE(rewrite(Input)); EXPECT_THAT(Changes, IsEmpty()); EXPECT_EQ(ErrorCount, 1); } // Tests for a conflict in edits from a single match for a rule. TEST_F(TransformerTest, OverlappingEditsInRule) { std::string Input = "int conflictOneRule() { return 3 + 7; }"; // Try to change the whole binary-operator expression AND one its operands: StringRef O = "O", L = "L"; Transformer T(makeRule(binaryOperator(hasLHS(expr().bind(L))).bind(O), {changeTo(node(std::string(O)), cat("DELETE_OP")), changeTo(node(std::string(L)), cat("DELETE_LHS"))}), consumer()); T.registerMatchers(&MatchFinder); EXPECT_FALSE(rewrite(Input)); EXPECT_THAT(Changes, IsEmpty()); EXPECT_EQ(ErrorCount, 1); } // Tests for a conflict in edits across multiple matches (of the same rule). TEST_F(TransformerTest, OverlappingEditsMultipleMatches) { std::string Input = "int conflictOneRule() { return -7; }"; // Try to change the whole binary-operator expression AND one its operands: StringRef E = "E"; Transformer T(makeRule(expr().bind(E), changeTo(node(std::string(E)), cat("DELETE_EXPR"))), consumer()); T.registerMatchers(&MatchFinder); // The rewrite process fails because the changes conflict with each other... EXPECT_FALSE(rewrite(Input)); // ... but two changes were produced. EXPECT_EQ(Changes.size(), 2u); EXPECT_EQ(ErrorCount, 0); } TEST_F(TransformerTest, ErrorOccurredMatchSkipped) { // Syntax error in the function body: std::string Input = "void errorOccurred() { 3 }"; Transformer T(makeRule(functionDecl(hasName("errorOccurred")), changeTo(cat("DELETED;"))), consumer()); T.registerMatchers(&MatchFinder); // The rewrite process itself fails... EXPECT_FALSE(rewrite(Input)); // ... and no changes or errors are produced in the process. EXPECT_THAT(Changes, IsEmpty()); EXPECT_EQ(ErrorCount, 0); } // Transformation of macro source text when the change encompasses the entirety // of the expanded text. TEST_F(TransformerTest, SimpleMacro) { std::string Input = R"cc( #define ZERO 0 int f(string s) { return ZERO; } )cc"; std::string Expected = R"cc( #define ZERO 0 int f(string s) { return 999; } )cc"; StringRef zero = "zero"; RewriteRule R = makeRule(integerLiteral(equals(0)).bind(zero), changeTo(node(std::string(zero)), cat("999"))); testRule(R, Input, Expected); } // Transformation of macro source text when the change encompasses the entirety // of the expanded text, for the case of function-style macros. TEST_F(TransformerTest, FunctionMacro) { std::string Input = R"cc( #define MACRO(str) strlen((str).c_str()) int f(string s) { return MACRO(s); } )cc"; std::string Expected = R"cc( #define MACRO(str) strlen((str).c_str()) int f(string s) { return REPLACED; } )cc"; testRule(ruleStrlenSize(), Input, Expected); } // Tests that expressions in macro arguments can be rewritten. TEST_F(TransformerTest, MacroArg) { std::string Input = R"cc( #define PLUS(e) e + 1 int f(string s) { return PLUS(strlen(s.c_str())); } )cc"; std::string Expected = R"cc( #define PLUS(e) e + 1 int f(string s) { return PLUS(REPLACED); } )cc"; testRule(ruleStrlenSize(), Input, Expected); } // Tests that expressions in macro arguments can be rewritten, even when the // macro call occurs inside another macro's definition. TEST_F(TransformerTest, MacroArgInMacroDef) { std::string Input = R"cc( #define NESTED(e) e #define MACRO(str) NESTED(strlen((str).c_str())) int f(string s) { return MACRO(s); } )cc"; std::string Expected = R"cc( #define NESTED(e) e #define MACRO(str) NESTED(strlen((str).c_str())) int f(string s) { return REPLACED; } )cc"; testRule(ruleStrlenSize(), Input, Expected); } // Tests the corner case of the identity macro, specifically that it is // discarded in the rewrite rather than preserved (like PLUS is preserved in the // previous test). This behavior is of dubious value (and marked with a FIXME // in the code), but we test it to verify (and demonstrate) how this case is // handled. TEST_F(TransformerTest, IdentityMacro) { std::string Input = R"cc( #define ID(e) e int f(string s) { return ID(strlen(s.c_str())); } )cc"; std::string Expected = R"cc( #define ID(e) e int f(string s) { return REPLACED; } )cc"; testRule(ruleStrlenSize(), Input, Expected); } // Tests that two changes in a single macro expansion do not lead to conflicts // in applying the changes. TEST_F(TransformerTest, TwoChangesInOneMacroExpansion) { std::string Input = R"cc( #define PLUS(a,b) (a) + (b) int f() { return PLUS(3, 4); } )cc"; std::string Expected = R"cc( #define PLUS(a,b) (a) + (b) int f() { return PLUS(LIT, LIT); } )cc"; testRule(makeRule(integerLiteral(), changeTo(cat("LIT"))), Input, Expected); } // Tests case where the rule's match spans both source from the macro and its // arg, with the begin location (the "anchor") being the arg. TEST_F(TransformerTest, MatchSpansMacroTextButChangeDoesNot) { std::string Input = R"cc( #define PLUS_ONE(a) a + 1 int f() { return PLUS_ONE(3); } )cc"; std::string Expected = R"cc( #define PLUS_ONE(a) a + 1 int f() { return PLUS_ONE(LIT); } )cc"; StringRef E = "expr"; testRule(makeRule(binaryOperator(hasLHS(expr().bind(E))), changeTo(node(std::string(E)), cat("LIT"))), Input, Expected); } // Tests case where the rule's match spans both source from the macro and its // arg, with the begin location (the "anchor") being inside the macro. TEST_F(TransformerTest, MatchSpansMacroTextButChangeDoesNotAnchoredInMacro) { std::string Input = R"cc( #define PLUS_ONE(a) 1 + a int f() { return PLUS_ONE(3); } )cc"; std::string Expected = R"cc( #define PLUS_ONE(a) 1 + a int f() { return PLUS_ONE(LIT); } )cc"; StringRef E = "expr"; testRule(makeRule(binaryOperator(hasRHS(expr().bind(E))), changeTo(node(std::string(E)), cat("LIT"))), Input, Expected); } // No rewrite is applied when the changed text does not encompass the entirety // of the expanded text. That is, the edit would have to be applied to the // macro's definition to succeed and editing the expansion point would not // suffice. TEST_F(TransformerTest, NoPartialRewriteOMacroExpansion) { std::string Input = R"cc( #define ZERO_PLUS 0 + 3 int f(string s) { return ZERO_PLUS; })cc"; StringRef zero = "zero"; RewriteRule R = makeRule(integerLiteral(equals(0)).bind(zero), changeTo(node(std::string(zero)), cat("0"))); testRule(R, Input, Input); } // This test handles the corner case where a macro expands within another macro // to matching code, but that code is an argument to the nested macro call. A // simple check of isMacroArgExpansion() vs. isMacroBodyExpansion() will get // this wrong, and transform the code. TEST_F(TransformerTest, NoPartialRewriteOfMacroExpansionForMacroArgs) { std::string Input = R"cc( #define NESTED(e) e #define MACRO(str) 1 + NESTED(strlen((str).c_str())) int f(string s) { return MACRO(s); } )cc"; testRule(ruleStrlenSize(), Input, Input); } #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST // Verifies that `Type` and `QualType` are not allowed as top-level matchers in // rules. TEST(TransformerDeathTest, OrderedRuleTypes) { RewriteRule QualTypeRule = makeRule(qualType(), changeTo(cat("Q"))); EXPECT_DEATH(transformer::detail::buildMatchers(QualTypeRule), "Matcher must be.*node matcher"); RewriteRule TypeRule = makeRule(arrayType(), changeTo(cat("T"))); EXPECT_DEATH(transformer::detail::buildMatchers(TypeRule), "Matcher must be.*node matcher"); } #endif // Edits are able to span multiple files; in this case, a header and an // implementation file. TEST_F(TransformerTest, MultipleFiles) { std::string Header = R"cc(void RemoveThisFunction();)cc"; std::string Source = R"cc(#include "input.h" void RemoveThisFunction();)cc"; Transformer T( makeRule(functionDecl(hasName("RemoveThisFunction")), changeTo(cat(""))), consumer()); T.registerMatchers(&MatchFinder); auto Factory = newFrontendActionFactory(&MatchFinder); EXPECT_TRUE(runToolOnCodeWithArgs( Factory->create(), Source, std::vector<std::string>(), "input.cc", "clang-tool", std::make_shared<PCHContainerOperations>(), {{"input.h", Header}})); std::sort(Changes.begin(), Changes.end(), [](const AtomicChange &L, const AtomicChange &R) { return L.getFilePath() < R.getFilePath(); }); ASSERT_EQ(Changes[0].getFilePath(), "./input.h"); EXPECT_THAT(Changes[0].getInsertedHeaders(), IsEmpty()); EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty()); llvm::Expected<std::string> UpdatedCode = clang::tooling::applyAllReplacements(Header, Changes[0].getReplacements()); ASSERT_TRUE(static_cast<bool>(UpdatedCode)) << "Could not update code: " << llvm::toString(UpdatedCode.takeError()); EXPECT_EQ(format(*UpdatedCode), format(R"cc(;)cc")); ASSERT_EQ(Changes[1].getFilePath(), "input.cc"); EXPECT_THAT(Changes[1].getInsertedHeaders(), IsEmpty()); EXPECT_THAT(Changes[1].getRemovedHeaders(), IsEmpty()); UpdatedCode = clang::tooling::applyAllReplacements( Source, Changes[1].getReplacements()); ASSERT_TRUE(static_cast<bool>(UpdatedCode)) << "Could not update code: " << llvm::toString(UpdatedCode.takeError()); EXPECT_EQ(format(*UpdatedCode), format(R"cc(#include "input.h" ;)cc")); } TEST_F(TransformerTest, AddIncludeMultipleFiles) { std::string Header = R"cc(void RemoveThisFunction();)cc"; std::string Source = R"cc(#include "input.h" void Foo() {RemoveThisFunction();})cc"; Transformer T( makeRule(callExpr(callee( functionDecl(hasName("RemoveThisFunction")).bind("fun"))), addInclude(node("fun"), "header.h")), consumer()); T.registerMatchers(&MatchFinder); auto Factory = newFrontendActionFactory(&MatchFinder); EXPECT_TRUE(runToolOnCodeWithArgs( Factory->create(), Source, std::vector<std::string>(), "input.cc", "clang-tool", std::make_shared<PCHContainerOperations>(), {{"input.h", Header}})); ASSERT_EQ(Changes.size(), 1U); ASSERT_EQ(Changes[0].getFilePath(), "./input.h"); EXPECT_THAT(Changes[0].getInsertedHeaders(), ElementsAre("header.h")); EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty()); llvm::Expected<std::string> UpdatedCode = clang::tooling::applyAllReplacements(Header, Changes[0].getReplacements()); ASSERT_TRUE(static_cast<bool>(UpdatedCode)) << "Could not update code: " << llvm::toString(UpdatedCode.takeError()); EXPECT_EQ(format(*UpdatedCode), format(Header)); } } // namespace
#include "slam/slam.h" #include "mona/line_renderer.hpp" #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <cstring> using namespace gl; line_renderer::line_renderer(): strip(GL_LINE_STRIP), s("../../../res/shaders/lines.vert", "../../../res/shaders/lines.frag") { glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); } void line_renderer::gen_buffer() { glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo ); glBindBuffer(GL_ARRAY_BUFFER, vbo ); glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(glm::vec3), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr ); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); fixed_size = vertices.size(); } void line_renderer::draw(const glm::mat4& mvp, glm::vec4 color, float thickness) const { glLineWidth(thickness); s.use(); s.set_uniform("color", color / 255.f); s.set_uniform("mvp", mvp); glBindVertexArray(vao); glDrawArrays(strip, 0, vertices.size()); glBindVertexArray(0); glLineWidth(1.f); s.unuse(); } auto line_renderer::reset(const std::vector<glm::vec3>& vertices) -> void { // TODO: we don't even need to store this this->vertices = vertices; // TODO: allow resizing assert(vertices.size() == fixed_size); glBindBuffer(GL_ARRAY_BUFFER, vbo); auto* ptr = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); if (!ptr) { std::clog << "Error: cannot get VBO: " << vbo << "\n"; //glBindBuffer(GL_ARRAY_BUFFER, 0); std::exit(0); } std::memcpy(ptr, vertices.data(), vertices.size()*sizeof(glm::vec3)); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); } auto line_renderer::set_strip(bool strip) -> void { this->strip = strip? GL_LINE_STRIP: GL_LINES; }
#include <bits/stdc++.h> #define int long long int #define len length #define pb push_back #define all(a) a.begin(), a.end() #define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i] #define vi vector<int> #define pii pair <int, int> #define mii map <int, int> #define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) using namespace std; //Constants const int MOD = 1000000007; // 1e9 + 7 const int N = 1000005; // 1e6 +5 /* -------------------------------Solution Sarted--------------------------------------*/ int32_t main() { faster; #ifndef ONLINE_JUDGE freopen("ip.txt", "r", stdin); freopen("op.txt", "w", stdout); #endif int t; cin >> t; while(t--) { int n, cnt = 0; cin >> n; vi a(n), col(n, -1); scnarr(a, n); for(int i = 0; i < n; ++i){ if(a[i] != a[i +1]){ cnt++; } } if(a[n -1] == a[0]) cnt--; else cnt++; if(cnt <= 0){ cout << 1 << endl; for(int i = 0; i < n; ++i) cout << 1 << " "; cout << endl; }else if(cnt&1){ int st, end; cout << 3 << endl; if(a[n -1] == a[0]){ for(int i = 0; i < n -1; ++i){ col[i] = 3; if(a[i] != a[i +1]){ st = i +1; break; } } for(int i = n -1; i > 0; --i){ col[i] = 3; if(a[i] != a[i -1]){ end = i -1; break; } } } } } return 0; } //Author : Ankit Raj //InSearchForMeanings //Problem Link :
#pragma once #include <string> namespace csv { inline void leftTrim(std::string& string); inline void rightTrim(std::string& string); void trim(std::string& string); }
#include "Optim/SGD.h" namespace engine { void SGD::update(std::vector<Node*> update_nodes, float learning_rate) { for (auto node : update_nodes) { node->update([&](Node* pNode)->Node * { Eigen::MatrixXf delta = -1 * learning_rate * pNode->getGradient(pNode); pNode->setValue(pNode->getValue() + delta); return pNode; }); } } void SGD::minimize(Loss* loss) { } }
/* ============================================================================== NestedAllpass.cpp Created: 8 Dec 2017 9:39:16am Author: Pelle Juul Christensen ============================================================================== */ #include "Nested.h" #include "Processor.h" Nested::Nested(float delayTime, float gain, Processor *innerProcess, int sampleRate) : delay(delayTime, sampleRate) { this->gain = gain; this->innerProcess = innerProcess; } float Nested::process(float x) { float sum2 = -gain * x + innerProcess->process(delay.read()); float sum1 = gain * sum2 + x; delay.write(sum1); return sum2; }
/** * This header file implements the DoubleMeanFilter helper class, which *is based on MeanFilter helper class. * * Version: 1.1.5 * Created on: 27/03/2017 * Modified on: 27/03/2017 * Author: Adriano Henrique Rossette Leite (adrianohrl@gmail.com) * Maintainer: Expertinos UNIFEI (expertinos.unifei@gmail.com) */ #include "utilities/double_mean_filter.h" namespace utilities { /** * @brief DoubleMeanFilter::DoubleMeanFilter * @param number_of_samples */ DoubleMeanFilter::DoubleMeanFilter(unsigned int number_of_samples) : MeanFilter<double>::MeanFilter(number_of_samples) { } /** * @brief DoubleMeanFilter::~DoubleMeanFilter */ DoubleMeanFilter::~DoubleMeanFilter() {} /** * @brief DoubleMeanFilter::getMeanValue */ double DoubleMeanFilter::getMeanValue() const { double sum(0.0); std::list<double>::const_iterator it(Filter<double>::begin()); while (it != Filter<double>::end()) { sum += *it; it++; } return sum / Filter<double>::size(); } }
// RUN: %clang_cc1 -analyze -std=c++11 -analyzer-checker=alpha.clone.CloneChecker -verify %s // This tests if sub-sequences can match with normal sequences. void log2(int a); void log(); int max(int a, int b) { log2(a); log(); // expected-warning{{Duplicate code detected}} if (a > b) return a; return b; } int maxClone(int a, int b) { log(); // expected-note{{Similar code here}} if (a > b) return a; return b; } // Functions below are not clones and should not be reported. int foo(int a, int b) { // no-warning return a + b; }
//----------------------------------------------------------------------------- // File: typing.cpp // Summary: Measure the time it takes for a user to type // abcdefghijklmnopqrstuvxyz // Version: 0.0 // Owner: Christoffer Karlsson //----------------------------------------------------------------------------- // Log: 2018-04-14 File created by Christoffer // //----------------------------------------------------------------------------- // Preprocessor directives #include <cstring> // strlen #include <limits> // numeric_limits, streamsize #include <iostream> // cin, cout, endl #include "..\..\..\libs\include\Clock.h" // give_me_the_time #include "..\..\..\libs\include\MyTime.h" // MyTime #include "compare.h" // equal #include "typing.h" // OS specific adjustments #ifdef _WIN32 // Windows #define CLEARSCREEN system("cls") #elif __APPLE__ // Mac OS #define CLEARSCREEN system("clear") #elif __linux__ // Linux #define CLEARSCREEN system("clear") #else error "Unknown compiler" #endif // Usings using std::cin; using std::cout; using std::endl; using std::strlen; using std::numeric_limits; using std::streamsize; //----------------------------------------------------------------------------- // int run() // // Summary: Measure the time it takes for a user to type // abcdefghijklmnopqrstuvxyz // Returns: 0 when user stops execution. //----------------------------------------------------------------------------- int Typing::run() { // Setup auto compare = new Compare(); auto clock = new Clock(); const char EXPECTED[] = "abcdefghijklmnopqrstuvxyz"; _printIntroduction(); // Execute do { char userInput[1000]; auto start = clock->give_me_the_time(); _printTask(EXPECTED); _getUserInput(userInput); auto stop = clock->give_me_the_time(); CLEARSCREEN; if (compare->equal(EXPECTED, userInput)) { cout << "It took: " << start - stop << " (hh:mm:ss)." << endl << "Good work!" << endl; } else { cout << "The strings didn't match." << endl; } } while (_userYesOrNo("Try again?")); // Cleanup delete compare; delete clock; return 0; } //----------------------------------------------------------------------------- // void _printIntroduction() // // Summary: Prints an explanation of the purpose of the application. // Returns: - //----------------------------------------------------------------------------- void Typing::_printIntroduction() { CLEARSCREEN; cout << "This application will measure your typing speed." << endl << "When you hit enter the string will be shown and the measurement " << "will start." << endl; cin.get(); } //----------------------------------------------------------------------------- // void _printTask(const char * EXPECTED) // // Summary: Prints the task that the user should perform. // Returns: - //----------------------------------------------------------------------------- void Typing::_printTask(const char * EXPECTED) { CLEARSCREEN; cout << "Please type the following and then press enter:" << endl << EXPECTED << endl; } //----------------------------------------------------------------------------- // bool userYesOrNo(const char *QUESTION) // // Summary: Asks the user the supplied question. // Returns: True if the answer isn't n or N. //----------------------------------------------------------------------------- bool Typing::_userYesOrNo(const char *QUESTION) { char input[1000]; // Ask the user if program should re-run and read input cout << endl << QUESTION << " (Y/n): "; _getUserInput(input); cout << endl; // Check if answer is negative auto answer = toupper(input[0]) != 'N'; return answer; } //----------------------------------------------------------------------------- // void _getUserInput(char * userInput) // // Summary: Reads first MAX_READ_INPUT_LENGTH chars of user input into // userInput and then clear cin buffer. // Returns: - //----------------------------------------------------------------------------- void Typing::_getUserInput(char * userInput) { cin.getline(userInput, numeric_limits<streamsize>::max()); if (cin.fail()) { // Clear error cin.clear(); // Clear input (this has to be done after error clearing) cin.ignore(numeric_limits<streamsize>::max(), '\n'); } }
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true #include "KokkosKernels_config.h" #if defined (KOKKOSKERNELS_INST_KOKKOS_COMPLEX_DOUBLE_) \ && defined (KOKKOSKERNELS_INST_LAYOUTRIGHT) \ && defined (KOKKOSKERNELS_INST_EXECSPACE_THREADS) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) #include "KokkosBlas1_axpby_spec.hpp" namespace KokkosBlas { namespace Impl { KOKKOSBLAS1_AXPBY_ETI_SPEC_INST(Kokkos::complex<double>, Kokkos::LayoutRight, Kokkos::Threads, Kokkos::HostSpace) } // Impl } // KokkosBlas #endif
#include<bits/stdc++.h> using namespace std; void solve(){ //create pair pair<int,int>p; p.first=100; p.second=200; cout<<p.first<<" "<<p.second<<"\n"; //return 0; } int main(){ int t; cin>>t; while(t--){ solve(); cout<<"\n"; } return 0; }
/*========================================================================= Program: Visualization Toolkit Module: vtkPReflectionFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPReflectionFilter.h" #include "vtkObjectFactory.h" #include "vtkBoundingBox.h" #include "vtkMultiProcessController.h" vtkStandardNewMacro(vtkPReflectionFilter); vtkCxxSetObjectMacro(vtkPReflectionFilter, Controller, vtkMultiProcessController); //---------------------------------------------------------------------------- vtkPReflectionFilter::vtkPReflectionFilter() { this->Controller = 0; this->SetController(vtkMultiProcessController::GetGlobalController()); } //---------------------------------------------------------------------------- vtkPReflectionFilter::~vtkPReflectionFilter() { this->SetController(0); } //---------------------------------------------------------------------------- int vtkPReflectionFilter::ComputeBounds(vtkDataObject* input, double bounds[6]) { vtkBoundingBox bbox; if (this->Superclass::ComputeBounds(input, bounds)) { bbox.SetBounds(bounds); } if (this->Controller) { this->Controller->GetCommunicator()->ComputeGlobalBounds( this->Controller->GetLocalProcessId(), this->Controller->GetNumberOfProcesses(), &bbox); bbox.GetBounds(bounds); } return 1; } //---------------------------------------------------------------------------- void vtkPReflectionFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Controller: " << this->Controller << endl; }
#include "fly/path/path_monitor.hpp" #include "fly/fly.hpp" #include "fly/logger/logger.hpp" #include "fly/path/path_config.hpp" #include "fly/task/task_runner.hpp" #include <system_error> #include FLY_OS_IMPL_PATH(path, path_monitor) namespace fly::path { //================================================================================================== std::shared_ptr<PathMonitor> PathMonitor::create( std::shared_ptr<fly::task::SequencedTaskRunner> task_runner, std::shared_ptr<PathConfig> config) { auto path_monitor = std::make_shared<PathMonitorImpl>(std::move(task_runner), std::move(config)); return path_monitor->start() ? path_monitor : nullptr; } //================================================================================================== PathMonitor::PathMonitor( std::shared_ptr<fly::task::SequencedTaskRunner> task_runner, std::shared_ptr<PathConfig> config) noexcept : m_task_runner(std::move(task_runner)), m_config(std::move(config)) { } //================================================================================================== PathMonitor::~PathMonitor() { remove_all_paths(); } //================================================================================================== bool PathMonitor::start() { return poll_paths_later(); } //================================================================================================== bool PathMonitor::add_path(const std::filesystem::path &path, PathEventCallback callback) { std::error_code error; if (callback == nullptr) { LOGW("Ignoring null callback for {}", path); } else if (!std::filesystem::is_directory(path, error)) { LOGW("Ignoring non-directory {}: {}", path, error.message()); } else { std::lock_guard<std::mutex> lock(m_mutex); if (PathInfo *info = get_or_create_path_info(path); info != nullptr) { LOGD("Monitoring all files in {}", path); info->m_path_handler = callback; return true; } } return false; } //================================================================================================== bool PathMonitor::remove_path(const std::filesystem::path &path) { std::lock_guard<std::mutex> lock(m_mutex); if (auto it = m_path_info.find(path); it != m_path_info.end()) { LOGI("Removed monitor for {}", path); m_path_info.erase(it); return true; } LOGW("Wasn't monitoring {}", path); return false; } //================================================================================================== void PathMonitor::remove_all_paths() { std::lock_guard<std::mutex> lock(m_mutex); m_path_info.clear(); } //================================================================================================== bool PathMonitor::add_file(const std::filesystem::path &file, PathEventCallback callback) { std::error_code error; if (callback == nullptr) { LOGW("Ignoring null callback for {}", file); } else if (std::filesystem::is_directory(file, error)) { LOGW("Ignoring directory {}: {}", file, error.message()); } else if (!std::filesystem::is_directory(file.parent_path(), error)) { LOGW("Ignoring file under non-directory {}: {}", file, error.message()); } else { std::lock_guard<std::mutex> lock(m_mutex); if (PathInfo *info = get_or_create_path_info(file.parent_path()); info != nullptr) { LOGD("Monitoring file {}", file); info->m_file_handlers[file.filename()] = callback; return true; } } return false; } //================================================================================================== bool PathMonitor::remove_file(const std::filesystem::path &file) { bool prune_path = false; { std::lock_guard<std::mutex> lock(m_mutex); auto path_it = m_path_info.find(file.parent_path()); if (path_it == m_path_info.end()) { LOGW("Wasn't monitoring {}", file); return false; } PathInfo *info = path_it->second.get(); auto file_it = info->m_file_handlers.find(file.filename()); if (file_it == info->m_file_handlers.end()) { LOGW("Wasn't monitoring {}", file); return false; } LOGD("Stopped monitoring {}", file); info->m_file_handlers.erase(file_it); prune_path = info->m_file_handlers.empty() && !(info->m_path_handler); } return prune_path ? remove_path(file.parent_path()) : true; } //================================================================================================== PathMonitor::PathInfo *PathMonitor::get_or_create_path_info(const std::filesystem::path &path) { PathInfo *info = nullptr; if (auto it = m_path_info.find(path); it != m_path_info.end()) { info = it->second.get(); } else { std::unique_ptr<PathInfo> created_info = create_path_info(path); if (created_info && created_info->is_valid()) { info = created_info.get(); m_path_info[path] = std::move(created_info); } } return info; } //================================================================================================== bool PathMonitor::poll_paths_later() { if (!is_valid()) { return false; } auto task = [](std::shared_ptr<PathMonitor> self) { self->poll(self->m_config->poll_interval()); self->poll_paths_later(); }; std::weak_ptr<PathMonitor> weak_self = shared_from_this(); return m_task_runner->post_task(FROM_HERE, std::move(weak_self), std::move(task)); } } // namespace fly::path
// 日本語 UTF-8 #include "targetver.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
#include <bits/stdc++.h> using namespace std; int main () { int n1, n2, media; cin >> n1 >> media; n2 = media * 2 - n1; cout << n2 << endl; return 0; }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <vector> // vector<bool> // static void swap(reference x, reference y) noexcept; #include <vector> #include <cassert> int main() { bool a[] = {false, true, false, true}; bool* an = a + sizeof(a)/sizeof(a[0]); std::vector<bool> v(a, an); std::vector<bool>::reference r1 = v[0]; std::vector<bool>::reference r2 = v[3]; #if __has_feature(cxx_noexcept) static_assert((noexcept(v.swap(r1,r2))), ""); #endif assert(!r1); assert( r2); v.swap(r1, r2); assert( r1); assert(!r2); }
// // Created by fs2001 on 2021/12/29. // #include "normal_texture.h" NormalTexture::NormalTexture(const std::string &f, double zoom) : zoom(zoom) { cv::Mat img = cv::imread(f, 1); this->width = img.cols; this->height = img.rows; this->texture = new Vec[img.cols * img.rows]; for (int y = 0; y < img.rows; y++) for (int x = 0; x < img.cols; x++) { int i = (img.cols - x - 1) * img.rows + y; this->texture[i].x = double(img.at<cv::Vec3b>(y, x)[2]); this->texture[i].y = double(img.at<cv::Vec3b>(y, x)[1]); this->texture[i].z = double(img.at<cv::Vec3b>(y, x)[0]); this->texture[i] = this->texture[i] / 255.0; } } Vec NormalTexture::getNormalSphere(const Vec &point) const { double u = 0.5 + 0.5 * atan2(point.z, point.x) / M_PI; double v = 0.5 - asin(point.y) / M_PI; Vec directionX = Vec(point.y, -point.x, 0).norm(); Vec directionY = directionX.cross(point).norm(); directionY = directionY.z >= 0 ? directionY : directionY * (-1); u = fmod(u * zoom, 1); v = fmod(v * zoom, 1); Vec originalNormal = this->texture[int((this->width - int(u * this->width) - 1) * this->height + int(v * this->height))] * 2 - Vec(1, 1, 1); return (directionX * originalNormal.x + directionY * originalNormal.y + Vec(point.x, point.y, point.z).norm() * -1 * originalNormal.z).norm() * -1; }
/** * Copyright Verimag laboratory. * * contributors: * Jacques Combaz (jacques.combaz@univ-grenoble-alpes.fr) * * This software is a computer program whose purpose is to generate * executable code from BIP models. * * This software is governed by the CeCILL-B license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-B * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ #ifndef _BIP_Engine_UnexpectedEventError_HPP_ #define _BIP_Engine_UnexpectedEventError_HPP_ // inherited classes #include <UnexpectedEventErrorItf.hpp> #include "BipError.hpp" class UnexpectedEventError : public virtual BipErrorItf, public BipError, public UnexpectedEventErrorItf { public: // constructors UnexpectedEventError(Atom &atom, AtomExternalPort &port); // destructor virtual ~UnexpectedEventError(); }; #endif // _BIP_Engine_UnexpectedEventError_HPP_
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin unary_plus.cpp$$ $spell Cpp cstddef $$ $section AD Unary Plus Operator: Example and Test$$ $srcthisfile%0%// BEGIN C++%// END C++%1%$$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> bool UnaryPlus(void) { bool ok = true; using CppAD::AD; // domain space vector size_t n = 1; CPPAD_TESTVECTOR(AD<double>) x(n); x[0] = 3.; // declare independent variables and start tape recording CppAD::Independent(x); // range space vector size_t m = 1; CPPAD_TESTVECTOR(AD<double>) y(m); y[0] = + x[0]; // create f: x -> y and stop tape recording CppAD::ADFun<double> f(x, y); // check values ok &= ( y[0] == 3. ); // forward computation of partials w.r.t. x[0] CPPAD_TESTVECTOR(double) dx(n); CPPAD_TESTVECTOR(double) dy(m); size_t p = 1; dx[0] = 1.; dy = f.Forward(p, dx); ok &= ( dy[0] == 1. ); // dy[0] / dx[0] // reverse computation of dertivative of y[0] CPPAD_TESTVECTOR(double) w(m); CPPAD_TESTVECTOR(double) dw(n); w[0] = 1.; dw = f.Reverse(p, w); ok &= ( dw[0] == 1. ); // dy[0] / dx[0] // use a VecAD<Base>::reference object with unary plus CppAD::VecAD<double> v(1); AD<double> zero(0); v[zero] = x[0]; AD<double> result = + v[zero]; ok &= (result == y[0]); return ok; } // END C++
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmSegmentedPaletteColorLookupTable.h" #include "gdcmDataSet.h" // http://blog.goo.ne.jp/satomi_takeo/e/3643e5249b2a9650f9e10ef1c830e8b8 // #include <map> #include <algorithm> #include <iterator> #include <vector> #include <deque> namespace gdcm { // abstract class for segment. template <typename EntryType> class Segment { public: virtual ~Segment() = default; typedef std::map<const EntryType*, const Segment*> SegmentMap; virtual bool Expand(const SegmentMap& instances, std::vector<EntryType>& expanded) const = 0; const EntryType* First() const { return _first; } const EntryType* Last() const { return _last; } struct ToMap { std::pair< typename SegmentMap::key_type, typename SegmentMap::mapped_type > operator()(const Segment* segment) const { return std::make_pair(segment->First(), segment); } }; protected: Segment(const EntryType* first, const EntryType* last) { _first = first; _last = last; } const EntryType* _first; const EntryType* _last; }; // discrete segment (opcode = 0) template <typename EntryType> class DiscreteSegment : public Segment<EntryType> { public: typedef typename Segment<EntryType>::SegmentMap SegmentMap; DiscreteSegment(const EntryType* first) : Segment<EntryType>(first, first+2+*(first+1)) {} bool Expand(const SegmentMap&, std::vector<EntryType>& expanded) const override { std::copy(this->_first + 2, this->_last, std::back_inserter(expanded)); return true; } }; // linear segment (opcode = 1) template <typename EntryType> class LinearSegment : public Segment<EntryType> { public: typedef typename Segment<EntryType>::SegmentMap SegmentMap; LinearSegment(const EntryType* first) : Segment<EntryType>(first, first+3) {} bool Expand(const SegmentMap&, std::vector<EntryType>& expanded) const override { if ( expanded.empty() ) { // linear segment can't be the first segment. return false; } EntryType length = *(this->_first + 1); EntryType y0 = expanded.back(); EntryType y1 = *(this->_first + 2); double y01 = y1 - y0; for ( EntryType i = 0; i <length; ++i ) { double value_float = static_cast<double>(y0) + (static_cast<double>(i)/static_cast<double>(length)) * y01; EntryType value_int = static_cast<EntryType>(value_float + 0.5); expanded.push_back(value_int); } return true; } }; // indirect segment (opcode = 2) template <typename EntryType> class IndirectSegment : public Segment<EntryType> { public: typedef typename Segment<EntryType>::SegmentMap SegmentMap; IndirectSegment(const EntryType* first) : Segment<EntryType>(first, first+2+4/sizeof(EntryType)) {} bool Expand(const SegmentMap& instances, std::vector<EntryType>& expanded) const override { if ( instances.empty() ) { // some other segments are required as references. return false; } const EntryType* first_segment = instances.begin()->first; const unsigned short* pOffset = reinterpret_cast<const unsigned short*>(this->_first + 2); unsigned long offsetBytes = (*pOffset) | (static_cast<unsigned long>(*(pOffset + 1)) << 16); const EntryType* copied_part_head = first_segment + offsetBytes / sizeof(EntryType); typename SegmentMap::const_iterator ppHeadSeg = instances.find(copied_part_head); if ( ppHeadSeg == instances.end() ) { // referred segment not found return false; } EntryType nNumCopies = *(this->_first + 1); typename SegmentMap::const_iterator ppSeg = ppHeadSeg; while ( std::distance(ppHeadSeg, ppSeg) <nNumCopies ) { assert( ppSeg != instances.end() ); ppSeg->second->Expand(instances, expanded); ++ppSeg; } return true; } }; template <typename EntryType> void ExpandPalette(const EntryType* raw_values, uint32_t length, std::vector<EntryType>& palette) { typedef std::deque<Segment<EntryType>*> SegmentList; SegmentList segments; const EntryType* raw_seg = raw_values; while ( (std::distance(raw_values, raw_seg) * sizeof(EntryType)) <length ) { Segment<EntryType>* segment = nullptr; if ( *raw_seg == 0 ) { segment = new DiscreteSegment<EntryType>(raw_seg); } else if ( *raw_seg == 1 ) { segment = new LinearSegment<EntryType>(raw_seg); } else if ( *raw_seg == 2 ) { segment = new IndirectSegment<EntryType>(raw_seg); } if ( segment ) { segments.push_back(segment); raw_seg = segment->Last(); } else { // invalid opcode break; } } typename Segment<EntryType>::SegmentMap instances; std::transform(segments.begin(), segments.end(), std::inserter(instances, instances.end()), typename Segment<EntryType>::ToMap()); typename SegmentList::iterator ppSeg = segments.begin(); typename SegmentList::iterator endOfSegments = segments.end(); for ( ; ppSeg != endOfSegments; ++ppSeg ) { (*ppSeg)->Expand(instances, palette); } ppSeg = segments.begin(); for ( ; ppSeg != endOfSegments; ++ppSeg ) { delete *ppSeg; } } SegmentedPaletteColorLookupTable::SegmentedPaletteColorLookupTable() = default; SegmentedPaletteColorLookupTable::~SegmentedPaletteColorLookupTable() = default; void SegmentedPaletteColorLookupTable::SetLUT(LookupTableType type, const unsigned char *array, unsigned int length) { if( BitSample == 8 ) { assert(0); // TODO } else if( BitSample == 16 ) { const uint16_t *array16 = (const uint16_t*)(const void*)array; const uint16_t *segment_values = array16; std::vector<uint16_t> palette; unsigned int num_entries = GetLUTLength(type); palette.reserve(num_entries); assert( length % 2 == 0 ); // FIXME: inplace byteswapping (BAD!) SwapperNoOp::SwapArray(const_cast<uint16_t*>(segment_values),length/2); ExpandPalette(segment_values, length, palette); LookupTable::SetLUT(type, (unsigned char*)&palette[0], (unsigned int)(palette.size() * 2)); } } } // end namespace gdcm
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/logging.h" #include <string.h> #if RTC_LOG_ENABLED() #if defined(WEBRTC_WIN) #include <windows.h> #if _MSC_VER < 1900 #define snprintf _snprintf #endif #undef ERROR // wingdi.h #endif #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) #include <CoreServices/CoreServices.h> #elif defined(WEBRTC_ANDROID) #include <android/log.h> // Android has a 1024 limit on log inputs. We use 60 chars as an // approx for the header/tag portion. // See android/system/core/liblog/logd_write.c static const int kMaxLogLineSize = 1024 - 60; #endif // WEBRTC_MAC && !defined(WEBRTC_IOS) || WEBRTC_ANDROID #include <stdio.h> #include <time.h> #include <algorithm> #include <cstdarg> #include <vector> #include "absl/base/attributes.h" #include "rtc_base/checks.h" #include "rtc_base/critical_section.h" #include "rtc_base/platform_thread_types.h" #include "rtc_base/string_encode.h" #include "rtc_base/string_utils.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/thread_annotations.h" #include "rtc_base/time_utils.h" namespace rtc { namespace { // By default, release builds don't log, debug builds at info level #if !defined(NDEBUG) static LoggingSeverity g_min_sev = LS_INFO; static LoggingSeverity g_dbg_sev = LS_INFO; #else static LoggingSeverity g_min_sev = LS_NONE; static LoggingSeverity g_dbg_sev = LS_NONE; #endif // Return the filename portion of the string (that following the last slash). const char* FilenameFromPath(const char* file) { const char* end1 = ::strrchr(file, '/'); const char* end2 = ::strrchr(file, '\\'); if (!end1 && !end2) return file; else return (end1 > end2) ? end1 + 1 : end2 + 1; } // Global lock for log subsystem, only needed to serialize access to streams_. CriticalSection g_log_crit; } // namespace ///////////////////////////////////////////////////////////////////////////// // LogMessage ///////////////////////////////////////////////////////////////////////////// bool LogMessage::log_to_stderr_ = true; // The list of logging streams currently configured. // Note: we explicitly do not clean this up, because of the uncertain ordering // of destructors at program exit. Let the person who sets the stream trigger // cleanup by setting to null, or let it leak (safe at program exit). ABSL_CONST_INIT LogSink* LogMessage::streams_ RTC_GUARDED_BY(g_log_crit) = nullptr; // Boolean options default to false (0) bool LogMessage::thread_, LogMessage::timestamp_; LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev) : LogMessage(file, line, sev, ERRCTX_NONE, 0) {} LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev, LogErrorContext err_ctx, int err) : severity_(sev) { if (timestamp_) { // Use SystemTimeMillis so that even if tests use fake clocks, the timestamp // in log messages represents the real system time. int64_t time = TimeDiff(SystemTimeMillis(), LogStartTime()); // Also ensure WallClockStartTime is initialized, so that it matches // LogStartTime. WallClockStartTime(); print_stream_ << "[" << rtc::LeftPad('0', 3, rtc::ToString(time / 1000)) << ":" << rtc::LeftPad('0', 3, rtc::ToString(time % 1000)) << "] "; } if (thread_) { PlatformThreadId id = CurrentThreadId(); print_stream_ << "[" << id << "] "; } if (file != nullptr) { #if defined(WEBRTC_ANDROID) tag_ = FilenameFromPath(file); print_stream_ << "(line " << line << "): "; #else print_stream_ << "(" << FilenameFromPath(file) << ":" << line << "): "; #endif } if (err_ctx != ERRCTX_NONE) { char tmp_buf[1024]; SimpleStringBuilder tmp(tmp_buf); tmp.AppendFormat("[0x%08X]", err); switch (err_ctx) { case ERRCTX_ERRNO: tmp << " " << strerror(err); break; #ifdef WEBRTC_WIN case ERRCTX_HRESULT: { char msgbuf[256]; DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; if (DWORD len = FormatMessageA( flags, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), msgbuf, sizeof(msgbuf) / sizeof(msgbuf[0]), nullptr)) { while ((len > 0) && isspace(static_cast<unsigned char>(msgbuf[len - 1]))) { msgbuf[--len] = 0; } tmp << " " << msgbuf; } break; } #endif // WEBRTC_WIN default: break; } extra_ = tmp.str(); } } #if defined(WEBRTC_ANDROID) LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev, const char* tag) : LogMessage(file, line, sev, ERRCTX_NONE, 0 /* err */) { tag_ = tag; print_stream_ << tag << ": "; } #endif // DEPRECATED. Currently only used by downstream projects that use // implementation details of logging.h. Work is ongoing to remove those // dependencies. LogMessage::LogMessage(const char* file, int line, LoggingSeverity sev, const std::string& tag) : LogMessage(file, line, sev) { print_stream_ << tag << ": "; } LogMessage::~LogMessage() { FinishPrintStream(); const std::string str = print_stream_.Release(); if (severity_ >= g_dbg_sev) { #if defined(WEBRTC_ANDROID) OutputToDebug(str, severity_, tag_); #else OutputToDebug(str, severity_); #endif } CritScope cs(&g_log_crit); for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) { if (severity_ >= entry->min_severity_) { #if defined(WEBRTC_ANDROID) entry->OnLogMessage(str, severity_, tag_); #else entry->OnLogMessage(str, severity_); #endif } } } void LogMessage::AddTag(const char* tag) { #ifdef WEBRTC_ANDROID tag_ = tag; #endif } rtc::StringBuilder& LogMessage::stream() { return print_stream_; } int LogMessage::GetMinLogSeverity() { return g_min_sev; } LoggingSeverity LogMessage::GetLogToDebug() { return g_dbg_sev; } int64_t LogMessage::LogStartTime() { static const int64_t g_start = SystemTimeMillis(); return g_start; } uint32_t LogMessage::WallClockStartTime() { static const uint32_t g_start_wallclock = time(nullptr); return g_start_wallclock; } void LogMessage::LogThreads(bool on) { thread_ = on; } void LogMessage::LogTimestamps(bool on) { timestamp_ = on; } void LogMessage::LogToDebug(LoggingSeverity min_sev) { g_dbg_sev = min_sev; CritScope cs(&g_log_crit); UpdateMinLogSeverity(); } void LogMessage::SetLogToStderr(bool log_to_stderr) { log_to_stderr_ = log_to_stderr; } int LogMessage::GetLogToStream(LogSink* stream) { CritScope cs(&g_log_crit); LoggingSeverity sev = LS_NONE; for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) { if (stream == nullptr || stream == entry) { sev = std::min(sev, entry->min_severity_); } } return sev; } void LogMessage::AddLogToStream(LogSink* stream, LoggingSeverity min_sev) { CritScope cs(&g_log_crit); stream->min_severity_ = min_sev; stream->next_ = streams_; streams_ = stream; UpdateMinLogSeverity(); } void LogMessage::RemoveLogToStream(LogSink* stream) { CritScope cs(&g_log_crit); for (LogSink** entry = &streams_; *entry != nullptr; entry = &(*entry)->next_) { if (*entry == stream) { *entry = (*entry)->next_; break; } } UpdateMinLogSeverity(); } void LogMessage::ConfigureLogging(const char* params) { LoggingSeverity current_level = LS_VERBOSE; LoggingSeverity debug_level = GetLogToDebug(); std::vector<std::string> tokens; tokenize(params, ' ', &tokens); for (const std::string& token : tokens) { if (token.empty()) continue; // Logging features if (token == "tstamp") { LogTimestamps(); } else if (token == "thread") { LogThreads(); // Logging levels } else if (token == "verbose") { current_level = LS_VERBOSE; } else if (token == "info") { current_level = LS_INFO; } else if (token == "warning") { current_level = LS_WARNING; } else if (token == "error") { current_level = LS_ERROR; } else if (token == "none") { current_level = LS_NONE; // Logging targets } else if (token == "debug") { debug_level = current_level; } } #if defined(WEBRTC_WIN) && !defined(WINUWP) if ((LS_NONE != debug_level) && !::IsDebuggerPresent()) { // First, attempt to attach to our parent's console... so if you invoke // from the command line, we'll see the output there. Otherwise, create // our own console window. // Note: These methods fail if a console already exists, which is fine. if (!AttachConsole(ATTACH_PARENT_PROCESS)) ::AllocConsole(); } #endif // defined(WEBRTC_WIN) && !defined(WINUWP) LogToDebug(debug_level); } void LogMessage::UpdateMinLogSeverity() RTC_EXCLUSIVE_LOCKS_REQUIRED(g_log_crit) { LoggingSeverity min_sev = g_dbg_sev; for (LogSink* entry = streams_; entry != nullptr; entry = entry->next_) { min_sev = std::min(min_sev, entry->min_severity_); } g_min_sev = min_sev; } #if defined(WEBRTC_ANDROID) void LogMessage::OutputToDebug(const std::string& str, LoggingSeverity severity, const char* tag) { #else void LogMessage::OutputToDebug(const std::string& str, LoggingSeverity severity) { #endif bool log_to_stderr = log_to_stderr_; #if defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG) // On the Mac, all stderr output goes to the Console log and causes clutter. // So in opt builds, don't log to stderr unless the user specifically sets // a preference to do so. CFStringRef key = CFStringCreateWithCString( kCFAllocatorDefault, "logToStdErr", kCFStringEncodingUTF8); CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle()); if (key != nullptr && domain != nullptr) { Boolean exists_and_is_valid; Boolean should_log = CFPreferencesGetAppBooleanValue(key, domain, &exists_and_is_valid); // If the key doesn't exist or is invalid or is false, we will not log to // stderr. log_to_stderr = exists_and_is_valid && should_log; } if (key != nullptr) { CFRelease(key); } #endif // defined(WEBRTC_MAC) && !defined(WEBRTC_IOS) && defined(NDEBUG) #if defined(WEBRTC_WIN) // Always log to the debugger. // Perhaps stderr should be controlled by a preference, as on Mac? OutputDebugStringA(str.c_str()); if (log_to_stderr) { // This handles dynamically allocated consoles, too. if (HANDLE error_handle = ::GetStdHandle(STD_ERROR_HANDLE)) { log_to_stderr = false; DWORD written = 0; ::WriteFile(error_handle, str.data(), static_cast<DWORD>(str.size()), &written, 0); } } #endif // WEBRTC_WIN #if defined(WEBRTC_ANDROID) // Android's logging facility uses severity to log messages but we // need to map libjingle's severity levels to Android ones first. // Also write to stderr which maybe available to executable started // from the shell. int prio; switch (severity) { case LS_VERBOSE: prio = ANDROID_LOG_VERBOSE; break; case LS_INFO: prio = ANDROID_LOG_INFO; break; case LS_WARNING: prio = ANDROID_LOG_WARN; break; case LS_ERROR: prio = ANDROID_LOG_ERROR; break; default: prio = ANDROID_LOG_UNKNOWN; } int size = str.size(); int line = 0; int idx = 0; const int max_lines = size / kMaxLogLineSize + 1; if (max_lines == 1) { __android_log_print(prio, tag, "%.*s", size, str.c_str()); } else { while (size > 0) { const int len = std::min(size, kMaxLogLineSize); // Use the size of the string in the format (str may have \0 in the // middle). __android_log_print(prio, tag, "[%d/%d] %.*s", line + 1, max_lines, len, str.c_str() + idx); idx += len; size -= len; ++line; } } #endif // WEBRTC_ANDROID if (log_to_stderr) { fprintf(stderr, "%s", str.c_str()); fflush(stderr); } } // static bool LogMessage::IsNoop(LoggingSeverity severity) { if (severity >= g_dbg_sev || severity >= g_min_sev) return false; // TODO(tommi): We're grabbing this lock for every LogMessage instance that // is going to be logged. This introduces unnecessary synchronization for // a feature that's mostly used for testing. CritScope cs(&g_log_crit); return streams_ == nullptr; } void LogMessage::FinishPrintStream() { if (!extra_.empty()) print_stream_ << " : " << extra_; print_stream_ << "\n"; } namespace webrtc_logging_impl { void Log(const LogArgType* fmt, ...) { va_list args; va_start(args, fmt); LogMetadataErr meta; const char* tag = nullptr; switch (*fmt) { case LogArgType::kLogMetadata: { meta = {va_arg(args, LogMetadata), ERRCTX_NONE, 0}; break; } case LogArgType::kLogMetadataErr: { meta = va_arg(args, LogMetadataErr); break; } #ifdef WEBRTC_ANDROID case LogArgType::kLogMetadataTag: { const LogMetadataTag tag_meta = va_arg(args, LogMetadataTag); meta = {{nullptr, 0, tag_meta.severity}, ERRCTX_NONE, 0}; tag = tag_meta.tag; break; } #endif default: { RTC_NOTREACHED(); va_end(args); return; } } if (LogMessage::IsNoop(meta.meta.Severity())) { va_end(args); return; } LogMessage log_message(meta.meta.File(), meta.meta.Line(), meta.meta.Severity(), meta.err_ctx, meta.err); if (tag) { log_message.AddTag(tag); } for (++fmt; *fmt != LogArgType::kEnd; ++fmt) { switch (*fmt) { case LogArgType::kInt: log_message.stream() << va_arg(args, int); break; case LogArgType::kLong: log_message.stream() << va_arg(args, long); break; case LogArgType::kLongLong: log_message.stream() << va_arg(args, long long); break; case LogArgType::kUInt: log_message.stream() << va_arg(args, unsigned); break; case LogArgType::kULong: log_message.stream() << va_arg(args, unsigned long); break; case LogArgType::kULongLong: log_message.stream() << va_arg(args, unsigned long long); break; case LogArgType::kDouble: log_message.stream() << va_arg(args, double); break; case LogArgType::kLongDouble: log_message.stream() << va_arg(args, long double); break; case LogArgType::kCharP: { const char* s = va_arg(args, const char*); log_message.stream() << (s ? s : "(null)"); break; } case LogArgType::kStdString: log_message.stream() << *va_arg(args, const std::string*); break; case LogArgType::kStringView: log_message.stream() << *va_arg(args, const absl::string_view*); break; case LogArgType::kVoidP: log_message.stream() << rtc::ToHex( reinterpret_cast<uintptr_t>(va_arg(args, const void*))); break; default: RTC_NOTREACHED(); va_end(args); return; } } va_end(args); } } // namespace webrtc_logging_impl } // namespace rtc #endif namespace rtc { // Inefficient default implementation, override is recommended. void LogSink::OnLogMessage(const std::string& msg, LoggingSeverity severity, const char* tag) { OnLogMessage(tag + (": " + msg), severity); } void LogSink::OnLogMessage(const std::string& msg, LoggingSeverity /* severity */) { OnLogMessage(msg); } } // namespace rtc
#include<iostream> #include<bits/stdc++.h> using namespace std; #define ll long long #define mp make_pair #define pb push_back int dp[1001]; // n =w int minPrice(int price[], int i,int n, int w){ if(w==0) { return 0; } if(i>=n){ return INT_MAX; } if(dp[w]!=-1) return dp[w]; int minP = INT_MAX; if(price[i]!=-1){ if(minPrice(price, i, n, w-i)!=INT_MAX) minP = min(minP,price[i] + minPrice(price, i+1, n, w-i)); } minP = min(minP, minPrice(price, i+1, n, w-i)); return dp[w]=minP; } int main() { int n,w; cin>>n>>w; int price[n+1]; price[0]=-1; for(int i=1; i<=w; i++) cin>>price[i]; memset(dp,-1,sizeof(dp)); cout<<minPrice(price,0,w,w); return 0; }
// // ControlButtons.cpp - control buttons implementation // // cui framework, part of the liblec library // Copyright (c) 2016 Alec Musasa (alecmus at live dot com) // // Released under the MIT license. For full details see the // file LICENSE.txt // #include "../cui_rawImpl.h" LRESULT CALLBACK cui_rawImpl::ControlBtnProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LONG_PTR ptr = GetWindowLongPtr(hWnd, GWLP_USERDATA); ControlBtn* pThis = reinterpret_cast<ControlBtn*>(ptr); switch (msg) { case WM_ENABLE: { bool bEnabled = wParam == TRUE; if (bEnabled) { pThis->state = enumBtn::normal; InvalidateRect(hWnd, NULL, FALSE); } else { InvalidateRect(hWnd, NULL, FALSE); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC dc = BeginPaint(hWnd, &ps); RECT rc; GetClientRect(hWnd, &rc); int cx = rc.right - rc.left; int cy = rc.bottom - rc.top; // use double buffering to avoid flicker HDC hdc = CreateCompatibleDC(dc); if (!pThis->hbm_buffer) pThis->hbm_buffer = CreateCompatibleBitmap(dc, cx, cy); HBITMAP hbmOld = SelectBitmap(hdc, pThis->hbm_buffer); int iSize = rc.right - rc.left; Gdiplus::Graphics graphics(hdc); Gdiplus::Color color; color.SetFromCOLORREF(pThis->d->m_clrBackground); graphics.Clear(color); rc.left += iSize / 4; rc.right -= iSize / 4; rc.top += iSize / 4; rc.bottom -= iSize / 4; COLORREF m_clr = pThis->clrBtn; if (pThis->bHot) m_clr = pThis->clrBtnHot; else m_clr = pThis->clrBtn; if (!IsWindowEnabled(hWnd)) m_clr = pThis->d->m_clrDisabled; if (pThis->iUniqueID == pThis->d->m_iIDClose) { Gdiplus::PointF point_1(static_cast<Gdiplus::REAL>(rc.left), static_cast<Gdiplus::REAL>(rc.top)); Gdiplus::PointF point_2(static_cast<Gdiplus::REAL>(rc.right), static_cast<Gdiplus::REAL>(rc.bottom)); Gdiplus::PointF point_3(static_cast<Gdiplus::REAL>(rc.left), static_cast<Gdiplus::REAL>(rc.bottom)); Gdiplus::PointF point_4(static_cast<Gdiplus::REAL>(rc.right), static_cast<Gdiplus::REAL>(rc.top)); color.SetFromCOLORREF(m_clr); Gdiplus::Pen pen(color, 2.0f); graphics.DrawLine(&pen, point_1, point_2); graphics.DrawLine(&pen, point_3, point_4); } if (pThis->iUniqueID == pThis->d->m_iIDMax) { if (!IsMaximized(pThis->d->m_hWnd)) { RECT rect_max_box; rect_max_box.left = rc.left; rect_max_box.top = rc.top + 1; rect_max_box.right = rc.right; rect_max_box.bottom = rc.bottom; color.SetFromCOLORREF(m_clr); Gdiplus::Pen pen(color, 1.0f); Gdiplus::RectF rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_max_box); graphics.DrawRectangle(&pen, rect); rect_max_box.top = rect_max_box.top + 1; rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_max_box); graphics.DrawRectangle(&pen, rect); } else { RECT rect_restore_box; rect_restore_box.top = rc.top; rect_restore_box.right = rc.right; rect_restore_box.left = rect_restore_box.right - (4 * (rc.right - rc.left)) / 5; rect_restore_box.bottom = rect_restore_box.top + (4 * (rc.bottom - rc.top)) / 5; color.SetFromCOLORREF(m_clr); Gdiplus::Pen pen(color, 1.0f); Gdiplus::RectF rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_restore_box); graphics.DrawRectangle(&pen, rect); rect_restore_box.left = rc.left; rect_restore_box.bottom = rc.bottom; rect_restore_box.top = rect_restore_box.bottom - (4 * (rc.bottom - rc.top)) / 5; rect_restore_box.right = rect_restore_box.left + (4 * (rc.right - rc.left)) / 5; rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_restore_box); color.SetFromCOLORREF(pThis->d->m_clrBackground); Gdiplus::SolidBrush brush(color); graphics.FillRectangle(&brush, rect); graphics.DrawRectangle(&pen, rect); rect_restore_box.top = rect_restore_box.top + 1; rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_restore_box); graphics.DrawRectangle(&pen, rect); } } if (pThis->iUniqueID == pThis->d->m_iIDMin) { RECT rect_min_box; rect_min_box.left = rc.left; rect_min_box.top = rc.bottom - 1; rect_min_box.right = rc.right; rect_min_box.bottom = rc.bottom; color.SetFromCOLORREF(m_clr); Gdiplus::Pen pen(color, 1.0f); Gdiplus::RectF rect = liblec::cui::gui_raw::cui_rawImpl::convert_rect(rect_min_box); graphics.DrawRectangle(&pen, rect); } BitBlt(dc, 0, 0, cx, cy, hdc, 0, 0, SRCCOPY); EndPaint(hWnd, &ps); SelectBitmap(hdc, hbmOld); DeleteDC(hdc); } break; case WM_SHOWWINDOW: { if (wParam == FALSE) pThis->toolTip.bAllowToolTip = false; if (wParam == TRUE) pThis->toolTip.bAllowToolTip = true; } break; case WM_DESTROY: { // delete buffer, we're done if (pThis->hbm_buffer) { DeleteBitmap(pThis->hbm_buffer); pThis->hbm_buffer = NULL; } } break; case WM_SIZE: { // delete buffer, we need it recreated if (pThis->hbm_buffer) { DeleteBitmap(pThis->hbm_buffer); pThis->hbm_buffer = NULL; } InvalidateRect(hWnd, NULL, TRUE); } break; } // Any messages we don't process must be passed onto the original window function return CallWindowProc((WNDPROC)pThis->PrevProc, hWnd, msg, wParam, lParam); } // ControlBtnProc
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/rtp_rtcp/source/fec_test_helper.h" #include <memory> #include <utility> #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "modules/rtp_rtcp/source/rtp_packet.h" #include "modules/rtp_rtcp/source/rtp_utility.h" #include "rtc_base/checks.h" namespace webrtc { namespace test { namespace fec { namespace { constexpr uint8_t kFecPayloadType = 96; constexpr uint8_t kRedPayloadType = 97; constexpr uint8_t kVp8PayloadType = 120; constexpr int kPacketTimestampIncrement = 3000; } // namespace MediaPacketGenerator::MediaPacketGenerator(uint32_t min_packet_size, uint32_t max_packet_size, uint32_t ssrc, Random* random) : min_packet_size_(min_packet_size), max_packet_size_(max_packet_size), ssrc_(ssrc), random_(random) {} MediaPacketGenerator::~MediaPacketGenerator() = default; ForwardErrorCorrection::PacketList MediaPacketGenerator::ConstructMediaPackets( int num_media_packets, uint16_t start_seq_num) { RTC_DCHECK_GT(num_media_packets, 0); uint16_t seq_num = start_seq_num; int time_stamp = random_->Rand<int>(); ForwardErrorCorrection::PacketList media_packets; for (int i = 0; i < num_media_packets; ++i) { std::unique_ptr<ForwardErrorCorrection::Packet> media_packet( new ForwardErrorCorrection::Packet()); media_packet->data.SetSize( random_->Rand(min_packet_size_, max_packet_size_)); uint8_t* data = media_packet->data.MutableData(); // Generate random values for the first 2 bytes data[0] = random_->Rand<uint8_t>(); data[1] = random_->Rand<uint8_t>(); // The first two bits are assumed to be 10 by the FEC encoder. // In fact the FEC decoder will set the two first bits to 10 regardless of // what they actually were. Set the first two bits to 10 so that a memcmp // can be performed for the whole restored packet. data[0] |= 0x80; data[0] &= 0xbf; // FEC is applied to a whole frame. // A frame is signaled by multiple packets without the marker bit set // followed by the last packet of the frame for which the marker bit is set. // Only push one (fake) frame to the FEC. data[1] &= 0x7f; webrtc::ByteWriter<uint16_t>::WriteBigEndian(&data[2], seq_num); webrtc::ByteWriter<uint32_t>::WriteBigEndian(&data[4], time_stamp); webrtc::ByteWriter<uint32_t>::WriteBigEndian(&data[8], ssrc_); // Generate random values for payload. for (size_t j = 12; j < media_packet->data.size(); ++j) data[j] = random_->Rand<uint8_t>(); seq_num++; media_packets.push_back(std::move(media_packet)); } // Last packet, set marker bit. ForwardErrorCorrection::Packet* media_packet = media_packets.back().get(); RTC_DCHECK(media_packet); media_packet->data.MutableData()[1] |= 0x80; next_seq_num_ = seq_num; return media_packets; } ForwardErrorCorrection::PacketList MediaPacketGenerator::ConstructMediaPackets( int num_media_packets) { return ConstructMediaPackets(num_media_packets, random_->Rand<uint16_t>()); } uint16_t MediaPacketGenerator::GetNextSeqNum() { return next_seq_num_; } AugmentedPacketGenerator::AugmentedPacketGenerator(uint32_t ssrc) : num_packets_(0), ssrc_(ssrc), seq_num_(0), timestamp_(0) {} void AugmentedPacketGenerator::NewFrame(size_t num_packets) { num_packets_ = num_packets; timestamp_ += kPacketTimestampIncrement; } uint16_t AugmentedPacketGenerator::NextPacketSeqNum() { return ++seq_num_; } std::unique_ptr<AugmentedPacket> AugmentedPacketGenerator::NextPacket( size_t offset, size_t length) { std::unique_ptr<AugmentedPacket> packet(new AugmentedPacket()); packet->data.SetSize(length + kRtpHeaderSize); uint8_t* data = packet->data.MutableData(); for (size_t i = 0; i < length; ++i) data[i + kRtpHeaderSize] = offset + i; packet->data.SetSize(length + kRtpHeaderSize); packet->header.headerLength = kRtpHeaderSize; packet->header.markerBit = (num_packets_ == 1); packet->header.payloadType = kVp8PayloadType; packet->header.sequenceNumber = seq_num_; packet->header.timestamp = timestamp_; packet->header.ssrc = ssrc_; WriteRtpHeader(packet->header, data); ++seq_num_; --num_packets_; return packet; } void AugmentedPacketGenerator::WriteRtpHeader(const RTPHeader& header, uint8_t* data) { data[0] = 0x80; // Version 2. data[1] = header.payloadType; data[1] |= (header.markerBit ? kRtpMarkerBitMask : 0); ByteWriter<uint16_t>::WriteBigEndian(data + 2, header.sequenceNumber); ByteWriter<uint32_t>::WriteBigEndian(data + 4, header.timestamp); ByteWriter<uint32_t>::WriteBigEndian(data + 8, header.ssrc); } FlexfecPacketGenerator::FlexfecPacketGenerator(uint32_t media_ssrc, uint32_t flexfec_ssrc) : AugmentedPacketGenerator(media_ssrc), flexfec_ssrc_(flexfec_ssrc), flexfec_seq_num_(0), flexfec_timestamp_(0) {} std::unique_ptr<AugmentedPacket> FlexfecPacketGenerator::BuildFlexfecPacket( const ForwardErrorCorrection::Packet& packet) { RTC_DCHECK_LE(packet.data.size(), static_cast<size_t>(IP_PACKET_SIZE - kRtpHeaderSize)); RTPHeader header; header.sequenceNumber = flexfec_seq_num_; ++flexfec_seq_num_; header.timestamp = flexfec_timestamp_; flexfec_timestamp_ += kPacketTimestampIncrement; header.ssrc = flexfec_ssrc_; std::unique_ptr<AugmentedPacket> packet_with_rtp_header( new AugmentedPacket()); packet_with_rtp_header->data.SetSize(kRtpHeaderSize + packet.data.size()); WriteRtpHeader(header, packet_with_rtp_header->data.MutableData()); memcpy(packet_with_rtp_header->data.MutableData() + kRtpHeaderSize, packet.data.cdata(), packet.data.size()); return packet_with_rtp_header; } UlpfecPacketGenerator::UlpfecPacketGenerator(uint32_t ssrc) : AugmentedPacketGenerator(ssrc) {} RtpPacketReceived UlpfecPacketGenerator::BuildMediaRedPacket( const AugmentedPacket& packet, bool is_recovered) { RtpPacketReceived red_packet; // Copy RTP header. const size_t kHeaderLength = packet.header.headerLength; red_packet.Parse(packet.data.cdata(), kHeaderLength); RTC_DCHECK_EQ(red_packet.headers_size(), kHeaderLength); uint8_t* rtp_payload = red_packet.AllocatePayload(packet.data.size() + 1 - kHeaderLength); // Move payload type into rtp payload. rtp_payload[0] = red_packet.PayloadType(); red_packet.SetPayloadType(kRedPayloadType); // Copy the payload. memcpy(rtp_payload + 1, packet.data.cdata() + kHeaderLength, packet.data.size() - kHeaderLength); red_packet.set_recovered(is_recovered); return red_packet; } RtpPacketReceived UlpfecPacketGenerator::BuildUlpfecRedPacket( const ForwardErrorCorrection::Packet& packet) { // Create a fake media packet to get a correct header. 1 byte RED header. ++num_packets_; std::unique_ptr<AugmentedPacket> fake_packet = NextPacket(0, packet.data.size() + 1); RtpPacketReceived red_packet; red_packet.Parse(fake_packet->data); red_packet.SetMarker(false); uint8_t* rtp_payload = red_packet.AllocatePayload(packet.data.size() + 1); rtp_payload[0] = kFecPayloadType; red_packet.SetPayloadType(kRedPayloadType); memcpy(rtp_payload + 1, packet.data.cdata(), packet.data.size()); red_packet.set_recovered(false); return red_packet; } } // namespace fec } // namespace test } // namespace webrtc
/****************************************************************************** # Author: Ian LaMotte-Kerr # Lab: Discussion 4 # Date: today # Description: # Input: # Output: # Sources: #******************************************************************************/ #include <iostream> #include <iomanip> using namespace std; const int MAXCHAR = 5; int main() { srand(time(0)); int randfill; int rarr[MAXCHAR] = {0}; int arr[MAXCHAR] = {0}; bool match = false; cout<<"gonna need some ints please. 1 at a time, press enter between each number (0-9): \n"; for (int i = 0;i < MAXCHAR; i++) { int num; cout<<"index: "<<i<<" : "; cin>>num; if (num > 0 and num < 10 ) { arr[i] = num; } else { cout<<"yeah, thats not gonna work. Try again: "; i--; } } cout<<setw(25)<<setfill('_')<<"\n"; cout<<"\nYour picks: "; for (int i = 0; i < MAXCHAR; i++) { cout<<arr[i]<<" "; randfill = rand() % 10; rarr[i] = randfill; } cout<<"\nRand picks: "; for (int i = 0; i < MAXCHAR; i++) { cout<<rarr[i]<<" "; } cout<<endl; cout<<"\nLets compare: "<<endl; cout<<setw(25)<<setfill('_')<<"\n"; for (int i = 0; i < MAXCHAR; i++) { if (arr[i] == rarr[i]) { cout<<"index "<<i<<" match: "<<arr[i]<<" | "<<rarr[i]<<endl; match = true; } else { match = false; cout<<"index "<<i<<" knope: "<<arr[i]<<" | "<<rarr[i]<<endl; cout<<"\nUnfortunately, you did not win. Better luck next time.\n"; break; } } cout<<endl; return 0; }
#include <cppunit/TestSuite.h> #include <cppunit/TestCaller.h> #include <UrchinCommon.h> #include <common/util/FileUtilTest.h> #include <AssertHelper.h> using namespace urchin; void FileUtilTest::getDirectoryUnix() { std::string filenamePath = "/home/jean/binaryFile"; std::string result = FileUtil::getDirectory(filenamePath); AssertHelper::assertTrue(result == "/home/jean/"); } void FileUtilTest::getDirectoryWindows() { std::string filenamePath = R"(C:\home\jean\binaryFile)"; std::string result = FileUtil::getDirectory(filenamePath); AssertHelper::assertTrue(result == R"(C:\home\jean\)"); } void FileUtilTest::relativePath() { std::string referenceDirectory = "xxx/yyy/zzz/www/"; std::string path = "xxx/yyy/aaa/bbb/"; std::string result = FileUtil::getRelativePath(referenceDirectory, path); AssertHelper::assertTrue(result == "../../aaa/bbb/"); } void FileUtilTest::relativePathEqual() { std::string referenceDirectory = "xxx/yyy/"; std::string path = "xxx/yyy/"; std::string result = FileUtil::getRelativePath(referenceDirectory, path); AssertHelper::assertTrue(result.empty()); } void FileUtilTest::simplifyDirectoryPathUnix() { std::string directoryPath = "xxx/yyy/../zzz/www/../rrr/"; std::string result = FileUtil::simplifyDirectoryPath(directoryPath); AssertHelper::assertTrue(result == "xxx/zzz/rrr/"); } void FileUtilTest::simplifyDirectoryPathWindows() { std::string directoryPath = R"(xxx\yyy\..\zzz\www\..\rrr\)"; std::string result = FileUtil::simplifyDirectoryPath(directoryPath); AssertHelper::assertTrue(result == R"(xxx\zzz\rrr\)"); } CppUnit::Test* FileUtilTest::suite() { auto* suite = new CppUnit::TestSuite("FileUtilTest"); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("getDirectoryUnix", &FileUtilTest::getDirectoryUnix)); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("getDirectoryWindows", &FileUtilTest::getDirectoryWindows)); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("relativePath", &FileUtilTest::relativePath)); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("relativePathEqual", &FileUtilTest::relativePathEqual)); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("simplifyDirectoryPathUnix", &FileUtilTest::simplifyDirectoryPathUnix)); suite->addTest(new CppUnit::TestCaller<FileUtilTest>("simplifyDirectoryPathWindows", &FileUtilTest::simplifyDirectoryPathWindows)); return suite; }
/* * Copyright (C) 2019-2020 Zilliz. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include "arrow/render_api.h" TEST(CHOROPLETH_MAP_TEST, BLUE_TO_RED) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, SKYBLUE_TO_WHITE) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"skyblue_to_white\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, GREEN_YELLOW_RED) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"green_yellow_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, BLUE_WHITE_RED) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_white_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, WHITE_BLUE) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"white_blue\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, BLUE_GREEN_YELLOW) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_green_yellow\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, BLUE_TRANSPARENCY) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_transparency\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, RED_TRANSPARENCY) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"red_transparency\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, PURPLE_TO_YELLOW) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"purple_to_yellow\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INVALID_COLOR_STYLE_TEST) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"xxxxxx\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INVALID_JSON_TEST) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": \"INVALID_NUMBER\"}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INT8) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::Int8Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INT16) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::Int16Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INT32) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::Int32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INT64) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::Int64Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, UINT8) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt8Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, UINT16) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt16Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, UINT32) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt32Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, UINT64) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::UInt64Builder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, FLOAT) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::FloatBuilder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, DOUBLE) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::DoubleBuilder color_builder; status = color_builder.Append(5); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); } TEST(CHOROPLETH_MAP_TEST, INVALID_DATA_TYPE_TEST) { // param1: wkt string std::string wkt_string1 = "POLYGON ((" "-73.98128 40.754771, " "-73.980185 40.754771, " "-73.980185 40.755587, " "-73.98128 40.755587, " "-73.98128 40.754771))"; arrow::StringBuilder string_builder; auto status = string_builder.Append(wkt_string1); std::shared_ptr<arrow::StringArray> string_array; status = string_builder.Finish(&string_array); // param2: color std::shared_ptr<arrow::Array> color_array; arrow::StringBuilder color_builder; status = color_builder.Append(""); status = color_builder.Finish(&color_array); // param3: conf const std::string vega = "{\n" " \"width\": 1900,\n" " \"height\": 1410,\n" " \"description\": \"choropleth_map\",\n" " \"data\": [\n" " {\n" " \"name\": \"data\",\n" " \"url\": \"data/data.csv\"\n" " }\n" " ],\n" " \"scales\": [\n" " {\n" " \"name\": \"building\",\n" " \"type\": \"linear\",\n" " \"domain\": {\"data\": \"data\", \"field\": \"c0\"}\n" " }\n" " ],\n" " \"marks\": [\n" " {\n" " \"encode\": {\n" " \"enter\": {\n" " \"bounding_box\": {\"value\": " "[-73.984092,40.753893,-73.977588,40.756342]},\n" " \"color_style\": {\"value\": \"blue_to_red\"},\n" " \"ruler\": {\"value\": [2.5, 5]},\n" " \"opacity\": {\"value\": 1.0}\n" " }\n" " }\n" " }\n" " ]\n" "}"; arctern::render::choropleth_map(string_array, color_array, vega); }
/** * Copyright 2019 The Gamma Authors. * * This source code is licensed under the Apache License, Version 2.0 license * found in the LICENSE file in the root directory of this source tree. */ #include "gamma_engine.h" #include <fcntl.h> #include <locale.h> #ifndef __APPLE__ #include <malloc.h> #endif #include <string.h> #include <sys/mman.h> #include <time.h> #include <unistd.h> #include <chrono> #include <cstring> #include <fstream> #include <iomanip> #include <mutex> #include <thread> #include <vector> #include "cjson/cJSON.h" #include "common/gamma_common_data.h" #include "gamma_table_io.h" #include "io/raw_vector_io.h" #include "omp.h" #include "search/error_code.h" #include "util/bitmap.h" #include "util/log.h" #include "util/utils.h" using std::string; using namespace tig_gamma::table; namespace tig_gamma { bool RequestConcurrentController::Acquire(int req_num) { #ifndef __APPLE__ int num = __sync_fetch_and_add(&cur_concurrent_num_, req_num); if (num < concurrent_threshold_) { return true; } else { LOG(WARNING) << "cur_threads_num [" << num << "] concurrent_threshold [" << concurrent_threshold_ << "]"; return false; } #else return true; #endif } void RequestConcurrentController::Release(int req_num) { #ifndef __APPLE__ __sync_fetch_and_sub(&cur_concurrent_num_, req_num); #else return; #endif } RequestConcurrentController::RequestConcurrentController() { concurrent_threshold_ = 0; max_threads_ = 0; cur_concurrent_num_ = 0; GetMaxThread(); } int RequestConcurrentController::GetMaxThread() { #ifndef __APPLE__ // Get system config and calculate max threads int omp_max_threads = omp_get_max_threads(); int threads_max = GetSystemInfo("cat /proc/sys/kernel/threads-max"); int max_map_count = GetSystemInfo("cat /proc/sys/vm/max_map_count"); int pid_max = GetSystemInfo("cat /proc/sys/kernel/pid_max"); LOG(INFO) << "System info: threads_max [" << threads_max << "] max_map_count [" << max_map_count << "] pid_max [" << pid_max << "]"; max_threads_ = std::min(threads_max, pid_max); max_threads_ = std::min(max_threads_, max_map_count / 2); // calculate concurrent threshold concurrent_threshold_ = (max_threads_ * 0.5) / (omp_max_threads + 1); LOG(INFO) << "max_threads [" << max_threads_ << "] concurrent_threshold [" << concurrent_threshold_ << "]"; if (concurrent_threshold_ == 0) { LOG(FATAL) << "concurrent_threshold cannot be 0!"; } return max_threads_; #else return 0; #endif } int RequestConcurrentController::GetSystemInfo(const char *cmd) { int num = 0; char buff[1024]; memset(buff, 0, sizeof(buff)); FILE *fstream = popen(cmd, "r"); if (fstream == nullptr) { LOG(ERROR) << "execute command failed: " << strerror(errno); num = -1; } else { fgets(buff, sizeof(buff), fstream); num = atoi(buff); pclose(fstream); } return num; } #ifdef DEBUG static string float_array_to_string(float *data, int len) { if (data == nullptr) return ""; std::stringstream ss; ss << "["; for (int i = 0; i < len; ++i) { ss << data[i]; if (i != len - 1) { ss << ","; } } ss << "]"; return ss.str(); } static string VectorQueryToString(VectorQuery *vector_query) { std::stringstream ss; ss << "name:" << std::string(vector_query->name->value, vector_query->name->len) << " min score:" << vector_query->min_score << " max score:" << vector_query->max_score << " boost:" << vector_query->boost << " has boost:" << vector_query->has_boost << " value:" << float_array_to_string((float *)vector_query->value->value, vector_query->value->len / sizeof(float)); return ss.str(); } // static string RequestToString(const Request *request) { // std::stringstream ss; // ss << "{req_num:" << request->req_num << " topn:" << request->topn // << " has_rank:" << request->has_rank // << " vec_num:" << request->vec_fields_num; // for (int i = 0; i < request->vec_fields_num; ++i) { // ss << " vec_id:" << i << " [" << // VectorQueryToString(request->vec_fields[i]) // << "]"; // } // ss << "}"; // return ss.str(); // } #endif // DEBUG #ifndef __APPLE__ static std::thread *gMemTrimThread = nullptr; void MemTrimHandler() { LOG(INFO) << "memory trim thread start......"; while (1) { malloc_trim(0); std::this_thread::sleep_for(std::chrono::seconds(60)); // 1 minute } LOG(INFO) << "memory trim thread exit!"; } #endif GammaEngine::GammaEngine(const string &index_root_path) : index_root_path_(index_root_path), date_time_format_("%Y-%m-%d-%H:%M:%S") { table_ = nullptr; vec_manager_ = nullptr; index_status_ = IndexStatus::UNINDEXED; delete_num_ = 0; b_running_ = 0; b_field_running_ = false; is_dirty_ = false; field_range_index_ = nullptr; created_table_ = false; b_loading_ = false; docids_bitmap_ = nullptr; #ifdef PERFORMANCE_TESTING search_num_ = 0; #endif } GammaEngine::~GammaEngine() { if (b_running_) { b_running_ = 0; std::mutex running_mutex; std::unique_lock<std::mutex> lk(running_mutex); running_cv_.wait(lk); } if (b_field_running_) { b_field_running_ = false; std::mutex running_mutex; std::unique_lock<std::mutex> lk(running_mutex); running_field_cv_.wait(lk); } if (vec_manager_) { delete vec_manager_; vec_manager_ = nullptr; } if (table_) { delete table_; table_ = nullptr; } if (field_range_index_) { delete field_range_index_; field_range_index_ = nullptr; } if (docids_bitmap_) { delete docids_bitmap_; docids_bitmap_ = nullptr; } } GammaEngine *GammaEngine::GetInstance(const string &index_root_path) { GammaEngine *engine = new GammaEngine(index_root_path); int ret = engine->Setup(); if (ret < 0) { LOG(ERROR) << "BuildSearchEngine [" << index_root_path << "] error!"; return nullptr; } return engine; } int GammaEngine::Setup() { if (!utils::isFolderExist(index_root_path_.c_str())) { mkdir(index_root_path_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } dump_path_ = index_root_path_ + "/retrieval_model_index"; if (!utils::isFolderExist(dump_path_.c_str())) { mkdir(dump_path_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } docids_bitmap_ = new bitmap::BitmapManager(); docids_bitmap_->SetDumpFilePath(index_root_path_ + "/bitmap"); int init_bitmap_size = 1000 * 10000;; int file_bytes_size = docids_bitmap_->FileBytesSize(); if (file_bytes_size != 0) { init_bitmap_size = file_bytes_size; } if (docids_bitmap_->Init(init_bitmap_size) != 0) { LOG(ERROR) << "Cannot create bitmap!"; return INTERNAL_ERR; } if (!table_) { table_ = new Table(index_root_path_); } if (!vec_manager_) { vec_manager_ = new VectorManager(VectorStorageType::Mmap, docids_bitmap_, index_root_path_); } #ifndef __APPLE__ if (gMemTrimThread == nullptr) { gMemTrimThread = new std::thread(MemTrimHandler); if (gMemTrimThread) { gMemTrimThread->detach(); } else { LOG(ERROR) << "create memory trim thread error"; } } #endif max_docid_ = 0; LOG(INFO) << "GammaEngine setup successed! bitmap_bytes_size=" << docids_bitmap_->BytesSize(); return 0; } int GammaEngine::Search(Request &request, Response &response_results) { #ifdef DEBUG // LOG(INFO) << "search request:" << RequestToString(request); #endif int ret = 0; int req_num = request.ReqNum(); if (req_num <= 0) { string msg = "req_num should not less than 0"; LOG(ERROR) << msg; return -1; } bool req_permit = RequestConcurrentController::GetInstance().Acquire(req_num); if (not req_permit) { LOG(WARNING) << "Resource temporarily unavailable"; RequestConcurrentController::GetInstance().Release(req_num); return -1; } // TODO: it may be opened later // utils::OnlineLogger logger; // if (0 != logger.Init(online_log_level)) { // LOG(WARNING) << "init online logger error!"; // } int topn = request.TopN(); bool brute_force_search = request.BruteForceSearch(); if ((not brute_force_search) && (index_status_ != IndexStatus::INDEXED)) { string msg = "index not trained!"; LOG(WARNING) << msg; for (int i = 0; i < req_num; ++i) { SearchResult result; result.msg = msg; result.result_code = SearchResultCode::INDEX_NOT_TRAINED; response_results.AddResults(std::move(result)); } RequestConcurrentController::GetInstance().Release(req_num); return -2; } std::vector<struct VectorQuery> &vec_fields = request.VecFields(); GammaQuery gamma_query; gamma_query.vec_query = vec_fields; gamma_query.condition = new GammaSearchCondition; gamma_query.condition->topn = topn; gamma_query.condition->multi_vector_rank = request.MultiVectorRank() == 1 ? true : false; gamma_query.condition->brute_force_search = brute_force_search; gamma_query.condition->l2_sqrt = request.L2Sqrt(); gamma_query.condition->retrieval_parameters = request.RetrievalParams(); gamma_query.condition->has_rank = request.HasRank(); #ifdef BUILD_GPU gamma_query.condition->range_filters = request.RangeFilters(); gamma_query.condition->term_filters = request.TermFilters(); gamma_query.condition->table = table_; #endif // BUILD_GPU #ifndef BUILD_GPU MultiRangeQueryResults range_query_result; std::vector<struct RangeFilter> &range_filters = request.RangeFilters(); size_t range_filters_num = range_filters.size(); std::vector<struct TermFilter> &term_filters = request.TermFilters(); size_t term_filters_num = term_filters.size(); if (range_filters_num > 0 || term_filters_num > 0) { int num = MultiRangeQuery(request, gamma_query.condition, response_results, &range_query_result); if (num == 0) { RequestConcurrentController::GetInstance().Release(req_num); return 0; } } #ifdef PERFORMANCE_TESTING gamma_query.condition->GetPerfTool().Perf("filter"); #endif #endif size_t vec_fields_num = vec_fields.size(); if (vec_fields_num > 0) { GammaResult gamma_results[req_num]; int doc_num = GetDocsNum(); for (int i = 0; i < req_num; ++i) { gamma_results[i].total = doc_num; } ret = vec_manager_->Search(gamma_query, gamma_results); if (ret != 0) { string msg = "search error [" + std::to_string(ret) + "]"; for (int i = 0; i < req_num; ++i) { SearchResult result; result.msg = msg; result.result_code = SearchResultCode::SEARCH_ERROR; response_results.AddResults(std::move(result)); } RequestConcurrentController::GetInstance().Release(req_num); return -3; } #ifdef PERFORMANCE_TESTING gamma_query.condition->GetPerfTool().Perf("search total"); #endif PackResults(gamma_results, response_results, request); #ifdef PERFORMANCE_TESTING gamma_query.condition->GetPerfTool().Perf("pack results"); #endif #ifdef BUILD_GPU } #else } else { GammaResult gamma_result; gamma_result.topn = topn; std::vector<std::pair<string, int>> fields_ids; std::vector<string> vec_names; const auto range_result = range_query_result.GetAllResult(); if (range_result == nullptr && term_filters_num > 0) { for (size_t i = 0; i < term_filters_num; ++i) { struct TermFilter &term_filter = term_filters[i]; string value = term_filter.field; int doc_id = -1; if (table_->GetDocIDByKey(term_filter.value, doc_id) != 0) { continue; } fields_ids.emplace_back(std::make_pair(value, doc_id)); vec_names.emplace_back(std::move(value)); } if (fields_ids.size() > 0) { gamma_result.init(topn, vec_names.data(), fields_ids.size()); std::vector<string> vec; int ret = vec_manager_->GetVector(fields_ids, vec); if (ret == 0) { int idx = 0; VectorDoc *doc = gamma_result.docs[gamma_result.results_count]; for (const auto &field_id : fields_ids) { int id = field_id.second; doc->docid = id; doc->fields[idx].name = vec[idx]; doc->fields[idx].source = nullptr; doc->fields[idx].source_len = 0; ++idx; } ++gamma_result.results_count; gamma_result.total = 1; } } } else { gamma_result.init(topn, nullptr, 0); for (int docid = 0; docid < max_docid_; ++docid) { if (range_query_result.Has(docid) && !docids_bitmap_->Test(docid)) { ++gamma_result.total; if (gamma_result.results_count < topn) { gamma_result.docs[gamma_result.results_count++]->docid = docid; } } } } // response_results.req_num = 1; // only one result PackResults(&gamma_result, response_results, request); } #endif #ifdef PERFORMANCE_TESTING LOG(INFO) << gamma_query.condition->GetPerfTool().OutputPerf().str(); #endif std::string online_log_level = request.OnlineLogLevel(); if (strncasecmp("debug", online_log_level.c_str(), 5) == 0) { response_results.SetOnlineLogMessage( gamma_query.condition->GetPerfTool().OutputPerf().str()); } RequestConcurrentController::GetInstance().Release(req_num); return ret; } int GammaEngine::MultiRangeQuery(Request &request, GammaSearchCondition *condition, Response &response_results, MultiRangeQueryResults *range_query_result) { std::vector<FilterInfo> filters; std::vector<struct RangeFilter> &range_filters = request.RangeFilters(); std::vector<struct TermFilter> &term_filters = request.TermFilters(); int range_filters_size = range_filters.size(); int term_filters_size = term_filters.size(); filters.resize(range_filters_size + term_filters_size); int idx = 0; for (int i = 0; i < range_filters_size; ++i) { struct RangeFilter &filter = range_filters[i]; filters[idx].field = table_->GetAttrIdx(filter.field); filters[idx].lower_value = filter.lower_value; filters[idx].upper_value = filter.upper_value; ++idx; } for (int i = 0; i < term_filters_size; ++i) { struct TermFilter &filter = term_filters[i]; filters[idx].field = table_->GetAttrIdx(filter.field); filters[idx].lower_value = filter.value; filters[idx].is_union = static_cast<FilterOperator>(filter.is_union); ++idx; } int retval = field_range_index_->Search(filters, range_query_result); if (retval == 0) { string msg = "No result: numeric filter return 0 result"; LOG(INFO) << msg; for (int i = 0; i < request.ReqNum(); ++i) { SearchResult result; result.msg = msg; result.result_code = SearchResultCode::SUCCESS; response_results.AddResults(std::move(result)); } } else if (retval < 0) { condition->range_query_result = nullptr; } else { condition->range_query_result = range_query_result; } return retval; } int GammaEngine::CreateTable(TableInfo &table) { if (!vec_manager_ || !table_) { LOG(ERROR) << "vector and table should not be null!"; return -1; } string dump_meta_path = index_root_path_ + "/dump.meta"; utils::JsonParser *meta_jp = nullptr; utils::ScopeDeleter1<utils::JsonParser> del1; if (utils::file_exist(dump_meta_path)) { long len = utils::get_file_size(dump_meta_path); if (len > 0) { utils::FileIO fio(dump_meta_path); if (fio.Open("r")) { LOG(ERROR) << "open file error, path=" << dump_meta_path; return IO_ERR; } char *buf = new char[len + 1]; buf[len] = '\0'; if ((size_t)len != fio.Read(buf, 1, (size_t)len)) { LOG(ERROR) << "read file error, path=" << dump_meta_path; return IO_ERR; } meta_jp = new utils::JsonParser(); del1.set(meta_jp); if (meta_jp->Parse(buf)) { return FORMAT_ERR; } } } if (vec_manager_->CreateVectorTable(table, meta_jp) != 0) { LOG(ERROR) << "Cannot create VectorTable!"; return -2; } TableParams disk_table_params; if (meta_jp) { utils::JsonParser table_jp; meta_jp->GetObject("table", table_jp); disk_table_params.Parse(table_jp); } int ret_table = table_->CreateTable(table, disk_table_params); indexing_size_ = table.IndexingSize(); if (ret_table != 0) { LOG(ERROR) << "Cannot create table!"; return -2; } if (!meta_jp) { utils::JsonParser dump_meta_; dump_meta_.PutInt("version", 320); // version=3.2.0 utils::JsonParser table_jp; table_->GetDumpConfig()->ToJson(table_jp); dump_meta_.PutObject("table", std::move(table_jp)); utils::JsonParser vectors_jp; for (auto &it : vec_manager_->RawVectors()) { DumpConfig *dc = it.second->GetDumpConfig(); if (dc) { utils::JsonParser jp; dc->ToJson(jp); vectors_jp.PutObject(dc->name, std::move(jp)); } } dump_meta_.PutObject("vectors", std::move(vectors_jp)); utils::FileIO fio(dump_meta_path); fio.Open("w"); string meta_str = dump_meta_.ToStr(true); fio.Write(meta_str.c_str(), 1, meta_str.size()); } #ifndef BUILD_GPU field_range_index_ = new MultiFieldsRangeIndex(index_root_path_, table_); if ((nullptr == field_range_index_) || (AddNumIndexFields() < 0)) { LOG(ERROR) << "add numeric index fields error!"; return -3; } auto func_build_field_index = std::bind(&GammaEngine::BuildFieldIndex, this); std::thread t(func_build_field_index); t.detach(); #endif std::string table_name = table.Name(); std::string path = index_root_path_ + "/" + table_name + ".schema"; TableSchemaIO tio(path); // rewrite it if the path is already existed if (tio.Write(table)) { LOG(ERROR) << "write table schema error, path=" << path; } uint32_t file_bytes_size = docids_bitmap_->FileBytesSize(); if (file_bytes_size + 1 >= docids_bitmap_->BytesSize() && docids_bitmap_->Load() == 0) { LOG(INFO) << "Load bitmap success."; } else { docids_bitmap_->Dump(); LOG(INFO) << "Full dump bitmap."; } LOG(INFO) << "create table [" << table_name << "] success!"; created_table_ = true; return 0; } int GammaEngine::AddOrUpdate(Doc &doc) { #ifdef PERFORMANCE_TESTING double start = utils::getmillisecs(); #endif std::vector<struct Field> &fields_table = doc.TableFields(); std::vector<struct Field> &fields_vec = doc.VectorFields(); std::string &key = doc.Key(); // add fields into table int docid = -1; table_->GetDocIDByKey(key, docid); if (docid == -1) { int ret = table_->Add(key, fields_table, max_docid_); if (ret != 0) return -2; #ifndef BUILD_GPU for (size_t i = 0; i < fields_table.size(); ++i) { struct Field &field = fields_table[i]; int idx = table_->GetAttrIdx(field.name); field_range_index_->Add(max_docid_, idx); } #endif // BUILD_GPU } else { if (Update(docid, fields_table, fields_vec)) { LOG(ERROR) << "update error, key=" << key << ", docid=" << docid; return -3; } is_dirty_ = true; return 0; } #ifdef PERFORMANCE_TESTING double end_table = utils::getmillisecs(); #endif // add vectors by VectorManager if (vec_manager_->AddToStore(max_docid_, fields_vec) != 0) { LOG(ERROR) << "Add to store error max_docid [" << max_docid_ << "]"; return -4; } ++max_docid_; docids_bitmap_->SetMaxID(max_docid_); if (not b_running_ and index_status_ == UNINDEXED) { if (max_docid_ >= indexing_size_) { LOG(INFO) << "Begin indexing."; this->BuildIndex(); } } #ifdef PERFORMANCE_TESTING double end = utils::getmillisecs(); if (max_docid_ % 10000 == 0) { LOG(INFO) << "table cost [" << end_table - start << "]ms, vec store cost [" << end - end_table << "]ms"; } #endif is_dirty_ = true; return 0; } int GammaEngine::AddOrUpdateDocs(Docs &docs, BatchResult &result) { #ifdef PERFORMANCE_TESTING double start = utils::getmillisecs(); #endif std::vector<Doc> &doc_vec = docs.GetDocs(); std::set<std::string> remove_dupliacte; int batch_size = 0, start_id = 0; auto batchAdd = [&](int start_id, int batch_size) { if (batch_size <= 0) return; int ret = table_->BatchAdd(start_id, batch_size, max_docid_, doc_vec, result); if (ret != 0) { LOG(ERROR) << "Add to table error"; return; } for (int i = start_id; i < start_id + batch_size; ++i) { Doc &doc = doc_vec[i]; #ifndef BUILD_GPU std::vector<struct Field> &fields_table = doc.TableFields(); for (size_t j = 0; j < fields_table.size(); ++j) { struct Field &field = fields_table[j]; int idx = table_->GetAttrIdx(field.name); field_range_index_->Add(max_docid_ + i - start_id, idx); } #endif // BUILD_GPU // add vectors by VectorManager std::vector<struct Field> &fields_vec = doc.VectorFields(); ret = vec_manager_->AddToStore(max_docid_ + i - start_id, fields_vec); if (ret != 0) { std::string msg = "Add to vector manager error"; result.SetResult(i, -1, msg); LOG(ERROR) << msg; continue; } } max_docid_ += batch_size; docids_bitmap_->SetMaxID(max_docid_); }; for (size_t i = 0; i < doc_vec.size(); ++i) { Doc &doc = doc_vec[i]; std::string &key = doc.Key(); auto ite = remove_dupliacte.find(key); if (ite == remove_dupliacte.end()) remove_dupliacte.insert(key); // add fields into table int docid = -1; table_->GetDocIDByKey(key, docid); if (docid == -1 && ite == remove_dupliacte.end()) { ++batch_size; continue; } else { batchAdd(start_id, batch_size); batch_size = 0; start_id = i + 1; std::vector<struct Field> &fields_table = doc.TableFields(); std::vector<struct Field> &fields_vec = doc.VectorFields(); if (ite != remove_dupliacte.end()) table_->GetDocIDByKey(key, docid); if (Update(docid, fields_table, fields_vec)) { LOG(ERROR) << "update error, key=" << key << ", docid=" << docid; continue; } } } batchAdd(start_id, batch_size); if (not b_running_ and index_status_ == UNINDEXED) { if (max_docid_ >= indexing_size_) { LOG(INFO) << "Begin indexing."; this->BuildIndex(); } } #ifdef PERFORMANCE_TESTING double end = utils::getmillisecs(); if (max_docid_ % 10000 == 0) { LOG(INFO) << "Doc_num[" << max_docid_ << "], BatchAdd[" << batch_size << "] total cost [" << end - start << "]ms"; } #endif is_dirty_ = true; return 0; } int GammaEngine::Update(Doc *doc) { return -1; } int GammaEngine::Update(int doc_id, std::vector<struct Field> &fields_table, std::vector<struct Field> &fields_vec) { int ret = vec_manager_->Update(doc_id, fields_vec); if (ret != 0) { return ret; } #ifndef BUILD_GPU for (size_t i = 0; i < fields_table.size(); ++i) { struct Field &field = fields_table[i]; int idx = table_->GetAttrIdx(field.name); field_range_index_->Delete(doc_id, idx); } #endif // BUILD_GPU if (table_->Update(fields_table, doc_id) != 0) { LOG(ERROR) << "table update error"; return -1; } #ifndef BUILD_GPU for (size_t i = 0; i < fields_table.size(); ++i) { struct Field &field = fields_table[i]; int idx = table_->GetAttrIdx(field.name); field_range_index_->Add(doc_id, idx); } #endif // BUILD_GPU #ifdef DEBUG LOG(INFO) << "update success! key=" << key; #endif is_dirty_ = true; return 0; } int GammaEngine::Delete(std::string &key) { int docid = -1, ret = 0; ret = table_->GetDocIDByKey(key, docid); if (ret != 0 || docid < 0) return -1; if (docids_bitmap_->Test(docid)) { return ret; } ++delete_num_; docids_bitmap_->Set(docid); docids_bitmap_->Dump(docid, 1); table_->Delete(key); vec_manager_->Delete(docid); is_dirty_ = true; return ret; } int GammaEngine::DelDocByQuery(Request &request) { #ifdef DEBUG // LOG(INFO) << "delete by query request:" << RequestToString(request); #endif #ifndef BUILD_GPU std::vector<struct RangeFilter> &range_filters = request.RangeFilters(); if (range_filters.size() <= 0) { LOG(ERROR) << "no range filter"; return 1; } MultiRangeQueryResults range_query_result; // Note its scope std::vector<FilterInfo> filters; filters.resize(range_filters.size()); int idx = 0; for (size_t i = 0; i < range_filters.size(); ++i) { struct RangeFilter &range_filter = range_filters[i]; filters[idx].field = table_->GetAttrIdx(range_filter.field); filters[idx].lower_value = range_filter.lower_value; filters[idx].upper_value = range_filter.upper_value; ++idx; } int retval = field_range_index_->Search(filters, &range_query_result); if (retval == 0) { LOG(ERROR) << "numeric index search error, ret=" << retval; return 1; } std::vector<int> doc_ids = range_query_result.ToDocs(); for (size_t i = 0; i < doc_ids.size(); ++i) { int docid = doc_ids[i]; if (docids_bitmap_->Test(docid)) { continue; } ++delete_num_; docids_bitmap_->Set(docid); docids_bitmap_->Dump(docid, 1); } #endif // BUILD_GPU is_dirty_ = true; return 0; } int GammaEngine::DelDocByFilter(Request &request, char **del_ids, int *str_len) { #ifndef BUILD_GPU *str_len = 0; MultiRangeQueryResults range_query_result; std::vector<FilterInfo> filters; std::vector<struct RangeFilter> &range_filters = request.RangeFilters(); std::vector<struct TermFilter> &term_filters = request.TermFilters(); int range_filters_size = range_filters.size(); int term_filters_size = term_filters.size(); filters.resize(range_filters_size + term_filters_size); int idx = 0; for (int i = 0; i < range_filters_size; ++i) { struct RangeFilter &filter = range_filters[i]; filters[idx].field = table_->GetAttrIdx(filter.field); filters[idx].lower_value = filter.lower_value; filters[idx].upper_value = filter.upper_value; ++idx; } for (int i = 0; i < term_filters_size; ++i) { struct TermFilter &filter = term_filters[i]; filters[idx].field = table_->GetAttrIdx(filter.field); filters[idx].lower_value = filter.value; filters[idx].is_union = static_cast<FilterOperator>(filter.is_union); ++idx; } int retval = field_range_index_->Search(filters, &range_query_result); int del_num = 0; cJSON *root = cJSON_CreateArray(); if (retval > 0) { for (int del_docid = 0; del_docid < max_docid_; ++del_docid) { if (range_query_result.Has(del_docid) == true) { std::string key; if (table_->GetKeyByDocid(del_docid, key) != 0) { // docid can be deleted. continue; } if (docids_bitmap_->Test(del_docid)) continue; docids_bitmap_->Set(del_docid); docids_bitmap_->Dump(del_docid, 1); table_->Delete(key); vec_manager_->Delete(del_docid); if (table_->IdType() == 0) { cJSON_AddItemToArray(root, cJSON_CreateString(key.c_str())); } else { long key_long; memcpy(&key_long, key.c_str(), sizeof(key_long)); cJSON_AddItemToArray(root, cJSON_CreateNumber(key_long)); } ++delete_num_; ++del_num; } } } LOG(INFO) << "DelDocByFilter(), Delete doc num: " << del_num; *del_ids = cJSON_PrintUnformatted(root); *str_len = strlen(*del_ids); if (root) cJSON_Delete(root); is_dirty_ = true; #endif // BUILD_GPU return 0; } int GammaEngine::GetDoc(const std::string &key, Doc &doc) { int docid = -1, ret = 0; ret = table_->GetDocIDByKey(key, docid); if (ret != 0 || docid < 0) { LOG(INFO) << "GetDocIDbyKey [" << key << "] error!"; return -1; } return GetDoc(docid, doc); } int GammaEngine::GetDoc(int docid, Doc &doc) { int ret = 0; if (docids_bitmap_->Test(docid)) { LOG(INFO) << "docid [" << docid << "] is deleted!"; return -1; } std::vector<std::string> index_names; vec_manager_->VectorNames(index_names); std::vector<string> table_fields; ret = table_->GetDocInfo(docid, doc, table_fields); if (ret != 0) { return ret; } std::vector<std::pair<std::string, int>> vec_fields_ids; for (size_t i = 0; i < index_names.size(); ++i) { vec_fields_ids.emplace_back(std::make_pair(index_names[i], docid)); } std::vector<std::string> vec; ret = vec_manager_->GetVector(vec_fields_ids, vec, true); if (ret == 0 && vec.size() == vec_fields_ids.size()) { for (size_t i = 0; i < index_names.size(); ++i) { struct Field field; field.name = index_names[i]; field.datatype = DataType::VECTOR; field.value = vec[i]; doc.AddField(field); } } return ret; } int GammaEngine::BuildIndex() { int running = __sync_fetch_and_add(&b_running_, 1); if (running) { if (vec_manager_->Indexing() != 0) { LOG(ERROR) << "Create index failed!"; return -1; } return 0; } auto func_indexing = std::bind(&GammaEngine::Indexing, this); std::thread t(func_indexing); t.detach(); return 0; } int GammaEngine::Indexing() { if (vec_manager_->Indexing() != 0) { LOG(ERROR) << "Create index failed!"; b_running_ = 0; return -1; } LOG(INFO) << "vector manager indexing success!"; int ret = 0; bool has_error = false; while (b_running_) { if (has_error) { usleep(5000 * 1000); // sleep 5000ms continue; } index_status_ = IndexStatus::INDEXED; bool index_is_dirty = false; int add_ret = vec_manager_->AddRTVecsToIndex(index_is_dirty); if (add_ret < 0) { has_error = true; LOG(ERROR) << "Add real time vectors to index error!"; continue; } if (index_is_dirty == true) { is_dirty_ = true; } usleep(1000 * 1000); // sleep 5000ms } running_cv_.notify_one(); LOG(INFO) << "Build index exited!"; return ret; } int GammaEngine::BuildFieldIndex() { b_field_running_ = true; std::map<std::string, enum DataType> attr_type_map; table_->GetAttrType(attr_type_map); int field_num = attr_type_map.size(); while (b_field_running_) { if (b_loading_) { usleep(5000 * 1000); // sleep 5000ms continue; } #pragma omp parallel for for (int i = 0; i < field_num; ++i) { } usleep(5000 * 1000); // sleep 5000ms } running_field_cv_.notify_one(); LOG(INFO) << "Build field index exited!"; return 0; } int GammaEngine::GetDocsNum() { return max_docid_ - delete_num_; } void GammaEngine::GetIndexStatus(EngineStatus &engine_status) { engine_status.SetIndexStatus(index_status_); long table_mem_bytes = table_->GetMemoryBytes(); long vec_mem_bytes = 0, index_mem_bytes = 0; vec_manager_->GetTotalMemBytes(index_mem_bytes, vec_mem_bytes); long total_mem_b = 0; #ifndef BUILD_GPU long dense_b = 0, sparse_b = 0; if (field_range_index_) { total_mem_b += field_range_index_->MemorySize(dense_b, sparse_b); } // long total_mem_kb = total_mem_b / 1024; // long total_mem_mb = total_mem_kb / 1024; // LOG(INFO) << "Field range memory [" << total_mem_kb << "]kb, [" // << total_mem_mb << "]MB, dense [" << dense_b / 1024 / 1024 // << "]MB sparse [" << sparse_b / 1024 / 1024 // << "]MB"; #endif // BUILD_GPU engine_status.SetTableMem(table_mem_bytes); engine_status.SetIndexMem(index_mem_bytes); engine_status.SetVectorMem(vec_mem_bytes); engine_status.SetFieldRangeMem(total_mem_b); engine_status.SetBitmapMem(docids_bitmap_->BytesSize()); engine_status.SetDocNum(GetDocsNum()); engine_status.SetMaxDocID(max_docid_ - 1); engine_status.SetMinIndexedNum(vec_manager_->MinIndexedNum()); } int GammaEngine::Dump() { int ret = table_->Sync(); if (ret != 0) { LOG(ERROR) << "dump table error, ret=" << ret; return -1; } if (is_dirty_) { int max_docid = max_docid_ - 1; std::time_t t = std::time(nullptr); char tm_str[100]; std::strftime(tm_str, sizeof(tm_str), date_time_format_.c_str(), std::localtime(&t)); string path = dump_path_ + "/" + tm_str; if (!utils::isFolderExist(path.c_str())) { mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } ret = vec_manager_->Dump(path, 0, max_docid); if (ret != 0) { LOG(ERROR) << "dump vector error, ret=" << ret; return -1; } const string dump_done_file = path + "/dump.done"; std::ofstream f_done; f_done.open(dump_done_file); if (!f_done.is_open()) { LOG(ERROR) << "Cannot create file " << dump_done_file; return -1; } f_done << "start_docid " << 0 << std::endl; f_done << "end_docid " << max_docid << std::endl; f_done.close(); if (last_dump_dir_ != "" && utils::remove_dir(last_dump_dir_.c_str())) { LOG(ERROR) << "remove last dump directory error, path=" << last_dump_dir_; } LOG(INFO) << "Dumped to [" << path << "], last dump directory(removed)=" << last_dump_dir_; last_dump_dir_ = path; is_dirty_ = false; } return 0; } int GammaEngine::CreateTableFromLocal(std::string &table_name) { std::vector<string> file_paths = utils::ls(index_root_path_); for (string &file_path : file_paths) { std::string::size_type pos = file_path.rfind(".schema"); if (pos == file_path.size() - 7) { std::string::size_type begin = file_path.rfind('/'); assert(begin != std::string::npos); begin += 1; table_name = file_path.substr(begin, pos - begin); LOG(INFO) << "local table name=" << table_name; TableSchemaIO tio(file_path); TableInfo table; if (tio.Read(table_name, table)) { LOG(ERROR) << "read table schema error, path=" << file_path; return -1; } if (CreateTable(table)) { LOG(ERROR) << "create table error when loading"; return -1; } return 0; } } return -1; } int GammaEngine::Load() { b_loading_ = true; if (!created_table_) { string table_name; if (CreateTableFromLocal(table_name)) { LOG(ERROR) << "create table from local error"; return -1; } LOG(INFO) << "create table from local success, table name=" << table_name; } std::vector<std::pair<std::time_t, string>> folders_tm; std::vector<string> folders = utils::ls_folder(dump_path_); std::vector<string> folders_not_done; for (const string &folder_name : folders) { if (folder_name == "") continue; string folder_path = dump_path_ + "/" + folder_name; string done_file = folder_path + "/dump.done"; if (!utils::file_exist(done_file)) { LOG(INFO) << "done file is not existed, skip it! path=" << done_file; folders_not_done.push_back(folder_path); continue; } struct tm result; strptime(folder_name.c_str(), date_time_format_.c_str(), &result); std::time_t t = std::mktime(&result); folders_tm.push_back(std::make_pair(t, folder_path)); } std::sort(folders_tm.begin(), folders_tm.end(), [](const std::pair<std::time_t, string> &a, const std::pair<std::time_t, string> &b) { return a.first < b.first; }); if (folders_tm.size() > 0) { string dump_done_file = folders_tm[folders_tm.size() - 1].second + "/dump.done"; utils::FileIO fio(dump_done_file); if (fio.Open("r")) { LOG(ERROR) << "Cannot read from file " << dump_done_file; return -1; } long fsize = utils::get_file_size(dump_done_file); char *buf = new char[fsize]; fio.Read(buf, 1, fsize); string buf_str(buf, fsize); std::vector<string> lines = utils::split(buf_str, "\n"); assert(lines.size() == 2); std::vector<string> items = utils::split(lines[1], " "); assert(items.size() == 2); int index_dump_num = (int)std::strtol(items[1].c_str(), nullptr, 10) + 1; LOG(INFO) << "read index_dump_num=" << index_dump_num << " from " << dump_done_file; delete[] buf; } max_docid_ = table_->GetStorageManagerSize(); string last_dir = ""; std::vector<string> dirs; if (folders_tm.size() > 0) { last_dir = folders_tm[folders_tm.size() - 1].second; LOG(INFO) << "Loading from " << last_dir; dirs.push_back(last_dir); } int ret = vec_manager_->Load(dirs, max_docid_); if (ret != 0) { LOG(ERROR) << "load vector error, ret=" << ret << ", path=" << last_dir; return ret; } ret = table_->Load(max_docid_); if (ret != 0) { LOG(ERROR) << "load profile error, ret=" << ret; return ret; } #ifndef BUILD_GPU int field_num = table_->FieldsNum(); for (int i = 0; i < max_docid_; ++i) { for (int j = 0; j < field_num; ++j) { field_range_index_->Add(i, j); } } #endif delete_num_ = 0; for (int i = 0; i < max_docid_; ++i) { if (docids_bitmap_->Test(i)) { ++delete_num_; } } if (not b_running_ and index_status_ == UNINDEXED) { if (max_docid_ >= indexing_size_) { LOG(INFO) << "Begin indexing. indexing_size=" << indexing_size_; this->BuildIndex(); } } // remove directorys which are not done for (const string &folder : folders_not_done) { if (utils::remove_dir(folder.c_str())) { LOG(ERROR) << "clean error, not done directory=" << folder; } } last_dump_dir_ = last_dir; LOG(INFO) << "load engine success! max docid=" << max_docid_ << ", load directory=" << last_dir << ", clean directorys(not done)=" << utils::join(folders_not_done, ','); b_loading_ = false; return 0; } int GammaEngine::AddNumIndexFields() { int retvals = 0; std::map<std::string, enum DataType> attr_type; retvals = table_->GetAttrType(attr_type); std::map<std::string, bool> attr_index; retvals = table_->GetAttrIsIndex(attr_index); for (const auto &it : attr_type) { string field_name = it.first; const auto &attr_index_it = attr_index.find(field_name); if (attr_index_it == attr_index.end()) { LOG(ERROR) << "Cannot find field [" << field_name << "]"; continue; } bool is_index = attr_index_it->second; if (not is_index) { continue; } int field_idx = table_->GetAttrIdx(field_name); LOG(INFO) << "Add range field [" << field_name << "]"; field_range_index_->AddField(field_idx, it.second); } return retvals; } int GammaEngine::PackResults(const GammaResult *gamma_results, Response &response_results, Request &request) { for (int i = 0; i < request.ReqNum(); ++i) { struct SearchResult result; result.total = gamma_results[i].total; result.result_items.resize(gamma_results[i].results_count); for (int j = 0; j < gamma_results[i].results_count; ++j) { VectorDoc *vec_doc = gamma_results[i].docs[j]; struct ResultItem result_item; PackResultItem(vec_doc, request, result_item); result.result_items[j] = std::move(result_item); } result.msg = "Success"; result.result_code = SearchResultCode::SUCCESS; response_results.AddResults(std::move(result)); } return 0; } int GammaEngine::PackResultItem(const VectorDoc *vec_doc, Request &request, struct ResultItem &result_item) { result_item.score = vec_doc->score; Doc doc; int docid = vec_doc->docid; std::vector<std::string> &vec_fields = request.Fields(); // add vector into result size_t fields_size = vec_fields.size(); if (fields_size != 0) { std::vector<std::pair<string, int>> vec_fields_ids; std::vector<string> table_fields; for (size_t i = 0; i < fields_size; ++i) { std::string &name = vec_fields[i]; if (!vec_manager_->Contains(name)) { table_fields.push_back(name); } else { vec_fields_ids.emplace_back(std::make_pair(name, docid)); } } std::vector<string> vec; int ret = vec_manager_->GetVector(vec_fields_ids, vec, true); table_->GetDocInfo(docid, doc, table_fields); if (ret == 0 && vec.size() == vec_fields_ids.size()) { for (size_t i = 0; i < vec_fields_ids.size(); ++i) { const string &field_name = vec_fields_ids[i].first; result_item.names.emplace_back(std::move(field_name)); result_item.values.emplace_back(vec[i]); } } else { // get vector error // TODO : release extra field ; } } else { std::vector<string> table_fields; table_->GetDocInfo(docid, doc, table_fields); } std::vector<struct Field> &fields = doc.TableFields(); for (struct Field &field : fields) { result_item.names.emplace_back(std::move(field.name)); result_item.values.emplace_back(std::move(field.value)); } cJSON *extra_json = cJSON_CreateObject(); cJSON *vec_result_json = cJSON_CreateArray(); cJSON_AddItemToObject(extra_json, EXTRA_VECTOR_RESULT.c_str(), vec_result_json); for (int i = 0; i < vec_doc->fields_len; ++i) { VectorDocField *vec_field = vec_doc->fields + i; cJSON *vec_field_json = cJSON_CreateObject(); cJSON_AddStringToObject(vec_field_json, EXTRA_VECTOR_FIELD_NAME.c_str(), vec_field->name.c_str()); string source = string(vec_field->source, vec_field->source_len); cJSON_AddStringToObject(vec_field_json, EXTRA_VECTOR_FIELD_SOURCE.c_str(), source.c_str()); cJSON_AddNumberToObject(vec_field_json, EXTRA_VECTOR_FIELD_SCORE.c_str(), vec_field->score); cJSON_AddItemToArray(vec_result_json, vec_field_json); } char *extra_data = cJSON_PrintUnformatted(extra_json); result_item.extra = std::string(extra_data, std::strlen(extra_data)); free(extra_data); cJSON_Delete(extra_json); return 0; } int GammaEngine::GetConfig(Config &conf) { conf.ClearCacheInfos(); vec_manager_->GetAllCacheSize(conf); uint32_t table_cache_size = 0; uint32_t str_cache_size = 0; table_->GetCacheSize(table_cache_size, str_cache_size); if (table_cache_size > 0) { conf.AddCacheInfo("table", (int)table_cache_size); } if (str_cache_size > 0) { conf.AddCacheInfo("string", (int)str_cache_size); } return 0; } int GammaEngine::SetConfig(Config &conf) { uint32_t table_cache_size = 0; uint32_t str_cache_size = 0; for (auto &c : conf.CacheInfos()) { if (c.field_name == "table" && c.cache_size > 0) { table_cache_size = (uint32_t)c.cache_size; } else if (c.field_name == "string" && c.cache_size > 0) { str_cache_size = (uint32_t)c.cache_size; } else { vec_manager_->AlterCacheSize(c); } } table_->AlterCacheSize(table_cache_size, str_cache_size); GetConfig(conf); return 0; } } // namespace tig_gamma
/** * @authors Moe_Sakiya sakiya@tun.moe * @date 2017-11-11 21:47:23 * */ #include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <algorithm> using namespace std; int tenpw(int a); int main(void) { char str[1001]; int num[1000], numptr, isNull, i, j, len; while (~scanf("%s", str)) { //变量初始化 len = strlen(str); numptr = 0; isNull = 1; //对字符串的逆序处理 for (i = --len; i >= 0; i--) { //读入并相减判断 if (str[i] == '5' ) { if (isNull == 0) numptr++; //如果为空什么都不做 } else { //处理数据部分 isNull = 0; num[numptr] = 0; //对读入的第一个数进行处理 num[numptr] += str[i] - '0'; //对接下来的数进行处理 for (j = 1; (str[i - j] != '5') && (i - j >= 0); j++) { num[numptr] += (str[i - j] - '0') * tenpw(j); } //结束处理 isNull = 1; numptr++; i -= j; } } //排序 sort(num, num + numptr); //吐出来 for (i = 0; i < numptr; i++) { printf("%d", num[i] ); if(i!=numptr-1) printf(" "); } printf("\n"); } return 0; } int tenpw(int a) { int i, tmp; tmp = 1; for (i = 0; i < a; i++ ) { tmp *= 10; } return tmp; }
#include "threepp/threepp.hpp" using namespace threepp; namespace { class CustomSineCurve : public Curve3 { public: float scale; explicit CustomSineCurve(float scale) : scale(scale) {} void getPoint(float t, Vector3 &target) override { float tx = t * 3 - 1.5f; float ty = std::sin(math::PI * 2 * t); float tz = 0; target.set(tx, ty, tz).multiplyScalar(scale); } }; }// namespace int main() { Canvas canvas; auto scene = Scene::create(); auto camera = PerspectiveCamera::create(75, canvas.getAspect(), 0.1f, 1000); camera->position.z = 20; GLRenderer renderer(canvas); renderer.setSize(canvas.getSize()); OrbitControls controls{camera, canvas}; auto curve = std::make_shared<CustomSineCurve>(10.f); const auto geometry = TubeGeometry::create(curve); const auto material = MeshBasicMaterial::create(); material->color.setHex(0xff0000); material->wireframe = true; auto mesh = Mesh::create(geometry, material); scene->add(mesh); canvas.animate([&]() { renderer.render(scene, camera); }); }
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include "atlas/grid/detail/partitioner/MatchingMeshPartitionerSphericalPolygon.h" #include <vector> #include "eckit/log/ProgressTimer.h" #include "atlas/grid/Grid.h" #include "atlas/grid/Iterator.h" #include "atlas/mesh/Nodes.h" #include "atlas/parallel/mpi/mpi.h" #include "atlas/runtime/Exception.h" #include "atlas/runtime/Log.h" #include "atlas/util/SphericalPolygon.h" namespace atlas { namespace grid { namespace detail { namespace partitioner { namespace { PartitionerBuilder<MatchingMeshPartitionerSphericalPolygon> __builder( "spherical-polygon" ); } void MatchingMeshPartitionerSphericalPolygon::partition( const Grid& grid, int partitioning[] ) const { const eckit::mpi::Comm& comm = atlas::mpi::comm(); const int mpi_rank = int( comm.rank() ); const int mpi_size = int( comm.size() ); ATLAS_TRACE( "MatchingMeshPartitionerSphericalPolygon::partition" ); ATLAS_ASSERT( grid.domain().global() ); Log::debug() << "MatchingMeshPartitionerSphericalPolygon::partition" << std::endl; // FIXME: THIS IS A HACK! the coordinates include North/South Pole (first/last // partitions only) bool includesNorthPole = ( mpi_rank == 0 ); bool includesSouthPole = ( mpi_rank == mpi_size - 1 ); const util::SphericalPolygon poly( prePartitionedMesh_.polygon( 0 ), prePartitionedMesh_.nodes().lonlat() ); const double maxlat = poly.coordinatesMax().lat(); const double minlat = poly.coordinatesMin().lat(); auto at_the_pole = [&]( const PointLonLat& P ) { return ( includesNorthPole && P.lat() >= maxlat ) || ( includesSouthPole && P.lat() < minlat ); }; { eckit::ProgressTimer timer( "Partitioning", grid.size(), "point", double( 10 ), atlas::Log::trace() ); size_t i = 0; for ( const PointXY Pxy : grid.xy() ) { ++timer; const PointLonLat P = grid.projection().lonlat( Pxy ); partitioning[i++] = at_the_pole( P ) || poly.contains( P ) ? mpi_rank : -1; } } // Synchronize partitioning, do a sanity check comm.allReduceInPlace( partitioning, grid.size(), eckit::mpi::Operation::MAX ); const int min = *std::min_element( partitioning, partitioning + grid.size() ); if ( min < 0 ) { throw_Exception( "Could not find partition for target node (source " "mesh does not contain all target grid points)", Here() ); } } } // namespace partitioner } // namespace detail } // namespace grid } // namespace atlas
// // Copyright (C) 2006-2011 Christoph Sommer <christoph.sommer@uibk.ac.at> // // Documentation for these modules is at http://veins.car2x.org/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include "applications/traci/TraCIDemo.h" #include "ModuleAccess.h" #include "NodeStatus.h" #include "UDPSocket.h" Define_Module(TraCIDemo); simsignal_t TraCIDemo::mobilityStateChangedSignal = registerSignal("mobilityStateChanged"); void TraCIDemo::initialize(int stage) { cSimpleModule::initialize(stage); if (stage == 0) { sentMessage = false; } else if (stage == 3) { bool isOperational; NodeStatus *nodeStatus = dynamic_cast<NodeStatus *>(findContainingNode(this)->getSubmodule("status")); isOperational = (!nodeStatus) || nodeStatus->getState() == NodeStatus::UP; if (!isOperational) throw cRuntimeError("This module doesn't support starting in node DOWN state"); traci = TraCIMobilityAccess().get(); traci->subscribe(mobilityStateChangedSignal, this); setupLowerLayer(); } } void TraCIDemo::setupLowerLayer() { socket.setOutputGate(gate("udp$o")); socket.joinLocalMulticastGroups(); socket.bind(12345); socket.setBroadcast(true); } void TraCIDemo::handleMessage(cMessage* msg) { if (msg->isSelfMessage()) { handleSelfMsg(msg); } else { handleLowerMsg(msg); } } void TraCIDemo::handleSelfMsg(cMessage* msg) { } void TraCIDemo::handleLowerMsg(cMessage* msg) { if (!sentMessage) sendMessage(); delete msg; } void TraCIDemo::receiveSignal(cComponent *source, simsignal_t signalID, cObject *obj) { Enter_Method_Silent(); if (signalID == mobilityStateChangedSignal) { handlePositionUpdate(); } } void TraCIDemo::sendMessage() { sentMessage = true; cPacket* newMessage = new cPacket(); socket.sendTo(newMessage, IPv4Address::ALL_HOSTS_MCAST, 12345); } void TraCIDemo::handlePositionUpdate() { if (traci->getPosition().x < 7350) { if (!sentMessage) sendMessage(); } }
// Copyright (c) 2011 Sirikata Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE file. #include <sirikata/oh/Platform.hpp> #include "ManualObjectQueryProcessor.hpp" static int oh_manual_query_plugin_refcount = 0; SIRIKATA_PLUGIN_EXPORT_C const char* name() { return "oh-manual-query"; } SIRIKATA_PLUGIN_EXPORT_C int increfcount() { return ++oh_manual_query_plugin_refcount; } SIRIKATA_PLUGIN_EXPORT_C int decrefcount() { assert(oh_manual_query_plugin_refcount>0); return --oh_manual_query_plugin_refcount; } SIRIKATA_PLUGIN_EXPORT_C int refcount() { return oh_manual_query_plugin_refcount; } SIRIKATA_PLUGIN_EXPORT_C void init() { using namespace Sirikata; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; if (oh_manual_query_plugin_refcount == 0) { Sirikata::OH::ObjectQueryProcessorFactory::getSingleton().registerConstructor( "manual", std::tr1::bind( &Sirikata::OH::Manual::ManualObjectQueryProcessor::create, _1, _2 ) ); } oh_manual_query_plugin_refcount++; } SIRIKATA_PLUGIN_EXPORT_C void destroy() { if (oh_manual_query_plugin_refcount==0) { Sirikata::OH::ObjectQueryProcessorFactory::getSingleton().unregisterConstructor("manual"); } }
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "op/bounded_relu.hpp" #include "ngraph/util.hpp" using namespace std; using namespace ngraph; op::BoundedRelu::BoundedRelu(shared_ptr<Node> arg, float alpha) : UnaryElementwiseArithmetic("BoundedRelu", {arg}), m_alpha(alpha) { constructor_validate_and_infer_types(); set_output_type(0, arg->get_element_type(), arg->get_shape()); } shared_ptr<Node> op::BoundedRelu::copy_with_new_args( const NodeVector& new_args) const { if (new_args.size() != 1) { throw ngraph_error("Incorrect number of new arguments"); } return make_shared<BoundedRelu>(new_args.at(0), m_alpha); }
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Some utility functions for use with command-line utilities. */ #include "DexFile.h" #include "ZipArchive.h" #include "CmdUtils.h" #include <stdlib.h> #include <string.h> #include <strings.h> #include <fcntl.h> #include <errno.h> #ifndef O_BINARY #define O_BINARY 0 #endif /* * Extract "classes.dex" from archive file. * * If "quiet" is set, don't report common errors. */ UnzipToFileResult dexUnzipToFile(const char* zipFileName, const char* outFileName, bool quiet) { UnzipToFileResult result = kUTFRSuccess; static const char* kFileToExtract = "classes.dex"; ZipArchive archive; ZipEntry entry; bool unlinkOnFailure = false; int fd = -1; if (dexZipOpenArchive(zipFileName, &archive) != 0) { if (!quiet) { fprintf(stderr, "Unable to open '%s' as zip archive\n", zipFileName); } result = kUTFRNotZip; goto bail; } fd = open(outFileName, O_WRONLY | O_CREAT | O_EXCL, 0600); if (fd < 0) { fprintf(stderr, "Unable to create output file '%s': %s\n", outFileName, strerror(errno)); result = kUTFROutputFileProblem; goto bail; } unlinkOnFailure = true; entry = dexZipFindEntry(&archive, kFileToExtract); if (entry == NULL) { if (!quiet) { fprintf(stderr, "Unable to find '%s' in '%s'\n", kFileToExtract, zipFileName); } result = kUTFRNoClassesDex; goto bail; } if (dexZipExtractEntryToFile(&archive, entry, fd) != 0) { fprintf(stderr, "Extract of '%s' from '%s' failed\n", kFileToExtract, zipFileName); result = kUTFRBadZip; goto bail; } bail: if (fd >= 0) close(fd); if (unlinkOnFailure && result != kUTFRSuccess) unlink(outFileName); dexZipCloseArchive(&archive); return result; } /* * Map the specified DEX file read-only (possibly after expanding it into a * temp file from a Jar). Pass in a MemMapping struct to hold the info. * If the file is an unoptimized DEX file, then byte-swapping and structural * verification are performed on it before the memory is made read-only. * * The temp file is deleted after the map succeeds. * * This is intended for use by tools (e.g. dexdump) that need to get a * read-only copy of a DEX file that could be in a number of different states. * * If "tempFileName" is NULL, a default value is used. The temp file is * deleted after the map succeeds. * * If "quiet" is set, don't report common errors. * * Returns 0 (kUTFRSuccess) on success. */ UnzipToFileResult dexOpenAndMap(const char* fileName, const char* tempFileName, MemMapping* pMap, bool quiet) { UnzipToFileResult result = kUTFRGenericFailure; int len = strlen(fileName); char tempNameBuf[32]; bool removeTemp = false; int fd = -1; if (len < 5) { if (!quiet) { fprintf(stderr, "ERROR: filename must end in .dex, .zip, .jar, or .apk\n"); } result = kUTFRBadArgs; goto bail; } if (strcasecmp(fileName + len -3, "dex") != 0) { if (tempFileName == NULL) { /* * Try .zip/.jar/.apk, all of which are Zip archives with * "classes.dex" inside. We need to extract the compressed * data to a temp file, the location of which varies. * * On the device we must use /sdcard because most other * directories aren't writable (either because of permissions * or because the volume is mounted read-only). On desktop * it's nice to use the designated temp directory. */ if (access("/tmp", W_OK) == 0) { sprintf(tempNameBuf, "/tmp/dex-temp-%d", getpid()); } else if (access("/sdcard", W_OK) == 0) { sprintf(tempNameBuf, "/sdcard/dex-temp-%d", getpid()); } else { fprintf(stderr, "NOTE: /tmp and /sdcard unavailable for temp files\n"); sprintf(tempNameBuf, "dex-temp-%d", getpid()); } tempFileName = tempNameBuf; } result = dexUnzipToFile(fileName, tempFileName, quiet); if (result == kUTFRSuccess) { //printf("+++ Good unzip to '%s'\n", tempFileName); fileName = tempFileName; removeTemp = true; } else if (result == kUTFRNotZip) { if (!quiet) { fprintf(stderr, "Not Zip, retrying as DEX\n"); } } else { if (!quiet && result == kUTFRNoClassesDex) { fprintf(stderr, "Zip has no classes.dex\n"); } goto bail; } } result = kUTFRGenericFailure; /* * Pop open the (presumed) DEX file. */ fd = open(fileName, O_RDONLY | O_BINARY); if (fd < 0) { if (!quiet) { fprintf(stderr, "ERROR: unable to open '%s': %s\n", fileName, strerror(errno)); } goto bail; } if (sysMapFileInShmemWritableReadOnly(fd, pMap) != 0) { fprintf(stderr, "ERROR: Unable to map '%s'\n", fileName); goto bail; } /* * This call will fail if the file exists on a filesystem that * doesn't support mprotect(). If that's the case, then the file * will have already been mapped private-writable by the previous * call, so we don't need to do anything special if this call * returns non-zero. */ sysChangeMapAccess(pMap->addr, pMap->length, true, pMap); if (dexSwapAndVerifyIfNecessary((u1*) pMap->addr, pMap->length)) { fprintf(stderr, "ERROR: Failed structural verification of '%s'\n", fileName); goto bail; } /* * Similar to above, this call will fail if the file wasn't ever * read-only to begin with. This is innocuous, though it is * undesirable from a memory hygiene perspective. */ sysChangeMapAccess(pMap->addr, pMap->length, false, pMap); /* * Success! Close the file and return with the start/length in pMap. */ result = kUTFRSuccess; bail: if (fd >= 0) close(fd); if (removeTemp) { /* this will fail if the OS doesn't allow removal of a mapped file */ if (unlink(tempFileName) != 0) { fprintf(stderr, "WARNING: unable to remove temp '%s'\n", tempFileName); } } return result; }
 #include <iostream> //#include <boost/type_index.hpp> using namespace std; //#pragma warning(disable : 4996) //3.1 namespace _nmsp1 { //TC的泛化版本 //template <typename T,typename U> template <typename T=int, typename U=int> struct TC { TC() { cout << "TC泛化版本的构造函数" << endl; } void functest1() { cout << "functest1泛化版本" << endl; } }; //TC的特化版本 //template <typename T = char> template <typename T> struct TC<T, int> { }; } //3.2 namespace _nmsp2 { template <typename T,typename U = T*> struct TC { //.... }; } //3.3 namespace _nmsp3 { //声明1,指定了V和W template <typename T,typename U, typename V = int,typename W = char> struct TC; //声明2,指定U template <typename T, typename U = char, typename V, typename W> struct TC; //定义泛化版本的TC template <typename T, typename U, typename V, typename W> struct TC { //... }; //4 typedef TC<int, float> IF_TC; using IF_TCU = TC<int, float>; } //5 namespace _nmsp4 { template <typename T , typename U ,size_t arrsize=8> //template <typename T, typename U, auto arrsize = 8> struct TC { T m_arr[arrsize]; //这个arrsize是在编译器期间,编译器就会传递进来arrsize的大小来确定数组m_arr的大小。 void functest2(); }; template <typename T, typename U, size_t arrsize> //template <typename T, typename U, auto arrsize> void TC<T,U, arrsize >::functest2() { cout << "functest2泛化版本" << endl; } } namespace _nmsp5 { template <const char *p> struct TC2 { TC2() { printf("TC2::TC2执行了,p= %s\n", p); } }; //const char* g_s = "hello"; //全局指针 const char g_s[] = "hello"; } int main() { /***** 第二节 类模板、变量模板、别名模板 三:缺省参数 3.1 常规缺省参数 类型模板参数缺省值的规矩:如果某个模板参数有缺省值,那么从这个有缺省值的模板参数开始, 后面的所有模板参数都得有缺省值。 类模板片特化版本中的类型模板参数不可以有缺省值。 3.2 后面的模板参数依赖前面的模板参数 3.3 在模板声明中指定缺省参数 四:类型别名 考虑到类型名比较长,所以 一般都用typedef ,或者using给这些类型名起一个额外的别名来简化书写。 五:非类型模板参数 数字是常量.类型一般也限制在整型、指针类型等等。 (1)全局指针不能作为函数参数 (2)字符串常量也无法作为模板参数 c++标准委员会有些特殊考虑。 TC2<"hello"> 为什么不允许浮点类型数字作为非类型模板参数,因为其保存的不是一个精确数字。 TC3<2.1111111>和TC3<2.11111109> ******/ //_nmsp1::TC<> mytc5; //使用了缺省模板参数,所以<>中啥也不用提供 //_nmsp1::TC<double> mytc6; //<>中第一个类型不使用缺省参数,第二个类型使用缺省参数 /*_nmsp2::TC<double> mytc5; _nmsp2::TC<double,int> mytc6;*/ //_nmsp3::TC<int> mytc; //第二、三、四个模板参数采用缺省值,所以<>里只提供了一个类型模板实参 //_nmsp3::IF_TC mytc10; //IF_TC等价于TC<int, float> ,所以整个代码行等价于:_nmsp3::TC<int, float> mytc10; //_nmsp3::IF_TCU mytc11; //IF_TCU等价于TC<int, float> /* _nmsp4::TC<double, double> mytc30; //缺省的第三个模板参数是8 for (size_t i = 0; i < 8; ++i) { mytc30.m_arr[i] = static_cast<double>(i); } cout << mytc30.m_arr[7] << endl; //7 _nmsp4::TC<double, double,18> mytc31; mytc31.m_arr[10] = 16.8; cout << mytc31.m_arr[10] << endl; //16.8 */ _nmsp5::TC2<_nmsp5::g_s> mytc40; //_nmsp5::TC2<"hello"> mytc41; return 0; }
 #include "SequencerException.h" using namespace strange::extensions::sequencer::api; namespace strange { namespace extensions { namespace sequencer { namespace impl { SequencerExceptionType SequencerException::gettype() const { return privatetype; } void SequencerException::settype(const SequencerExceptionType& value) { privatetype = value; } SequencerException::SequencerException() : Exception() { } SequencerException::SequencerException(const std::wstring& message, SequencerExceptionType exceptionType) : Exception(message) { settype(exceptionType); } } } } }
#include "oloop_query.h" #include "indexbits.h" #include "asyncpool.h" #include "tablepartitioned.h" #include "internoderouter.h" using namespace openset::async; using namespace openset::query; using namespace openset::result; // yes, we are passing queryMacros by value to get a copy OpenLoopQuery::OpenLoopQuery( ShuttleLambda<CellQueryResult_s>* shuttle, Database::TablePtr table, Macro_s macros, openset::result::ResultSet* result, int instance) : OpenLoop(table->getName(), oloopPriority_e::realtime), // queries are high priority and will preempt other running cells macros(std::move(macros)), shuttle(shuttle), table(table), parts(nullptr), maxLinearId(0), currentLinId(-1), interpreter(nullptr), instance(instance), runCount(0), startTime(0), population(0), index(nullptr), result(result) {} OpenLoopQuery::~OpenLoopQuery() { if (interpreter) { // free up any segment bits we may have made //for (auto bits : interpreter->segmentIndexes) // delete bits; delete interpreter; } } void OpenLoopQuery::prepare() { parts = table->getPartitionObjects(loop->partition, false); if (!parts) { suicide(); return; } maxLinearId = parts->people.customerCount(); // generate the index for this query indexing.mount(table.get(), macros, loop->partition, maxLinearId); bool countable; index = indexing.getIndex("_", countable); population = index->population(maxLinearId); interpreter = new Interpreter(macros); interpreter->setResultObject(result); // if we are in segment compare mode: if (macros.segments.size()) { std::vector<IndexBits*> segments; for (const auto& segmentName : macros.segments) { if (segmentName == "*"s) { auto tBits = new IndexBits(); tBits->makeBits(maxLinearId, 1); segments.push_back(tBits); } else { if (!parts->segments.count(segmentName)) { shuttle->reply( 0, result::CellQueryResult_s{ instance, {}, openset::errors::Error{ openset::errors::errorClass_e::run_time, openset::errors::errorCode_e::item_not_found, "missing segment '" + segmentName + "'" } } ); suicide(); return; } segments.push_back(parts->segments[segmentName].bits); } } interpreter->setCompareSegments(index, segments); } // map table, partition and select schema properties to the Customer object auto mappedColumns = interpreter->getReferencedColumns(); if (!person.mapTable(table.get(), loop->partition, mappedColumns)) { partitionRemoved(); suicide(); return; } person.setSessionTime(macros.sessionTime); startTime = Now(); } bool OpenLoopQuery::run() { while (true) { if (sliceComplete()) return true; // are we done? This will return the index of the // next set bit until there are no more, or maxLinId is met if (interpreter->error.inError() || !index->linearIter(currentLinId, maxLinearId)) { result->setAccTypesFromMacros(macros); shuttle->reply( 0, CellQueryResult_s { instance, {}, interpreter->error, }); parts->attributes.clearDirty(); suicide(); return false; } if (const auto personData = parts->people.getCustomerByLIN(currentLinId); personData != nullptr) { ++runCount; person.mount(personData); person.prepare(); interpreter->mount(&person); interpreter->exec(); // run the script on this customer - do some magic } } } void OpenLoopQuery::partitionRemoved() { shuttle->reply( 0, CellQueryResult_s { instance, {}, openset::errors::Error { openset::errors::errorClass_e::run_time, openset::errors::errorCode_e::partition_migrated, "please retry query" } }); }
// Generated from C:\Users\xiang\Documents\GitHub\js_parser\ECMAScript.g4 by ANTLR 4.7 #include "ECMAScriptVisitor.h"
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "db.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock("0xcd6210e5fba4f3f62e428ed0d4a5895ff43a327c66cd8ad1b41fbf1ff724bb8e"); static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // starting difficulty is 1 / 2^12 CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "ITTScoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; int64 nMinimumInputValue = CENT / 100; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { if (nVersion > CTransaction::CURRENT_VERSION) return false; BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, true, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n", hash.ToString().substr(0,10).c_str(), mapTx.size()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+10) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = 2 * COIN; //if(nHeight < 17280) // no block reward within the first 3 days // nSubsidy = 0; if(nHeight > 10519200) // no block reward after 5 years nSubsidy = 0; return nSubsidy + nFees; } static const int64 nTargetTimespan = 0.5 * 24 * 60 * 60; // ITTScoin: 0.5 days static const int64 nTargetSpacing = 60; // ITTScoin: 15 seconds static const int64 nInterval = nTargetTimespan / nTargetSpacing; // Thanks: Balthazar for suggesting the following fix // https://bitcointalk.org/index.php?topic=182430.msg1904506#msg1904506 static const int64 nReTargetHistoryFact = 4; // look at 4 times the retarget // interval into the block history // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special difficulty rule for testnet: if (fTestNet) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; if (pindexLast->nHeight > COINFIX1_BLOCK) { blockstogoback = nReTargetHistoryFact * nInterval; } // Go back by what we want to be nReTargetHistoryFact*nInterval blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = 0; if (pindexLast->nHeight > COINFIX1_BLOCK) // obtain average actual timespan nActualTimespan = (pindexLast->GetBlockTime() - pindexFirst->GetBlockTime())/nReTargetHistoryFact; else nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal ittscoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC. int64 nBIP30SwitchTime = 1349049600; bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime); // BIP16 didn't become active until October 1 2012 int64 nBIP16SwitchTime = 1349049600; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); if (fEnforceBIP30) { CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); // if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: // strMiscWarning = _("Warning: this version is obsolete, upgrade required"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (!CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "ITTScoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc0; pchMessageStart[2] = 0xb8; pchMessageStart[3] = 0xdb; hashGenesisBlock = uint256("0x1c2159904f47ae43c7fb4a90185f73d94fa7acd5ba7a30ee54440a2c02ff8a70"); } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis block: // block.nTime = 1434914370 // block.nNonce = 2085386442 // block.GetHash = 384b060671f4a93948e9c168216dadb0ca2fbc54aa11c86b0345b6af1c59b2f5 // CBlock(hash=384b060671f4a93948e9, PoW=00000951e146b0026411, ver=1, // hashPrevBlock=00000000000000000000, hashMerkleRoot=5a2e19825b, // nTime=1434914370, nBits=1e0ffff0, nNonce=2085386442, vtx=1) // CTransaction(hash=5a2e19825b, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d010441746f646f3a207265706c616365207769746820736f6d657468696e67207468617420656e7375726573206e6f207072656d696e696e6720746f6f6b20706c616365) // CTxOut(error) // vMerkleTree: 5a2e19825b // Genesis block const char* pszTimestamp = "todo: replace with something that ensures no premining took place"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 0; txNew.vout[0].scriptPubKey = CScript() << 0x0 << OP_CHECKSIG; // a privkey for that 'vanity' pubkey would be interesting ;) CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1435683246; block.nBits = 0x1e0ffff0; block.nNonce = 407531772; if (fTestNet) { block.nTime = 1434914370; block.nNonce = 387144609; } //// debug print printf("%s\n", block.GetHash().ToString().c_str()); printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0x5a2e19825b4162f68602039040f1e05d9f924ff00a3aff7327ca6abd6f3279bc")); // If genesis block hash does not match, then generate new genesis hash. if (false && block.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) break; if ((block.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); printf("block.GetHash = %s\n", block.GetHash().ToString().c_str()); } block.print(); assert(block.GetHash() == hashGenesisBlock); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file\n", nLoaded); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI if it applies to me if(AppliesToMe()) uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xfc, 0xd9, 0xb7, 0xdd }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%d invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Don't bother if send buffer is too full to respond anyway if (pfrom->vSend.size() >= SendBufferSize()) break; // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size // Litecoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes) bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetPoWHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); loop { unsigned int nHashesDone = 0; //unsigned int nNonceFound; uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (pblock->nNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
#include "pch.h" #include "LayerStack.h" namespace Running { LayerStack::LayerStack() { } LayerStack::~LayerStack() { for (Layer* layer : _layers) { delete layer; } } void LayerStack::PushLayer(Layer* layer) { _layers.emplace(_layers.begin() + _layerInsertIndex, layer); _layerInsertIndex++; } void LayerStack::PopLayer(Layer* layer) { auto it = std::find(_layers.begin(), _layers.end(), layer); if (it != _layers.end()) { _layers.erase(it); _layerInsertIndex--; } } void LayerStack::PushOverlay(Layer* overlay) { _layers.emplace_back(overlay); } void LayerStack::PopOverlay(Layer* overlay) { auto it = std::find(_layers.begin(), _layers.end(), overlay); if (it != _layers.end()) { _layers.erase(it); } } }
// // read_until.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/read_until.hpp> #include <cstring> #include "archetypes/async_result.hpp" #include <boost/asio/io_service.hpp> #include <boost/asio/streambuf.hpp> #include "unit_test.hpp" #if defined(BOOST_ASIO_HAS_BOOST_BIND) # include <boost/bind.hpp> #else // defined(BOOST_ASIO_HAS_BOOST_BIND) # include <functional> #endif // defined(BOOST_ASIO_HAS_BOOST_BIND) class test_stream { public: typedef boost::asio::io_service io_service_type; test_stream(boost::asio::io_service& io_service) : io_service_(io_service), length_(0), position_(0), next_read_length_(0) { } io_service_type& get_io_service() { return io_service_; } void reset(const void* data, size_t length) { using namespace std; // For memcpy. BOOST_ASIO_CHECK(length <= max_length); memcpy(data_, data, length); length_ = length; position_ = 0; next_read_length_ = length; } void next_read_length(size_t length) { next_read_length_ = length; } template <typename Mutable_Buffers> size_t read_some(const Mutable_Buffers& buffers) { size_t n = boost::asio::buffer_copy(buffers, boost::asio::buffer(data_, length_) + position_, next_read_length_); position_ += n; return n; } template <typename Mutable_Buffers> size_t read_some(const Mutable_Buffers& buffers, boost::system::error_code& ec) { ec = boost::system::error_code(); return read_some(buffers); } template <typename Mutable_Buffers, typename Handler> void async_read_some(const Mutable_Buffers& buffers, Handler handler) { size_t bytes_transferred = read_some(buffers); io_service_.post(boost::asio::detail::bind_handler( handler, boost::system::error_code(), bytes_transferred)); } private: io_service_type& io_service_; enum { max_length = 8192 }; char data_[max_length]; size_t length_; size_t position_; size_t next_read_length_; }; static const char read_data[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; void test_char_read_until() { boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); std::size_t length = boost::asio::read_until(s, sb1, 'Z'); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, 'Z'); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, 'Z'); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, 'Z', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, 'Z', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, 'Z', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Z', ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Z', ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Z', ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Y', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Y', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, 'Y', ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); } void test_string_read_until() { boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); std::size_t length = boost::asio::read_until(s, sb1, "XYZ"); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, "XYZ"); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, "XYZ"); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, "XYZ", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, "XYZ", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, "XYZ", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "XYZ", ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "XYZ", ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "XYZ", ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "WXY", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "WXY", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, "WXY", ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); } class match_char { public: explicit match_char(char c) : c_(c) {} template <typename Iterator> std::pair<Iterator, bool> operator()( Iterator begin, Iterator end) const { Iterator i = begin; while (i != end) if (c_ == *i++) return std::make_pair(i, true); return std::make_pair(i, false); } private: char c_; }; namespace boost { namespace asio { template <> struct is_match_condition<match_char> { enum { value = true }; }; } // namespace asio } // namespace boost void test_match_condition_read_until() { boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); std::size_t length = boost::asio::read_until(s, sb1, match_char('Z')); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, match_char('Z')); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, match_char('Z')); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, match_char('Z'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, match_char('Z'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb1.consume(sb1.size()); length = boost::asio::read_until(s, sb1, match_char('Z'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Z'), ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Z'), ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Z'), ec); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Y'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Y'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); sb2.consume(sb2.size()); length = boost::asio::read_until(s, sb2, match_char('Y'), ec); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); } void async_read_handler( const boost::system::error_code& err, boost::system::error_code* err_out, std::size_t bytes_transferred, std::size_t* bytes_out, bool* called) { *err_out = err; *bytes_out = bytes_transferred; *called = true; } void test_char_async_read_until() { #if defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = boost; #else // defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = std; using std::placeholders::_1; using std::placeholders::_2; #endif // defined(BOOST_ASIO_HAS_BOOST_BIND) boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; std::size_t length; bool called; s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Z', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Y', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Y', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, 'Y', bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); int i = boost::asio::async_read_until(s, sb2, 'Y', archetypes::lazy_handler()); BOOST_ASIO_CHECK(i == 42); ios.reset(); ios.run(); } void test_string_async_read_until() { #if defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = boost; #else // defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = std; using std::placeholders::_1; using std::placeholders::_2; #endif // defined(BOOST_ASIO_HAS_BOOST_BIND) boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; std::size_t length; bool called; s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "XYZ", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "WXY", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "WXY", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, "WXY", bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); int i = boost::asio::async_read_until(s, sb2, "WXY", archetypes::lazy_handler()); BOOST_ASIO_CHECK(i == 42); ios.reset(); ios.run(); } void test_match_condition_async_read_until() { #if defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = boost; #else // defined(BOOST_ASIO_HAS_BOOST_BIND) namespace bindns = std; using std::placeholders::_1; using std::placeholders::_2; #endif // defined(BOOST_ASIO_HAS_BOOST_BIND) boost::asio::io_service ios; test_stream s(ios); boost::asio::streambuf sb1; boost::asio::streambuf sb2(25); boost::system::error_code ec; std::size_t length; bool called; s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb1.consume(sb1.size()); boost::asio::async_read_until(s, sb1, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 26); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Z'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(ec == boost::asio::error::not_found); BOOST_ASIO_CHECK(length == 0); s.reset(read_data, sizeof(read_data)); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Y'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(1); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Y'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); s.next_read_length(10); ec = boost::system::error_code(); length = 0; called = false; sb2.consume(sb2.size()); boost::asio::async_read_until(s, sb2, match_char('Y'), bindns::bind(async_read_handler, _1, &ec, _2, &length, &called)); ios.reset(); ios.run(); BOOST_ASIO_CHECK(called); BOOST_ASIO_CHECK(!ec); BOOST_ASIO_CHECK(length == 25); s.reset(read_data, sizeof(read_data)); sb2.consume(sb2.size()); int i = boost::asio::async_read_until(s, sb2, match_char('Y'), archetypes::lazy_handler()); BOOST_ASIO_CHECK(i == 42); ios.reset(); ios.run(); } BOOST_ASIO_TEST_SUITE ( "read_until", BOOST_ASIO_TEST_CASE(test_char_read_until) BOOST_ASIO_TEST_CASE(test_string_read_until) BOOST_ASIO_TEST_CASE(test_match_condition_read_until) BOOST_ASIO_TEST_CASE(test_char_async_read_until) BOOST_ASIO_TEST_CASE(test_string_async_read_until) BOOST_ASIO_TEST_CASE(test_match_condition_async_read_until) )
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/phi/infermeta/binary.h" #include <algorithm> #include <vector> #include "paddle/phi/common/data_type.h" #include "paddle/phi/core/ddim.h" #include "paddle/phi/kernels/funcs/common_shape.h" namespace phi { void CompareInferMeta(const MetaTensor& x, const MetaTensor& y, int axis, MetaTensor* out) { auto dim_x = x.dims(); auto dim_y = y.dims(); if (dim_x == dim_y) { out->share_meta(x); } else { int max_dim = std::max(dim_x.size(), dim_y.size()); int axis = std::abs(dim_x.size() - dim_y.size()); std::vector<int> x_dims_array(max_dim); std::vector<int> y_dims_array(max_dim); std::vector<int> out_dims_array(max_dim); funcs::GetBroadcastDimsArrays(dim_x, dim_y, x_dims_array.data(), y_dims_array.data(), out_dims_array.data(), max_dim, axis); out->set_dims(make_ddim(out_dims_array)); out->share_lod(x); } out->set_dtype(DataType::BOOL); } void CompareAllInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out) { auto dim_x = x.dims(); auto dim_y = y.dims(); PADDLE_ENFORCE_GE( dim_x.size(), dim_y.size(), errors::InvalidArgument( "The size of dim_y should not be greater than dim_x's.")); out->share_lod(x); out->set_dims(make_ddim({1})); out->set_dtype(DataType::BOOL); } void DotInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out) { auto x_dims = x.dims(); auto x_rank = static_cast<size_t>(x_dims.size()); PADDLE_ENFORCE_EQ(true, 1 == x_rank || 2 == x_rank, phi::errors::PreconditionNotMet( "ShapeError: The dimensions of input tensor X (%s) " "should be 1 or 2", x_dims.to_str())); auto y_dims = y.dims(); PADDLE_ENFORCE_EQ( true, x_rank == static_cast<size_t>(y_dims.size()), phi::errors::PreconditionNotMet( "ShapeError: The shape of input tensor Y: %s should match with " "input tenosr X: %s", y_dims.to_str(), x_dims.to_str())); bool shape_match = true; for (size_t i = 0; i < x_rank; ++i) { if (x_dims[i] != y_dims[i]) { shape_match = false; break; } } PADDLE_ENFORCE_EQ(true, shape_match, phi::errors::PreconditionNotMet( "ShapeError: The shape of input tensor X: %s should " "be exactly the same " "with input tensor Y: %s", x_dims.to_str(), y_dims.to_str())); x_dims[x_dims.size() - 1] = 1; out->set_dims(x_dims); out->set_dtype(x.dtype()); out->set_layout(x.layout()); } void MatmulInferMeta(const MetaTensor& x, const MetaTensor& y, bool trans_x, bool trans_y, MetaTensor* out) { std::vector<int64_t> dims_x = phi::vectorize(x.dims()); std::vector<int64_t> dims_y = phi::vectorize(y.dims()); auto ndims_x = dims_x.size(); auto ndims_y = dims_y.size(); PADDLE_ENFORCE_GT(ndims_x, 0UL, phi::errors::InvalidArgument( "The Input(x) dims size must be greater than 0," " but reviced dims size is 0. ")); PADDLE_ENFORCE_GT(ndims_y, 0UL, phi::errors::InvalidArgument( "The Input(y) dims size must be greater than 0," " but reviced dims size is 0. ")); bool x_broadcasted = false, y_broadcasted = false; if (ndims_x == 1) { dims_x.insert(dims_x.begin(), 1); ndims_x = 2; x_broadcasted = true; } if (ndims_y == 1) { dims_y.push_back(1); ndims_y = 2; y_broadcasted = true; } size_t M, N; if (trans_x) { M = dims_x[ndims_x - 1]; } else { M = dims_x[ndims_x - 2]; } if (trans_y) { N = dims_y[ndims_y - 2]; } else { N = dims_y[ndims_y - 1]; } std::vector<int64_t> new_dims; if (ndims_x > ndims_y) { new_dims.assign(dims_x.begin(), dims_x.end() - 2); } else if (ndims_x < ndims_y) { new_dims.assign(dims_y.begin(), dims_y.end() - 2); } else { new_dims.reserve(ndims_x); for (size_t i = 0; i < ndims_x - 2; ++i) { new_dims.push_back(std::max(dims_x[i], dims_y[i])); } } if (!x_broadcasted) { new_dims.push_back(M); } if (!y_broadcasted) { new_dims.push_back(N); } if (x_broadcasted && y_broadcasted) { new_dims.push_back(1); } auto ddim_out = phi::make_ddim(new_dims); out->set_dims(ddim_out); out->set_dtype(x.dtype()); out->set_layout(x.layout()); } void ElementwiseInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out) { return ElementwiseRawInferMeta(x, y, -1, std::move(out)); } void ElementwiseRawInferMeta(const MetaTensor& x, const MetaTensor& y, int axis, MetaTensor* out) { if (x.dims() != y.dims()) { auto x_dims = x.dims(); auto y_dims = y.dims(); int max_dim = std::max(x_dims.size(), y_dims.size()); if (x_dims.size() == y_dims.size()) { PADDLE_ENFORCE_EQ((axis == -1) || (axis == 0), true, phi::errors::InvalidArgument( "axis should be -1 or 0 while the dimension of " "tensor X (%s) is equal to the dimension of " "tensor Y (%s), but received axis: %s", x_dims.size(), y_dims.size(), axis)); } PADDLE_ENFORCE_EQ((axis >= (-1 * max_dim)) && (axis < max_dim), true, phi::errors::InvalidArgument( "The axis range must be [%s, %s), but axis is %s. " "Please set the axis again.", -1 * max_dim, max_dim, axis)); axis = (axis < 0 ? (std::abs(x_dims.size() - y_dims.size()) + axis + 1) : axis); std::vector<int> x_dims_array(max_dim); std::vector<int> y_dims_array(max_dim); std::vector<int> out_dims_array(max_dim); funcs::GetBroadcastDimsArrays(x_dims, y_dims, x_dims_array.data(), y_dims_array.data(), out_dims_array.data(), max_dim, axis); auto out_dims = phi::make_ddim(out_dims_array); out->set_dims(out_dims); } else { out->set_dims(x.dims()); } out->set_dtype(x.dtype()); out->set_layout(x.layout()); out->share_lod(x); } void HuberLossInferMeta(const MetaTensor& input, const MetaTensor& label, float delta, MetaTensor* out, MetaTensor* residual, MetaConfig config) { auto input_dims = input.dims(); auto label_dims = label.dims(); PADDLE_ENFORCE_EQ(input_dims.size(), label_dims.size(), phi::errors::InvalidArgument( "Input(input) rank and Input(label) rank should be " "same, but received input rank(%d) != label rank(%d)", input_dims.size(), label_dims.size())); bool contain_unknown_dim = phi::contain_unknown_dim(input_dims) || phi::contain_unknown_dim(label_dims); if (config.is_runtime || !contain_unknown_dim) { PADDLE_ENFORCE_EQ( input_dims, label_dims, phi::errors::InvalidArgument( "The Input(input) and Input(label) should have the same " "shape, but received input shape [%s] != label shape [%s]", input_dims, label_dims)); } auto out_dims = label_dims; residual->set_dims(out_dims); out->set_dims(out_dims); out->share_lod(input); } void TriangularSolveInferMeta(const MetaTensor& x, const MetaTensor& y, bool upper, bool transpose, bool unitriangular, MetaTensor* out) { auto x_dims = x.dims(); auto y_dims = y.dims(); auto x_dims_n = x_dims.size(); auto y_dims_n = y_dims.size(); PADDLE_ENFORCE_GE(x_dims_n, 2, phi::errors::InvalidArgument( "The input tensor X's dimensions of TriangularSolveOp " "should be >= 2. But received X's " "dimensions = %d, X's shape = [%s]", x_dims.size(), x_dims)); PADDLE_ENFORCE_GE(y_dims_n, 2, phi::errors::InvalidArgument( "The input tensor Y's dimensions of TriangularSolveOp " "should be >=2. But received Y's " "dimensions = %d, Y's shape = [%s]", y_dims.size(), y_dims)); PADDLE_ENFORCE_EQ(x_dims[x_dims_n - 2], x_dims[x_dims_n - 1], phi::errors::InvalidArgument( "The inner-most 2 dimensions of Input(X) all should " "be square matrices " "But received X's shape[-2] = %d and shape[-1] = %d.", x_dims[x_dims_n - 2], x_dims[x_dims_n - 1])); std::vector<int64_t> x_dims_vec = phi::vectorize(x_dims); std::vector<int64_t> y_dims_vec = phi::vectorize(y_dims); std::vector<int64_t> x_dims_vec_cut(x_dims_vec.begin(), x_dims_vec.end() - 2); std::vector<int64_t> y_dims_vec_cut(y_dims_vec.begin(), y_dims_vec.end() - 2); std::vector<int64_t> expand_batch_portion = funcs::MatrixGetBroadcastBatchPortion(x_dims_vec_cut, y_dims_vec_cut); std::vector<int64_t> y_broadcast_dims({expand_batch_portion}); y_broadcast_dims.insert(y_broadcast_dims.end(), {y_dims_vec[y_dims_n - 2], y_dims_vec[y_dims_n - 1]}); // dim of 'out' is the same with 'Y' after broadcast out->set_dims(phi::make_ddim(y_broadcast_dims)); out->set_dtype(y.dtype()); out->set_layout(y.layout()); out->share_lod(y); } void IndexSampleInferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out, MetaConfig config) { auto input_dims = x.dims(); PADDLE_ENFORCE_EQ(input_dims.size(), 2, errors::InvalidArgument( "Inputs(X) shape of IndexSample op should be 2-D, but " "got X's shape = [%s], please check X shape.", input_dims)); auto index_dims = y.dims(); PADDLE_ENFORCE_EQ( index_dims.size(), 2, errors::InvalidArgument( "Inputs(Index) shape of IndexSample op should be 2-D, but " "got Index's shape [%s] , please check index shape.", input_dims)); if (config.is_runtime) { PADDLE_ENFORCE_EQ(input_dims[0], index_dims[0], errors::InvalidArgument( "Inputs(X)'s value of dimension 0 must same with " "Inputs(Index)'s value of dimension 0, but " "got %d of Inputs(X), and got %d of Inputs(Index), " "please check Inputs shape.", input_dims[0], index_dims[0])); } out->set_dtype(x.dtype()); out->set_dims(index_dims); out->share_lod(y); } void CrossInferMeta(const MetaTensor& x, const MetaTensor& y, int axis, MetaTensor* out) { auto x_dim = x.dims(); auto y_dim = y.dims(); auto dim = axis; bool dims_match = phi::funcs::CheckDims(x_dim, y_dim); PADDLE_ENFORCE_EQ( dims_match, true, phi::errors::InvalidArgument("The 'shape' of Input(X) should be equal to " "the 'shape' of Input(Y). But received " "Input(X).dimensions = [%s], " "Input(Y).dimensions = [%s]", x_dim, y_dim)); if (dim != DDim::kMaxRank) { PADDLE_ENFORCE_EQ( dim < x_dim.size() && dim >= (0 - x_dim.size()), true, phi::errors::OutOfRange( "Attr(dim) is out of range, It's expected " "to be in range of [-%d, %d]. But received Attr(dim) = %d.", x_dim.size(), x_dim.size() - 1, dim)); if (dim < 0) { dim += x_dim.size(); } PADDLE_ENFORCE_EQ(x_dim[dim] == 3 && y_dim[dim] == 3, true, phi::errors::InvalidArgument( "Input(X/Y).dims()[dim] should be equal to 3." "But received Input(X/Y).dims()[dim] = %d.", x_dim[dim])); } out->set_dims(x_dim); out->set_dtype(x.dtype()); out->set_layout(x.layout()); out->share_lod(x); } void Atan2InferMeta(const MetaTensor& x, const MetaTensor& y, MetaTensor* out) { out->share_meta(x); } void SegmentPoolInferMeta(const MetaTensor& x, const MetaTensor& segment_ids, const std::string& pooltype, MetaTensor* out, MetaTensor* summed_ids, MetaConfig config) { auto dims = x.dims(); dims[0] = -1; out->set_dims(dims); out->set_dtype(x.dtype()); out->set_layout(x.layout()); if (pooltype == "MEAN") { summed_ids->set_dims({-1, 1}); summed_ids->set_dtype(x.dtype()); summed_ids->set_layout(x.layout()); } } void BCELossInferMeta(const MetaTensor& input, const MetaTensor& label, MetaTensor* out, MetaConfig config) { auto input_dims = input.dims(); auto label_dims = label.dims(); int rank = input_dims.size(); PADDLE_ENFORCE_EQ(rank, label_dims.size(), phi::errors::InvalidArgument( "Input(X) and Input(Label) shall have the same rank." "But received: the rank of Input(X) is [%d], " "the rank of Input(Label) is [%d].", rank, label_dims.size())); bool check = true; if ((!config.is_runtime) && (phi::product(input_dims) <= 0 || phi::product(label_dims) <= 0)) { check = false; } if (check) { PADDLE_ENFORCE_EQ(input_dims, label_dims, phi::errors::InvalidArgument( "Input(X) and Input(Label) shall have the same " "shape. But received: the shape of Input(X) is " "[%s], the shape of Input(Label) is [%s].", input_dims, label_dims)); } out->set_dims(input_dims); out->set_dtype(input.dtype()); out->share_lod(input); } void BincountInferMeta(const MetaTensor& x, const paddle::optional<const MetaTensor&> weights, int minlength, MetaTensor* out) { auto input_dim = x.dims(); PADDLE_ENFORCE_GE(minlength, 0, phi::errors::InvalidArgument( "The minlength should be greater than or equal to 0." "But received minlength is %d", minlength)); PADDLE_ENFORCE_EQ( input_dim.size(), 1, phi::errors::InvalidArgument("The 'shape' of Input(X) must be 1-D tensor." "But the dimension of Input(X) is [%d]", input_dim.size())); if (weights.is_initialized()) { auto weights_dim = weights->dims(); PADDLE_ENFORCE_EQ(weights_dim.size(), 1, phi::errors::InvalidArgument( "The 'shape' of Input(Weights) must be 1-D tensor." "But the dimension of Input(Weights) is [%d]", weights_dim.size())); PADDLE_ENFORCE_EQ( weights_dim[0], input_dim[0], phi::errors::InvalidArgument( "The 'shape' of Input(Weights) must be equal to the 'shape' of " "Input(X)." "But received: the 'shape' of Input(Weights) is [%s]," "the 'shape' of Input(X) is [%s]", weights_dim, input_dim)); } out->set_dims(phi::make_ddim({-1})); if (weights.is_initialized()) { out->set_dtype(weights->dtype()); } else { out->set_dtype(x.dtype()); } out->share_lod(x); } void DistInferMeta(const MetaTensor& x, const MetaTensor& y, float p, MetaTensor* out) { auto x_dims = x.dims(); auto y_dims = y.dims(); PADDLE_ENFORCE_NE(phi::product(x_dims), 0, phi::errors::InvalidArgument( "The Input(X) has not been initialized properly. The " "shape of Input(X) = [%s].", x_dims)); PADDLE_ENFORCE_NE(phi::product(y_dims), 0, phi::errors::InvalidArgument( "The Input(Y) has not been initialized properly. The " "shape of Input(Y) = [%s].", y_dims)); out->set_dims({1}); out->set_dtype(x.dtype()); } void GatherNdInferMeta(const MetaTensor& x, const MetaTensor& index, MetaTensor* out) { auto x_dims = x.dims(); auto x_dims_size = x_dims.size(); auto index_dims = index.dims(); auto index_dims_size = index_dims.size(); PADDLE_ENFORCE_LE( index_dims[index_dims_size - 1], x_dims_size, phi::errors::InvalidArgument( "Input(Index).shape[-1] should be no greater than Input(X).rank")); PADDLE_ENFORCE_GE(index_dims_size, 1UL, phi::errors::InvalidArgument( "The rank of Input(Index) should be greater than 1")); std::vector<int64_t> result_dims; // The result dims is // Index.shape[:-1] + X.shape[Index.shape[-1]:] for (int i = 0; i < index_dims_size - 1; ++i) { result_dims.emplace_back(index_dims[i]); } for (int i = index_dims[index_dims_size - 1]; i < x_dims_size; ++i) { result_dims.emplace_back(x_dims[i]); } out->set_dims(phi::make_ddim(result_dims)); out->share_lod(x); out->set_dtype(x.dtype()); } void GatherTreeMeta(const MetaTensor& ids, const MetaTensor& parents, MetaTensor* out) { auto ids_dims = ids.dims(); auto parents_dims = parents.dims(); PADDLE_ENFORCE_EQ(ids_dims == parents_dims, true, phi::errors::InvalidArgument( "The shape of Input(Parents) must be same with the " "shape of Input(Ids).")); out->set_dims(ids_dims); } void LogLossInferMeta(const MetaTensor& input, const MetaTensor& label, float epsilon, MetaTensor* out, MetaConfig config) { auto pred_dims = input.dims(); auto label_dims = label.dims(); if (config.is_runtime || (phi::product(pred_dims) > 0 && phi::product(label_dims) > 0)) { PADDLE_ENFORCE_EQ( pred_dims, label_dims, phi::errors::InvalidArgument( "The dimensions of Input(Predicted) must be equal to the" "dimensions of Input(Labels), but received dimensions of " "Input(Predicted)" "is [%s], received dimensions of Input(Labels) is [%s].", pred_dims, label_dims)); } PADDLE_ENFORCE_EQ(pred_dims.size(), 2, phi::errors::InvalidArgument( "The dimensions of Input(Predicted) must be 2," "But received dimensions of Input(Predicted)" "is [%d]", pred_dims.size())); if (config.is_runtime) { PADDLE_ENFORCE_EQ(pred_dims[1], 1, phi::errors::InvalidArgument( "Each row of Input(Predicted) contains a real value, " "so the 2nd dimension of Input(X) must be 1," "But got [%d]", pred_dims[1])); } out->set_dims({pred_dims[0], 1}); out->set_dtype(input.dtype()); out->share_lod(input); } void MvInferMeta(const MetaTensor& x, const MetaTensor& vec, MetaTensor* out) { auto dim_x = x.dims(); auto dim_vec = vec.dims(); PADDLE_ENFORCE_EQ( dim_x.size(), 2, phi::errors::InvalidArgument("The rank of input X should be 2, but is %d", dim_x.size())); PADDLE_ENFORCE_EQ( dim_vec.size(), 1, phi::errors::InvalidArgument( "The rank of input Vec should be 1, but is %d", dim_vec.size())); PADDLE_ENFORCE_EQ(dim_x[1], dim_vec[0], phi::errors::InvalidArgument( "X's second dimension is expected to be equal to " "Vec's first dimension" "but recieved X'shape = [%s], Vec's shape = [%s]", dim_x, dim_vec)); auto dim_out = phi::make_ddim({dim_x[0]}); out->set_dims(dim_out); out->set_dtype(x.dtype()); out->set_layout(x.layout()); out->share_lod(x); } void SigmoidCrossEntropyWithLogitsInferMeta(const MetaTensor& x, const MetaTensor& label, bool normalize, int ignore_index, MetaTensor* out, MetaConfig config) { auto x_dims = x.dims(); auto labels_dims = label.dims(); int rank = x_dims.size(); PADDLE_ENFORCE_EQ(rank, labels_dims.size(), phi::errors::InvalidArgument( "Input(X) and Input(Label) shall have the same rank." "But received: the rank of Input(X) is [%d], " "the rank of Input(Label) is [%d].", rank, labels_dims.size())); bool check = true; if ((!config.is_runtime) && (phi::product(x_dims) <= 0 || phi::product(labels_dims) <= 0)) { check = false; } if (check) { PADDLE_ENFORCE_EQ( phi::slice_ddim(x_dims, 0, rank), phi::slice_ddim(labels_dims, 0, rank), phi::errors::InvalidArgument( "Input(X) and Input(Label) shall have the same shape " "except the last dimension. But received: the shape of " "Input(X) is [%s], the shape of Input(Label) is [%s].", x_dims, labels_dims)); } out->set_dims(x_dims); out->set_dtype(x.dtype()); out->share_lod(x); } } // namespace phi
#include <iostream> #include <algorithm> #include <cstdio> #include <algorithm> #include <math.h> #include <vector> #define maxN 100001 #define X first #define Y second #define d(a, b) ((a.X - b.X)*(a.X - b.X) + (a.Y - b.Y)*(a.Y - b.Y)) #define eps 1e-9 typedef long maxn; typedef long long maxa; typedef std::pair <maxa, maxa> p_t; maxn n, st, id[maxN]; p_t co[maxN]; double ang[maxN]; void Prepare() { std::cin >> n; for (maxn i = 0; i < n; i++) std::cin >> co[i].X >> co[i].Y, st = co[st].Y > co[i].Y ? i : co[st].Y == co[i].Y && co[st].X > co[i].X ? i : st, id[i] = i; } p_t toVec(p_t a, p_t b) { p_t v; v.X = b.X - a.X, v.Y = b.Y - a.Y; return v; } double cross(p_t a, p_t b) { return a.X * b.Y - a.Y * b.X; } bool ccw(p_t p, p_t q, p_t r) { return cross(toVec(p, q), toVec(p, r)) > 0; } bool collinear(p_t p, p_t q, p_t r) { return fabs(cross(toVec(p, q), toVec(p, r))) < eps; } bool cmp(const maxn x, const maxn y) { if (collinear(co[st], co[x], co[y])) return d(co[st], co[x]) < d(co[st], co[y]); return ang[x] > ang[y]; } void Process() { p_t v0; v0.X = 1, v0.Y = 0; maxa d0 = 1; for (maxn i = 0; i < n; i++) { if (i == st) continue; p_t v; v.X = co[i].X - co[st].X, v.Y = co[i].Y - co[st].Y; maxa dv = d(co[i], co[st]); ang[i] = (v0.X * v.X + v0.Y * v.Y) / (double)sqrt(d0 * dv); } std::sort(id, id + n, cmp); std::cout << co[st].X << co[st].Y << '\n'; for (maxn i = 0; i < n; i++) if (id[i] != st) std::cout << co[id[i]].X << ' ' << co[id[i]].Y << '\n'; } int main() { //freopen("closedpath.inp", "r", stdin); //freopen("closedpath.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); Prepare(); Process(); }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "Terminal.hpp" #include "../../terminal/parser/OutputStateMachineEngine.hpp" #include "TerminalDispatch.hpp" #include "../../inc/unicode.hpp" #include "../../inc/DefaultSettings.h" #include "../../inc/argb.h" #include "../../types/inc/utils.hpp" #include "../../types/inc/colorTable.hpp" #include <winrt/Microsoft.Terminal.Core.h> using namespace winrt::Microsoft::Terminal::Core; using namespace Microsoft::Terminal::Core; using namespace Microsoft::Console; using namespace Microsoft::Console::Render; using namespace Microsoft::Console::Types; using namespace Microsoft::Console::VirtualTerminal; using PointTree = interval_tree::IntervalTree<til::point, size_t>; static std::wstring _KeyEventsToText(std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) { std::wstring wstr = L""; for (const auto& ev : inEventsToWrite) { if (ev->EventType() == InputEventType::KeyEvent) { const auto& k = static_cast<KeyEvent&>(*ev); const auto wch = k.GetCharData(); wstr += wch; } } return wstr; } #pragma warning(suppress : 26455) // default constructor is throwing, too much effort to rearrange at this time. Terminal::Terminal() : _mutableViewport{ Viewport::Empty() }, _title{}, _colorTable{}, _defaultFg{ RGB(255, 255, 255) }, _defaultBg{ ARGB(0, 0, 0, 0) }, _screenReversed{ false }, _pfnWriteInput{ nullptr }, _scrollOffset{ 0 }, _snapOnInput{ true }, _altGrAliasing{ true }, _blockSelection{ false }, _selection{ std::nullopt }, _taskbarState{ 0 }, _taskbarProgress{ 0 }, _trimBlockSelection{ false } { auto dispatch = std::make_unique<TerminalDispatch>(*this); auto engine = std::make_unique<OutputStateMachineEngine>(std::move(dispatch)); _stateMachine = std::make_unique<StateMachine>(std::move(engine)); auto passAlongInput = [&](std::deque<std::unique_ptr<IInputEvent>>& inEventsToWrite) { if (!_pfnWriteInput) { return; } std::wstring wstr = _KeyEventsToText(inEventsToWrite); _pfnWriteInput(wstr); }; _terminalInput = std::make_unique<TerminalInput>(passAlongInput); _InitializeColorTable(); } void Terminal::Create(COORD viewportSize, SHORT scrollbackLines, IRenderTarget& renderTarget) { _mutableViewport = Viewport::FromDimensions({ 0, 0 }, viewportSize); _scrollbackLines = scrollbackLines; const COORD bufferSize{ viewportSize.X, Utils::ClampToShortMax(viewportSize.Y + scrollbackLines, 1) }; const TextAttribute attr{}; const UINT cursorSize = 12; _buffer = std::make_unique<TextBuffer>(bufferSize, attr, cursorSize, renderTarget); // Add regex pattern recognizers to the buffer // For now, we only add the URI regex pattern std::wstring_view linkPattern{ LR"(\b(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|$!:,.;]*[A-Za-z0-9+&@#/%=~_|$])" }; _hyperlinkPatternId = _buffer->AddPatternRecognizer(linkPattern); } // Method Description: // - Initializes the Terminal from the given set of settings. // Arguments: // - settings: the set of CoreSettings we need to use to initialize the terminal // - renderTarget: A render target the terminal can use for paint invalidation. void Terminal::CreateFromSettings(ICoreSettings settings, IRenderTarget& renderTarget) { const COORD viewportSize{ Utils::ClampToShortMax(settings.InitialCols(), 1), Utils::ClampToShortMax(settings.InitialRows(), 1) }; // TODO:MSFT:20642297 - Support infinite scrollback here, if HistorySize is -1 Create(viewportSize, Utils::ClampToShortMax(settings.HistorySize(), 0), renderTarget); UpdateSettings(settings); } // Method Description: // - Update our internal properties to match the new values in the provided // CoreSettings object. // Arguments: // - settings: an ICoreSettings with new settings values for us to use. void Terminal::UpdateSettings(ICoreSettings settings) { UpdateAppearance(settings); _snapOnInput = settings.SnapOnInput(); _altGrAliasing = settings.AltGrAliasing(); _wordDelimiters = settings.WordDelimiters(); _suppressApplicationTitle = settings.SuppressApplicationTitle(); _startingTitle = settings.StartingTitle(); _trimBlockSelection = settings.TrimBlockSelection(); _terminalInput->ForceDisableWin32InputMode(settings.ForceVTInput()); if (settings.TabColor() == nullptr) { _tabColor = std::nullopt; } else { _tabColor = til::color{ settings.TabColor().Value() }.with_alpha(0xff); } if (!_startingTabColor && settings.StartingTabColor()) { _startingTabColor = til::color{ settings.StartingTabColor().Value() }.with_alpha(0xff); } if (_pfnTabColorChanged) { _pfnTabColorChanged(GetTabColor()); } // TODO:MSFT:21327402 - if HistorySize has changed, resize the buffer so we // have a smaller scrollback. We should do this carefully - if the new buffer // size is smaller than where the mutable viewport currently is, we'll want // to make sure to rotate the buffer contents upwards, so the mutable viewport // remains at the bottom of the buffer. } // Method Description: // - Update our internal properties to match the new values in the provided // CoreAppearance object. // Arguments: // - appearance: an ICoreAppearance with new settings values for us to use. void Terminal::UpdateAppearance(const ICoreAppearance& appearance) { // Set the default background as transparent to prevent the // DX layer from overwriting the background image or acrylic effect til::color newBackgroundColor{ appearance.DefaultBackground() }; _defaultBg = newBackgroundColor.with_alpha(0); _defaultFg = appearance.DefaultForeground(); for (int i = 0; i < 16; i++) { _colorTable.at(i) = til::color{ appearance.GetColorTableEntry(i) }; } CursorType cursorShape = CursorType::VerticalBar; switch (appearance.CursorShape()) { case CursorStyle::Underscore: cursorShape = CursorType::Underscore; break; case CursorStyle::FilledBox: cursorShape = CursorType::FullBox; break; case CursorStyle::EmptyBox: cursorShape = CursorType::EmptyBox; break; case CursorStyle::Vintage: cursorShape = CursorType::Legacy; break; case CursorStyle::DoubleUnderscore: cursorShape = CursorType::DoubleUnderscore; break; default: case CursorStyle::Bar: cursorShape = CursorType::VerticalBar; break; } if (_buffer) { _buffer->GetCursor().SetStyle(appearance.CursorHeight(), til::color{ appearance.CursorColor() }, cursorShape); } _defaultCursorShape = cursorShape; } // Method Description: // - Resize the terminal as the result of some user interaction. // Arguments: // - viewportSize: the new size of the viewport, in chars // Return Value: // - S_OK if we successfully resized the terminal, S_FALSE if there was // nothing to do (the viewportSize is the same as our current size), or an // appropriate HRESULT for failing to resize. [[nodiscard]] HRESULT Terminal::UserResize(const COORD viewportSize) noexcept { const auto oldDimensions = _mutableViewport.Dimensions(); if (viewportSize == oldDimensions) { return S_FALSE; } const auto dx = ::base::ClampSub(viewportSize.X, oldDimensions.X); const auto oldTop = _mutableViewport.Top(); const short newBufferHeight = ::base::ClampAdd(viewportSize.Y, _scrollbackLines); COORD bufferSize{ viewportSize.X, newBufferHeight }; // Save cursor's relative height versus the viewport const short sCursorHeightInViewportBefore = ::base::ClampSub(_buffer->GetCursor().GetPosition().Y, _mutableViewport.Top()); // This will be used to determine where the viewport should be in the new buffer. const short oldViewportTop = _mutableViewport.Top(); short newViewportTop = oldViewportTop; short newVisibleTop = ::base::saturated_cast<short>(_VisibleStartIndex()); // If the original buffer had _no_ scroll offset, then we should be at the // bottom in the new buffer as well. Track that case now. const bool originalOffsetWasZero = _scrollOffset == 0; // skip any drawing updates that might occur until we swap _buffer with the new buffer or if we exit early. _buffer->GetCursor().StartDeferDrawing(); // we're capturing _buffer by reference here because when we exit, we want to EndDefer on the current active buffer. auto endDefer = wil::scope_exit([&]() noexcept { _buffer->GetCursor().EndDeferDrawing(); }); // First allocate a new text buffer to take the place of the current one. std::unique_ptr<TextBuffer> newTextBuffer; try { // GH#3848 - Stash away the current attributes the old text buffer is // using. We'll initialize the new buffer with the default attributes, // but after the resize, we'll want to make sure that the new buffer's // current attributes (the ones used for printing new text) match the // old buffer's. const auto oldBufferAttributes = _buffer->GetCurrentAttributes(); newTextBuffer = std::make_unique<TextBuffer>(bufferSize, TextAttribute{}, 0, // temporarily set size to 0 so it won't render. _buffer->GetRenderTarget()); newTextBuffer->GetCursor().StartDeferDrawing(); // Build a PositionInformation to track the position of both the top of // the mutable viewport and the top of the visible viewport in the new // buffer. // * the new value of mutableViewportTop will be used to figure out // where we should place the mutable viewport in the new buffer. This // requires a bit of trickiness to remain consistent with conpty's // buffer (as seen below). // * the new value of visibleViewportTop will be used to calculate the // new scrollOffset in the new buffer, so that the visible lines on // the screen remain roughly the same. TextBuffer::PositionInformation oldRows{ 0 }; oldRows.mutableViewportTop = oldViewportTop; oldRows.visibleViewportTop = newVisibleTop; const std::optional<short> oldViewStart{ oldViewportTop }; RETURN_IF_FAILED(TextBuffer::Reflow(*_buffer.get(), *newTextBuffer.get(), _mutableViewport, { oldRows })); newViewportTop = oldRows.mutableViewportTop; newVisibleTop = oldRows.visibleViewportTop; // Restore the active text attributes newTextBuffer->SetCurrentAttributes(oldBufferAttributes); } CATCH_RETURN(); // Conpty resizes a little oddly - if the height decreased, and there were // blank lines at the bottom, those lines will get trimmed. If there's not // blank lines, then the top will get "shifted down", moving the top line // into scrollback. See GH#3490 for more details. // // If the final position in the buffer is on the bottom row of the new // viewport, then we're going to need to move the top down. Otherwise, move // the bottom up. // // There are also important things to consider with line wrapping. // * If a line in scrollback wrapped that didn't previously, we'll need to // make sure to have the new viewport down another line. This will cause // our top to move down. // * If a line _in the viewport_ wrapped that didn't previously, then the // conpty buffer will also have that wrapped line, and will move the // cursor & text down a line in response. This causes our bottom to move // down. // // We're going to use a combo of both these things to calculate where the // new viewport should be. To keep in sync with conpty, we'll need to make // sure that any lines that entered the scrollback _stay in scrollback_. We // do that by taking the max of // * Where the old top line in the viewport exists in the new buffer (as // calculated by TextBuffer::Reflow) // * Where the bottom of the text in the new buffer is (and using that to // calculate another proposed top location). const COORD newCursorPos = newTextBuffer->GetCursor().GetPosition(); #pragma warning(push) #pragma warning(disable : 26496) // cpp core checks wants this const, but it's assigned immediately below... COORD newLastChar = newCursorPos; try { newLastChar = newTextBuffer->GetLastNonSpaceCharacter(); } CATCH_LOG(); #pragma warning(pop) const auto maxRow = std::max(newLastChar.Y, newCursorPos.Y); const short proposedTopFromLastLine = ::base::ClampAdd(::base::ClampSub(maxRow, viewportSize.Y), 1); const short proposedTopFromScrollback = newViewportTop; short proposedTop = std::max(proposedTopFromLastLine, proposedTopFromScrollback); // If we're using the new location of the old top line to place the // viewport, we might need to make an adjustment to it. // // We're using the last cell of the line to calculate where the top line is // in the new buffer. If that line wrapped, then all the lines below it // shifted down in the buffer. If there's space for all those lines in the // conpty buffer, then the originally unwrapped top line will _still_ be in // the buffer. In that case, don't stick to the _end_ of the old top line, // instead stick to the _start_, which is one line up. // // We can know if there's space in the conpty buffer by checking if the // maxRow (the highest row we've written text to) is above the viewport from // this proposed top position. if (proposedTop == proposedTopFromScrollback) { const auto proposedViewFromTop = Viewport::FromDimensions({ 0, proposedTopFromScrollback }, viewportSize); if (maxRow < proposedViewFromTop.BottomInclusive()) { if (dx < 0 && proposedTop > 0) { try { auto& row = newTextBuffer->GetRowByOffset(::base::ClampSub(proposedTop, 1)); if (row.WasWrapForced()) { proposedTop--; } } CATCH_LOG(); } } } // If the new bottom would be higher than the last row of text, then we // definitely want to use the last row of text to determine where the // viewport should be. const auto proposedViewFromTop = Viewport::FromDimensions({ 0, proposedTopFromScrollback }, viewportSize); if (maxRow > proposedViewFromTop.BottomInclusive()) { proposedTop = proposedTopFromLastLine; } // Make sure the proposed viewport is within the bounds of the buffer. // First make sure the top is >=0 proposedTop = std::max(static_cast<short>(0), proposedTop); // If the new bottom would be below the bottom of the buffer, then slide the // top up so that we'll still fit within the buffer. const auto newView = Viewport::FromDimensions({ 0, proposedTop }, viewportSize); const auto proposedBottom = newView.BottomExclusive(); if (proposedBottom > bufferSize.Y) { proposedTop = ::base::ClampSub(proposedTop, ::base::ClampSub(proposedBottom, bufferSize.Y)); } _mutableViewport = Viewport::FromDimensions({ 0, proposedTop }, viewportSize); _buffer.swap(newTextBuffer); // GH#3494: Maintain scrollbar position during resize // Make sure that we don't scroll past the mutableViewport at the bottom of the buffer newVisibleTop = std::min(newVisibleTop, _mutableViewport.Top()); // Make sure we don't scroll past the top of the scrollback newVisibleTop = std::max<short>(newVisibleTop, 0); // If the old scrolloffset was 0, then we weren't scrolled back at all // before, and shouldn't be now either. _scrollOffset = originalOffsetWasZero ? 0 : static_cast<int>(::base::ClampSub(_mutableViewport.Top(), newVisibleTop)); // GH#5029 - make sure to InvalidateAll here, so that we'll paint the entire visible viewport. try { _buffer->GetRenderTarget().TriggerRedrawAll(); } CATCH_LOG(); _NotifyScrollEvent(); return S_OK; } void Terminal::Write(std::wstring_view stringView) { auto lock = LockForWriting(); _stateMachine->ProcessString(stringView); } void Terminal::WritePastedText(std::wstring_view stringView) { auto option = ::Microsoft::Console::Utils::FilterOption::CarriageReturnNewline | ::Microsoft::Console::Utils::FilterOption::ControlCodes; std::wstring filtered = ::Microsoft::Console::Utils::FilterStringForPaste(stringView, option); if (IsXtermBracketedPasteModeEnabled()) { filtered.insert(0, L"\x1b[200~"); filtered.append(L"\x1b[201~"); } if (_pfnWriteInput) { _pfnWriteInput(filtered); } } // Method Description: // - Attempts to snap to the bottom of the buffer, if SnapOnInput is true. Does // nothing if SnapOnInput is set to false, or we're already at the bottom of // the buffer. // Arguments: // - <none> // Return Value: // - <none> void Terminal::TrySnapOnInput() { if (_snapOnInput && _scrollOffset != 0) { auto lock = LockForWriting(); _scrollOffset = 0; _NotifyScrollEvent(); } } // Routine Description: // - Relays if we are tracking mouse input // Parameters: // - <none> // Return value: // - true, if we are tracking mouse input. False, otherwise bool Terminal::IsTrackingMouseInput() const noexcept { return _terminalInput->IsTrackingMouseInput(); } // Method Description: // - Given a coord, get the URI at that location // Arguments: // - The position std::wstring Terminal::GetHyperlinkAtPosition(const COORD position) { auto attr = _buffer->GetCellDataAt(_ConvertToBufferCell(position))->TextAttr(); if (attr.IsHyperlink()) { auto uri = _buffer->GetHyperlinkUriFromId(attr.GetHyperlinkId()); return uri; } // also look through our known pattern locations in our pattern interval tree const auto result = GetHyperlinkIntervalFromPosition(position); if (result.has_value() && result->value == _hyperlinkPatternId) { const auto start = result->start; const auto end = result->stop; std::wstring uri; const auto startIter = _buffer->GetCellDataAt(_ConvertToBufferCell(start)); const auto endIter = _buffer->GetCellDataAt(_ConvertToBufferCell(end)); for (auto iter = startIter; iter != endIter; ++iter) { uri += iter->Chars(); } return uri; } return {}; } // Method Description: // - Gets the hyperlink ID of the text at the given terminal position // Arguments: // - The position of the text // Return value: // - The hyperlink ID uint16_t Terminal::GetHyperlinkIdAtPosition(const COORD position) { return _buffer->GetCellDataAt(_ConvertToBufferCell(position))->TextAttr().GetHyperlinkId(); } // Method description: // - Given a position in a URI pattern, gets the start and end coordinates of the URI // Arguments: // - The position // Return value: // - The interval representing the start and end coordinates std::optional<PointTree::interval> Terminal::GetHyperlinkIntervalFromPosition(const COORD position) { const auto results = _patternIntervalTree.findOverlapping(COORD{ position.X + 1, position.Y }, position); if (results.size() > 0) { for (const auto& result : results) { if (result.value == _hyperlinkPatternId) { return result; } } } return std::nullopt; } // Method Description: // - Send this particular (non-character) key event to the terminal. // - The terminal will translate the key and the modifiers pressed into the // appropriate VT sequence for that key chord. If we do translate the key, // we'll return true. In that case, the event should NOT be processed any further. // - Character events (e.g. WM_CHAR) are generally the best way to properly receive // keyboard input on Windows though, as the OS is suited best at handling the // translation of the current keyboard layout, dead keys, etc. // As a result of this false is returned for all key events that contain characters. // SendCharEvent may then be called with the data obtained from a character event. // - As a special case we'll always handle VK_TAB key events. // This must be done due to TermControl::_KeyDownHandler (one of the callers) // always marking tab key events as handled, causing no character event to be raised. // Arguments: // - vkey: The vkey of the last pressed key. // - scanCode: The scan code of the last pressed key. // - states: The Microsoft::Terminal::Core::ControlKeyStates representing the modifier key states. // - keyDown: If true, the key was pressed, otherwise the key was released. // Return Value: // - true if we translated the key event, and it should not be processed any further. // - false if we did not translate the key, and it should be processed into a character. bool Terminal::SendKeyEvent(const WORD vkey, const WORD scanCode, const ControlKeyStates states, const bool keyDown) { // GH#6423 - don't snap on this key if the key that was pressed was a // modifier key. We'll wait for a real keystroke to snap to the bottom. // GH#6481 - Additionally, make sure the key was actually pressed. This // check will make sure we behave the same as before GH#6309 if (!KeyEvent::IsModifierKey(vkey) && keyDown) { TrySnapOnInput(); } _StoreKeyEvent(vkey, scanCode); // Certain applications like AutoHotKey and its keyboard remapping feature, // send us key events using SendInput() whose values are outside of the valid range. // GH#7064 if (vkey == 0 || vkey >= 0xff) { return false; } // While not explicitly permitted, a wide range of software, including Windows' own touch keyboard, // sets the wScan member of the KEYBDINPUT structure to 0, resulting in scanCode being 0 as well. // --> Alternatively get the scanCode from the vkey if possible. // GH#7495 const auto sc = scanCode ? scanCode : _ScanCodeFromVirtualKey(vkey); if (sc == 0) { return false; } const auto isAltOnlyPressed = states.IsAltPressed() && !states.IsCtrlPressed(); // DON'T manually handle Alt+Space - the system will use this to bring up // the system menu for restore, min/maximize, size, move, close. // (This doesn't apply to Ctrl+Alt+Space.) if (isAltOnlyPressed && vkey == VK_SPACE) { return false; } // By default Windows treats Ctrl+Alt as an alias for AltGr. // When the altGrAliasing setting is set to false, this behaviour should be disabled. // // Whenever possible _CharacterFromKeyEvent() will return a valid character. // For instance both Ctrl+Alt+Q as well as AltGr+Q return @ on a German keyboard. // // We can achieve the altGrAliasing functionality by skipping the call to _CharacterFromKeyEvent, // as TerminalInput::HandleKey will then fall back to using the vkey which // is the underlying ASCII character (e.g. A-Z) on the keyboard in our case. // See GH#5525/GH#6211 for more details const auto isSuppressedAltGrAlias = !_altGrAliasing && states.IsAltPressed() && states.IsCtrlPressed() && !states.IsAltGrPressed(); const auto ch = isSuppressedAltGrAlias ? UNICODE_NULL : _CharacterFromKeyEvent(vkey, sc, states); // Delegate it to the character event handler if this key event can be // mapped to one (see method description above). For Alt+key combinations // we'll not receive another character event for some reason though. // -> Don't delegate the event if this is a Alt+key combination. // // As a special case we'll furthermore always handle VK_TAB // key events here instead of in Terminal::SendCharEvent. // See the method description for more information. if (!isAltOnlyPressed && vkey != VK_TAB && ch != UNICODE_NULL) { return false; } KeyEvent keyEv{ keyDown, 1, vkey, sc, ch, states.Value() }; return _terminalInput->HandleKey(&keyEv); } // Method Description: // - Send this particular mouse event to the terminal. The terminal will translate // the button and the modifiers pressed into the appropriate VT sequence for that // mouse event. If we do translate the key, we'll return true. In that case, the // event should NOT be processed any further. If we return false, the event // was NOT translated, and we should instead use the event normally // Arguments: // - viewportPos: the position of the mouse event relative to the viewport origin. // - uiButton: the WM mouse button event code // - states: The Microsoft::Terminal::Core::ControlKeyStates representing the modifier key states. // - wheelDelta: the amount that the scroll wheel changed (should be 0 unless button is a WM_MOUSE*WHEEL) // Return Value: // - true if we translated the key event, and it should not be processed any further. // - false if we did not translate the key, and it should be processed into a character. bool Terminal::SendMouseEvent(const COORD viewportPos, const unsigned int uiButton, const ControlKeyStates states, const short wheelDelta, const TerminalInput::MouseButtonState state) { // GH#6401: VT applications should be able to receive mouse events from outside the // terminal buffer. This is likely to happen when the user drags the cursor offscreen. // We shouldn't throw away perfectly good events when they're offscreen, so we just // clamp them to be within the range [(0, 0), (W, H)]. #pragma warning(suppress : 26496) // analysis can't tell we're assigning through a reference below auto clampedPos{ viewportPos }; _mutableViewport.ToOrigin().Clamp(clampedPos); return _terminalInput->HandleMouse(clampedPos, uiButton, GET_KEYSTATE_WPARAM(states.Value()), wheelDelta, state); } // Method Description: // - Send this particular character to the terminal. // - This method is the counterpart to SendKeyEvent and behaves almost identical. // The difference is the focus on sending characters to the terminal, // whereas SendKeyEvent handles the sending of keys like the arrow keys. // Arguments: // - ch: The UTF-16 code unit to be sent. // - scanCode: The scan code of the last pressed key. Can be left 0. // - states: The Microsoft::Terminal::Core::ControlKeyStates representing the modifier key states. // Return Value: // - true if we translated the character event, and it should not be processed any further. // - false otherwise. bool Terminal::SendCharEvent(const wchar_t ch, const WORD scanCode, const ControlKeyStates states) { // DON'T manually handle Alt+Space - the system will use this to bring up // the system menu for restore, min/maximize, size, move, close. if (ch == L' ' && states.IsAltPressed() && !states.IsCtrlPressed()) { return false; } auto vkey = _TakeVirtualKeyFromLastKeyEvent(scanCode); if (vkey == 0 && scanCode != 0) { vkey = _VirtualKeyFromScanCode(scanCode); } if (vkey == 0) { vkey = _VirtualKeyFromCharacter(ch); } // Unfortunately, the UI doesn't give us both a character down and a // character up event, only a character received event. So fake sending both // to the terminal input translator. Unless it's in win32-input-mode, it'll // ignore the keyup. KeyEvent keyDown{ true, 1, vkey, scanCode, ch, states.Value() }; KeyEvent keyUp{ false, 1, vkey, scanCode, ch, states.Value() }; const auto handledDown = _terminalInput->HandleKey(&keyDown); const auto handledUp = _terminalInput->HandleKey(&keyUp); return handledDown || handledUp; } // Method Description: // - Invalidates the regions described in the given pattern tree for the rendering purposes // Arguments: // - The interval tree containing regions that need to be invalidated void Terminal::_InvalidatePatternTree(interval_tree::IntervalTree<til::point, size_t>& tree) { const auto vis = _VisibleStartIndex(); auto invalidate = [=](const PointTree::interval& interval) { COORD startCoord{ gsl::narrow<SHORT>(interval.start.x()), gsl::narrow<SHORT>(interval.start.y() + vis) }; COORD endCoord{ gsl::narrow<SHORT>(interval.stop.x()), gsl::narrow<SHORT>(interval.stop.y() + vis) }; _InvalidateFromCoords(startCoord, endCoord); }; tree.visit_all(invalidate); } // Method Description: // - Given start and end coords, invalidates all the regions between them // Arguments: // - The start and end coords void Terminal::_InvalidateFromCoords(const COORD start, const COORD end) { if (start.Y == end.Y) { SMALL_RECT region{ start.X, start.Y, end.X, end.Y }; _buffer->GetRenderTarget().TriggerRedraw(Viewport::FromInclusive(region)); } else { const auto rowSize = gsl::narrow<SHORT>(_buffer->GetRowByOffset(0).size()); // invalidate the first line SMALL_RECT region{ start.X, start.Y, rowSize - 1, start.Y }; _buffer->GetRenderTarget().TriggerRedraw(Viewport::FromInclusive(region)); if ((end.Y - start.Y) > 1) { // invalidate the lines in between the first and last line region = til::rectangle(0, start.Y + 1, rowSize - 1, end.Y - 1); _buffer->GetRenderTarget().TriggerRedraw(Viewport::FromInclusive(region)); } // invalidate the last line region = til::rectangle(0, end.Y, end.X, end.Y); _buffer->GetRenderTarget().TriggerRedraw(Viewport::FromInclusive(region)); } } // Method Description: // - Returns the keyboard's scan code for the given virtual key code. // Arguments: // - vkey: The virtual key code. // Return Value: // - The keyboard's scan code. WORD Terminal::_ScanCodeFromVirtualKey(const WORD vkey) noexcept { return LOWORD(MapVirtualKeyW(vkey, MAPVK_VK_TO_VSC)); } // Method Description: // - Returns the virtual key code for the given keyboard's scan code. // Arguments: // - scanCode: The keyboard's scan code. // Return Value: // - The virtual key code. 0 if no mapping can be found. WORD Terminal::_VirtualKeyFromScanCode(const WORD scanCode) noexcept { return LOWORD(MapVirtualKeyW(scanCode, MAPVK_VSC_TO_VK)); } // Method Description: // - Returns any virtual key code that produces the given character. // Arguments: // - scanCode: The keyboard's scan code. // Return Value: // - The virtual key code. 0 if no mapping can be found. WORD Terminal::_VirtualKeyFromCharacter(const wchar_t ch) noexcept { const auto vkey = LOWORD(VkKeyScanW(ch)); return vkey == -1 ? 0 : vkey; } // Method Description: // - Translates the specified virtual key code and keyboard state to the corresponding character. // Arguments: // - vkey: The virtual key code that initiated this keyboard event. // - scanCode: The scan code that initiated this keyboard event. // - states: The current keyboard state. // Return Value: // - The character that would result from this virtual key code and keyboard state. wchar_t Terminal::_CharacterFromKeyEvent(const WORD vkey, const WORD scanCode, const ControlKeyStates states) noexcept try { // We might want to use GetKeyboardState() instead of building our own keyState. // The question is whether that's necessary though. For now it seems to work fine as it is. std::array<BYTE, 256> keyState = {}; keyState.at(VK_SHIFT) = states.IsShiftPressed() ? 0x80 : 0; keyState.at(VK_CONTROL) = states.IsCtrlPressed() ? 0x80 : 0; keyState.at(VK_MENU) = states.IsAltPressed() ? 0x80 : 0; // For the following use of ToUnicodeEx() please look here: // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-tounicodeex // Technically ToUnicodeEx() can produce arbitrarily long sequences of diacritics etc. // Since we only handle the case of a single UTF-16 code point, we can set the buffer size to 2 though. std::array<wchar_t, 2> buffer; // wFlags: // * If bit 0 is set, a menu is active. // If this flag is not specified ToUnicodeEx will send us character events on certain Alt+Key combinations (e.g. Alt+Arrow-Up). // * If bit 2 is set, keyboard state is not changed (Windows 10, version 1607 and newer) const auto result = ToUnicodeEx(vkey, scanCode, keyState.data(), buffer.data(), gsl::narrow_cast<int>(buffer.size()), 0b101, nullptr); // TODO:GH#2853 We're only handling single UTF-16 code points right now, since that's the only thing KeyEvent supports. return result == 1 || result == -1 ? buffer.at(0) : 0; } catch (...) { LOG_CAUGHT_EXCEPTION(); return UNICODE_INVALID; } // Method Description: // - It's possible for a single scan code on a keyboard to // produce different key codes depending on the keyboard state. // MapVirtualKeyW(scanCode, MAPVK_VSC_TO_VK) will always chose one of the // possibilities no matter what though and thus can't be used in SendCharEvent. // - This method stores the key code from a key event (SendKeyEvent). // If the key event contains character data, handling of the event will be // denied, in order to delegate the work to the character event handler. // - The character event handler (SendCharEvent) will now pick up // the stored key code to restore the full key event data. // Arguments: // - vkey: The virtual key code. // - scanCode: The scan code. void Terminal::_StoreKeyEvent(const WORD vkey, const WORD scanCode) { _lastKeyEventCodes.emplace(KeyEventCodes{ vkey, scanCode }); } // Method Description: // - This method acts as a counterpart to _StoreKeyEvent and extracts a stored // key code. As a safety measure it'll ensure that the given scan code // matches the stored scan code from the previous key event. // - See _StoreKeyEvent for more information. // Arguments: // - scanCode: The scan code. // Return Value: // - The key code matching the given scan code. Otherwise 0. WORD Terminal::_TakeVirtualKeyFromLastKeyEvent(const WORD scanCode) noexcept { const auto codes = _lastKeyEventCodes.value_or(KeyEventCodes{}); _lastKeyEventCodes.reset(); return codes.ScanCode == scanCode ? codes.VirtualKey : 0; } // Method Description: // - Acquire a read lock on the terminal. // Return Value: // - a shared_lock which can be used to unlock the terminal. The shared_lock // will release this lock when it's destructed. [[nodiscard]] std::shared_lock<std::shared_mutex> Terminal::LockForReading() { return std::shared_lock<std::shared_mutex>(_readWriteLock); } // Method Description: // - Acquire a write lock on the terminal. // Return Value: // - a unique_lock which can be used to unlock the terminal. The unique_lock // will release this lock when it's destructed. [[nodiscard]] std::unique_lock<std::shared_mutex> Terminal::LockForWriting() { return std::unique_lock<std::shared_mutex>(_readWriteLock); } Viewport Terminal::_GetMutableViewport() const noexcept { return _mutableViewport; } short Terminal::GetBufferHeight() const noexcept { return _mutableViewport.BottomExclusive(); } // ViewStartIndex is also the length of the scrollback int Terminal::ViewStartIndex() const noexcept { return _mutableViewport.Top(); } int Terminal::ViewEndIndex() const noexcept { return _mutableViewport.BottomInclusive(); } // _VisibleStartIndex is the first visible line of the buffer int Terminal::_VisibleStartIndex() const noexcept { return std::max(0, ViewStartIndex() - _scrollOffset); } int Terminal::_VisibleEndIndex() const noexcept { return std::max(0, ViewEndIndex() - _scrollOffset); } Viewport Terminal::_GetVisibleViewport() const noexcept { const COORD origin{ 0, gsl::narrow<short>(_VisibleStartIndex()) }; return Viewport::FromDimensions(origin, _mutableViewport.Dimensions()); } // Writes a string of text to the buffer, then moves the cursor (and viewport) // in accordance with the written text. // This method is our proverbial `WriteCharsLegacy`, and great care should be made to // keep it minimal and orderly, lest it become WriteCharsLegacy2ElectricBoogaloo // TODO: MSFT 21006766 // This needs to become stream logic on the buffer itself sooner rather than later // because it's otherwise impossible to avoid the Electric Boogaloo-ness here. // I had to make a bunch of hacks to get Japanese and emoji to work-ish. void Terminal::_WriteBuffer(const std::wstring_view& stringView) { auto& cursor = _buffer->GetCursor(); // Defer the cursor drawing while we are iterating the string, for a better performance. // We can not waste time displaying a cursor event when we know more text is coming right behind it. cursor.StartDeferDrawing(); for (size_t i = 0; i < stringView.size(); i++) { const auto wch = stringView.at(i); const COORD cursorPosBefore = cursor.GetPosition(); COORD proposedCursorPosition = cursorPosBefore; // TODO: MSFT 21006766 // This is not great but I need it demoable. Fix by making a buffer stream writer. // // If wch is a surrogate character we need to read 2 code units // from the stringView to form a single code point. const auto isSurrogate = wch >= 0xD800 && wch <= 0xDFFF; const auto view = stringView.substr(i, isSurrogate ? 2 : 1); const OutputCellIterator it{ view, _buffer->GetCurrentAttributes() }; const auto end = _buffer->Write(it); const auto cellDistance = end.GetCellDistance(it); const auto inputDistance = end.GetInputDistance(it); if (inputDistance > 0) { // If "wch" was a surrogate character, we just consumed 2 code units above. // -> Increment "i" by 1 in that case and thus by 2 in total in this iteration. proposedCursorPosition.X += gsl::narrow<SHORT>(cellDistance); i += inputDistance - 1; } else { // If _WriteBuffer() is called with a consecutive string longer than the viewport/buffer width // the call to _buffer->Write() will refuse to write anything on the current line. // GetInputDistance() thus returns 0, which would in turn cause i to be // decremented by 1 below and force the outer loop to loop forever. // This if() basically behaves as if "\r\n" had been encountered above and retries the write. // With well behaving shells during normal operation this safeguard should normally not be encountered. proposedCursorPosition.X = 0; proposedCursorPosition.Y++; // Try the character again. i--; // If we write the last cell of the row here, TextBuffer::Write will // mark this line as wrapped for us. If the next character we // process is a newline, the Terminal::CursorLineFeed will unmark // this line as wrapped. // TODO: GH#780 - This should really be a _deferred_ newline. If // the next character to come in is a newline or a cursor // movement or anything, then we should _not_ wrap this line // here. } _AdjustCursorPosition(proposedCursorPosition); } cursor.EndDeferDrawing(); } void Terminal::_AdjustCursorPosition(const COORD proposedPosition) { #pragma warning(suppress : 26496) // cpp core checks wants this const but it's modified below. auto proposedCursorPosition = proposedPosition; auto& cursor = _buffer->GetCursor(); const Viewport bufferSize = _buffer->GetSize(); // If we're about to scroll past the bottom of the buffer, instead cycle the // buffer. SHORT rowsPushedOffTopOfBuffer = 0; const auto newRows = std::max(0, proposedCursorPosition.Y - bufferSize.Height() + 1); if (proposedCursorPosition.Y >= bufferSize.Height()) { for (auto dy = 0; dy < newRows; dy++) { _buffer->IncrementCircularBuffer(); proposedCursorPosition.Y--; rowsPushedOffTopOfBuffer++; } // manually erase our pattern intervals since the locations have changed now _patternIntervalTree = {}; } // Update Cursor Position cursor.SetPosition(proposedCursorPosition); // Move the viewport down if the cursor moved below the viewport. bool updatedViewport = false; const auto scrollAmount = std::max(0, proposedCursorPosition.Y - _mutableViewport.BottomInclusive()); if (scrollAmount > 0) { const auto newViewTop = std::max(0, proposedCursorPosition.Y - (_mutableViewport.Height() - 1)); if (newViewTop != _mutableViewport.Top()) { _mutableViewport = Viewport::FromDimensions({ 0, gsl::narrow<short>(newViewTop) }, _mutableViewport.Dimensions()); updatedViewport = true; } } // If the viewport moved, or we circled the buffer, we might need to update // our _scrollOffset if (updatedViewport || newRows != 0) { const auto oldScrollOffset = _scrollOffset; // scroll if... // - no selection is active // - viewport is already at the bottom const bool scrollToOutput = !IsSelectionActive() && _scrollOffset == 0; _scrollOffset = scrollToOutput ? 0 : _scrollOffset + scrollAmount + newRows; // Clamp the range to make sure that we don't scroll way off the top of the buffer _scrollOffset = std::clamp(_scrollOffset, 0, _buffer->GetSize().Height() - _mutableViewport.Height()); // If the new scroll offset is different, then we'll still want to raise a scroll event updatedViewport = updatedViewport || (oldScrollOffset != _scrollOffset); } // If the viewport moved, then send a scrolling notification. if (updatedViewport) { _NotifyScrollEvent(); } if (rowsPushedOffTopOfBuffer != 0) { // We have to report the delta here because we might have circled the text buffer. // That didn't change the viewport and therefore the TriggerScroll(void) // method can't detect the delta on its own. COORD delta{ 0, -rowsPushedOffTopOfBuffer }; _buffer->GetRenderTarget().TriggerScroll(&delta); } _NotifyTerminalCursorPositionChanged(); } void Terminal::UserScrollViewport(const int viewTop) { // we're going to modify state here that the renderer could be reading. auto lock = LockForWriting(); const auto clampedNewTop = std::max(0, viewTop); const auto realTop = ViewStartIndex(); const auto newDelta = realTop - clampedNewTop; // if viewTop > realTop, we want the offset to be 0. _scrollOffset = std::max(0, newDelta); // We can use the void variant of TriggerScroll here because // we adjusted the viewport so it can detect the difference // from the previous frame drawn. _buffer->GetRenderTarget().TriggerScroll(); } int Terminal::GetScrollOffset() noexcept { return _VisibleStartIndex(); } void Terminal::_NotifyScrollEvent() noexcept try { if (_pfnScrollPositionChanged) { const auto visible = _GetVisibleViewport(); const auto top = visible.Top(); const auto height = visible.Height(); const auto bottom = this->GetBufferHeight(); _pfnScrollPositionChanged(top, height, bottom); } } CATCH_LOG() void Terminal::_NotifyTerminalCursorPositionChanged() noexcept { if (_pfnCursorPositionChanged) { try { _pfnCursorPositionChanged(); } CATCH_LOG(); } } void Terminal::SetWriteInputCallback(std::function<void(std::wstring&)> pfn) noexcept { _pfnWriteInput.swap(pfn); } void Terminal::SetWarningBellCallback(std::function<void()> pfn) noexcept { _pfnWarningBell.swap(pfn); } void Terminal::SetTitleChangedCallback(std::function<void(const std::wstring_view&)> pfn) noexcept { _pfnTitleChanged.swap(pfn); } void Terminal::SetTabColorChangedCallback(std::function<void(const std::optional<til::color>)> pfn) noexcept { _pfnTabColorChanged.swap(pfn); } void Terminal::SetCopyToClipboardCallback(std::function<void(const std::wstring_view&)> pfn) noexcept { _pfnCopyToClipboard.swap(pfn); } void Terminal::SetScrollPositionChangedCallback(std::function<void(const int, const int, const int)> pfn) noexcept { _pfnScrollPositionChanged.swap(pfn); } void Terminal::SetCursorPositionChangedCallback(std::function<void()> pfn) noexcept { _pfnCursorPositionChanged.swap(pfn); } // Method Description: // - Allows setting a callback for when the background color is changed // Arguments: // - pfn: a function callback that takes a color void Terminal::SetBackgroundCallback(std::function<void(const til::color)> pfn) noexcept { _pfnBackgroundColorChanged.swap(pfn); } // Method Description: // - Allows settings a callback for settings the taskbar progress indicator // Arguments: // - pfn: a function callback that takes 2 size_t parameters, one indicating the progress state // and the other indicating the progress value void Microsoft::Terminal::Core::Terminal::TaskbarProgressChangedCallback(std::function<void()> pfn) noexcept { _pfnTaskbarProgressChanged.swap(pfn); } void Terminal::_InitializeColorTable() try { const gsl::span<COLORREF> tableView = { _colorTable.data(), _colorTable.size() }; // First set up the basic 256 colors Utils::Initialize256ColorTable(tableView); // Then use fill the first 16 values with the Campbell scheme Utils::InitializeCampbellColorTable(tableView); // Then make sure all the values have an alpha of 255 Utils::SetColorTableAlpha(tableView, 0xff); } CATCH_LOG() // Method Description: // - Sets the cursor to be currently on. On/Off is tracked independently of // cursor visibility (hidden/visible). On/off is controlled by the cursor // blinker. Visibility is usually controlled by the client application. If the // cursor is hidden, then the cursor will remain hidden. If the cursor is // Visible, then it will immediately become visible. // Arguments: // - isVisible: whether the cursor should be visible void Terminal::SetCursorOn(const bool isOn) { auto lock = LockForWriting(); _buffer->GetCursor().SetIsOn(isOn); } bool Terminal::IsCursorBlinkingAllowed() const noexcept { const auto& cursor = _buffer->GetCursor(); return cursor.IsBlinkingAllowed(); } // Method Description: // - Update our internal knowledge about where regex patterns are on the screen // - This is called by TerminalControl (through a throttled function) when the visible // region changes (for example by text entering the buffer or scrolling) void Terminal::UpdatePatterns() noexcept { auto lock = LockForWriting(); auto oldTree = _patternIntervalTree; _patternIntervalTree = _buffer->GetPatterns(_VisibleStartIndex(), _VisibleEndIndex()); _InvalidatePatternTree(oldTree); _InvalidatePatternTree(_patternIntervalTree); } // Method Description: // - Clears and invalidates the interval pattern tree // - This is called to prevent the renderer from rendering patterns while the // visible region is changing void Terminal::ClearPatternTree() noexcept { auto oldTree = _patternIntervalTree; _patternIntervalTree = {}; _InvalidatePatternTree(oldTree); } // Method Description: // - Returns the tab color // If the starting color exits, it's value is preferred const std::optional<til::color> Terminal::GetTabColor() const noexcept { return _startingTabColor.has_value() ? _startingTabColor : _tabColor; } BlinkingState& Terminal::GetBlinkingState() const noexcept { return _blinkingState; } // Method Description: // - Gets the internal taskbar state value // Return Value: // - The taskbar state const size_t Microsoft::Terminal::Core::Terminal::GetTaskbarState() const noexcept { return _taskbarState; } // Method Description: // - Gets the internal taskbar progress value // Return Value: // - The taskbar progress const size_t Microsoft::Terminal::Core::Terminal::GetTaskbarProgress() const noexcept { return _taskbarProgress; }
#include <iostream> const int MAXN = 400; const int MAXM = 800; int Field[MAXN * MAXM]; int get_parent(int x) { if(Field[x - 1] == x) return x; Field[x - 1] = get_parent(Field[x - 1]); return Field[x - 1]; } void connect(int x, int y) { x = get_parent(x); y = get_parent(y); if(x != y) Field[x - 1] = y; } int main() { //std::cin.tie(0); //std::ios::sync_with_stdio(false); int n, m; std::cin >> n >> m; for(int i = 1; i <= n * m; i++) { Field[i - 1] = i; } std::string cmd; std::cin >> cmd; while(cmd != "END") { int x, y; std::cin >> x >> y; if(cmd == "BUILD") { // std::cout << "building " << std::endl; connect(x, y); } else { // std::cout << "connecting " << std::endl; // std::cout << get_parent(x) << " " << get_parent(y) << std::endl; std::cout << (get_parent(x) == get_parent(y) ? "yes" : "no") << std::endl; } std::cin >> cmd; } return 0; }
#pragma once #include "stdafx.h" #include "MyRTSPClient.h" /** Static method to create an new instance of our version of a RTSPClient */ MyRTSPClient* MyRTSPClient::createNew(UsageEnvironment& env, char const* rtspURL) { int level= g_logLevel; return new MyRTSPClient(env, rtspURL, level, "Cisco", 0); } /** Singleton constructor */ MyRTSPClient::MyRTSPClient(UsageEnvironment& env, char const* rtspURL, int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum) : RTSPClient(env,rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum), m_sink(NULL) { TRACE_INFO("Created RTSP client"); TRACE_INFO(rtspURL); m_sink=H264VideoSink::createNew(env, *scs.subsession, "DMH_STREAM");//rtspClient->url()); } /** Destructor. No work at this level */ MyRTSPClient::~MyRTSPClient() { TRACE_INFO("Destroy RTSP client"); if(m_sink!=NULL) delete m_sink; m_sink=NULL; }
/*============================================================================= Copyright (c) 2011-2015 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_COMPOST_EFFECTS_AUTO_PAN_HPP #define SPROUT_COMPOST_EFFECTS_AUTO_PAN_HPP #include <iterator> #include <type_traits> #include <sprout/config.hpp> #include <sprout/utility/lvalue_forward.hpp> #include <sprout/math/constants.hpp> #include <sprout/math/sin.hpp> #include <sprout/range/adaptor/transformed.hpp> #include <sprout/range/adaptor/outdirected.hpp> #include <sprout/range/adaptor/indexed.hpp> #include <sprout/compost/formats/stereo.hpp> namespace sprout { namespace compost { // // auto_pan_outdirected_value // template<typename Value, typename IntType, bool IsLeft> struct auto_pan_outdirected_value { public: typedef Value value_type; typedef IntType int_type; private: value_type depth_; value_type rate_; int_type samples_per_sec_; private: template<bool Left, typename Outdirected> SPROUT_CONSTEXPR typename std::enable_if< Left, typename std::iterator_traits<Outdirected>::value_type >::type calc(Outdirected const& x) const { return (1 + depth_ * sprout::sin(sprout::math::two_pi<Value>() * rate_ * x.index() / samples_per_sec_)) * *x; } template<bool Left, typename Outdirected> SPROUT_CONSTEXPR typename std::enable_if< !Left, typename std::iterator_traits<Outdirected>::value_type >::type calc(Outdirected const& x) const { return (1 + depth_ * sprout::sin(sprout::math::two_pi<Value>() * rate_ * x.index() / samples_per_sec_ + sprout::math::pi<Value>())) * *x; } public: SPROUT_CONSTEXPR auto_pan_outdirected_value( value_type const& depth, value_type const& rate, int_type samples_per_sec = 44100 ) : depth_(depth), rate_(rate), samples_per_sec_(samples_per_sec) {} template<typename Outdirected> SPROUT_CONSTEXPR typename std::iterator_traits<Outdirected>::value_type operator()(Outdirected const& x) const { return calc<IsLeft>(x); } }; namespace effects { // // auto_pan_holder // template<typename T, typename IntType = int> class auto_pan_holder { public: typedef T value_type; typedef IntType int_type; private: value_type depth_; value_type rate_; int_type samples_per_sec_; public: SPROUT_CONSTEXPR auto_pan_holder() SPROUT_DEFAULTED_DEFAULT_CONSTRUCTOR_DECL auto_pan_holder(auto_pan_holder const&) = default; SPROUT_CONSTEXPR auto_pan_holder( value_type const& depth, value_type const& rate, int_type samples_per_sec = 44100 ) : depth_(depth), rate_(rate), samples_per_sec_(samples_per_sec) {} SPROUT_CONSTEXPR value_type const& depth() const { return depth_; } SPROUT_CONSTEXPR value_type const& rate() const { return rate_; } SPROUT_CONSTEXPR int_type const& samples_per_sec() const { return samples_per_sec_; } }; // // auto_pan_forwarder // class auto_pan_forwarder { public: template<typename T, typename IntType> SPROUT_CONSTEXPR sprout::compost::effects::auto_pan_holder<T, IntType> operator()(T const& depth, T const& rate, IntType samples_per_sec) const { return sprout::compost::effects::auto_pan_holder<T, IntType>(depth, rate, samples_per_sec); } template<typename T> SPROUT_CONSTEXPR sprout::compost::effects::auto_pan_holder<T> operator()(T const& depth, T const& rate) const { return sprout::compost::effects::auto_pan_holder<T>(depth, rate); } }; // // auto_pan // namespace { SPROUT_STATIC_CONSTEXPR sprout::compost::effects::auto_pan_forwarder auto_pan = {}; } // anonymous-namespace // // operator| // template<typename Range, typename T, typename IntType> inline SPROUT_CONSTEXPR auto operator|(Range&& lhs, sprout::compost::effects::auto_pan_holder<T, IntType> const& rhs) -> decltype( SPROUT_FORWARD(Range, lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::auto_pan_outdirected_value<T, IntType, true>(rhs.depth(), rhs.rate(), rhs.samples_per_sec()) ) | sprout::compost::formats::stereo( SPROUT_FORWARD(Range, lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::auto_pan_outdirected_value<T, IntType, false>(rhs.depth(), rhs.rate(), rhs.samples_per_sec()) ) ) ) { return SPROUT_FORWARD(Range, lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::auto_pan_outdirected_value<T, IntType, true>(rhs.depth(), rhs.rate(), rhs.samples_per_sec()) ) | sprout::compost::formats::stereo( SPROUT_FORWARD(Range, lhs) | sprout::adaptors::indexed | sprout::adaptors::outdirected | sprout::adaptors::transformed( sprout::compost::auto_pan_outdirected_value<T, IntType, false>(rhs.depth(), rhs.rate(), rhs.samples_per_sec()) ) ) ; } } // namespace effects using sprout::compost::effects::auto_pan; } // namespace compost } // namespace sprout #endif // #ifndef SPROUT_COMPOST_EFFECTS_AUTO_PAN_HPP
/* * Copyright (c) 2018, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "memory_manager.h" namespace rmm { /** -----------------------------------------------------------------------* * Record a memory manager event in the log. * * @param[in] event The type of event (Alloc, Realloc, or Free) * @param[in] DeviceId The device to which this event applies. * @param[in] ptr The device pointer being allocated or freed. * @param[in] t The timestamp to record. * @param[in] size The size of allocation (only needed for Alloc/Realloc). * @param[in] stream The stream on which the allocation is happening * (only needed for Alloc/Realloc). * ----------------------------------------------------------------------**/ void Logger::record(MemEvent_t event, int deviceId, void* ptr, TimePt start, TimePt end, size_t freeMem, size_t totalMem, size_t size, cudaStream_t stream, std::string filename, unsigned int line) { std::lock_guard<std::mutex> guard(log_mutex); if (Alloc == event) current_allocations.insert(ptr); else if (Free == event) current_allocations.erase(ptr); events.push_back({event, deviceId, ptr, size, stream, freeMem, totalMem, current_allocations.size(), start, end, filename, line}); } /** -----------------------------------------------------------------------* * @brief Output a comma-separated value string of the current log to the * provided ostream * * @param[in] csv The output stream to put the CSV log string into. * ----------------------------------------------------------------------**/ void Logger::to_csv(std::ostream &csv) { csv << "Event Type,Device ID,Address,Stream,Size (bytes),Free Memory," << "Total Memory,Current Allocs,Start,End,Elapsed,Location\n"; for (auto& e : events) { auto event_str = "Alloc"; if (e.event == Realloc) event_str = "Realloc"; if (e.event == Free) event_str = "Free"; std::chrono::duration<double> elapsed = e.end-e.start; csv << event_str << "," << e.deviceId << "," << e.ptr << "," << e.stream << "," << e.size << "," << e.freeMem << "," << e.totalMem << "," << e.currentAllocations << "," << std::chrono::duration<double>(e.start-base_time).count() << "," << std::chrono::duration<double>(e.end-base_time).count() << "," << elapsed.count() << "," << e.filename << ":" << e.line << std::endl; } } /** ---------------------------------------------------------------------------* * @brief Clear the log * --------------------------------------------------------------------------**/ void Logger::clear() { std::lock_guard<std::mutex> guard(log_mutex); events.clear(); } }
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2018 The QBICcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "main.h" #include "addrman.h" #include "masternode-budget.h" #include "masternode-sync.h" #include "masternode.h" #include "masternodeman.h" #include "obfuscation.h" #include "util.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; int nSubmittedFinalBudget; int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (Params().NetworkID() == CBaseChainParams::MAIN) return 43200; //for testing purposes return 144; //ten times per day } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization) { CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) { strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (fBudgetFinalization) { // Collateral for budget finalization // Note: there are still old valid budgets out there, but the check for the new 5 QBIC finalization collateral // will also cover the old 50 QBIC finalization collateral. LogPrint("mnbudget", "Final Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Final Budget: o.nValue(%ld) >= BUDGET_FEE_TX(%ld) ?\n", o.nValue, BUDGET_FEE_TX); if(o.nValue >= BUDGET_FEE_TX) { foundOpReturn = true; } } } else { // Collateral for normal budget proposal LogPrint("mnbudget", "Normal Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Normal Budget: o.nValue(%ld) >= PROPOSAL_FEE_TX(%ld) ?\n", o.nValue, PROPOSAL_FEE_TX); if(o.nValue >= PROPOSAL_FEE_TX) { foundOpReturn = true; } } } } if (!foundOpReturn) { strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have swiftTX information, so accept 1 confirmation if (conf >= Params().Budget_Fee_Confirmations()) { return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while (it1 != mapOrphanMasternodeBudgetVotes.end()) { if (budget.UpdateProposal(((*it1).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while (it2 != mapOrphanFinalizedBudgetVotes.end()) { if (budget.UpdateFinalizedBudget(((*it2).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Done\n"); } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if (!locked) return; if (!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if (nSubmittedHeight >= nBlockStart){ LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n", nSubmittedHeight, nBlockStart); return; } // Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet int finalizationWindow = ((GetBudgetPaymentCycleBlocks() / 30) * 2); if (Params().NetworkID() == CBaseChainParams::TESTNET) { // NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget, // because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck() finalizationWindow = 64; // 56 + 4 finalization confirmations + 4 minutes buffer for propagation } int nFinalizationStart = nBlockStart - finalizationWindow; int nOffsetToStart = nFinalizationStart - nCurrentHeight; if (nBlockStart - nCurrentHeight > finalizationWindow) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Too early for finalization. Current block is %ld, next Superblock is %ld.\n", nCurrentHeight, nBlockStart); LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - First possible block for finalization: %ld. Last possible block for finalization: %ld. You have to wait for %ld block(s) until Budget finalization will be possible\n", nFinalizationStart, nBlockStart, nOffsetToStart); return; } std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if (vecTxBudgetPayments.size() < 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0); if (mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if (!mapCollateralTxids.count(tempBudget.GetHash())) { CWalletTx wtx; if (!pwalletMain->GetBudgetFinalizationCollateralTX(wtx, tempBudget.GetHash(), false)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // Get our change address CReserveKey reservekey(pwalletMain); // Send the tx to the network. Do NOT use SwiftTx, locking might need too much time to propagate, especially for testnet pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(txidCollateral); CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if (conf < Params().Budget_Fee_Confirmations() + 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", Params().Budget_Fee_Confirmations() + 1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() { pathDB = GetDataDir() / "budget.dat"; strMagicMessage = "MasternodeBudget"; } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("mnbudget","Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("mnbudget","Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("mnbudget","Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrint("mnbudget","Budget manager - result:\n"); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrint("mnbudget","Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrint("mnbudget","Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrint("mnbudget","Error reading budget.dat: "); if (readResult == CBudgetDB::IncorrectFormat) LogPrint("mnbudget","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("mnbudget","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("mnbudget","Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrint("mnbudget","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if (!finalizedBudget.IsValid(strError)) return false; if (mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if (!budgetProposal.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if (mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ()); return true; } void CBudgetManager::CheckAndRemove() { int nHeight = 0; // Add some verbosity once loading blocks from files has finished { TRY_LOCK(cs_main, locked); if ((locked) && (chainActive.Tip() != NULL)) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev) { nHeight = pindexPrev->nHeight; } } } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight); map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets; map<uint256, CBudgetProposal> tmpMapProposals; std::string strError = ""; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size before: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid finalized budget: %s\n", strError); } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid finalized budget: %s %s\n", pfinalizedBudget->strBudgetName.c_str(), pfinalizedBudget->nFeeTXHash.ToString().c_str()); } if (pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); } ++it; } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid budget proposal - %s\n", strError); strError = ""; } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid budget proposal: %s %s\n", pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str()); } if (pbudgetProposal->fValid) { tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); } ++it2; } // Remove invalid entries by overwriting complete map mapFinalizedBudgets.swap(tmpMapFinalizedBudgets); mapProposals.swap(tmpMapProposals); // clang doesn't accept copy assignemnts :-/ // mapFinalizedBudgets = tmpMapFinalizedBudgets; // mapProposals = tmpMapProposals; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size after: %d\n", mapFinalizedBudgets.size()); LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size after: %d\n", mapProposals.size()); LogPrint("mnbudget","CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nHeight); if (fProofOfStake) { if (nHighestCount > 0) { unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld, nHighestCount = %d\n", address2.ToString(), nAmount, nHighestCount); } else { LogPrint("mnbudget","CBudgetManager::FillBlockPayee - No Budget payment, nHighestCount = %d\n", nHighestCount); } } else { //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if (nHighestCount > 0) { txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } } CFinalizedBudget* CBudgetManager::FindFinalizedBudget(uint256 nHash) { if (mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal* CBudgetManager::FindProposal(const std::string& strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) { pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if (nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal* CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if (mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsBudgetPaymentBlock() - nHighestCount: %lli, 5%% of Masternodes: %lli. Number of finalized budgets: %lli\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); // If budget doesn't have 5% of the network votes, then we should pay a masternode instead if (nHighestCount > nFivePercent) return true; return false; } TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nHighestCount = 0; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::vector<CFinalizedBudget*> ret; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking %lli finalized budgets\n", mapFinalizedBudgets.size()); // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsTransactionValid() - nHighestCount: %lli, 5%% of Masternodes: %lli mapFinalizedBudgets.size(): %ld\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if (nHighestCount < nFivePercent) return TrxValidationStatus::InValid; // check the highest finalized budgets (+/- 10% to assist in consensus) std::string strProposals = ""; int nCountThreshold = nHighestCount - mnodeman.CountEnabled(ActiveProtocol()) / 10; bool fThreshold = false; it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); strProposals = pfinalizedBudget->GetProposals(); LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking budget (%s) with blockstart %lli, blockend %lli, nBlockHeight %lli, votes %lli, nCountThreshold %lli\n", strProposals.c_str(), pfinalizedBudget->GetBlockStart(), pfinalizedBudget->GetBlockEnd(), nBlockHeight, pfinalizedBudget->GetVoteCount(), nCountThreshold); if (pfinalizedBudget->GetVoteCount() > nCountThreshold) { fThreshold = true; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetVoteCount() > nCountThreshold passed\n"); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() passed\n"); transactionStatus = pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() passed\n"); return TrxValidationStatus::Valid; } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() error\n"); } } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() failed, budget is outside current payment cycle and will be ignored.\n"); } } ++it; } // If not enough masternodes autovoted for any of the finalized budgets pay a masternode instead if(!fThreshold) { transactionStatus = TrxValidationStatus::VoteThreshold; } // We looked through all of the known budgets return transactionStatus; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int>& left, const std::pair<CBudgetProposal*, int>& right) { if (left.second != right.second) return (left.second > right.second); return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while (it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; LogPrint("mnbudget","CBudgetManager::GetBudget() - Processing Budget %s\n", pbudgetProposal->strProposalName.c_str()); //prop start/end should be inside this period if (pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(ActiveProtocol()) / 10 && pbudgetProposal->IsEstablished()) { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 passed: Budget added\n"); } else { pbudgetProposal->SetAllotted(0); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 failed: no amount allotted\n"); } } else { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); } ++it2; } return vBudgetProposalsRet; } // Sort by votes, if there's a tie sort by their feeHash TX struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int>& left, const std::pair<CFinalizedBudget*, int>& right) { if (left.second != right.second) return left.second > right.second; return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while (it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs); std::string ret = "unknown-budget"; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { CTxBudgetPayment payment; if (pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)) { if (ret == "unknown-budget") { ret = payment.nProposalHash.ToString(); } else { ret += ","; ret += payment.nProposalHash.ToString(); } } else { LogPrint("mnbudget","CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } } ++it; } return ret; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if (chainActive.Tip() == NULL) return 0; if (Params().NetworkID() == CBaseChainParams::TESTNET) { CAmount nSubsidy = 500 * COIN; return ((nSubsidy / 100) * 10) * 146; } //get block value and calculate from that CAmount nSubsidy = 0; if (nHeight <= Params().LAST_POW_BLOCK() && nHeight >= 151200) { nSubsidy = 50 * COIN; } else if (nHeight <= 302399 && nHeight > Params().LAST_POW_BLOCK()) { nSubsidy = 50 * COIN; } else if (nHeight <= 345599 && nHeight >= 302400) { nSubsidy = 45 * COIN; } else if (nHeight <= 388799 && nHeight >= 345600) { nSubsidy = 40 * COIN; } else if (nHeight <= 431999 && nHeight >= 388800) { nSubsidy = 35 * COIN; } else if (nHeight <= 475199 && nHeight >= 432000) { nSubsidy = 30 * COIN; } else if (nHeight <= 518399 && nHeight >= 475200) { nSubsidy = 25 * COIN; } else if (nHeight <= 561599 && nHeight >= 518400) { nSubsidy = 20 * COIN; } else if (nHeight <= 604799 && nHeight >= 561600) { nSubsidy = 15 * COIN; } else if (nHeight <= 647999 && nHeight >= 604800) { nSubsidy = 10 * COIN; } else if (nHeight >= Params().Zerocoin_Block_V2_Start()) { nSubsidy = 10 * COIN; } else { nSubsidy = 5 * COIN; } // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (nHeight <= 172800) { return 648000 * COIN; } else { return ((nSubsidy / 100) * 10) * 1440 * 30; } } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if (!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals if (chainActive.Height() % 14 != 0) return; // incremental sync with our peers if (masternodeSync.IsSynced()) { LogPrint("mnbudget","CBudgetManager::NewBlock - incremental sync started\n"); if (chainActive.Height() % 1440 == rand() % 1440) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->nVersion >= ActiveProtocol()) Sync(pnode, 0, true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrint("mnbudget","CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while (it != askedForSourceProposalOrBudget.end()) { if ((*it).second > GetTime() - (60 * 60 * 24)) { ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrint("mnbudget","CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { (*it2).second.CleanAndRemove(false); ++it2; } LogPrint("mnbudget","CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while (it3 != mapFinalizedBudgets.end()) { (*it3).second.CleanAndRemove(false); ++it3; } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while (it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)) { ++it4; continue; } if (!(*it4).IsValid(strError)) { LogPrint("mnbudget","mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if (AddProposal(budgetProposal)) { (*it4).Relay(); } LogPrint("mnbudget","mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while (it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf, true)) { ++it5; continue; } if (!(*it5).IsValid(strError)) { LogPrint("mnbudget","fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrint("mnbudget","fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if (AddFinalizedBudget(finalizedBudget)) { (*it5).Relay(); } it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrint("mnbudget","CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if (fLiteMode) return; if (!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (nProp == 0) { if (pfrom->HasFulfilledRequest("mnvs")) { LogPrint("mnbudget","mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrint("mnbudget", "mnvs - Sent Masternode votes to peer %i\n", pfrom->GetId()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if (mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { LogPrint("mnbudget","Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if (!budgetProposalBroadcast.IsValid(strError)) { LogPrint("mnbudget","mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if (AddProposal(budgetProposal)) { budgetProposalBroadcast.Relay(); } masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrint("mnbudget","mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenMasternodeBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget","mvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : mvote - signature invalid\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrint("mnbudget","mvote - new budget vote for budget %s - %s\n", vote.nProposalHash.ToString(), vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if (mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf, true)) { LogPrint("mnbudget","fbs - Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","fbs - invalid finalized budget - %s\n", strError); return; } LogPrint("mnbudget","fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if (AddFinalizedBudget(finalizedBudget)) { finalizedBudgetBroadcast.Relay(); } masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenFinalizedBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : fbvote - signature invalid\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrint("mnbudget","fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrint("mnbudget","fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if (mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid && (nProp == 0 || (*it1).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) { if ((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid && (nProp == 0 || (*it3).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) { if ((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapProposals.count(vote.nProposalHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nProposalHash)) { pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError); } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapFinalizedBudgets.count(vote.nBudgetHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nBudgetHash)) { pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget " + vote.nBudgetHash.ToString() + " not found!"; return false; } LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Finalized Proposal %s added\n", vote.nBudgetHash.ToString()); return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if (GetNays() - GetYeas() > mnodeman.CountEnabled(ActiveProtocol()) / 10) { strError = "Proposal " + strProposalName + ": Active removal"; return false; } if (nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if (nBlockEnd < nBlockStart) { strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (end before start)"; return false; } if (nAmount < 10 * COIN) { strError = "Proposal " + strProposalName + ": Invalid nAmount"; return false; } if (address == CScript()) { strError = "Proposal " + strProposalName + ": Invalid Payment Address"; return false; } if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)) { strError = "Proposal " + strProposalName + ": Invalid collateral"; return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if (address.IsPayToScriptHash()) { strError = "Proposal " + strProposalName + ": Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(ActiveProtocol())/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if (nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Proposal " + strProposalName + ": Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) { strError = "Proposal " + strProposalName + ": Tip is NULL"; return true; } // Calculate maximum block this proposal will be valid, which is start of proposal + (number of payments * cycle) int nProposalEnd = GetBlockStart() + (GetBudgetPaymentCycleBlocks() * GetTotalPaymentCount()); // if (GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() / 2) { if(nProposalEnd < pindexPrev->nHeight){ strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (" + std::to_string(nProposalEnd) + ") < current height (" + std::to_string(pindexPrev->nHeight) + ")"; return false; } return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { std::string strAction = "New vote inserted:"; LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() { int yeas = 0; int nays = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES) yeas++; if ((*it).second.nVote == VOTE_NO) nays++; ++it; } if (yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas + nays)); } int CBudgetProposal::GetYeas() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetNays() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetAbstains() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetBlockStartCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return -1; if (pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() { // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) // return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; // End block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd; } int CBudgetProposal::GetTotalPaymentCount() { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) // nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks() / 2; // Calculate the end of the cycle for this vote, vote will be deleted after next cycle nBlockEnd = nCycleStart + (GetBudgetPaymentCycleBlocks() + 1) * nPaymentCount; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = 0; nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { if (fDebug){ LogPrint("mnbudget","CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.prevout.hash.ToString()); } return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = 0; nTime = 0; fValid = true; fAutoChecked = false; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; } bool CFinalizedBudget::AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); std::string strAction = "New vote inserted:"; if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; LogPrint("mnbudget","CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if (!fMasterNode || fAutoChecked) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck fMasterNode=%d fAutoChecked=%d\n", fMasterNode, fAutoChecked); return; } // Do this 1 in 4 blocks -- spread out the voting activity // -- this function is only called every fourteenth block, so this is really 1 in 56 blocks if (rand() % 4 != 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - waiting\n"); return; } fAutoChecked = true; //we only need to check this once if (strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if (vBudgetProposals.size() == 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - No Budget-Proposals found, aborting\n"); return; } if (vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Budget-Proposal length (%ld) doesn't match Budget-Payment length (%ld).\n", vBudgetProposals.size(), vecBudgetPayments.size()); return; } for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { if (i > vBudgetProposals.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Proposal size mismatch, i=%d > (vBudgetProposals.size() - 1)=%d\n", i, vBudgetProposals.size() - 1); return; } if (vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if (vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if (vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() { CAmount ret = 0; for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH (CTxBudgetPayment& budgetPayment, vecBudgetPayments) { CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if (pbudgetProposal) token = pbudgetProposal->GetName(); if (ret == "") { ret = token; } else { ret += "," + token; } } return ret; } std::string CFinalizedBudget::GetStatus() { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for (int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if (!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)) { LogPrint("mnbudget","CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if (!pbudgetProposal) { if (retBadHashes == "") { retBadHashes = "Unknown proposal hash! Check this proposal before voting: " + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if (pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if (retBadPayeeOrAmount == "") { retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if (retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) { // All(!) finalized budgets have the name "main", so get some additional information about them std::string strProposals = GetProposals(); // Must be the correct block for payment to happen (once a month) if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { strError = "Invalid BlockStart"; return false; } // The following 2 checks check the same (basically if vecBudgetPayments.size() > 100) if (GetBlockEnd() - nBlockStart > 100) { strError = "Invalid BlockEnd"; return false; } if ((int)vecBudgetPayments.size() > 100) { strError = "Invalid budget payments count (too many)"; return false; } if (strBudgetName == "") { strError = "Invalid Budget Name"; return false; } if (nBlockStart == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid BlockStart == 0"; return false; } if (nFeeTXHash == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid FeeTx == 0"; return false; } // Can only pay out 10% of the possible coins (min value of coins) if (GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Payout (more than max)"; return false; } std::string strError2 = ""; if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf, true)) { { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Collateral : " + strError2; return false; } } } // Remove obsolete finalized budgets after some time CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; // Get start of current budget-cycle int nCurrentHeight = chainActive.Height(); int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); // Remove budgets where the last payment (from max. 100) ends before 2 budget-cycles before the current one int nMaxAge = nBlockStart - (2 * GetBudgetPaymentCycleBlocks()); if (GetBlockEnd() < nMaxAge) { strError = strprintf("Budget " + strBudgetName + " (" + strProposals + ") (ends at block %ld) too old and obsolete", GetBlockEnd()); return false; } return true; } bool CFinalizedBudget::IsPaidAlready(uint256 nProposalHash, int nBlockHeight) { // Remove budget-payments from former/future payment cycles map<uint256, int>::iterator it = mapPayment_History.begin(); int nPaidBlockHeight = 0; uint256 nOldProposalHash; for(it = mapPayment_History.begin(); it != mapPayment_History.end(); /* No incrementation needed */ ) { nPaidBlockHeight = (*it).second; if((nPaidBlockHeight < GetBlockStart()) || (nPaidBlockHeight > GetBlockEnd())) { nOldProposalHash = (*it).first; LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d from old cycle deleted\n", nOldProposalHash.ToString().c_str(), nPaidBlockHeight); mapPayment_History.erase(it++); } else { ++it; } } // Now that we only have payments from the current payment cycle check if this budget was paid already if(mapPayment_History.count(nProposalHash) == 0) { // New proposal payment, insert into map for checks with later blocks from this cycle mapPayment_History.insert(std::pair<uint256, int>(nProposalHash, nBlockHeight)); LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d added to payment history\n", nProposalHash.ToString().c_str(), nBlockHeight); return false; } // This budget was paid already -> reject transaction so it gets paid to a masternode instead return true; } TrxValidationStatus CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if (nCurrentBudgetPayment < 0) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return TrxValidationStatus::InValid; } if (nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid last block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return TrxValidationStatus::InValid; } bool paid = false; BOOST_FOREACH (CTxOut out, txNew.vout) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - nCurrentBudgetPayment=%d, payee=%s == out.scriptPubKey=%s, amount=%ld == out.nValue=%ld\n", nCurrentBudgetPayment, vecBudgetPayments[nCurrentBudgetPayment].payee.ToString().c_str(), out.scriptPubKey.ToString().c_str(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, out.nValue); if (vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) { // Check if this proposal was paid already. If so, pay a masternode instead paid = IsPaidAlready(vecBudgetPayments[nCurrentBudgetPayment].nProposalHash, nBlockHeight); if(paid) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Double Budget Payment of %d for proposal %d detected. Paying a masternode instead.\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); // No matter what we've found before, stop all checks here. In future releases there might be more than one budget payment // per block, so even if the first one was not paid yet this one disables all budget payments for this block. transactionStatus = TrxValidationStatus::DoublePayment; break; } else { transactionStatus = TrxValidationStatus::Valid; LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Found valid Budget Payment of %d for proposal %d\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); } } } if (transactionStatus == TrxValidationStatus::InValid) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d c: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, nCurrentBudgetPayment); } return transactionStatus; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrint("mnbudget","CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = 0; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH (CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH (CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = 0; nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Unknown Masternode %s\n", strMessage); return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Verify message failed %s %s\n", strMessage, errorMessage); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); }
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <cstring> using namespace std; struct Edge { int From, To, Pow; }; vector<Edge> G[501]; int dis[501], cnt[501]; bool inq[501], vis[501]; bool Spfa(int s, int n) { memset(dis, 0x3f, sizeof dis); memset(inq, 0, sizeof inq); memset(cnt, 0, sizeof cnt); dis[s] = 0; queue<int> q; q.push(s); inq[s] = true; cnt[s] = 1; vis[s] = true; while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for (int i = 0; i < G[u].size(); i++) { Edge &e = G[u][i]; vis[e.To] = true; int tmp = dis[e.To]; dis[e.To] = min(dis[e.To], dis[e.From] + e.Pow); if (tmp != dis[e.To] && !inq[e.To]) { if (++cnt[e.To] == n) return false; q.push(e.To); inq[e.To] = true; } } } return true; } int main() { ios::sync_with_stdio(false); int f; cin >> f; for (int i = 1; i <= f; i++) { int n, m, w; cin >> n >> m >> w; for (int j = 1; j <= n; j++) G[j].clear(); for (int j = 1; j <= m; j++) { int s, e, t; cin >> s >> e >> t; G[s].push_back(Edge{ s,e,t }); G[e].push_back(Edge{ e,s,t }); } for (int j = 1; j <= w; j++) { int s, e, t; cin >> s >> e >> t; G[s].push_back(Edge{ s,e,-t }); } memset(vis, 0, sizeof vis); bool x = false; for (int i = 1; i <= n; i++) { if (!vis[i] && !Spfa(i, n)) { x = true; break; } } cout << (x ? "YES" : "NO") << endl; } }
/* * Copyright (C) 2010, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "modules/webaudio/RealtimeAnalyser.h" #include "platform/audio/AudioBus.h" #include "platform/audio/AudioUtilities.h" #include "platform/audio/VectorMath.h" #include "wtf/MainThread.h" #include "wtf/MathExtras.h" #include <algorithm> #include <complex> #include <limits.h> namespace blink { const double RealtimeAnalyser::DefaultSmoothingTimeConstant = 0.8; const double RealtimeAnalyser::DefaultMinDecibels = -100; const double RealtimeAnalyser::DefaultMaxDecibels = -30; const unsigned RealtimeAnalyser::DefaultFFTSize = 2048; // All FFT implementations are expected to handle power-of-two sizes MinFFTSize <= size <= MaxFFTSize. const unsigned RealtimeAnalyser::MinFFTSize = 32; const unsigned RealtimeAnalyser::MaxFFTSize = 32768; const unsigned RealtimeAnalyser::InputBufferSize = RealtimeAnalyser::MaxFFTSize * 2; RealtimeAnalyser::RealtimeAnalyser() : m_inputBuffer(InputBufferSize) , m_writeIndex(0) , m_fftSize(DefaultFFTSize) , m_magnitudeBuffer(DefaultFFTSize / 2) , m_smoothingTimeConstant(DefaultSmoothingTimeConstant) , m_minDecibels(DefaultMinDecibels) , m_maxDecibels(DefaultMaxDecibels) { m_analysisFrame = adoptPtr(new FFTFrame(DefaultFFTSize)); } bool RealtimeAnalyser::setFftSize(size_t size) { ASSERT(isMainThread()); // Only allow powers of two. unsigned log2size = static_cast<unsigned>(log2(size)); bool isPOT(1UL << log2size == size); if (!isPOT || size > MaxFFTSize || size < MinFFTSize) return false; if (m_fftSize != size) { m_analysisFrame = adoptPtr(new FFTFrame(size)); // m_magnitudeBuffer has size = fftSize / 2 because it contains floats reduced from complex values in m_analysisFrame. m_magnitudeBuffer.allocate(size / 2); m_fftSize = size; } return true; } void RealtimeAnalyser::writeInput(AudioBus* bus, size_t framesToProcess) { bool isBusGood = bus && bus->numberOfChannels() > 0 && bus->channel(0)->length() >= framesToProcess; ASSERT(isBusGood); if (!isBusGood) return; // FIXME : allow to work with non-FFTSize divisible chunking bool isDestinationGood = m_writeIndex < m_inputBuffer.size() && m_writeIndex + framesToProcess <= m_inputBuffer.size(); ASSERT(isDestinationGood); if (!isDestinationGood) return; // Perform real-time analysis const float* source = bus->channel(0)->data(); float* dest = m_inputBuffer.data() + m_writeIndex; // The source has already been sanity checked with isBusGood above. memcpy(dest, source, sizeof(float) * framesToProcess); // Sum all channels in one if numberOfChannels > 1. unsigned numberOfChannels = bus->numberOfChannels(); if (numberOfChannels > 1) { for (unsigned i = 1; i < numberOfChannels; ++i) { source = bus->channel(i)->data(); VectorMath::vadd(dest, 1, source, 1, dest, 1, framesToProcess); } const float scale = 1.0 / numberOfChannels; VectorMath::vsmul(dest, 1, &scale, dest, 1, framesToProcess); } m_writeIndex += framesToProcess; if (m_writeIndex >= InputBufferSize) m_writeIndex = 0; } namespace { void applyWindow(float* p, size_t n) { ASSERT(isMainThread()); // Blackman window double alpha = 0.16; double a0 = 0.5 * (1 - alpha); double a1 = 0.5; double a2 = 0.5 * alpha; for (unsigned i = 0; i < n; ++i) { double x = static_cast<double>(i) / static_cast<double>(n); double window = a0 - a1 * cos(twoPiDouble * x) + a2 * cos(twoPiDouble * 2.0 * x); p[i] *= float(window); } } } // namespace void RealtimeAnalyser::doFFTAnalysis() { ASSERT(isMainThread()); // Unroll the input buffer into a temporary buffer, where we'll apply an analysis window followed by an FFT. size_t fftSize = this->fftSize(); AudioFloatArray temporaryBuffer(fftSize); float* inputBuffer = m_inputBuffer.data(); float* tempP = temporaryBuffer.data(); // Take the previous fftSize values from the input buffer and copy into the temporary buffer. unsigned writeIndex = m_writeIndex; if (writeIndex < fftSize) { memcpy(tempP, inputBuffer + writeIndex - fftSize + InputBufferSize, sizeof(*tempP) * (fftSize - writeIndex)); memcpy(tempP + fftSize - writeIndex, inputBuffer, sizeof(*tempP) * writeIndex); } else { memcpy(tempP, inputBuffer + writeIndex - fftSize, sizeof(*tempP) * fftSize); } // Window the input samples. applyWindow(tempP, fftSize); // Do the analysis. m_analysisFrame->doFFT(tempP); float* realP = m_analysisFrame->realData(); float* imagP = m_analysisFrame->imagData(); // Blow away the packed nyquist component. imagP[0] = 0; // Normalize so than an input sine wave at 0dBfs registers as 0dBfs (undo FFT scaling factor). const double magnitudeScale = 1.0 / fftSize; // A value of 0 does no averaging with the previous result. Larger values produce slower, but smoother changes. double k = m_smoothingTimeConstant; k = std::max(0.0, k); k = std::min(1.0, k); // Convert the analysis data from complex to magnitude and average with the previous result. float* destination = magnitudeBuffer().data(); size_t n = magnitudeBuffer().size(); for (size_t i = 0; i < n; ++i) { std::complex<double> c(realP[i], imagP[i]); double scalarMagnitude = abs(c) * magnitudeScale; destination[i] = float(k * destination[i] + (1 - k) * scalarMagnitude); } } void RealtimeAnalyser::getFloatFrequencyData(DOMFloat32Array* destinationArray) { ASSERT(isMainThread()); ASSERT(destinationArray); doFFTAnalysis(); // Convert from linear magnitude to floating-point decibels. const double minDecibels = m_minDecibels; unsigned sourceLength = magnitudeBuffer().size(); size_t len = std::min(sourceLength, destinationArray->length()); if (len > 0) { const float* source = magnitudeBuffer().data(); float* destination = destinationArray->data(); for (unsigned i = 0; i < len; ++i) { float linearValue = source[i]; double dbMag = !linearValue ? minDecibels : AudioUtilities::linearToDecibels(linearValue); destination[i] = float(dbMag); } } } void RealtimeAnalyser::getByteFrequencyData(DOMUint8Array* destinationArray) { ASSERT(isMainThread()); ASSERT(destinationArray); doFFTAnalysis(); // Convert from linear magnitude to unsigned-byte decibels. unsigned sourceLength = magnitudeBuffer().size(); size_t len = std::min(sourceLength, destinationArray->length()); if (len > 0) { const double rangeScaleFactor = m_maxDecibels == m_minDecibels ? 1 : 1 / (m_maxDecibels - m_minDecibels); const double minDecibels = m_minDecibels; const float* source = magnitudeBuffer().data(); unsigned char* destination = destinationArray->data(); for (unsigned i = 0; i < len; ++i) { float linearValue = source[i]; double dbMag = !linearValue ? minDecibels : AudioUtilities::linearToDecibels(linearValue); // The range m_minDecibels to m_maxDecibels will be scaled to byte values from 0 to UCHAR_MAX. double scaledValue = UCHAR_MAX * (dbMag - minDecibels) * rangeScaleFactor; // Clip to valid range. if (scaledValue < 0) scaledValue = 0; if (scaledValue > UCHAR_MAX) scaledValue = UCHAR_MAX; destination[i] = static_cast<unsigned char>(scaledValue); } } } void RealtimeAnalyser::getFloatTimeDomainData(DOMFloat32Array* destinationArray) { ASSERT(isMainThread()); ASSERT(destinationArray); unsigned fftSize = this->fftSize(); size_t len = std::min(fftSize, destinationArray->length()); if (len > 0) { bool isInputBufferGood = m_inputBuffer.size() == InputBufferSize && m_inputBuffer.size() > fftSize; ASSERT(isInputBufferGood); if (!isInputBufferGood) return; float* inputBuffer = m_inputBuffer.data(); float* destination = destinationArray->data(); unsigned writeIndex = m_writeIndex; for (unsigned i = 0; i < len; ++i) { // Buffer access is protected due to modulo operation. float value = inputBuffer[(i + writeIndex - fftSize + InputBufferSize) % InputBufferSize]; destination[i] = value; } } } void RealtimeAnalyser::getByteTimeDomainData(DOMUint8Array* destinationArray) { ASSERT(isMainThread()); ASSERT(destinationArray); unsigned fftSize = this->fftSize(); size_t len = std::min(fftSize, destinationArray->length()); if (len > 0) { bool isInputBufferGood = m_inputBuffer.size() == InputBufferSize && m_inputBuffer.size() > fftSize; ASSERT(isInputBufferGood); if (!isInputBufferGood) return; float* inputBuffer = m_inputBuffer.data(); unsigned char* destination = destinationArray->data(); unsigned writeIndex = m_writeIndex; for (unsigned i = 0; i < len; ++i) { // Buffer access is protected due to modulo operation. float value = inputBuffer[(i + writeIndex - fftSize + InputBufferSize) % InputBufferSize]; // Scale from nominal -1 -> +1 to unsigned byte. double scaledValue = 128 * (value + 1); // Clip to valid range. if (scaledValue < 0) scaledValue = 0; if (scaledValue > UCHAR_MAX) scaledValue = UCHAR_MAX; destination[i] = static_cast<unsigned char>(scaledValue); } } } } // namespace blink
// Concord // // Copyright (c) 2021 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 // License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the LICENSE // file. #pragma once #include <stdint.h> #include <functional> #include <deque> #include <memory> #include "assertUtils.hpp" namespace concord::util { /** * This is a template class that implements a simple memory pool for a single type of element. * A common use case for this class is the pre-allocation of N elements at the start. This is done in order to: * 1) Make sure the only possible allocation failures in the module can happen on boot (startup). * 2) Avoid allocation/deallocation of memory. Specifically, for small memory chunks, in the long term this can cause * performance issues and memory defragmentation. * Currently, the class does not implements pool of elements of pointer or array type. */ template <typename T> class SimpleMemoryPool { static_assert(!std::is_array<T>::value, "Array type not supported!"); static_assert(!std::is_pointer<T>::value, "Pointer type not supported!"); public: using ElementPtr = std::shared_ptr<T>; SimpleMemoryPool(size_t maxNumElements, std::function<void(ElementPtr&)> allocCallback = nullptr, std::function<void(ElementPtr&)> freeCallback = nullptr, std::function<void()> ctorCallback = nullptr) : maxNumElements_(maxNumElements), allocCallback_{allocCallback}, freeCallback_(freeCallback) { if (maxNumElements == 0) throw std::invalid_argument("maxNumElements cannnot be 0!"); if (ctorCallback) ctorCallback(); for (size_t i{0}; i < maxNumElements_; ++i) { auto element = std::make_shared<T>(); freeQ_.push_back(element); } } size_t numFreeElements() const { return freeQ_.size(); } size_t numAllocatedElements() const { return allocatedQ_.size(); } bool empty() { return freeQ_.empty(); }; bool full() { return allocatedQ_.empty(); }; size_t maxElements() { return maxNumElements_; }; ElementPtr alloc() { if (freeQ_.empty()) { throw std::runtime_error("No more free elements!"); } auto ret = freeQ_.front(); freeQ_.pop_front(); allocatedQ_.push_back(ret); if (allocCallback_) { allocCallback_(ret); } return ret; } void free(ElementPtr& element) { if (freeQ_.size() == maxNumElements_) { throw std::runtime_error("All elements have been already returned!"); } if (std::find(allocatedQ_.begin(), allocatedQ_.end(), element) == allocatedQ_.end()) { throw std::runtime_error("Trying to free unrocognized element (element was not allocated by this pool)!"); } auto ret = allocatedQ_.front(); allocatedQ_.pop_front(); if (freeCallback_) { freeCallback_(ret); } freeQ_.push_back(std::move(element)); } private: const size_t maxNumElements_; std::deque<ElementPtr> freeQ_; std::deque<ElementPtr> allocatedQ_; std::function<void(ElementPtr&)> allocCallback_; std::function<void(ElementPtr&)> freeCallback_; }; // SimpleMemoryPool } // namespace concord::util
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2012 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <stdio.h> #include "pin.H" #include <iostream> UINT64 icount = 0; UINT32 icountMax = 10000; VOID docount() { if (++icount == icountMax) { fprintf(stderr, "Send detach request form analysis routine after %d instructions\n", icountMax); PIN_Detach(); } } VOID Instruction(INS ins, VOID *v) { INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END); } VOID Fini(INT32 code, VOID *v) { std::cerr << "Count: " << icount << endl; } int main(int argc, char * argv[]) { PIN_Init(argc, argv); INS_AddInstrumentFunction(Instruction, 0); PIN_AddFiniFunction(Fini, 0); // Never returns PIN_StartProgram(); return 0; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "google_apis/gcm/engine/connection_handler_impl.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/test_timeouts.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include "google/protobuf/wire_format_lite.h" #include "google_apis/gcm/base/mcs_util.h" #include "google_apis/gcm/base/socket_stream.h" #include "google_apis/gcm/protocol/mcs.pb.h" #include "net/base/ip_address.h" #include "net/base/test_completion_callback.h" #include "net/log/net_log_source.h" #include "net/socket/socket_test_util.h" #include "net/socket/stream_socket.h" #include "net/test/gtest_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gtest/include/gtest/gtest.h" namespace gcm { namespace { typedef std::unique_ptr<google::protobuf::MessageLite> ScopedMessage; typedef std::vector<net::MockRead> ReadList; typedef std::vector<net::MockWrite> WriteList; const uint64_t kAuthId = 54321; const uint64_t kAuthToken = 12345; const char kMCSVersion = 41; // The protocol version. const int kMCSPort = 5228; // The server port. const char kDataMsgFrom[] = "data_from"; const char kDataMsgCategory[] = "data_category"; const char kDataMsgFrom2[] = "data_from2"; const char kDataMsgCategory2[] = "data_category2"; const char kDataMsgFromLong[] = "this is a long from that will result in a message > 128 bytes"; const char kDataMsgCategoryLong[] = "this is a long category that will result in a message > 128 bytes"; const char kDataMsgFromLong2[] = "this is a second long from that will result in a message > 128 bytes"; const char kDataMsgCategoryLong2[] = "this is a second long category that will result in a message > 128 bytes"; const uint8_t kInvalidTag = 100; // An invalid tag. // ---- Helpers for building messages. ---- // Encode a protobuf packet with protobuf type |tag| and serialized protobuf // bytes |proto| into the MCS message form (tag + varint size + bytes). std::string EncodePacket(uint8_t tag, const std::string& proto) { std::string result; google::protobuf::io::StringOutputStream string_output_stream(&result); { google::protobuf::io::CodedOutputStream coded_output_stream( &string_output_stream); const unsigned char tag_byte[1] = { tag }; coded_output_stream.WriteRaw(tag_byte, 1); coded_output_stream.WriteVarint32(proto.size()); coded_output_stream.WriteRaw(proto.c_str(), proto.size()); // ~CodedOutputStream must run before the move constructor at the // return statement. http://crbug.com/338962 } return result; } // Encode a handshake request into the MCS message form. std::string EncodeHandshakeRequest() { std::string result; const char version_byte[1] = {kMCSVersion}; result.append(version_byte, 1); ScopedMessage login_request( BuildLoginRequest(kAuthId, kAuthToken, "")); result.append(EncodePacket(kLoginRequestTag, login_request->SerializeAsString())); return result; } // Build a serialized login response protobuf. std::string BuildLoginResponse() { std::string result; mcs_proto::LoginResponse login_response; login_response.set_id("id"); result.append(login_response.SerializeAsString()); return result; } // Encoode a handshake response into the MCS message form. std::string EncodeHandshakeResponse() { std::string result; const char version_byte[1] = {kMCSVersion}; result.append(version_byte, 1); result.append(EncodePacket(kLoginResponseTag, BuildLoginResponse())); return result; } // Build a serialized data message stanza protobuf. std::string BuildDataMessage(const std::string& from, const std::string& category) { mcs_proto::DataMessageStanza data_message; data_message.set_from(from); data_message.set_category(category); return data_message.SerializeAsString(); } // Build a corrupt data message that will force the protobuf parser to backup // after completion (useful in testing memory corruption cases due to a // CodedInputStream going out of scope). std::string BuildCorruptDataMessage() { // Manually construct the message with invalid data. We set field 2 (id) to // be an invalid string. const int kMsgTag = (2 << google::protobuf::internal::WireFormatLite::kTagTypeBits) | google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED; const int kStringLength = -1; // Corrupted length. const char kStringData[] = "id"; std::string data_message_proto; google::protobuf::io::StringOutputStream string_output_stream( &data_message_proto); { google::protobuf::io::CodedOutputStream coded_output_stream( &string_output_stream); coded_output_stream.WriteVarint32(kMsgTag); coded_output_stream.WriteVarint32( static_cast<google::protobuf::uint32>(kStringLength)); coded_output_stream.WriteRaw(&kStringData, sizeof(kStringData)); // ~CodedOutputStream must run before the move constructor at the // return statement. http://crbug.com/338962 } return data_message_proto; } class GCMConnectionHandlerImplTest : public testing::Test { public: GCMConnectionHandlerImplTest(); ~GCMConnectionHandlerImplTest() override; net::StreamSocket* BuildSocket(const ReadList& read_list, const WriteList& write_list); // Pump |message_loop_|, resetting |run_loop_| after completion. void PumpLoop(); ConnectionHandlerImpl* connection_handler() { return connection_handler_.get(); } base::MessageLoop* message_loop() { return &message_loop_; } net::StaticSocketDataProvider* data_provider() { return data_provider_.get(); } int last_error() const { return last_error_; } // Initialize the connection handler, setting |dst_proto| as the destination // for any received messages. void Connect(ScopedMessage* dst_proto); // Runs the message loop until a message is received. void WaitForMessage(); private: void ReadContinuation(ScopedMessage* dst_proto, ScopedMessage new_proto); void WriteContinuation(); void ConnectionContinuation(int error); // SocketStreams and their data provider. ReadList mock_reads_; WriteList mock_writes_; std::unique_ptr<net::StaticSocketDataProvider> data_provider_; // The connection handler being tested. std::unique_ptr<ConnectionHandlerImpl> connection_handler_; // The last connection error received. int last_error_; // net:: components. std::unique_ptr<net::StreamSocket> socket_; net::MockClientSocketFactory socket_factory_; net::AddressList address_list_; base::MessageLoopForIO message_loop_; std::unique_ptr<base::RunLoop> run_loop_; }; GCMConnectionHandlerImplTest::GCMConnectionHandlerImplTest() : last_error_(0) { address_list_ = net::AddressList::CreateFromIPAddress( net::IPAddress::IPv4Localhost(), kMCSPort); } GCMConnectionHandlerImplTest::~GCMConnectionHandlerImplTest() { } net::StreamSocket* GCMConnectionHandlerImplTest::BuildSocket( const ReadList& read_list, const WriteList& write_list) { mock_reads_ = read_list; mock_writes_ = write_list; data_provider_ = std::make_unique<net::StaticSocketDataProvider>( mock_reads_, mock_writes_); socket_factory_.AddSocketDataProvider(data_provider_.get()); run_loop_ = std::make_unique<base::RunLoop>(); socket_ = socket_factory_.CreateTransportClientSocket( address_list_, NULL, NULL, net::NetLogSource()); net::TestCompletionCallback callback; int rv = socket_->Connect(callback.callback()); EXPECT_THAT(rv, net::test::IsError(net::ERR_IO_PENDING)); rv = callback.WaitForResult(); EXPECT_THAT(rv, net::test::IsOk()); EXPECT_TRUE(socket_->IsConnected()); return socket_.get(); } void GCMConnectionHandlerImplTest::PumpLoop() { run_loop_->RunUntilIdle(); run_loop_ = std::make_unique<base::RunLoop>(); } void GCMConnectionHandlerImplTest::Connect( ScopedMessage* dst_proto) { connection_handler_ = std::make_unique<ConnectionHandlerImpl>( TestTimeouts::tiny_timeout(), base::Bind(&GCMConnectionHandlerImplTest::ReadContinuation, base::Unretained(this), dst_proto), base::Bind(&GCMConnectionHandlerImplTest::WriteContinuation, base::Unretained(this)), base::Bind(&GCMConnectionHandlerImplTest::ConnectionContinuation, base::Unretained(this))); EXPECT_FALSE(connection_handler()->CanSendMessage()); connection_handler_->Init(*BuildLoginRequest(kAuthId, kAuthToken, ""), TRAFFIC_ANNOTATION_FOR_TESTS, socket_.get()); } void GCMConnectionHandlerImplTest::ReadContinuation( ScopedMessage* dst_proto, ScopedMessage new_proto) { *dst_proto = std::move(new_proto); run_loop_->Quit(); } void GCMConnectionHandlerImplTest::WaitForMessage() { run_loop_->Run(); run_loop_ = std::make_unique<base::RunLoop>(); } void GCMConnectionHandlerImplTest::WriteContinuation() { run_loop_->Quit(); } void GCMConnectionHandlerImplTest::ConnectionContinuation(int error) { last_error_ = error; if (error != net::OK) connection_handler_->Reset(); run_loop_->Quit(); } // Initialize the connection handler and ensure the handshake completes // successfully. TEST_F(GCMConnectionHandlerImplTest, Init) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); ReadList read_list(1, net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); EXPECT_FALSE(connection_handler()->CanSendMessage()); WaitForMessage(); // The login send. WaitForMessage(); // The login response. ASSERT_TRUE(received_message.get()); EXPECT_EQ(BuildLoginResponse(), received_message->SerializeAsString()); EXPECT_TRUE(connection_handler()->CanSendMessage()); } // Simulate the handshake response returning an older version. Initialization // should fail. TEST_F(GCMConnectionHandlerImplTest, InitFailedVersionCheck) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); // Overwrite the version byte. handshake_response[0] = 37; ReadList read_list(1, net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. Should result in a connection error. EXPECT_FALSE(received_message.get()); EXPECT_FALSE(connection_handler()->CanSendMessage()); EXPECT_EQ(net::ERR_FAILED, last_error()); } // Attempt to initialize, but receive no server response, resulting in a time // out. TEST_F(GCMConnectionHandlerImplTest, InitTimeout) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); ReadList read_list(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. Should result in a connection error. EXPECT_FALSE(received_message.get()); EXPECT_FALSE(connection_handler()->CanSendMessage()); EXPECT_EQ(net::ERR_TIMED_OUT, last_error()); } // Attempt to initialize, but receive an incomplete server response, resulting // in a time out. TEST_F(GCMConnectionHandlerImplTest, InitIncompleteTimeout) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size() / 2)); read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. Should result in a connection error. EXPECT_FALSE(received_message.get()); EXPECT_FALSE(connection_handler()->CanSendMessage()); EXPECT_EQ(net::ERR_TIMED_OUT, last_error()); } // Reinitialize the connection handler after failing to initialize. TEST_F(GCMConnectionHandlerImplTest, ReInit) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); ReadList read_list(1, net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. Should result in a connection error. EXPECT_FALSE(received_message.get()); EXPECT_FALSE(connection_handler()->CanSendMessage()); EXPECT_EQ(net::ERR_TIMED_OUT, last_error()); // Build a new socket and reconnect, successfully this time. std::string handshake_response = EncodeHandshakeResponse(); read_list[0] = net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size()); BuildSocket(read_list, write_list); Connect(&received_message); EXPECT_FALSE(connection_handler()->CanSendMessage()); WaitForMessage(); // The login send. WaitForMessage(); // The login response. ASSERT_TRUE(received_message.get()); EXPECT_EQ(BuildLoginResponse(), received_message->SerializeAsString()); EXPECT_TRUE(connection_handler()->CanSendMessage()); } // Verify that messages can be received after initialization. TEST_F(GCMConnectionHandlerImplTest, RecvMsg) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFrom, kDataMsgCategory); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Verify that if two messages arrive at once, they're treated appropriately. TEST_F(GCMConnectionHandlerImplTest, Recv2Msgs) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFrom, kDataMsgCategory); std::string data_message_proto2 = BuildDataMessage(kDataMsgFrom2, kDataMsgCategory2); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); data_message_pkt += EncodePacket(kDataMessageStanzaTag, data_message_proto2); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::SYNCHRONOUS, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The first data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); received_message.reset(); WaitForMessage(); // The second data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto2, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Receive a long (>128 bytes) message. TEST_F(GCMConnectionHandlerImplTest, RecvLongMsg) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); DCHECK_GT(data_message_pkt.size(), 128U); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Receive a long (>128 bytes) message in two synchronous parts. TEST_F(GCMConnectionHandlerImplTest, RecvLongMsg2Parts) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); DCHECK_GT(data_message_pkt.size(), 128U); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); int bytes_in_first_message = data_message_pkt.size() / 2; read_list.push_back(net::MockRead(net::SYNCHRONOUS, data_message_pkt.c_str(), bytes_in_first_message)); read_list.push_back(net::MockRead(net::SYNCHRONOUS, data_message_pkt.c_str() + bytes_in_first_message, data_message_pkt.size() - bytes_in_first_message)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(net::OK, last_error()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); } // Receive two long (>128 bytes) message. TEST_F(GCMConnectionHandlerImplTest, Recv2LongMsgs) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong); std::string data_message_proto2 = BuildDataMessage(kDataMsgFromLong2, kDataMsgCategoryLong2); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); data_message_pkt += EncodePacket(kDataMessageStanzaTag, data_message_proto2); DCHECK_GT(data_message_pkt.size(), 256U); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::SYNCHRONOUS, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The first data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); received_message.reset(); WaitForMessage(); // The second data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto2, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Simulate a message where the end of the data does not arrive in time and the // read times out. TEST_F(GCMConnectionHandlerImplTest, ReadTimeout) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFrom, kDataMsgCategory); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); int bytes_in_first_message = data_message_pkt.size() / 2; ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), bytes_in_first_message)); read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str() + bytes_in_first_message, data_message_pkt.size() - bytes_in_first_message)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. received_message.reset(); WaitForMessage(); // Should time out. EXPECT_FALSE(received_message.get()); EXPECT_EQ(net::ERR_TIMED_OUT, last_error()); EXPECT_FALSE(connection_handler()->CanSendMessage()); } // Receive a message with zero data bytes. TEST_F(GCMConnectionHandlerImplTest, RecvMsgNoData) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_pkt = EncodePacket(kHeartbeatPingTag, ""); ASSERT_EQ(data_message_pkt.size(), 2U); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. received_message.reset(); WaitForMessage(); // The heartbeat ping. EXPECT_TRUE(received_message.get()); EXPECT_EQ(GetMCSProtoTag(*received_message), kHeartbeatPingTag); EXPECT_EQ(net::OK, last_error()); EXPECT_TRUE(connection_handler()->CanSendMessage()); } // Send a message after performing the handshake. TEST_F(GCMConnectionHandlerImplTest, SendMsg) { mcs_proto::DataMessageStanza data_message; data_message.set_from(kDataMsgFrom); data_message.set_category(kDataMsgCategory); std::string handshake_request = EncodeHandshakeRequest(); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message.SerializeAsString()); WriteList write_list; write_list.push_back(net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); write_list.push_back(net::MockWrite(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); std::string handshake_response = EncodeHandshakeResponse(); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. EXPECT_TRUE(connection_handler()->CanSendMessage()); connection_handler()->SendMessage(data_message); EXPECT_FALSE(connection_handler()->CanSendMessage()); WaitForMessage(); // The message send. EXPECT_TRUE(connection_handler()->CanSendMessage()); } // Attempt to send a message after the socket is disconnected due to a timeout. TEST_F(GCMConnectionHandlerImplTest, SendMsgSocketDisconnected) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list; write_list.push_back(net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::SYNCHRONOUS, net::ERR_IO_PENDING)); net::StreamSocket* socket = BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. EXPECT_TRUE(connection_handler()->CanSendMessage()); socket->Disconnect(); mcs_proto::DataMessageStanza data_message; data_message.set_from(kDataMsgFrom); data_message.set_category(kDataMsgCategory); connection_handler()->SendMessage(data_message); EXPECT_FALSE(connection_handler()->CanSendMessage()); WaitForMessage(); // The message send. Should result in an error EXPECT_FALSE(connection_handler()->CanSendMessage()); EXPECT_EQ(net::ERR_CONNECTION_CLOSED, last_error()); } // Receive a message with a custom data packet that is larger than the // default data limit (and the socket buffer limit). Should successfully // read the packet by using the in-memory buffer. TEST_F(GCMConnectionHandlerImplTest, ExtraLargeDataPacket) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); const std::string kVeryLongFrom(20000, '0'); std::string data_message_proto = BuildDataMessage(kVeryLongFrom, kDataMsgCategory); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Receive two messages with a custom data packet that is larger than the // default data limit (and the socket buffer limit). Should successfully // read the packet by using the in-memory buffer. TEST_F(GCMConnectionHandlerImplTest, 2ExtraLargeDataPacketMsgs) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); const std::string kVeryLongFrom(20000, '0'); std::string data_message_proto = BuildDataMessage(kVeryLongFrom, kDataMsgCategory); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), data_message_pkt.size())); read_list.push_back(net::MockRead(net::SYNCHRONOUS, data_message_pkt.c_str(), data_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); received_message.reset(); WaitForMessage(); // The second data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Make sure a message with an invalid tag is handled gracefully and resets // the connection with an invalid argument error. TEST_F(GCMConnectionHandlerImplTest, InvalidTag) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string invalid_message = "0"; std::string invalid_message_pkt = EncodePacket(kInvalidTag, invalid_message); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, invalid_message_pkt.c_str(), invalid_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. received_message.reset(); WaitForMessage(); // The invalid message. EXPECT_FALSE(received_message.get()); EXPECT_EQ(net::ERR_INVALID_ARGUMENT, last_error()); } // Receive a message where the size field spans two socket reads. TEST_F(GCMConnectionHandlerImplTest, RecvMsgSplitSize) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildDataMessage(kDataMsgFromLong, kDataMsgCategoryLong); std::string data_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); DCHECK_GT(data_message_pkt.size(), 128U); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); // The first two bytes are the tag byte and the first byte of the size packet. read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str(), 2)); // Start from the second byte of the size packet. read_list.push_back(net::MockRead(net::ASYNC, data_message_pkt.c_str() + 2, data_message_pkt.size() - 2)); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. WaitForMessage(); // The data message. ASSERT_TRUE(received_message.get()); EXPECT_EQ(data_message_proto, received_message->SerializeAsString()); EXPECT_EQ(net::OK, last_error()); } // Make sure a message with invalid data is handled gracefully and resets // the connection with a FAILED error. TEST_F(GCMConnectionHandlerImplTest, InvalidData) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildCorruptDataMessage(); std::string invalid_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, invalid_message_pkt.c_str(), invalid_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. received_message.reset(); WaitForMessage(); // The invalid message. EXPECT_FALSE(received_message.get()); EXPECT_EQ(net::ERR_FAILED, last_error()); } // Make sure a long message with invalid data is handled gracefully and resets // the connection with a FAILED error. TEST_F(GCMConnectionHandlerImplTest, InvalidDataLong) { std::string handshake_request = EncodeHandshakeRequest(); WriteList write_list(1, net::MockWrite(net::ASYNC, handshake_request.c_str(), handshake_request.size())); std::string handshake_response = EncodeHandshakeResponse(); std::string data_message_proto = BuildCorruptDataMessage(); // Pad the corrupt data so it's beyond the normal single packet length. data_message_proto.resize(1 << 12); std::string invalid_message_pkt = EncodePacket(kDataMessageStanzaTag, data_message_proto); ReadList read_list; read_list.push_back(net::MockRead(net::ASYNC, handshake_response.c_str(), handshake_response.size())); read_list.push_back(net::MockRead(net::ASYNC, invalid_message_pkt.c_str(), invalid_message_pkt.size())); BuildSocket(read_list, write_list); ScopedMessage received_message; Connect(&received_message); WaitForMessage(); // The login send. WaitForMessage(); // The login response. received_message.reset(); WaitForMessage(); // The invalid message. EXPECT_FALSE(received_message.get()); EXPECT_EQ(net::ERR_FAILED, last_error()); } } // namespace } // namespace gcm
#pragma once #include <iostream> #include <math.h> #include "../UI/UI.hpp" using namespace std; class SdlEyes : public UiItem { public: bool Draw() override { ImGui::Begin("Eyes", &Running, ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); if (!Running) { ImGui::End(); return false; } Update(); ImGui::SetCursorPos(ImVec2(X, Y)); ImGui::Image(EyeBase, EyeBase->Size()); ImGui::SetCursorPos(ImVec2(X + EyeW + EyeSpace, Y)); ImGui::Image(EyeBase, EyeBase->Size()); ImGui::SetCursorPos(ImVec2(eyeX, eyeY)); ImGui::Image(EyeInner, EyeInner->Size()); ImGui::SetCursorPos(ImVec2(eye2X, eyeY)); ImGui::Image(EyeInner, EyeInner->Size()); ImGui::End(); return true; } SdlEyes() { EyeBase = ImGuiSDL::LoadTexture("romfs:/demo/Eye.png"); EyeInner = ImGuiSDL::LoadTexture("romfs:/demo/EyeInner.png"); auto eyeS = EyeBase->Size(); EyeW = eyeS.x; EyeSpace = eyeS.x / 3.0; TotalW = EyeW * 2 + EyeSpace; TotalH = eyeS.y; EyeInnerRadius = EyeInner->Size().x / 2.0; } virtual ~SdlEyes() { ImGuiSDL::FreeTexture(EyeBase); ImGuiSDL::FreeTexture(EyeInner); } int TotalW; int TotalH; private: bool Running = true; int eyeX = 0, eyeY = 0; int eye2X = 0; Texture *EyeBase; Texture *EyeInner; int X = 10, Y = 50; int EyeInnerRadius; int EyeW; int EyeSpace; float dist(int Ax, int Ay, int Bx, int By) { return sqrtf(powf(Ax - Bx, 2) + powf(Ay - By, 2)); } void Update() { auto mouse = ImGui::GetIO().MousePos; int curX = mouse.x; int curY = mouse.y; auto WinPos = ImGui::GetWindowPos(); int CenterX = X + TotalW / 2 + WinPos.x; int CenterY = Y + TotalH / 2 + WinPos.y; int LECenterX = CenterX - EyeInnerRadius - EyeSpace; int RECenterX = CenterX + EyeInnerRadius + EyeSpace; // Get the unit vector pointing towards the mouse position. float dx = curX - LECenterX; float dx1 = curX - RECenterX; float dy = curY - CenterY; float dist = sqrtf(dx * dx + dy * dy); dx /= dist; dx1 /= sqrtf(dx1 * dx1 + dy * dy); dy /= dist; // This point is 1/4 of the way // from the center to the edge of the eye. eyeX = LECenterX + dx * EyeW / 4.0 - EyeSpace -WinPos.x; eye2X = RECenterX + dx1 * EyeW / 4.0 - WinPos.x; eyeY = CenterY + dy * TotalH / 4.0 - WinPos.y; } };