/** * TODO: unit test channel_pow_stats::update_pbs_avg */ bool channel_pow_stats::update_bps_avg( uint64_t bytes_recv, const pow_hash& msg_pow ) { // normalize the proof of work for the message size fc::bigint msg( &msg_pow, sizeof(msg_pow) ); msg *= ( (bytes_recv / 1024) + 1); // give the average work per kb // for the purposes of this calculation, there is no such thing as a message less than // 1 KB in size. if( bytes_recv < 1024 ) bytes_recv = 1024; // first check the work, if it is valid we can work it into our // POW average, otherwise we will ignore it. if( msg_pow > target_pow ) return false; // how much time has elapsed since the last bytes that passed auto ellapsed_us = (fc::time_point::now() - last_recv).count(); last_recv = fc::time_point::now(); // prevent long delays between message from biasing the average too much // also protects against OS time changes if( ellapsed_us > BITCHAT_BANDWIDTH_WINDOW_US ) { ellapsed_us = BITCHAT_BANDWIDTH_WINDOW_US/32; } // calculate the weighted average for the bitrate auto total = avg_bits_per_usec*BITCHAT_BANDWIDTH_WINDOW_US + (8 * bytes_recv * ellapsed_us); avg_bits_per_usec = total / (BITCHAT_BANDWIDTH_WINDOW_US + ellapsed_us); // use the same weighting factors to weight the update to the average POW fc::bigint avg( &average_pow, sizeof(average_pow) ); fc::bigint wsum = (avg * BITCHAT_BANDWIDTH_WINDOW_US + msg*ellapsed_us) / (BITCHAT_BANDWIDTH_WINDOW_US+ellapsed_us); fc::bigint tar( &target_pow, sizeof(target_pow) ); if( avg_bits_per_usec >= target_bits_per_usec ) { tar *= wsum * bigint( 990000ll); tar /= bigint(1000000ll); } else { // increase target (making it easier to get under) tar = wsum * bigint(1010000ll); tar /= bigint(1000000ll); } std::vector<char> tarw(tar); std::vector<char> avgw(wsum); target_pow = pow_hash(); memcpy( (char*)&target_pow + sizeof(pow_hash)-tarw.size(), tarw.data(), tarw.size() ); memcpy( (char*)&average_pow + sizeof(pow_hash)-avgw.size(), avgw.data(), avgw.size() ); return true; }
u256 calculateEthashDifficulty( ChainOperationParams const& _chainParams, BlockHeader const& _bi, BlockHeader const& _parent) { const unsigned c_expDiffPeriod = 100000; if (!_bi.number()) throw GenesisBlockCannotBeCalculated(); auto const& minimumDifficulty = _chainParams.minimumDifficulty; auto const& difficultyBoundDivisor = _chainParams.difficultyBoundDivisor; auto const& durationLimit = _chainParams.durationLimit; bigint target; // stick to a bigint for the target. Don't want to risk going negative. if (_bi.number() < _chainParams.homesteadForkBlock) // Frontier-era difficulty adjustment target = _bi.timestamp() >= _parent.timestamp() + durationLimit ? _parent.difficulty() - (_parent.difficulty() / difficultyBoundDivisor) : (_parent.difficulty() + (_parent.difficulty() / difficultyBoundDivisor)); else { bigint const timestampDiff = bigint(_bi.timestamp()) - _parent.timestamp(); bigint const adjFactor = _bi.number() < _chainParams.byzantiumForkBlock ? max<bigint>(1 - timestampDiff / 10, -99) : // Homestead-era difficulty adjustment max<bigint>((_parent.hasUncles() ? 2 : 1) - timestampDiff / 9, -99); // Byzantium-era difficulty adjustment target = _parent.difficulty() + _parent.difficulty() / 2048 * adjFactor; } bigint o = target; unsigned exponentialIceAgeBlockNumber = unsigned(_parent.number() + 1); // EIP-1234 Constantinople Ice Age delay if (_bi.number() >= _chainParams.constantinopleForkBlock) { if (exponentialIceAgeBlockNumber >= 5000000) exponentialIceAgeBlockNumber -= 5000000; else exponentialIceAgeBlockNumber = 0; } // EIP-649 Byzantium Ice Age delay else if (_bi.number() >= _chainParams.byzantiumForkBlock) { if (exponentialIceAgeBlockNumber >= 3000000) exponentialIceAgeBlockNumber -= 3000000; else exponentialIceAgeBlockNumber = 0; } unsigned periodCount = exponentialIceAgeBlockNumber / c_expDiffPeriod; if (periodCount > 1) o += (bigint(1) << (periodCount - 2)); // latter will eventually become huge, so ensure // it's a bigint. o = max<bigint>(minimumDifficulty, o); return u256(min<bigint>(o, std::numeric_limits<u256>::max())); }
Secp256k1() : EllipticCurve( bigint("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"), 0,7, { bigint("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"), bigint("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8") }, bigint("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),1) {}
int main (int argc, char **argv) { random_update (); bigint m, r, s1, s2; barrett b; for (int i = 120; i < 162; i++) { m = random_bigint (i); m.setbit (0, 1); b.set (m); for (int j = i - 33; j <= 2 * i; j++) { r = random_bigint (j); s1 = mod (r, m); s2 = b.reduce (r); if (s1 != s2) panic << "r = " << r << "\n" << " " << s1 << "\n != " << s2 << "\n" << " [" << strbuf ("%*s", mpz_sizeinbase (&s1, 16), bigint (abs (s1 - s2)).cstr ()) << "]\n"; } } return 0; }
NEXT CASE(RETURNDATACOPY) { ON_OP(); if (m_rev < EVMC_BYZANTIUM) throwBadInstruction(); bigint const endOfAccess = bigint(m_SP[1]) + bigint(m_SP[2]); if (m_returnData.size() < endOfAccess) throwBufferOverrun(endOfAccess); m_copyMemSize = toInt63(m_SP[2]); updateMem(memNeed(m_SP[0], m_SP[2])); updateIOGas(); copyDataToMemory(&m_returnData, m_SP); }
void SealEngineFace::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const { _bi.verify(_s, _parent, _block); if (_s != CheckNothingNew) { if (_bi.difficulty() < chainParams().minimumDifficulty) BOOST_THROW_EXCEPTION( InvalidDifficulty() << RequirementError( bigint(chainParams().minimumDifficulty), bigint(_bi.difficulty()))); if (_bi.gasLimit() < chainParams().minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError( bigint(chainParams().minGasLimit), bigint(_bi.gasLimit()))); if (_bi.gasLimit() > chainParams().maxGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError( bigint(chainParams().maxGasLimit), bigint(_bi.gasLimit()))); if (_bi.number() && _bi.extraData().size() > chainParams().maximumExtraDataSize) { BOOST_THROW_EXCEPTION( ExtraDataTooBig() << RequirementError(bigint(chainParams().maximumExtraDataSize), bigint(_bi.extraData().size())) << errinfo_extraData(_bi.extraData())); } u256 const& daoHardfork = chainParams().daoHardforkBlock; if (daoHardfork != 0 && daoHardfork + 9 >= daoHardfork && _bi.number() >= daoHardfork && _bi.number() <= daoHardfork + 9) if (_bi.extraData() != fromHex("0x64616f2d686172642d666f726b")) BOOST_THROW_EXCEPTION( ExtraDataIncorrect() << errinfo_comment("Received block from the wrong fork (invalid extradata).")); } if (_parent) { auto gasLimit = _bi.gasLimit(); auto parentGasLimit = _parent.gasLimit(); if (gasLimit < chainParams().minGasLimit || gasLimit > chainParams().maxGasLimit || gasLimit <= parentGasLimit - parentGasLimit / chainParams().gasLimitBoundDivisor || gasLimit >= parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor) BOOST_THROW_EXCEPTION( InvalidGasLimit() << errinfo_min( (bigint)((bigint)parentGasLimit - (bigint)(parentGasLimit / chainParams().gasLimitBoundDivisor))) << errinfo_got((bigint)gasLimit) << errinfo_max((bigint)((bigint)parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor))); } }
int main() { int h = 0, n; bigint x; char *buf1; while (scanf(" %as %d", &buf1, &n) != EOF) { x = bigint(buf1); printf("#%d\n%s\n\n", ++h, string(x.root(n)).c_str()); free(buf1); } }
void u_test(bigint test) //tests the constructors. Pass in default constructor { assert (test.digits[0] == 0); assert (test.digits[1] == -1); test = bigint("0"); assert (test.digits[0] == 0); assert (test.digits[1] == -1); test = bigint(0); assert (test.digits[0] == 0); assert (test.digits[1] == -1); test = bigint(123); assert (test.digits[0] == 3 && test.digits[1] == 2 && test.digits[2] == 1 && test.digits[3] == -1); test = bigint("123"); assert (test.digits[0] == 3 && test.digits[1] == 2 && test.digits[2] == 1 && test.digits[3] == -1); }
void Ethash::BlockHeaderRaw::populateFromHeader(RLP const& _header, Strictness _s) { m_mixHash = _header[BlockInfo::BasicFields].toHash<h256>(); m_nonce = _header[BlockInfo::BasicFields + 1].toHash<h64>(); // check it hashes according to proof of work or that it's the genesis block. if (_s == CheckEverything && m_parentHash && !verify()) { InvalidBlockNonce ex; ex << errinfo_nonce(m_nonce); ex << errinfo_mixHash(m_mixHash); ex << errinfo_seedHash(seedHash()); EthashProofOfWork::Result er = EthashAux::eval(seedHash(), hashWithout(), m_nonce); ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash)); ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_target(boundary()); BOOST_THROW_EXCEPTION(ex); } else if (_s == QuickNonce && m_parentHash && !preVerify()) { InvalidBlockNonce ex; ex << errinfo_hash256(hashWithout()); ex << errinfo_difficulty(m_difficulty); ex << errinfo_nonce(m_nonce); BOOST_THROW_EXCEPTION(ex); } if (_s != CheckNothing) { if (m_difficulty < c_minimumDifficulty) BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(m_difficulty)) ); if (m_gasLimit < c_minGasLimit) BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(m_gasLimit)) ); if (m_number && m_extraData.size() > c_maximumExtraDataSize) BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(m_extraData.size())) << errinfo_extraData(m_extraData)); } }
int main (int argc, char * const argv[]) { // check the correct number of inputs if (argc != 2) { std::cout << "Please specify n (n>=1)" << std::endl; return -1; } int num = atoi(argv[1]); BigInteger bigint(num); bigint = ComplexFactorial(bigint); std::cout << bigint << std::endl; return 0; }
static void buildRLP(js::mValue& _v, RLPStream& _rlp) { if (_v.type() == js::array_type) { RLPStream s; for (auto& i: _v.get_array()) buildRLP(i, s); _rlp.appendList(s.out()); } else if (_v.type() == js::int_type) _rlp.append(_v.get_uint64()); else if (_v.type() == js::str_type) { auto s = _v.get_str(); if (s.size() && s[0] == '#') _rlp.append(bigint(s.substr(1))); else _rlp.append(s); } }
void process(const std::string& input_file, const std::string& output_file) { std::ifstream input(input_file.c_str()); std::ofstream output(output_file.c_str()); std::string line; std::getline(input, line); // Ignore the first line. for (int i = 1; std::getline(input, line); i++) { if (line.empty()) continue; std::vector<std::string> elements; boost::split(elements, line, boost::is_any_of(" ")); std::vector<bigint> events; for (std::vector<std::string>::iterator it = ++elements.begin(); it != elements.end(); it++) events.push_back(bigint(*it)); output << "Case #" << i << ": " << calculate_apocalypse(events).get_str() << std::endl; } }
int main (int argc, char **argv) { random_update (); bigint r, s1, s2; for (int i = 0; i < 1024; i++) { r = random_bigint (rnd.getword () % 2048); s1 = r * r; mpz_square (&s2, &r); if (s1 != s2) panic << "r = " << r << "\n" << " " << s1 << "\n != " << s2 << "\n" << " [" << strbuf ("%*s", int (mpz_sizeinbase (&s1, 16)), bigint (abs (s1 - s2)).cstr ()) << "]\n"; } return 0; }
void compare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax, merkle_node *lnode, merkle_rpc_node *rnode, uint vnode, dhash_ctype ctype, missingfnc_t missingfnc, rpcfnc_t rpcfnc) { trace << (lnode->isleaf () ? "L" : "I") << " vs " << (rnode->isleaf ? "L" : "I") << "\n"; vec<chordID> lkeys = ltree->database_get_IDs (rnode->depth, rnode->prefix); if (rnode->isleaf) { vec<chordID> rkeys; for (u_int i = 0; i < rnode->child_hash.size (); i++) rkeys.push_back (tobigint(rnode->child_hash[i])); compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc); } else if (lnode->isleaf () && !rnode->isleaf) { bigint tmpmin = tobigint (rnode->prefix); bigint node_width = bigint (1) << (160 - rnode->depth); bigint tmpmax = tmpmin + node_width - 1; // further constrain to be within the host's range of interest if (between (tmpmin, tmpmax, rngmin)) tmpmin = rngmin; if (between (tmpmin, tmpmax, rngmax)) tmpmax = rngmax; vNew merkle_getkeyrange (vnode, ctype, tmpmin, tmpmax, lkeys, missingfnc, rpcfnc); } }
bigint operator+(const bigint& other) const { return bigint(add(num, other.num), base); }
bigint& bigint::operator--() { return *this = *this - bigint(1); }
bigint bigint::operator--(int) { bigint tmp = *this; *this = *this - bigint(1); return tmp; }
bigint& bigint::operator++() { return *this = *this + bigint(1); }
bigint bigint::operator++(int) { bigint tmp = *this; *this = *this + bigint(1); return tmp; }
bigint operator +(const bigint& x){ return bigint(*this) += x; }
//=========================================================================== int main () { { { /*---------------Test Add-------------*/ //------------------------------------------------------ // Setup fixture bigint left(0); bigint right(0); bigint result; // Test result = left + right; // Verify assert(left == 0); assert(right == 0); assert(result == 0); left = bigint(123); right = bigint(123); result = left+right; assert(left == 123); assert(right == 123); assert(result == 246); left = bigint(999); right = bigint(999); result = left+right; assert(left == 999); assert(right==999); assert(result == 1998); } /*--------------------------Test Multiply-------------------------*/ { //------------------------------------------------------ // Setup fixture bigint left(0); bigint right(0); bigint result; // Test result = left * right; // Verify assert(left == 0); assert(right == 0); assert(result == 0); } { //------------------------------------------------------ // Setup fixture bigint left(1); bigint right(0); bigint result; // Test result = left * right; // Verify assert(left == 1); assert(right == 0); assert(result == 0); } { //------------------------------------------------------ // Setup fixture bigint left(0); bigint right(1); bigint result; // Test result = left * right; // Verify assert(left == 0); assert(right == 1); assert(result == 0); } { //------------------------------------------------------ // Setup fixture bigint left(123); bigint right(56); bigint result; // Test result = left * right; // Verify assert(left == 123); assert(right == 56); assert(result == 6888); } { //------------------------------------------------------ // Setup fixture bigint left(65); bigint right(321); bigint result; // Test result = left * right; // Verify assert(left == 65); assert(right == 321); assert(result == 20865); } { //------------------------------------------------------ // Setup fixture bigint left(9999); bigint right(2); bigint result; // Test result = left * right; // Verify assert(left == 9999); assert(right == 2); assert(result == 19998); } { //------------------------------------------------------ // Setup fixture bigint left(2); bigint right(999999); bigint result; // Test result = left * right; // Verify assert(left == 2); assert(right == 999999); assert(result == 1999998); } { //------------------------------------------------------ // Setup fixture bigint left("2222"); bigint right("888888888888888888888888888888888888"); bigint result; // Test result = left * right; // Verify assert(left == "2222"); assert(right == "888888888888888888888888888888888888"); assert(result == "1975111111111111111111111111111111109136"); } { //------------------------------------------------------ // Setup fixture bigint left("777777777777777777777777777777777777777777777"); bigint right("333333"); bigint result; // Test result = left * right; // Verify assert(left == "777777777777777777777777777777777777777777777"); assert(right == "333333"); assert(result == "259258999999999999999999999999999999999999999740741"); } { //------------------------------------------------------ // Setup fixture bigint left("111111111111111111111111111111111111111111"); bigint right("999999999999999999999999999999999999999999"); bigint result; // Test result = left * right; // Verify assert(left == "111111111111111111111111111111111111111111"); assert(right == "999999999999999999999999999999999999999999"); assert(result == "111111111111111111111111111111111111111110888888888888888888888888888888888888888889"); } //Add test cases as needed. std::cout << "Done testing multiply" << std::endl; } std::cout << "Done with testing addition." << std::endl; /*------------------------Test Times 10--------------------------------*/ { //------------------------------------------------------ // Setup fixture bigint bi(3); // Test bi.shiftLeft(0); //Or whatever you call it. // Verify assert(bi == 3); } //Add test cases as needed. std::cout << "Done testing times10" << std::endl; }
// assume that this is larger than other bigint operator-(const bigint& other) const { return bigint(sub(num, other.num), base); }
bigint operator %(const bigint& x){ return bigint(*this) %= x; }
bigint operator /(const bigint& x){ return bigint(*this).div(x); }
void CUserQueryHiveLog::Core() { std::string pchSqlPermissions ;//= "insert into rtb_hive_data"; //char insertMysqlValue[2000]; std::string insertMysqlValue; std::string createTable; //10000000 std::string tableValue ="( id int(10) unsigned NOT NULL AUTO_INCREMENT ,\ log_time datetime DEFAULT NULL ,\ reqParams varchar(1000) DEFAULT NULL ,\ reqAction varchar(1000) DEFAULT NULL ,\ resultValue varchar(19800) DEFAULT NULL ,\ queryTime bigint(20) DEFAULT NULL,\ log_dayID bigint(20) DEFAULT NULL ,\ log_HourID bigint(20) DEFAULT NULL ,\ PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;"; char chSource[10]; char chProvider[10]; char logDate[30]; std::string strHiveDate; while(true) { strHiveDate = BdxUserQueryHiveLogGetDate(); createTable = "create table if not exists apigateway_hive_data_"+ strHiveDate + tableValue; //memset(insertMysqlValue,0,2000); memset(chSource,0,10); memset(chProvider,0,10); memset(logDate,0,30); pchSqlPermissions = "insert into apigateway_hive_data_" + strHiveDate +"(log_time,reqParams,reqAction,resultValue,queryTime,log_dayID,log_hourID)values"; std::vector<HIVELOCALLOG_S>::iterator itr; BdxQueryHiveLogOpenFile(); //BdxQueryHiveLogGetReport(); time_t timep; time(&timep); #ifdef __MYSQL__ if(!m_stMysqlServerInfoHive->GetMysqlInitState()) { m_stMysqlServerInfoHive->InitMysql(g_mySqlInfoHive.m_stMysqlLinkInfo.m_pchIp,g_mySqlInfoHive.m_stMysqlLinkInfo.m_uiPort,g_mySqlInfoHive.pchUserName,g_mySqlInfoHive.pchPassWord,g_mySqlInfoHive.pchDbName); } m_stMysqlServerInfoHive->ExecuteMySql(createTable.c_str());//create table //printf("Line:%d,create table %s\n",__LINE__,createTable.c_str()); LOG(DEBUG,"create table %s",createTable.c_str()); #endif struct tm* timeinfo = localtime(&timep); for(u_int i = 0; i < CUserQueryWorkThreads::m_vecHiveLog.size(); ++i) { while(!CUserQueryWorkThreads::m_vecHiveLog[i].empty()) { m_stHiveLog = CUserQueryWorkThreads::m_vecHiveLog[i].front(); CUserQueryWorkThreads::m_vecHiveLog[i].pop(); fprintf(m_pFile, "%04d-%02d-%02d %02d:%02d\t", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1,timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min); fprintf(m_pFile,"%s\t%s\t%s\t%s\t%s\t%s\n",m_stHiveLog.strReqParams.c_str(),m_stHiveLog.strAction.c_str(),m_stHiveLog.strValue.c_str(),m_stHiveLog.strQuerytime.c_str(),m_stHiveLog.strDayId.c_str(),m_stHiveLog.strHourId.c_str()); #ifdef __MYSQL__ sprintf(logDate, "%04d-%02d-%02d %02d:%02d",timeinfo->tm_year + 1900, timeinfo->tm_mon + 1,timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min); insertMysqlValue =pchSqlPermissions + "('"+std::string(logDate)+"','" + m_stHiveLog.strReqParams +"','" + m_stHiveLog.strAction +"','" + m_stHiveLog.strValue + "','" + m_stHiveLog.strQuerytime +"','" + m_stHiveLog.strDayId + "','" + m_stHiveLog.strHourId + "');"; //printf("Line:%d,insertMysqlValue=%s\n",__LINE__,insertMysqlValue.c_str()); m_stMysqlServerInfoHive->ExecuteMySql(std::string("set names utf8").c_str());//set charset m_stMysqlServerInfoHive->ExecuteMySql((std::string("alter database ")+g_mySqlInfoHive.pchDbName+ std::string(" default character set utf8")).c_str());//set charset if(m_stMysqlServerInfoHive->ExecuteMySql(insertMysqlValue.c_str())) { LOG(DEBUG,"%s success",insertMysqlValue.c_str()); //printf("Line:%d,Insert into mysql is success.....%s\n",__LINE__,insertMysqlValue.c_str()); } else { LOG(DEBUG," %s error!!!!1",insertMysqlValue.c_str()); //printf("Line:%d,Insert into mysql is error.....\n",__LINE__); } #endif } //CUserQueryWorkThreads::m_vecHiveLog[i].clear(); } fflush(m_pFile); //sleep(3000); sleep(m_stHiveLogPrm.m_uiStatisticsTime); } }
int main (int argc, char **argv) { random_update (); bigint m, m2, r, r2, ri, s1, s2; montgom b; for (int i = 120; i < 162; i++) { int res = 0; m = random_bigint (i); m.setbit (0, 1); b.set (m); m2 = m * b.getr (); for (int j = i - 33; j <= 2 * i; j++) { r = random_zn (m2); r.trunc (j); s1 = mod (r * b.getri (), m); //s2 = b.mreduce (r); b.mpz_mreduce (&s2, &r); if (s1 != s2) { res |= 1; int sz = mpz_sizeinbase (&s1, 16); panic << "mreduce failed\n" << " m = " << m << "\n" << " r = " << r << "\n" << " " << s1 << "\n != " << s2 << "\n" << " [" << strbuf ("%*s", sz, bigint (abs (s1 - s2)).cstr ()) << "]\n"; } } // r = s1; r = random_zn (m); r2 = random_zn (m); assert (r < m && r2 < m); s1 = mod (r * r2 * b.getri (), m); b.mpz_mmul (&s2, &r, &r2); if (s1 != s2) { res |= 2; int sz = mpz_sizeinbase (&s1, 16); panic << "mmul failed\n" << " m = " << m << "\n" << " r = " << r << "\n" << " " << s1 << "\n != " << s2 << "\n" << " [" << strbuf ("%*s", sz, bigint (abs (s1 - s2)).cstr ()) << "]\n"; } s1 = powm (r, r2, m); b.mpz_powm (&s2, &r, &r2); if (s1 != s2) { res |= 4; int sz = mpz_sizeinbase (&s1, 16); panic << "powm failed\n" << " m = " << m << "\n" << " r = " << r << "\n" << " " << s1 << "\n != " << s2 << "\n" << " [" << strbuf ("%*s", sz, bigint (abs (s1 - s2)).cstr ()) << "]\n"; } #if 0 warn ("%s mreduce.. %d\n", (res&1) ? "fail" : "ok", i); warn ("%s mmul.. %d\n", (res&2) ? "fail" : "ok", i); warn ("%s powm.. %d\n", (res&4) ? "fail" : "ok", i); #endif } return 0; }
void merkle_syncer::next (void) { trace << "local range [" << local_rngmin << "," << local_rngmax << "]\n"; assert (!sync_done); assert (!fatal_err); // st is queue of pending index nodes while (st.size ()) { pair<merkle_rpc_node, int> &p = st.back (); merkle_rpc_node *rnode = &p.first; assert (!rnode->isleaf); merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix); if (!lnode) { fatal << "lookup_exact didn't match for " << rnode->prefix << " at depth " << rnode->depth << "\n"; } trace << "starting from slot " << p.second << "\n"; while (p.second < 64) { u_int i = p.second; p.second += 1; trace << "CHECKING: " << i; bigint remote = tobigint (rnode->child_hash[i]); bigint local = tobigint (lnode->child_hash(i)); u_int depth = rnode->depth + 1; //prefix is the high bits of the first key // the node is responsible for. merkle_hash prefix = rnode->prefix; prefix.write_slot (rnode->depth, i); bigint slot_rngmin = tobigint (prefix); bigint slot_width = bigint (1) << (160 - 6*depth); bigint slot_rngmax = slot_rngmin + slot_width - 1; bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax); strbuf tr; if (remote != local) { tr << " differ. local " << local << " != remote " << remote; if (overlaps) { tr << " .. sending\n"; sendnode (depth, prefix); trace << tr; ltree->lookup_release(lnode); return; } else { tr << " .. not sending\n"; } } else { tr << " same. local " << local << " == remote " << remote << "\n"; } trace << tr; } ltree->lookup_release(lnode); assert (p.second == 64); st.pop_back (); } trace << "DONE .. in NEXT\n"; setdone (); trace << "OK!\n"; }
bigint operator -(const bigint& x){ return bigint(*this) -= x; }
bigint operator*(const bigint& other) const { return bigint(mul(num, other.num), base); }