diff --git a/libethereum/Block.cpp b/libethereum/Block.cpp index 695ba77e7..731d656f8 100644 --- a/libethereum/Block.cpp +++ b/libethereum/Block.cpp @@ -58,77 +58,77 @@ using skale::State; static const unsigned c_maxSyncTransactions = 1024; namespace { - class DummyLastBlockHashes : public eth::LastBlockHashesFace { - public: - h256s precedingHashes(h256 const & /* _mostRecentHash */ ) const override { return {}; } +class DummyLastBlockHashes : public eth::LastBlockHashesFace { +public: + h256s precedingHashes( h256 const& /* _mostRecentHash */ ) const override { return {}; } - void clear() override {} - }; + void clear() override {} +}; } // namespace -Block::Block(BlockChain const &_bc, boost::filesystem::path const &_dbPath, - dev::h256 const &_genesis, BaseState _bs, Address const &_author) - : m_state(Invalid256, _dbPath, _genesis, _bs), - m_precommit(Invalid256), - m_author(_author) { - noteChain(_bc); +Block::Block( BlockChain const& _bc, boost::filesystem::path const& _dbPath, + dev::h256 const& _genesis, BaseState _bs, Address const& _author ) + : m_state( Invalid256, _dbPath, _genesis, _bs ), + m_precommit( Invalid256 ), + m_author( _author ) { + noteChain( _bc ); m_previousBlock.clear(); m_currentBlock.clear(); // assert(m_state.root() == m_previousBlock.stateRoot()); } -Block::Block(const BlockChain &_bc, h256 const &_hash, const State &_state, BaseState /*_bs*/, - const Address &_author) - : m_state(_state), m_precommit(Invalid256), m_author(_author) { - noteChain(_bc); +Block::Block( const BlockChain& _bc, h256 const& _hash, const State& _state, BaseState /*_bs*/, + const Address& _author ) + : m_state( _state ), m_precommit( Invalid256 ), m_author( _author ) { + noteChain( _bc ); m_previousBlock.clear(); m_currentBlock.clear(); - if (!_bc.isKnown(_hash)) { + if ( !_bc.isKnown( _hash ) ) { // Might be worth throwing here. cwarn << "Invalid block given for state population: " << _hash; - BOOST_THROW_EXCEPTION(BlockNotFound() << errinfo_target(_hash)); + BOOST_THROW_EXCEPTION( BlockNotFound() << errinfo_target( _hash ) ); } #ifndef HISTORIC_STATE - if (_bc.currentHash() != _hash && _bc.genesisHash() != _hash) { + if ( _bc.currentHash() != _hash && _bc.genesisHash() != _hash ) { throw std::logic_error( - "Can't populate block with historical state because it is not supported"); + "Can't populate block with historical state because it is not supported" ); } #endif - auto b = _bc.block(_hash); - BlockHeader bi(b); // No need to check - it's already in the DB. + auto b = _bc.block( _hash ); + BlockHeader bi( b ); // No need to check - it's already in the DB. m_currentBlock = bi; - if (!bi.number()) { + if ( !bi.number() ) { // Genesis required: // We know there are no transactions, so just populate directly. // m_state = State(m_state.accountStartNonce(), m_state.db(), // BaseState::Empty); // TODO: try with PreExisting. - sync(_bc, _hash, bi); + sync( _bc, _hash, bi ); } } -Block::Block(Block const &_s) - : m_state(_s.m_state), - m_transactions(_s.m_transactions), - m_receipts(_s.m_receipts), - m_transactionSet(_s.m_transactionSet), - m_precommit(_s.m_state), - m_previousBlock(_s.m_previousBlock), - m_currentBlock(_s.m_currentBlock), - m_currentBytes(_s.m_currentBytes), - m_author(_s.m_author), - m_sealEngine(_s.m_sealEngine) { +Block::Block( Block const& _s ) + : m_state( _s.m_state ), + m_transactions( _s.m_transactions ), + m_receipts( _s.m_receipts ), + m_transactionSet( _s.m_transactionSet ), + m_precommit( _s.m_state ), + m_previousBlock( _s.m_previousBlock ), + m_currentBlock( _s.m_currentBlock ), + m_currentBytes( _s.m_currentBytes ), + m_author( _s.m_author ), + m_sealEngine( _s.m_sealEngine ) { m_committedToSeal = false; } -Block &Block::operator=(Block const &_s) { - if (&_s == this) +Block& Block::operator=( Block const& _s ) { + if ( &_s == this ) return *this; m_state = _s.m_state; @@ -152,7 +152,7 @@ Block &Block::operator=(Block const &_s) { // in particular we do not copy receipts and transactions // as well as raw bytes Block Block::getReadOnlyCopy() const { - Block copy(Null); + Block copy( Null ); copy.m_state = m_state.createReadOnlySnapBasedCopy(); copy.m_author = m_author; copy.m_sealEngine = m_sealEngine; @@ -164,16 +164,16 @@ Block Block::getReadOnlyCopy() const { }; -void Block::resetCurrent(int64_t _timestamp) { +void Block::resetCurrent( int64_t _timestamp ) { m_transactions.clear(); m_receipts.clear(); m_transactionSet.clear(); m_currentBlock = BlockHeader(); - m_currentBlock.setAuthor(m_author); - m_currentBlock.setTimestamp(_timestamp); // max( m_previousBlock.timestamp() + 1, _timestamp + m_currentBlock.setAuthor( m_author ); + m_currentBlock.setTimestamp( _timestamp ); // max( m_previousBlock.timestamp() + 1, _timestamp // ) ); m_currentBytes.clear(); - sealEngine()->populateFromParent(m_currentBlock, m_previousBlock); + sealEngine()->populateFromParent( m_currentBlock, m_previousBlock ); // TODO: check. @@ -186,85 +186,85 @@ void Block::resetCurrent(int64_t _timestamp) { m_state = m_state.createStateCopyAndClearCaches(); } -SealEngineFace *Block::sealEngine() const { - if (!m_sealEngine) - BOOST_THROW_EXCEPTION(ChainOperationWithUnknownBlockChain()); +SealEngineFace* Block::sealEngine() const { + if ( !m_sealEngine ) + BOOST_THROW_EXCEPTION( ChainOperationWithUnknownBlockChain() ); return m_sealEngine; } -void Block::noteChain(BlockChain const &_bc) { - if (!m_sealEngine) { - m_state.noteAccountStartNonce(_bc.chainParams().accountStartNonce); - m_precommit.noteAccountStartNonce(_bc.chainParams().accountStartNonce); +void Block::noteChain( BlockChain const& _bc ) { + if ( !m_sealEngine ) { + m_state.noteAccountStartNonce( _bc.chainParams().accountStartNonce ); + m_precommit.noteAccountStartNonce( _bc.chainParams().accountStartNonce ); m_sealEngine = _bc.sealEngine(); } } PopulationStatistics Block::populateFromChain( - BlockChain const &_bc, h256 const &_h, ImportRequirements::value _ir) { - noteChain(_bc); + BlockChain const& _bc, h256 const& _h, ImportRequirements::value _ir ) { + noteChain( _bc ); - PopulationStatistics ret{0.0, 0.0}; + PopulationStatistics ret{ 0.0, 0.0 }; - if (!_bc.isKnown(_h)) { + if ( !_bc.isKnown( _h ) ) { // Might be worth throwing here. cwarn << "Invalid block given for state population: " << _h; - BOOST_THROW_EXCEPTION(BlockNotFound() << errinfo_target(_h)); + BOOST_THROW_EXCEPTION( BlockNotFound() << errinfo_target( _h ) ); } - if (_bc.currentHash() != _h && _bc.genesisHash() != _h) { + if ( _bc.currentHash() != _h && _bc.genesisHash() != _h ) { throw std::logic_error( - "Can't populate block with historical state because it is not supported"); + "Can't populate block with historical state because it is not supported" ); } else { - throw std::logic_error("Not implemented. And maybe should not."); + throw std::logic_error( "Not implemented. And maybe should not." ); } - auto b = _bc.block(_h); - BlockHeader bi(b); // No need to check - it's already in the DB. - if (bi.number()) { + auto b = _bc.block( _h ); + BlockHeader bi( b ); // No need to check - it's already in the DB. + if ( bi.number() ) { // Non-genesis: // 1. Start at parent's end state (state root). - BlockHeader bip(_bc.block(bi.parentHash())); - sync(_bc, bi.parentHash(), bip); + BlockHeader bip( _bc.block( bi.parentHash() ) ); + sync( _bc, bi.parentHash(), bip ); // 2. Enact the block's transactions onto this state. m_author = bi.author(); Timer t; auto vb = _bc.verifyBlock( - &b, function(), _ir | ImportRequirements::TransactionBasic); + &b, function< void( Exception& ) >(), _ir | ImportRequirements::TransactionBasic ); ret.verify = t.elapsed(); t.restart(); - enact(vb, _bc); + enact( vb, _bc ); ret.enact = t.elapsed(); } else { // Genesis required: // We know there are no transactions, so just populate directly. - std::logic_error("Not implemented"); + std::logic_error( "Not implemented" ); // m_state = State(m_state.accountStartNonce(), m_state.db(), // BaseState::Empty); // TODO: try with PreExisting. - sync(_bc, _h, bi); + sync( _bc, _h, bi ); } return ret; } -bool Block::sync(BlockChain const &_bc) { - return sync(_bc, _bc.currentHash()); +bool Block::sync( BlockChain const& _bc ) { + return sync( _bc, _bc.currentHash() ); } -bool Block::sync(BlockChain const &_bc, State const &_state) { +bool Block::sync( BlockChain const& _bc, State const& _state ) { m_state = _state; m_precommit = _state; - return sync(_bc); + return sync( _bc ); } -bool Block::sync(BlockChain const &_bc, h256 const &_block, BlockHeader const &_bi) { - noteChain(_bc); +bool Block::sync( BlockChain const& _bc, h256 const& _block, BlockHeader const& _bi ) { + noteChain( _bc ); bool ret = false; // BLOCK - BlockHeader bi = _bi ? _bi : _bc.info(_block); + BlockHeader bi = _bi ? _bi : _bc.info( _block ); #if ETH_PARANOIA if ( !bi ) while ( 1 ) { @@ -285,13 +285,13 @@ bool Block::sync(BlockChain const &_bc, h256 const &_block, BlockHeader const &_ } } #endif - if (bi == m_currentBlock) { + if ( bi == m_currentBlock ) { // We mined the last block. // Our state is good - we just need to move on to next. m_previousBlock = m_currentBlock; // see at end resetCurrent(); ret = true; - } else if (bi == m_previousBlock) { + } else if ( bi == m_previousBlock ) { // No change since last sync. // Carry on as we were. } else { @@ -347,100 +347,100 @@ bool Block::sync(BlockChain const &_bc, h256 const &_block, BlockHeader const &_ ret = true; } #endif - resetCurrent(m_currentBlock.timestamp()); + resetCurrent( m_currentBlock.timestamp() ); return ret; } // Note - this function is only used in tests -pair Block::sync( - BlockChain const &_bc, TransactionQueue &_tq, GasPricer const &_gp, unsigned msTimeout) { - MICROPROFILE_SCOPEI("Block", "sync tq", MP_BURLYWOOD); +pair< TransactionReceipts, bool > Block::sync( + BlockChain const& _bc, TransactionQueue& _tq, GasPricer const& _gp, unsigned msTimeout ) { + MICROPROFILE_SCOPEI( "Block", "sync tq", MP_BURLYWOOD ); - if (isSealed()) - BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock()); + if ( isSealed() ) + BOOST_THROW_EXCEPTION( InvalidOperationOnSealedBlock() ); - noteChain(_bc); + noteChain( _bc ); // TRANSACTIONS - pair ret; + pair< TransactionReceipts, bool > ret; - Transactions transactions = _tq.topTransactions(c_maxSyncTransactions, m_transactionSet); - ret.second = (transactions.size() == c_maxSyncTransactions); // say there's more to the + Transactions transactions = _tq.topTransactions( c_maxSyncTransactions, m_transactionSet ); + ret.second = ( transactions.size() == c_maxSyncTransactions ); // say there's more to the // caller if we hit the limit - for (Transaction &transaction: transactions) { - transaction.checkOutExternalGas(_bc.chainParams(), _bc.info().timestamp(), _bc.number()); + for ( Transaction& transaction : transactions ) { + transaction.checkOutExternalGas( _bc.chainParams(), _bc.info().timestamp(), _bc.number() ); } - assert(_bc.currentHash() == m_currentBlock.parentHash()); - auto deadline = chrono::steady_clock::now() + chrono::milliseconds(msTimeout); + assert( _bc.currentHash() == m_currentBlock.parentHash() ); + auto deadline = chrono::steady_clock::now() + chrono::milliseconds( msTimeout ); - for (int goodTxs = max(0, (int) transactions.size() - 1); - goodTxs < (int) transactions.size();) { + for ( int goodTxs = max( 0, ( int ) transactions.size() - 1 ); + goodTxs < ( int ) transactions.size(); ) { goodTxs = 0; - for (auto const &t: transactions) - if (!m_transactionSet.count(t.sha3())) { + for ( auto const& t : transactions ) + if ( !m_transactionSet.count( t.sha3() ) ) { try { - if (t.gasPrice() >= _gp.ask(*this)) { + if ( t.gasPrice() >= _gp.ask( *this ) ) { // Timer t; - execute(_bc.lastBlockHashes(), t, Permanence::Uncommitted); - ret.first.push_back(m_receipts.back()); + execute( _bc.lastBlockHashes(), t, Permanence::Uncommitted ); + ret.first.push_back( m_receipts.back() ); ++goodTxs; // cnote << "TX took:" << t.elapsed() * 1000; - } else if (t.gasPrice() < _gp.ask(*this) * 9 / 10) { - LOG(m_logger) + } else if ( t.gasPrice() < _gp.ask( *this ) * 9 / 10 ) { + LOG( m_logger ) << t.sha3() << " Dropping El Cheapo transaction (<90% of ask price)"; - _tq.drop(t.sha3()); + _tq.drop( t.sha3() ); } - } catch (InvalidNonce const &in) { - bigint const &req = *boost::get_error_info(in); - bigint const &got = *boost::get_error_info(in); + } catch ( InvalidNonce const& in ) { + bigint const& req = *boost::get_error_info< errinfo_required >( in ); + bigint const& got = *boost::get_error_info< errinfo_got >( in ); - if (req > got) { + if ( req > got ) { // too old - LOG(m_logger) << t.sha3() << " Dropping old transaction (nonce too low)"; - _tq.drop(t.sha3()); - } else if (got > req + _tq.waiting(t.sender())) { + LOG( m_logger ) << t.sha3() << " Dropping old transaction (nonce too low)"; + _tq.drop( t.sha3() ); + } else if ( got > req + _tq.waiting( t.sender() ) ) { // too new - LOG(m_logger) + LOG( m_logger ) << t.sha3() << " Dropping new transaction (too many nonces ahead)"; - _tq.drop(t.sha3()); + _tq.drop( t.sha3() ); } else - _tq.setFuture(t.sha3()); - } catch (BlockGasLimitReached const &e) { - bigint const &got = *boost::get_error_info(e); - if (got > m_currentBlock.gasLimit()) { - LOG(m_logger) + _tq.setFuture( t.sha3() ); + } catch ( BlockGasLimitReached const& e ) { + bigint const& got = *boost::get_error_info< errinfo_got >( e ); + if ( got > m_currentBlock.gasLimit() ) { + LOG( m_logger ) << t.sha3() << " Dropping over-gassy transaction (gas > block's gas limit)"; - LOG(m_logger) + LOG( m_logger ) << "got: " << got << " required: " << m_currentBlock.gasLimit(); - _tq.drop(t.sha3()); + _tq.drop( t.sha3() ); } else { - LOG(m_logger) << t.sha3() - << " Temporarily no gas left in current block (txs gas > " - "block's gas limit)"; + LOG( m_logger ) << t.sha3() + << " Temporarily no gas left in current block (txs gas > " + "block's gas limit)"; //_tq.drop(t.sha3()); // Temporarily no gas left in current block. // OPTIMISE: could note this and then we don't evaluate until a block that // does have the gas left. for now, just leave alone. } - } catch (Exception const &_e) { + } catch ( Exception const& _e ) { // Something else went wrong - drop it. - LOG(m_logger) + LOG( m_logger ) << t.sha3() - << " Dropping invalid transaction: " << diagnostic_information(_e); - _tq.drop(t.sha3()); - } catch (std::exception const &) { + << " Dropping invalid transaction: " << diagnostic_information( _e ); + _tq.drop( t.sha3() ); + } catch ( std::exception const& ) { // Something else went wrong - drop it. - _tq.drop(t.sha3()); + _tq.drop( t.sha3() ); cwarn << t.sha3() << "Transaction caused low-level exception :("; } } - if (chrono::steady_clock::now() > deadline) { + if ( chrono::steady_clock::now() > deadline ) { ret.second = - true; // say there's more to the caller if we ended up crossing the deadline. + true; // say there's more to the caller if we ended up crossing the deadline. break; } } @@ -449,52 +449,51 @@ pair Block::sync( return ret; } -inline void Block::doPartialCatchupTestIfRequested(unsigned i) { - static const char *FAIL_AT_TX_NUM = std::getenv("TEST_FAIL_AT_TX_NUM"); +inline void Block::doPartialCatchupTestIfRequested( unsigned i ) { + static const char* FAIL_AT_TX_NUM = std::getenv( "TEST_FAIL_AT_TX_NUM" ); static int64_t transactionCount = 0; - if (FAIL_AT_TX_NUM) { - if (transactionCount == std::stoi(FAIL_AT_TX_NUM)) { + if ( FAIL_AT_TX_NUM ) { + if ( transactionCount == std::stoi( FAIL_AT_TX_NUM ) ) { // fail hard for test cerror << "Test: crashing skaled on purpose after processing " << i << " transactions in block"; - exit(-1); + exit( -1 ); } transactionCount++; } } -tuple Block::syncEveryone(BlockChain const &_bc, - const Transactions &_transactions, uint64_t _timestamp, - u256 _gasPrice) { - if (isSealed()) - BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock()); +tuple< TransactionReceipts, unsigned > Block::syncEveryone( BlockChain const& _bc, + const Transactions& _transactions, uint64_t _timestamp, u256 _gasPrice ) { + if ( isSealed() ) + BOOST_THROW_EXCEPTION( InvalidOperationOnSealedBlock() ); - noteChain(_bc); + noteChain( _bc ); - assert(_bc.currentHash() == m_currentBlock.parentHash()); + assert( _bc.currentHash() == m_currentBlock.parentHash() ); - this->resetCurrent(_timestamp); + this->resetCurrent( _timestamp ); m_state = m_state.createStateCopyAndClearCaches(); // mainly for debugging TransactionReceipts saved_receipts = - m_receipts = m_state.safePartialTransactionReceipts(info().number()); + m_receipts = m_state.safePartialTransactionReceipts( info().number() ); TransactionReceipts receipts = m_receipts; unsigned countBad = 0; - if (m_receipts.size() > 0) { + if ( m_receipts.size() > 0 ) { cwarn << "Recovering from a previous crash while processing TRANSACTION:" << m_receipts.size() << ":BLOCK:" << info().number(); // count bad transactions in previously executed transactions // a bad transaction is in the block but does not use any gas u256 cumulativeGas = 0; - for (auto const &receipt: m_receipts) { - if (receipt.cumulativeGasUsed() == cumulativeGas) { + for ( auto const& receipt : m_receipts ) { + if ( receipt.cumulativeGasUsed() == cumulativeGas ) { countBad++; } cumulativeGas = receipt.cumulativeGasUsed(); @@ -502,44 +501,45 @@ tuple Block::syncEveryone(BlockChain const &_bc, } - for (unsigned i = 0; i < _transactions.size(); ++i) { - Transaction const &tr = _transactions[i]; + for ( unsigned i = 0; i < _transactions.size(); ++i ) { + Transaction const& tr = _transactions[i]; try { - if (i < saved_receipts.size()) { + if ( i < saved_receipts.size() ) { // this transaction has already been executed and we have a // receipt for it. We do not need to execute it again - m_transactions.push_back(tr); - m_transactionSet.insert(tr.sha3()); - continue;; + m_transactions.push_back( tr ); + m_transactionSet.insert( tr.sha3() ); + continue; + ; } // Tell skaled to fail in a middle of blog processing // this is used in partial catchup tests - doPartialCatchupTestIfRequested(i); + doPartialCatchupTestIfRequested( i ); - if (!tr.isInvalid() && !tr.hasExternalGas() && tr.gasPrice() < _gasPrice) { - LOG(m_logger) << "Transaction " << tr.sha3() << " WouldNotBeInBlock: gasPrice " - << tr.gasPrice() << " < " << _gasPrice; + if ( !tr.isInvalid() && !tr.hasExternalGas() && tr.gasPrice() < _gasPrice ) { + LOG( m_logger ) << "Transaction " << tr.sha3() << " WouldNotBeInBlock: gasPrice " + << tr.gasPrice() << " < " << _gasPrice; - if (SkipInvalidTransactionsPatch::isEnabledInWorkingBlock()) { + if ( SkipInvalidTransactionsPatch::isEnabledInWorkingBlock() ) { // Add to the user-originated transactions that we've executed. - m_transactions.push_back(tr); - m_transactionSet.insert(tr.sha3()); + m_transactions.push_back( tr ); + m_transactionSet.insert( tr.sha3() ); // TODO deduplicate // "bad" transaction receipt for failed transactions TransactionReceipt const null_receipt = - info().number() >= sealEngine()->chainParams().byzantiumForkBlock ? - TransactionReceipt(0, info().gasUsed(), LogEntries()) : - TransactionReceipt(EmptyTrie, info().gasUsed(), LogEntries()); + info().number() >= sealEngine()->chainParams().byzantiumForkBlock ? + TransactionReceipt( 0, info().gasUsed(), LogEntries() ) : + TransactionReceipt( EmptyTrie, info().gasUsed(), LogEntries() ); - m_receipts.push_back(null_receipt); - receipts.push_back(null_receipt); + m_receipts.push_back( null_receipt ); + receipts.push_back( null_receipt ); // we need to record the receipt in case we crash m_state.safeSetAndCommitPartialTransactionReceipt( - null_receipt.rlp(), info().number(), i); + null_receipt.rlp(), info().number(), i ); ++countBad; } @@ -547,21 +547,21 @@ tuple Block::syncEveryone(BlockChain const &_bc, } ExecutionResult res = - execute(_bc.lastBlockHashes(), tr, Permanence::Committed, OnOpFunc(), i); + execute( _bc.lastBlockHashes(), tr, Permanence::Committed, OnOpFunc(), i ); - if (!SkipInvalidTransactionsPatch::isEnabledInWorkingBlock() || - res.excepted != TransactionException::WouldNotBeInBlock) { - receipts.push_back(m_receipts.back()); + if ( !SkipInvalidTransactionsPatch::isEnabledInWorkingBlock() || + res.excepted != TransactionException::WouldNotBeInBlock ) { + receipts.push_back( m_receipts.back() ); // if added but bad - if (res.excepted == TransactionException::WouldNotBeInBlock) + if ( res.excepted == TransactionException::WouldNotBeInBlock ) ++countBad; } - } catch (Exception &ex) { - ex << errinfo_transactionIndex(i); - clog(VerbosityError, "block") << "FAILED transaction after consensus! " << ex.what(); + } catch ( Exception& ex ) { + ex << errinfo_transactionIndex( i ); + clog( VerbosityError, "block" ) << "FAILED transaction after consensus! " << ex.what(); } } @@ -575,24 +575,24 @@ tuple Block::syncEveryone(BlockChain const &_bc, // since we committed changes corresponding to a particular block // we need to create a new readonly snap - LDB_CHECK(m_state.getOriginalDb()); - m_state.getOriginalDb()->createBlockSnap(info().number()); + LDB_CHECK( m_state.getOriginalDb() ); + m_state.getOriginalDb()->createBlockSnap( info().number() ); // do a simple sanity check from time to time static uint64_t sanityCheckCounter = 0; - if (sanityCheckCounter++ % 10000 == 0) { - LDB_CHECK(m_state.safePartialTransactionReceipts(info().number()).empty()); + if ( sanityCheckCounter++ % 10000 == 0 ) { + LDB_CHECK( m_state.safePartialTransactionReceipts( info().number() ).empty() ); } - LDB_CHECK(receipts.size() >= countBad); + LDB_CHECK( receipts.size() >= countBad ); - return make_tuple(receipts, receipts.size() - countBad); + return make_tuple( receipts, receipts.size() - countBad ); } -u256 Block::enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc) { - MICROPROFILE_SCOPEI("Block", "enactOn", MP_INDIANRED); +u256 Block::enactOn( VerifiedBlockRef const& _block, BlockChain const& _bc ) { + MICROPROFILE_SCOPEI( "Block", "enactOn", MP_INDIANRED ); - noteChain(_bc); + noteChain( _bc ); #if ETH_TIMED_ENACTMENTS Timer t; @@ -603,8 +603,8 @@ u256 Block::enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc) { #endif // Check family: - BlockHeader biParent = _bc.info(_block.info.parentHash()); - _block.info.verify(CheckNothingNew /*CheckParent*/, biParent); + BlockHeader biParent = _bc.info( _block.info.parentHash() ); + _block.info.verify( CheckNothingNew /*CheckParent*/, biParent ); #if ETH_TIMED_ENACTMENTS populateVerify = t.elapsed(); @@ -612,15 +612,15 @@ u256 Block::enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc) { #endif BlockHeader biGrandParent; - if (biParent.number()) - biGrandParent = _bc.info(biParent.parentHash()); + if ( biParent.number() ) + biGrandParent = _bc.info( biParent.parentHash() ); #if ETH_TIMED_ENACTMENTS populateGrand = t.elapsed(); t.restart(); #endif - sync(_bc, _block.info.parentHash(), BlockHeader()); + sync( _bc, _block.info.parentHash(), BlockHeader() ); resetCurrent(); m_state = m_state.createStateCopyAndClearCaches(); @@ -631,31 +631,31 @@ u256 Block::enactOn(VerifiedBlockRef const &_block, BlockChain const &_bc) { #endif m_previousBlock = biParent; - auto ret = enact(_block, _bc); + auto ret = enact( _block, _bc ); #if ETH_TIMED_ENACTMENTS enactment = t.elapsed(); - if (populateVerify + populateGrand + syncReset + enactment > 0.5) - LOG (m_logger) << "popVer/popGrand/syncReset/enactment = " << populateVerify << " / " - << populateGrand << " / " << syncReset << " / " << enactment; + if ( populateVerify + populateGrand + syncReset + enactment > 0.5 ) + LOG( m_logger ) << "popVer/popGrand/syncReset/enactment = " << populateVerify << " / " + << populateGrand << " / " << syncReset << " / " << enactment; #endif return ret; } // note :: this is only used in tests -u256 Block::enact(VerifiedBlockRef const &_block, BlockChain const &_bc) { - noteChain(_bc); +u256 Block::enact( VerifiedBlockRef const& _block, BlockChain const& _bc ) { + noteChain( _bc ); - DEV_TIMED_FUNCTION_ABOVE(500); + DEV_TIMED_FUNCTION_ABOVE( 500 ); // m_currentBlock is assumed to be prepopulated and reset. - assert(m_previousBlock.hash() == _block.info.parentHash()); - assert(m_currentBlock.parentHash() == _block.info.parentHash()); + assert( m_previousBlock.hash() == _block.info.parentHash() ); + assert( m_currentBlock.parentHash() == _block.info.parentHash() ); - if (m_currentBlock.parentHash() != m_previousBlock.hash()) + if ( m_currentBlock.parentHash() != m_previousBlock.hash() ) // Internal client error. - BOOST_THROW_EXCEPTION(InvalidParentHash()); + BOOST_THROW_EXCEPTION( InvalidParentHash() ); // Populate m_currentBlock with the correct values. m_currentBlock.noteDirty(); @@ -664,156 +664,155 @@ u256 Block::enact(VerifiedBlockRef const &_block, BlockChain const &_bc) { // cnote << "playback begins:" << m_currentBlock.hash() << "(without: " << // m_currentBlock.hash(WithoutSeal) << ")"; cnote << m_state; - RLP rlp(_block.block); + RLP rlp( _block.block ); - vector receipts; + vector< bytes > receipts; // All ok with the block generally. Play back the transactions now... unsigned i = 0; - DEV_TIMED_ABOVE("txExec", 500)for (Transaction const &tr: _block.transactions) { - try { - const_cast< Transaction & >( tr ).checkOutExternalGas( - _bc.chainParams(), _bc.info().timestamp(), _bc.number()); - execute(_bc.lastBlockHashes(), tr, - skale::Permanence::Committed, OnOpFunc(), - i); - } catch (Exception &ex) { - ex << errinfo_transactionIndex(i); - throw; - } - - RLPStream receiptRLP; - m_receipts.back().streamRLP(receiptRLP); - receipts.push_back(receiptRLP.out()); - ++i; + DEV_TIMED_ABOVE( "txExec", 500 ) for ( Transaction const& tr : _block.transactions ) { + try { + const_cast< Transaction& >( tr ).checkOutExternalGas( + _bc.chainParams(), _bc.info().timestamp(), _bc.number() ); + execute( _bc.lastBlockHashes(), tr, skale::Permanence::Committed, OnOpFunc(), i ); + } catch ( Exception& ex ) { + ex << errinfo_transactionIndex( i ); + throw; } + RLPStream receiptRLP; + m_receipts.back().streamRLP( receiptRLP ); + receipts.push_back( receiptRLP.out() ); + ++i; + } + h256 receiptsRoot; - DEV_TIMED_ABOVE(".receiptsRoot()", 500)receiptsRoot = orderedTrieRoot(receipts); + DEV_TIMED_ABOVE( ".receiptsRoot()", 500 ) receiptsRoot = orderedTrieRoot( receipts ); - if (receiptsRoot != m_currentBlock.receiptsRoot()) { + if ( receiptsRoot != m_currentBlock.receiptsRoot() ) { InvalidReceiptsStateRoot ex; - ex << Hash256RequirementError(m_currentBlock.receiptsRoot(), receiptsRoot); - ex << errinfo_receipts(receipts); + ex << Hash256RequirementError( m_currentBlock.receiptsRoot(), receiptsRoot ); + ex << errinfo_receipts( receipts ); // ex << errinfo_vmtrace(vmTrace(_block.block, _bc, ImportRequirements::None)); - for (auto const &receipt: m_receipts) { - if (!receipt.hasStatusCode()) { + for ( auto const& receipt : m_receipts ) { + if ( !receipt.hasStatusCode() ) { cwarn << "Skale does not support state root in receipt"; break; } } - BOOST_THROW_EXCEPTION(ex); + BOOST_THROW_EXCEPTION( ex ); } - if (m_currentBlock.logBloom() != logBloom()) { + if ( m_currentBlock.logBloom() != logBloom() ) { InvalidLogBloom ex; - ex << LogBloomRequirementError(m_currentBlock.logBloom(), logBloom()); - ex << errinfo_receipts(receipts); - BOOST_THROW_EXCEPTION(ex); + ex << LogBloomRequirementError( m_currentBlock.logBloom(), logBloom() ); + ex << errinfo_receipts( receipts ); + BOOST_THROW_EXCEPTION( ex ); } // Initialise total difficulty calculation. u256 tdIncrease = m_currentBlock.difficulty(); // Check uncles & apply their rewards to state. - if (rlp[2].itemCount() > 2) { + if ( rlp[2].itemCount() > 2 ) { TooManyUncles ex; - ex << errinfo_max(2); - ex << errinfo_got(rlp[2].itemCount()); - BOOST_THROW_EXCEPTION(ex); + ex << errinfo_max( 2 ); + ex << errinfo_got( rlp[2].itemCount() ); + BOOST_THROW_EXCEPTION( ex ); } - vector rewarded; + vector< BlockHeader > rewarded; h256Hash excluded; - DEV_TIMED_ABOVE("allKin", 500)excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6); - excluded.insert(m_currentBlock.hash()); + DEV_TIMED_ABOVE( "allKin", 500 ) excluded = _bc.allKinFrom( m_currentBlock.parentHash(), 6 ); + excluded.insert( m_currentBlock.hash() ); unsigned ii = 0; - DEV_TIMED_ABOVE("uncleCheck", 500)for (auto const &i: rlp[2]) { - try { - auto h = sha3(i.data()); - if (excluded.count(h)) { - UncleInChain ex; - ex << errinfo_comment("Uncle in block already mentioned"); - ex << errinfo_unclesExcluded(excluded); - ex << errinfo_hash256(sha3(i.data())); - BOOST_THROW_EXCEPTION(ex); - } - excluded.insert(h); - - // CheckNothing since it's a VerifiedBlock. - BlockHeader uncle(i.data(), HeaderData, h); - - BlockHeader uncleParent; - if (!_bc.isKnown(uncle.parentHash())) - BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(uncle.parentHash())); - uncleParent = BlockHeader(_bc.block(uncle.parentHash())); - - // m_currentBlock.number() - uncle.number() m_cB.n - uP.n() - // 1 2 - // 2 - // 3 - // 4 - // 5 - // 6 7 - // (8 Invalid) - bigint depth = (bigint) m_currentBlock.number() - (bigint) uncle.number(); - if (depth > 6) { - UncleTooOld ex; - ex << errinfo_uncleNumber(uncle.number()); - ex << errinfo_currentNumber(m_currentBlock.number()); - BOOST_THROW_EXCEPTION(ex); - } else if (depth < 1) { - UncleIsBrother ex; - ex << errinfo_uncleNumber(uncle.number()); - ex << errinfo_currentNumber(m_currentBlock.number()); - BOOST_THROW_EXCEPTION(ex); - } - // cB - // cB.p^1 1 depth, valid uncle - // cB.p^2 ---/ 2 - // cB.p^3 -----/ 3 - // cB.p^4 -------/ 4 - // cB.p^5 ---------/ 5 - // cB.p^6 -----------/ 6 - // cB.p^7 -------------/ - // cB.p^8 - auto expectedUncleParent = _bc.details(m_currentBlock.parentHash()).parent; - for (unsigned i = 1; i < depth; - expectedUncleParent = _bc.details(expectedUncleParent).parent, ++i) { - } - if (expectedUncleParent != uncleParent.hash()) { - UncleParentNotInChain ex; - ex << errinfo_uncleNumber(uncle.number()); - ex << errinfo_currentNumber(m_currentBlock.number()); - BOOST_THROW_EXCEPTION(ex); - } - uncle.verify(CheckNothingNew /*CheckParent*/, uncleParent); - - rewarded.push_back(uncle); - ++ii; - } catch (Exception &ex) { - ex << errinfo_uncleIndex(ii); - throw; + DEV_TIMED_ABOVE( "uncleCheck", 500 ) for ( auto const& i : rlp[2] ) { + try { + auto h = sha3( i.data() ); + if ( excluded.count( h ) ) { + UncleInChain ex; + ex << errinfo_comment( "Uncle in block already mentioned" ); + ex << errinfo_unclesExcluded( excluded ); + ex << errinfo_hash256( sha3( i.data() ) ); + BOOST_THROW_EXCEPTION( ex ); + } + excluded.insert( h ); + + // CheckNothing since it's a VerifiedBlock. + BlockHeader uncle( i.data(), HeaderData, h ); + + BlockHeader uncleParent; + if ( !_bc.isKnown( uncle.parentHash() ) ) + BOOST_THROW_EXCEPTION( UnknownParent() << errinfo_hash256( uncle.parentHash() ) ); + uncleParent = BlockHeader( _bc.block( uncle.parentHash() ) ); + + // m_currentBlock.number() - uncle.number() m_cB.n - uP.n() + // 1 2 + // 2 + // 3 + // 4 + // 5 + // 6 7 + // (8 Invalid) + bigint depth = ( bigint ) m_currentBlock.number() - ( bigint ) uncle.number(); + if ( depth > 6 ) { + UncleTooOld ex; + ex << errinfo_uncleNumber( uncle.number() ); + ex << errinfo_currentNumber( m_currentBlock.number() ); + BOOST_THROW_EXCEPTION( ex ); + } else if ( depth < 1 ) { + UncleIsBrother ex; + ex << errinfo_uncleNumber( uncle.number() ); + ex << errinfo_currentNumber( m_currentBlock.number() ); + BOOST_THROW_EXCEPTION( ex ); } + // cB + // cB.p^1 1 depth, valid uncle + // cB.p^2 ---/ 2 + // cB.p^3 -----/ 3 + // cB.p^4 -------/ 4 + // cB.p^5 ---------/ 5 + // cB.p^6 -----------/ 6 + // cB.p^7 -------------/ + // cB.p^8 + auto expectedUncleParent = _bc.details( m_currentBlock.parentHash() ).parent; + for ( unsigned i = 1; i < depth; + expectedUncleParent = _bc.details( expectedUncleParent ).parent, ++i ) { + } + if ( expectedUncleParent != uncleParent.hash() ) { + UncleParentNotInChain ex; + ex << errinfo_uncleNumber( uncle.number() ); + ex << errinfo_currentNumber( m_currentBlock.number() ); + BOOST_THROW_EXCEPTION( ex ); + } + uncle.verify( CheckNothingNew /*CheckParent*/, uncleParent ); + + rewarded.push_back( uncle ); + ++ii; + } catch ( Exception& ex ) { + ex << errinfo_uncleIndex( ii ); + throw; } + } - assert(_bc.sealEngine()); - DEV_TIMED_ABOVE("applyRewards", 500)applyRewards(rewarded, - _bc.sealEngine()->blockReward(previousInfo().timestamp(), - m_currentBlock.number())); + assert( _bc.sealEngine() ); + DEV_TIMED_ABOVE( "applyRewards", 500 ) + applyRewards( rewarded, + _bc.sealEngine()->blockReward( previousInfo().timestamp(), m_currentBlock.number() ) ); - if (m_currentBlock.gasUsed() != gasUsed()) { + if ( m_currentBlock.gasUsed() != gasUsed() ) { // Do not commit changes of state - BOOST_THROW_EXCEPTION(InvalidGasUsed() << RequirementError( - bigint(m_currentBlock.gasUsed()), bigint(gasUsed()))); + BOOST_THROW_EXCEPTION( InvalidGasUsed() << RequirementError( + bigint( m_currentBlock.gasUsed() ), bigint( gasUsed() ) ) ); } // Commit all cached state changes to the state trie. bool removeEmptyAccounts = - m_currentBlock.number() >= _bc.chainParams().EIP158ForkBlock; // TODO: use EVMSchedule - DEV_TIMED_ABOVE("commit", 500)m_state.commit(removeEmptyAccounts ? dev::eth::CommitBehaviour::RemoveEmptyAccounts : - dev::eth::CommitBehaviour::KeepEmptyAccounts); + m_currentBlock.number() >= _bc.chainParams().EIP158ForkBlock; // TODO: use EVMSchedule + DEV_TIMED_ABOVE( "commit", 500 ) + m_state.commit( removeEmptyAccounts ? dev::eth::CommitBehaviour::RemoveEmptyAccounts : + dev::eth::CommitBehaviour::KeepEmptyAccounts ); return tdIncrease; } @@ -879,11 +878,11 @@ ExecutionResult Block::executeHistoricCall( LastBlockHashesFace const& _lh, Tran #endif -ExecutionResult Block::execute(LastBlockHashesFace const &_lh, Transaction const &_t, - Permanence _p, OnOpFunc const &_onOp, int64_t _transactionIndex) { - MICROPROFILE_SCOPEI("Block", "execute transaction", MP_CORNFLOWERBLUE); - if (isSealed()) - BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock()); +ExecutionResult Block::execute( LastBlockHashesFace const& _lh, Transaction const& _t, + Permanence _p, OnOpFunc const& _onOp, int64_t _transactionIndex ) { + MICROPROFILE_SCOPEI( "Block", "execute transaction", MP_CORNFLOWERBLUE ); + if ( isSealed() ) + BOOST_THROW_EXCEPTION( InvalidOperationOnSealedBlock() ); // Uncommitting is a non-trivial operation - only do it once we've verified as much of the // transaction as possible. @@ -891,51 +890,51 @@ ExecutionResult Block::execute(LastBlockHashesFace const &_lh, Transaction const EnvInfo envInfo = EnvInfo( - info(), _lh, previousInfo().timestamp(), gasUsed(), m_sealEngine->chainParams().chainID); + info(), _lh, previousInfo().timestamp(), gasUsed(), m_sealEngine->chainParams().chainID ); // "bad" transaction receipt for failed transactions TransactionReceipt const null_receipt = - envInfo.number() >= sealEngine()->chainParams().byzantiumForkBlock ? - TransactionReceipt(0, envInfo.gasUsed(), LogEntries()) : - TransactionReceipt(EmptyTrie, envInfo.gasUsed(), LogEntries()); + envInfo.number() >= sealEngine()->chainParams().byzantiumForkBlock ? + TransactionReceipt( 0, envInfo.gasUsed(), LogEntries() ) : + TransactionReceipt( EmptyTrie, envInfo.gasUsed(), LogEntries() ); - std::pair resultReceipt{ExecutionResult(), - null_receipt}; + std::pair< ExecutionResult, TransactionReceipt > resultReceipt{ ExecutionResult(), + null_receipt }; try { - if (_t.isInvalid()) + if ( _t.isInvalid() ) throw -1; // will catch below resultReceipt = m_state.execute( - envInfo, m_sealEngine->chainParams(), _t, _p, _onOp, _transactionIndex); + envInfo, m_sealEngine->chainParams(), _t, _p, _onOp, _transactionIndex ); // use fake receipt created above if execution throws!! - } catch (const TransactionException &ex) { + } catch ( const TransactionException& ex ) { // shoul not happen as exception in execute() means that tx should not be in block cerror << DETAILED_ERROR; - assert(false); - } catch (const std::exception &ex) { - h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3(WithoutSignature); - LOG(m_logger) << "Transaction " << sha << " WouldNotBeInBlock: " << ex.what(); - if (_p != Permanence::Reverted) // if it is not call + assert( false ); + } catch ( const std::exception& ex ) { + h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3( WithoutSignature ); + LOG( m_logger ) << "Transaction " << sha << " WouldNotBeInBlock: " << ex.what(); + if ( _p != Permanence::Reverted ) // if it is not call _p = Permanence::CommittedWithoutState; resultReceipt.first.excepted = TransactionException::WouldNotBeInBlock; - } catch (...) { - h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3(WithoutSignature); - LOG(m_logger) << "Transaction " << sha << " WouldNotBeInBlock: ..."; - if (_p != Permanence::Reverted) // if it is not call + } catch ( ... ) { + h256 sha = _t.hasSignature() ? _t.sha3() : _t.sha3( WithoutSignature ); + LOG( m_logger ) << "Transaction " << sha << " WouldNotBeInBlock: ..."; + if ( _p != Permanence::Reverted ) // if it is not call _p = Permanence::CommittedWithoutState; resultReceipt.first.excepted = TransactionException::WouldNotBeInBlock; } // catch - if (_p == Permanence::Committed || _p == Permanence::CommittedWithoutState || - _p == Permanence::Uncommitted) { + if ( _p == Permanence::Committed || _p == Permanence::CommittedWithoutState || + _p == Permanence::Uncommitted ) { // Add to the user-originated transactions that we've executed. - if (!SkipInvalidTransactionsPatch::isEnabledWhen(previousInfo().timestamp()) || - resultReceipt.first.excepted != TransactionException::WouldNotBeInBlock) { - m_transactions.push_back(_t); - m_receipts.push_back(resultReceipt.second); - m_transactionSet.insert(_t.sha3()); + if ( !SkipInvalidTransactionsPatch::isEnabledWhen( previousInfo().timestamp() ) || + resultReceipt.first.excepted != TransactionException::WouldNotBeInBlock ) { + m_transactions.push_back( _t ); + m_receipts.push_back( resultReceipt.second ); + m_transactionSet.insert( _t.sha3() ); } } @@ -946,7 +945,7 @@ ExecutionResult Block::execute(LastBlockHashesFace const &_lh, Transaction const // because we do not commit to disk in some of the tests // In the future we can test performance of not clearing // cache on each commit - if (_p == Permanence::Committed) { + if ( _p == Permanence::Committed ) { m_state = m_state.createStateCopyAndClearCaches(); } @@ -954,76 +953,76 @@ ExecutionResult Block::execute(LastBlockHashesFace const &_lh, Transaction const } void Block::applyRewards( - vector const &_uncleBlockHeaders, u256 const &_blockReward) { + vector< BlockHeader > const& _uncleBlockHeaders, u256 const& _blockReward ) { u256 r = _blockReward; - for (auto const &i: _uncleBlockHeaders) { + for ( auto const& i : _uncleBlockHeaders ) { m_state.addBalance( - i.author(), _blockReward * (8 + i.number() - m_currentBlock.number()) / 8); + i.author(), _blockReward * ( 8 + i.number() - m_currentBlock.number() ) / 8 ); r += _blockReward / 32; } - m_state.addBalance(m_currentBlock.author(), r); + m_state.addBalance( m_currentBlock.author(), r ); } void Block::performIrregularModifications() { - u256 const &daoHardfork = m_sealEngine->chainParams().daoHardforkBlock; - if (daoHardfork != 0 && info().number() == daoHardfork) { - Address recipient("0xbf4ed7b27f1d666546e30d74d50d173d20bca754"); + u256 const& daoHardfork = m_sealEngine->chainParams().daoHardforkBlock; + if ( daoHardfork != 0 && info().number() == daoHardfork ) { + Address recipient( "0xbf4ed7b27f1d666546e30d74d50d173d20bca754" ); Addresses allDAOs = childDaos(); - for (Address const &dao: allDAOs) - m_state.transferBalance(dao, recipient, m_state.balance(dao)); - m_state.commit(dev::eth::CommitBehaviour::KeepEmptyAccounts); + for ( Address const& dao : allDAOs ) + m_state.transferBalance( dao, recipient, m_state.balance( dao ) ); + m_state.commit( dev::eth::CommitBehaviour::KeepEmptyAccounts ); } } void Block::updateBlockhashContract() { - u256 const &blockNumber = info().number(); + u256 const& blockNumber = info().number(); - u256 const &forkBlock = m_sealEngine->chainParams().experimentalForkBlock; - if (blockNumber == forkBlock) { - if (m_state.addressInUse(c_blockhashContractAddress)) { - if (m_state.code(c_blockhashContractAddress) != c_blockhashContractCode) { + u256 const& forkBlock = m_sealEngine->chainParams().experimentalForkBlock; + if ( blockNumber == forkBlock ) { + if ( m_state.addressInUse( c_blockhashContractAddress ) ) { + if ( m_state.code( c_blockhashContractAddress ) != c_blockhashContractCode ) { State state = m_state.createStateCopyAndClearCaches(); - state.setCode(c_blockhashContractAddress, bytes(c_blockhashContractCode), - m_sealEngine->evmSchedule(this->m_previousBlock.timestamp(), blockNumber) - .accountVersion); - state.commit(dev::eth::CommitBehaviour::KeepEmptyAccounts); + state.setCode( c_blockhashContractAddress, bytes( c_blockhashContractCode ), + m_sealEngine->evmSchedule( this->m_previousBlock.timestamp(), blockNumber ) + .accountVersion ); + state.commit( dev::eth::CommitBehaviour::KeepEmptyAccounts ); } } else { - m_state.createContract(c_blockhashContractAddress); - m_state.setCode(c_blockhashContractAddress, bytes(c_blockhashContractCode), - m_sealEngine->evmSchedule(this->m_previousBlock.timestamp(), blockNumber) - .accountVersion); - m_state.commit(dev::eth::CommitBehaviour::KeepEmptyAccounts); + m_state.createContract( c_blockhashContractAddress ); + m_state.setCode( c_blockhashContractAddress, bytes( c_blockhashContractCode ), + m_sealEngine->evmSchedule( this->m_previousBlock.timestamp(), blockNumber ) + .accountVersion ); + m_state.commit( dev::eth::CommitBehaviour::KeepEmptyAccounts ); } } - if (blockNumber >= forkBlock) { + if ( blockNumber >= forkBlock ) { DummyLastBlockHashes lastBlockHashes; // assuming blockhash contract won't need BLOCKHASH // itself // HACK 0 here is for gasPrice - Executive e(*this, lastBlockHashes, 0); + Executive e( *this, lastBlockHashes, 0 ); h256 const parentHash = m_previousBlock.hash(); - if (!e.call(c_blockhashContractAddress, SystemAddress, 0, 0, parentHash.ref(), 1000000)) + if ( !e.call( c_blockhashContractAddress, SystemAddress, 0, 0, parentHash.ref(), 1000000 ) ) e.go(); e.finalize(); - m_state.commit(dev::eth::CommitBehaviour::RemoveEmptyAccounts); + m_state.commit( dev::eth::CommitBehaviour::RemoveEmptyAccounts ); } } void Block::commitToSeal( - BlockChain const &_bc, bytes const &_extraData, dev::h256 const &_stateRootHash) { - if (isSealed()) - BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock()); + BlockChain const& _bc, bytes const& _extraData, dev::h256 const& _stateRootHash ) { + if ( isSealed() ) + BOOST_THROW_EXCEPTION( InvalidOperationOnSealedBlock() ); - noteChain(_bc); + noteChain( _bc ); - if (m_committedToSeal) + if ( m_committedToSeal ) uncommitToSeal(); else m_precommit = m_state; - vector uncleBlockHeaders; + vector< BlockHeader > uncleBlockHeaders; RLPStream unclesData; unsigned unclesCount = 0; @@ -1035,89 +1034,89 @@ void Block::commitToSeal( BytesMap receiptsMap; RLPStream txs; - txs.appendList(m_transactions.size()); + txs.appendList( m_transactions.size() ); - for (unsigned i = 0; i < m_transactions.size(); ++i) { + for ( unsigned i = 0; i < m_transactions.size(); ++i ) { RLPStream k; k << i; RLPStream receiptrlp; - receipt(i).streamRLP(receiptrlp); - receiptsMap.insert(std::make_pair(k.out(), receiptrlp.out())); + receipt( i ).streamRLP( receiptrlp ); + receiptsMap.insert( std::make_pair( k.out(), receiptrlp.out() ) ); dev::bytes txOutput = m_transactions[i].toBytes(); - if (EIP1559TransactionsPatch::isEnabledInWorkingBlock() && - m_transactions[i].txType() != dev::eth::TransactionType::Legacy) { + if ( EIP1559TransactionsPatch::isEnabledInWorkingBlock() && + m_transactions[i].txType() != dev::eth::TransactionType::Legacy ) { RLPStream s; - s.append(txOutput); + s.append( txOutput ); txOutput = s.out(); } - transactionsMap.insert(std::make_pair(k.out(), txOutput)); + transactionsMap.insert( std::make_pair( k.out(), txOutput ) ); - txs.appendRaw(txOutput); + txs.appendRaw( txOutput ); } - txs.swapOut(m_currentTxs); + txs.swapOut( m_currentTxs ); - RLPStream(unclesCount).appendRaw(unclesData.out(), unclesCount).swapOut(m_currentUncles); + RLPStream( unclesCount ).appendRaw( unclesData.out(), unclesCount ).swapOut( m_currentUncles ); // Apply rewards last of all. - assert(_bc.sealEngine()); - applyRewards(uncleBlockHeaders, - _bc.sealEngine()->blockReward(previousInfo().timestamp(), m_currentBlock.number())); + assert( _bc.sealEngine() ); + applyRewards( uncleBlockHeaders, + _bc.sealEngine()->blockReward( previousInfo().timestamp(), m_currentBlock.number() ) ); // Commit any and all changes to the trie that are in the cache, then update the state root // accordingly. // bool removeEmptyAccounts = // m_currentBlock.number() >= _bc.chainParams().EIP158ForkBlock; // TODO: use EVMSchedule - DEV_TIMED_ABOVE("commit", 500) - // We do not commit now because will do it in blockchain syncing - // m_state.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : - // State::CommitBehaviour::KeepEmptyAccounts); - - LOG (m_loggerDetailed) << cc::debug("Post-reward stateRoot: ") - << cc::notice("is not calculated in Skale state"); - LOG(m_loggerDetailed) << m_state; - - m_currentBlock.setLogBloom(logBloom()); - m_currentBlock.setGasUsed(gasUsed()); - m_currentBlock.setRoots(hash256(transactionsMap), hash256(receiptsMap), - sha3(m_currentUncles), _stateRootHash); - - m_currentBlock.setParentHash(m_previousBlock.hash()); - m_currentBlock.setExtraData(_extraData); - if (m_currentBlock.extraData().size() > 32) { + DEV_TIMED_ABOVE( "commit", 500 ) + // We do not commit now because will do it in blockchain syncing + // m_state.commit(removeEmptyAccounts ? State::CommitBehaviour::RemoveEmptyAccounts : + // State::CommitBehaviour::KeepEmptyAccounts); + + LOG( m_loggerDetailed ) << cc::debug( "Post-reward stateRoot: " ) + << cc::notice( "is not calculated in Skale state" ); + LOG( m_loggerDetailed ) << m_state; + + m_currentBlock.setLogBloom( logBloom() ); + m_currentBlock.setGasUsed( gasUsed() ); + m_currentBlock.setRoots( hash256( transactionsMap ), hash256( receiptsMap ), + sha3( m_currentUncles ), _stateRootHash ); + + m_currentBlock.setParentHash( m_previousBlock.hash() ); + m_currentBlock.setExtraData( _extraData ); + if ( m_currentBlock.extraData().size() > 32 ) { auto ed = m_currentBlock.extraData(); - ed.resize(32); - m_currentBlock.setExtraData(ed); + ed.resize( 32 ); + m_currentBlock.setExtraData( ed ); } m_committedToSeal = true; } void Block::uncommitToSeal() { - if (m_committedToSeal) { + if ( m_committedToSeal ) { m_state = m_precommit; m_committedToSeal = false; } } -bool Block::sealBlock(bytesConstRef _header) { - if (!m_committedToSeal) +bool Block::sealBlock( bytesConstRef _header ) { + if ( !m_committedToSeal ) return false; - if (BlockHeader(_header, HeaderData).hash(WithoutSeal) != - m_currentBlock.hash(WithoutSeal)) + if ( BlockHeader( _header, HeaderData ).hash( WithoutSeal ) != + m_currentBlock.hash( WithoutSeal ) ) return false; // Compile block: RLPStream ret; - ret.appendList(3); - ret.appendRaw(_header); - ret.appendRaw(m_currentTxs); - ret.appendRaw(m_currentUncles); - ret.swapOut(m_currentBytes); - m_currentBlock = BlockHeader(_header, HeaderData); + ret.appendList( 3 ); + ret.appendRaw( _header ); + ret.appendRaw( m_currentTxs ); + ret.appendRaw( m_currentUncles ); + ret.swapOut( m_currentBytes ); + m_currentBlock = BlockHeader( _header, HeaderData ); // cnote << "Mined " << m_currentBlock.hash() << "(parent: " << m_currentBlock.parentHash() << //")"; // TODO: move into SealEngine @@ -1131,24 +1130,24 @@ bool Block::sealBlock(bytesConstRef _header) { } -h256 Block::stateRootBeforeTx(unsigned _i) const { - _i = min(_i, m_transactions.size()); +h256 Block::stateRootBeforeTx( unsigned _i ) const { + _i = min< unsigned >( _i, m_transactions.size() ); try { - return (_i > 0 ? receipt(_i - 1).stateRoot() : m_previousBlock.stateRoot()); - } catch (TransactionReceiptVersionError const &) { + return ( _i > 0 ? receipt( _i - 1 ).stateRoot() : m_previousBlock.stateRoot() ); + } catch ( TransactionReceiptVersionError const& ) { return {}; } } LogBloom Block::logBloom() const { LogBloom ret; - for (TransactionReceipt const &i: m_receipts) + for ( TransactionReceipt const& i : m_receipts ) ret |= i.bloom(); return ret; } void Block::cleanup() { - MICROPROFILE_SCOPEI("Block", "cleanup", MP_BEIGE); + MICROPROFILE_SCOPEI( "Block", "cleanup", MP_BEIGE ); // Commit the new trie to disk. // LOG(m_logger) << "Committing to disk: stateRoot " << m_currentBlock.stateRoot() << " = " @@ -1167,13 +1166,13 @@ void Block::cleanup() { m_state.commit(); // TODO: State API for this? - LOG(m_logger) << "Committed: stateRoot is not calculated in Skale state"; + LOG( m_logger ) << "Committed: stateRoot is not calculated in Skale state"; m_previousBlock = m_currentBlock; - sealEngine()->populateFromParent(m_currentBlock, m_previousBlock); + sealEngine()->populateFromParent( m_currentBlock, m_previousBlock ); - LOG(m_logger) << "finalising enactment. current -> previous, hash is " - << m_previousBlock.hash(); + LOG( m_logger ) << "finalising enactment. current -> previous, hash is " + << m_previousBlock.hash(); resetCurrent(); } diff --git a/libethereum/Client.cpp b/libethereum/Client.cpp index 5b478932e..96a6bb8a7 100644 --- a/libethereum/Client.cpp +++ b/libethereum/Client.cpp @@ -1073,10 +1073,10 @@ h256 Client::importTransaction( Transaction const& _t, TransactionBroadcast _txO gasBidPrice = this->gasBidPrice(); - // We need to check external gas under mutex to be sure about current block number - // correctness - const_cast< Transaction& >( _t ).checkOutExternalGas( - chainParams(), bc().info().timestamp(), number() ); + // We need to check external gas under mutex to be sure about current block number + // correctness + const_cast< Transaction& >( _t ).checkOutExternalGas( + chainParams(), bc().info().timestamp(), number() ); Executive::verifyTransaction( _t, bc().info().timestamp(), diff --git a/libethereum/SkaleHost.cpp b/libethereum/SkaleHost.cpp index 85a40dee6..6d630ac8c 100644 --- a/libethereum/SkaleHost.cpp +++ b/libethereum/SkaleHost.cpp @@ -580,7 +580,7 @@ void SkaleHost::createBlock( const ConsensusExtFace::transactions_vector& _appro Transaction t( data, CheckTransaction::Everything, true, EIP1559TransactionsPatch::isEnabledInWorkingBlock() ); t.checkOutExternalGas( - m_client.chainParams(), latestInfo.timestamp(), m_client.number()); + m_client.chainParams(), latestInfo.timestamp(), m_client.number() ); out_txns.push_back( t ); m_debugTracer.tracepoint( "drop_good" ); m_tq.dropGood( t ); diff --git a/libethereum/TransactionQueue.h b/libethereum/TransactionQueue.h index ca49b0877..827935f37 100644 --- a/libethereum/TransactionQueue.h +++ b/libethereum/TransactionQueue.h @@ -273,8 +273,8 @@ class TransactionQueue { queue.m_currentByAddressAndNonce[_second.transaction.sender()].begin()->first; return ( height1 < height2 || - ( height1 == height2 && - _first.transaction.gasPrice() > _second.transaction.gasPrice() ) ); + ( height1 == height2 && + _first.transaction.gasPrice() > _second.transaction.gasPrice() ) ); } }; diff --git a/libskale/State.cpp b/libskale/State.cpp index 46de9315a..1ffc4ac48 100644 --- a/libskale/State.cpp +++ b/libskale/State.cpp @@ -541,7 +541,7 @@ void State::commit( dev::eth::CommitBehaviour _commitBehaviour ) { // for testeth GeneralState tests, though, there is no db connected to the // State , so we do not clear caches // since they play the role of the db - if (m_db_ptr->connected()) { + if ( m_db_ptr->connected() ) { m_cache.clear(); m_unchangedCacheEntries.clear(); } diff --git a/libskale/httpserveroverride.h b/libskale/httpserveroverride.h index f3ca11d98..03af090df 100644 --- a/libskale/httpserveroverride.h +++ b/libskale/httpserveroverride.h @@ -41,10 +41,6 @@ typedef intptr_t ssize_t; #endif #include -#define RAPIDJSON_ASSERT( x ) \ - if ( !( x ) ) { \ - throw std::out_of_range( #x " failed with provided JSON" ); \ - } #define RAPIDJSON_ASSERT_THROWS #include #include diff --git a/libweb3jsonrpc/JsonHelper.h b/libweb3jsonrpc/JsonHelper.h index f5cb095fa..c1590a8c6 100644 --- a/libweb3jsonrpc/JsonHelper.h +++ b/libweb3jsonrpc/JsonHelper.h @@ -30,10 +30,6 @@ #include #include -#define RAPIDJSON_ASSERT( x ) \ - if ( !( x ) ) { \ - throw std::out_of_range( #x " failed with provided JSON" ); \ - } #define RAPIDJSON_ASSERT_THROWS #include diff --git a/skale-vm/main.cpp b/skale-vm/main.cpp index 23d59f685..091338133 100644 --- a/skale-vm/main.cpp +++ b/skale-vm/main.cpp @@ -352,7 +352,6 @@ int main( int argc, char** argv ) { bytes output = std::move( res.output ); if ( mode == Mode::Statistics ) { - cout << "Gas used: " << res.gasUsed << " (+" << t.baseGasRequired( evmSchedule ) << " for transaction, -" << res.gasRefunded << " refunded)\n"; diff --git a/storage_benchmark/main.cpp b/storage_benchmark/main.cpp index 9ee184e72..4d18780be 100644 --- a/storage_benchmark/main.cpp +++ b/storage_benchmark/main.cpp @@ -128,7 +128,7 @@ void testState() { cout << "Balances reads:" << endl; cout << measure_performance( - [&state, &address]() { state.createStateCopyAndClearCaches().balance(address ); }, + [&state, &address]() { state.createStateCopyAndClearCaches().balance( address ); }, 100000 ) / 1e6 << " Mreads per second" << endl; @@ -150,7 +150,7 @@ void testState() { cout << "EVM storate reads:" << endl; cout << measure_performance( [&state, &address, &memory_address]() { - state.createReadOnlySnapBasedCopy().storage(address, memory_address ); + state.createReadOnlySnapBasedCopy().storage( address, memory_address ); memory_address = ( memory_address + 1 ) % 1024; }, 1000 ) / @@ -176,8 +176,9 @@ void testState() { cout << "EVM code reads:" << endl; cout << measure_performance( - [&state, &address]() { state.createReadOnlySnapBasedCopy().code(address ); }, 1000 ) / - 1e6 + [&state, &address]() { state.createReadOnlySnapBasedCopy().code( address ); }, + 1000 ) / + 1e6 << " Mreads per second" << endl; } diff --git a/test/tools/fuzzTesting/BoostRandomCode.cpp b/test/tools/fuzzTesting/BoostRandomCode.cpp index 595ee45ef..43224e39b 100644 --- a/test/tools/fuzzTesting/BoostRandomCode.cpp +++ b/test/tools/fuzzTesting/BoostRandomCode.cpp @@ -55,13 +55,14 @@ BoostRandomCode::BoostRandomCode() { u256 BoostRandomCode::randomUniInt( u256 const& _minVal, u256 const& _maxVal ) { assert( _minVal <= _maxVal ); - std::uniform_int_distribution< uint64_t > uint64Dist{0, std::numeric_limits< uint64_t >::max()}; + std::uniform_int_distribution< uint64_t > uint64Dist{ 0, + std::numeric_limits< uint64_t >::max() }; u256 value = _minVal + ( u256 ) uint64Dist( gen ) % ( _maxVal - _minVal ); return value; } uint8_t BoostRandomCode::weightedOpcode( std::vector< int > const& _weights ) { - DescreteDistrib opCodeProbability = DescreteDistrib{_weights.begin(), _weights.end()}; + DescreteDistrib opCodeProbability = DescreteDistrib{ _weights.begin(), _weights.end() }; return opCodeProbability( gen ); } } // namespace test diff --git a/test/tools/fuzzTesting/fuzzHelper.cpp b/test/tools/fuzzTesting/fuzzHelper.cpp index 3b1df9682..2207923b6 100644 --- a/test/tools/fuzzTesting/fuzzHelper.cpp +++ b/test/tools/fuzzTesting/fuzzHelper.cpp @@ -31,7 +31,7 @@ using namespace dev; using namespace std; -const static std::array< eth::Instruction, 47 > invalidOpcodes{{eth::Instruction::INVALID, +const static std::array< eth::Instruction, 47 > invalidOpcodes{ { eth::Instruction::INVALID, eth::Instruction::PUSHC, eth::Instruction::JUMPC, eth::Instruction::JUMPCI, eth::Instruction::JUMPTO, eth::Instruction::JUMPIF, eth::Instruction::JUMPSUB, eth::Instruction::JUMPV, eth::Instruction::JUMPSUBV, eth::Instruction::BEGINSUB, @@ -45,7 +45,7 @@ const static std::array< eth::Instruction, 47 > invalidOpcodes{{eth::Instruction eth::Instruction::XROR, eth::Instruction::XPUSH, eth::Instruction::XMLOAD, eth::Instruction::XMSTORE, eth::Instruction::XSLOAD, eth::Instruction::XSSTORE, eth::Instruction::XVTOWIDE, eth::Instruction::XWIDETOV, eth::Instruction::XPUT, - eth::Instruction::XGET, eth::Instruction::XSWIZZLE, eth::Instruction::XSHUFFLE}}; + eth::Instruction::XGET, eth::Instruction::XSWIZZLE, eth::Instruction::XSHUFFLE } }; namespace dev { namespace test { @@ -227,7 +227,7 @@ std::string RandomCodeBase::generate( int _maxOpNumber, RandomCodeOptions const& opcode = makeOpcodeDefined( opcode ); eth::Instruction inst = ( eth::Instruction ) opcode; eth::InstructionInfo info = eth::instructionInfo( inst ); - if ( std::string{info.name}.find( "PUSH" ) != std::string::npos ) { + if ( std::string{ info.name }.find( "PUSH" ) != std::string::npos ) { code += toCompactHex( opcode ); code += fillArguments( inst, _options ); } else { diff --git a/test/tools/jsontests/BlockChainTests.cpp b/test/tools/jsontests/BlockChainTests.cpp index 4c60a6489..036480b44 100644 --- a/test/tools/jsontests/BlockChainTests.cpp +++ b/test/tools/jsontests/BlockChainTests.cpp @@ -237,7 +237,7 @@ json_spirit::mObject fillBCTest( json_spirit::mObject const& _input ) { size_t importBlockNumber = 0; string chainname = "default"; string chainnetwork = "default"; - std::map< string, ChainBranch* > chainMap = {{chainname, new ChainBranch( genesisBlock )}}; + std::map< string, ChainBranch* > chainMap = { { chainname, new ChainBranch( genesisBlock ) } }; if ( _input.count( "network" ) > 0 ) output["network"] = _input.at( "network" ); @@ -387,13 +387,13 @@ json_spirit::mObject fillBCTest( json_spirit::mObject const& _input ) { } output["blocks"] = blArray; - output["postState"] = fillJsonWithState(testChain.topBlock().state() ); + output["postState"] = fillJsonWithState( testChain.topBlock().state() ); output["lastblockhash"] = toHexPrefixed( testChain.topBlock().blockHeader().hash( WithSeal ) ); // make all values hex in pre section State prestate = State(); ImportTest::importState( _input.at( "pre" ).get_obj(), prestate ); - output["pre"] = fillJsonWithState(prestate ); + output["pre"] = fillJsonWithState( prestate ); for ( auto iterator = chainMap.begin(); iterator != chainMap.end(); iterator++ ) delete iterator->second; @@ -507,7 +507,8 @@ void testBCTest( json_spirit::mObject const& _o ) { if ( blockFromFields.blockHeader().parentHash() == preHash ) { State const postState = testChain.topBlock().state(); assert( testChain.getInterface().sealEngine() ); - bigint reward = calculateMiningReward( testChain.topBlock().blockHeader().timestamp(), testChain.topBlock().blockHeader().number(), + bigint reward = calculateMiningReward( testChain.topBlock().blockHeader().timestamp(), + testChain.topBlock().blockHeader().number(), uncleNumbers.size() >= 1 ? uncleNumbers[0] : 0, uncleNumbers.size() >= 2 ? uncleNumbers[1] : 0, testChain.getInterface().sealEngine()->chainParams() ); @@ -537,15 +538,15 @@ void testBCTest( json_spirit::mObject const& _o ) { // blocks!"); State postState = State(); // Compare post states - postState.setStorageLimit(1000000000); + postState.setStorageLimit( 1000000000 ); BOOST_REQUIRE( ( _o.count( "postState" ) > 0 ) ); ImportTest::importState( _o.at( "postState" ).get_obj(), postState ); ImportTest::compareStates( postState, testChain.topBlock().state() ); ImportTest::compareStates( postState, blockchain.topBlock().state() ); } -bigint calculateMiningReward( time_t _committedBlockTimestamp, u256 const& _blNumber, u256 const& _unNumber1, u256 const& _unNumber2, - ChainOperationParams const& _cp ) { +bigint calculateMiningReward( time_t _committedBlockTimestamp, u256 const& _blNumber, + u256 const& _unNumber1, u256 const& _unNumber2, ChainOperationParams const& _cp ) { bigint const baseReward = _cp.blockReward( _committedBlockTimestamp, _blNumber ); bigint reward = baseReward; // INCLUDE_UNCLE = BASE_REWARD / 32 @@ -584,10 +585,9 @@ void overwriteBlockHeaderForTest( header.transactionsRoot(), ho.count( "receiptTrie" ) ? h256( ho["receiptTrie"].get_str() ) : header.receiptsRoot(), ho.count( "bloom" ) ? LogBloom( ho["bloom"].get_str() ) : header.logBloom(), - ho.count( "difficulty" ) ? - toInt( ho["difficulty"] ) : - ho.count( "relDifficulty" ) ? header.difficulty() + toInt( ho["relDifficulty"] ) : - header.difficulty(), + ho.count( "difficulty" ) ? toInt( ho["difficulty"] ) : + ho.count( "relDifficulty" ) ? header.difficulty() + toInt( ho["relDifficulty"] ) : + header.difficulty(), ho.count( "number" ) ? toInt( ho["number"] ) : header.number(), ho.count( "gasLimit" ) ? toInt( ho["gasLimit"] ) : header.gasLimit(), ho.count( "gasUsed" ) ? toInt( ho["gasUsed"] ) : header.gasUsed(), @@ -754,11 +754,10 @@ void overwriteUncleHeaderForTest( mObject& uncleHeaderObj, TestBlock& uncle, uncleHeader.transactionsRoot(), uncleHeader.receiptsRoot(), uncleHeader.logBloom(), overwrite == "difficulty" ? toInt( uncleHeaderObj.at( "difficulty" ) ) : - overwrite == "timestamp" ? + overwrite == "timestamp" ? ( ( const Ethash* ) sealEngine ) - ->calculateDifficulty( - uncleHeader, importedBlocks.at( ( size_t ) uncleHeader.number() - 1 ) - .blockHeader() ) : + ->calculateDifficulty( uncleHeader, + importedBlocks.at( ( size_t ) uncleHeader.number() - 1 ).blockHeader() ) : uncleHeader.difficulty(), overwrite == "number" ? toInt( uncleHeaderObj.at( "number" ) ) : uncleHeader.number(), overwrite == "gasLimit" ? toInt( uncleHeaderObj.at( "gasLimit" ) ) : @@ -833,7 +832,7 @@ mObject writeBlockHeaderToJson( BlockHeader const& _bi ) { } void checkExpectedException( mObject& _blObj, Exception const& _e ) { - string exWhat{_e.what()}; + string exWhat{ _e.what() }; bool isNetException = ( _blObj.count( "expectException" + test::netIdToString( test::TestBlockChain::s_sealEngineNetwork ) ) > 0 ); @@ -1021,10 +1020,10 @@ BOOST_AUTO_TEST_CASE( bcGasPricerTest ) {} BOOST_AUTO_TEST_CASE( bcUncleHeaderValidity ) {} // Commenting this out as we do not support this BOOST_AUTO_TEST_CASE( bcValidBlockTest ) {} -BOOST_AUTO_TEST_CASE( bcWalletTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( bcForgedTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + bcWalletTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + bcForgedTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_CASE( bcRandomBlockhashTest ) {} BOOST_AUTO_TEST_SUITE_END() @@ -1041,110 +1040,103 @@ BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE( BCGeneralStateTests, bcGeneralTestsFixture ) // Frontier Tests -BOOST_AUTO_TEST_CASE( stCallCodes, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( stCallCodes, *boost::unit_test::precondition( dev::test::run_not_express ) ) { } -BOOST_AUTO_TEST_CASE( stCallCreateCallCodeTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stExample, - *boost::unit_test::precondition( dev::test::run_not_express ) * +BOOST_AUTO_TEST_CASE( + stCallCreateCallCodeTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stExample, *boost::unit_test::precondition( dev::test::run_not_express ) * boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stInitCodeTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stLogTests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemoryTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stPreCompiledContracts, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stPreCompiledContracts2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRandom, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRandom2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRecursiveCreate, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRefundTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSolidityTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSpecialTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSystemOperationsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stTransactionTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stTransitionTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stWalletTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stInitCodeTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stLogTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemoryTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stPreCompiledContracts, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stPreCompiledContracts2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stRandom, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stRandom2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRecursiveCreate, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRefundTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSolidityTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSpecialTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSystemOperationsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stTransactionTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stTransitionTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stWalletTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Homestead Tests BOOST_AUTO_TEST_CASE( stCallDelegateCodesCallCodeHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stCallDelegateCodesHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stHomesteadSpecific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stDelegatecallTestHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stCallDelegateCodesHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stHomesteadSpecific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stDelegatecallTestHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // EIP150 Tests -BOOST_AUTO_TEST_CASE( stChangedEIP150, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stEIP150singleCodeGasPrices, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemExpandingEIP150Calls, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stEIP150Specific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stChangedEIP150, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP150singleCodeGasPrices, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemExpandingEIP150Calls, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP150Specific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // EIP158 Tests -BOOST_AUTO_TEST_CASE( stEIP158Specific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stNonZeroCallsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroCallsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroCallsRevert, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRevertTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP158Specific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stNonZeroCallsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroCallsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroCallsRevert, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRevertTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Metropolis Tests -BOOST_AUTO_TEST_CASE( stStackTests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stStaticCall, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stReturnDataTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroKnowledge, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroKnowledge2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stBugs, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stStackTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stStaticCall, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stReturnDataTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroKnowledge, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroKnowledge2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stBugs, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Constantinople Tests -BOOST_AUTO_TEST_CASE( stShift, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stShift, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Stress Tests -BOOST_AUTO_TEST_CASE( stAttackTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemoryStressTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stQuadraticComplexityTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stAttackTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemoryStressTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stQuadraticComplexityTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Bad opcodes test -BOOST_AUTO_TEST_CASE( stBadOpcode, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( stBadOpcode, *boost::unit_test::precondition( dev::test::run_not_express ) ) { } // New Tests -BOOST_AUTO_TEST_CASE( stArgsZeroOneBalance, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stArgsZeroOneBalance, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_SUITE_END() diff --git a/test/tools/jsontests/BlockChainTests.h b/test/tools/jsontests/BlockChainTests.h index 0312859b9..870258539 100644 --- a/test/tools/jsontests/BlockChainTests.h +++ b/test/tools/jsontests/BlockChainTests.h @@ -77,8 +77,8 @@ void checkJsonSectionForInvalidBlock( mObject& _blObj ); void checkExpectedException( mObject& _blObj, Exception const& _e ); void checkBlocks( TestBlock const& _blockFromFields, TestBlock const& _blockFromRlp, string const& _testname ); -bigint calculateMiningReward( time_t _committedBlockTimestamp, u256 const& _blNumber, u256 const& _unNumber1, u256 const& _unNumber2, - ChainOperationParams const& _cp ); +bigint calculateMiningReward( time_t _committedBlockTimestamp, u256 const& _blNumber, + u256 const& _unNumber1, u256 const& _unNumber2, ChainOperationParams const& _cp ); json_spirit::mObject fillBCTest( json_spirit::mObject const& _input ); void testBCTest( json_spirit::mObject const& _o ); diff --git a/test/tools/jsontests/StateTests.cpp b/test/tools/jsontests/StateTests.cpp index 85e886413..9ca46cbcd 100644 --- a/test/tools/jsontests/StateTests.cpp +++ b/test/tools/jsontests/StateTests.cpp @@ -78,7 +78,7 @@ json_spirit::mValue StateTestSuite::doTests( inputTest.count( "transaction" ) > 0, testname + " transaction not set!" ); ImportTest importer( inputTest, outputTest ); - Listener::ExecTimeGuard guard{i.first}; + Listener::ExecTimeGuard guard{ i.first }; importer.executeTest( _fillin ); if ( _fillin ) { @@ -162,43 +162,40 @@ class GeneralTestFixture { BOOST_FIXTURE_TEST_SUITE( GeneralStateTests, GeneralTestFixture ) // Frontier Tests -BOOST_AUTO_TEST_CASE( stCallCodes, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( stCallCodes, *boost::unit_test::precondition( dev::test::run_not_express ) ) { } -BOOST_AUTO_TEST_CASE( stCallCreateCallCodeTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stExample, *boost::unit_test::precondition( dev::test::run_not_express ) * +BOOST_AUTO_TEST_CASE( + stCallCreateCallCodeTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stExample, *boost::unit_test::precondition( dev::test::run_not_express ) * boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stInitCodeTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stLogTests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemoryTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stPreCompiledContracts, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stPreCompiledContracts2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRandom, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRandom2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRecursiveCreate, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRefundTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSolidityTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSpecialTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stSystemOperationsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stTransactionTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stTransitionTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stWalletTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stInitCodeTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stLogTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemoryTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stPreCompiledContracts, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stPreCompiledContracts2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stRandom, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stRandom2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRecursiveCreate, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRefundTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSolidityTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSpecialTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stSystemOperationsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stTransactionTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stTransitionTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stWalletTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Homestead Tests BOOST_AUTO_TEST_CASE( stCallDelegateCodesCallCodeHomestead, @@ -207,72 +204,71 @@ BOOST_AUTO_TEST_CASE( stCallDelegateCodesCallCodeHomestead, BOOST_AUTO_TEST_CASE( stCallDelegateCodesHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) * boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stHomesteadSpecific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stDelegatecallTestHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stHomesteadSpecific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stDelegatecallTestHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // EIP150 Tests -BOOST_AUTO_TEST_CASE( stChangedEIP150, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stEIP150singleCodeGasPrices, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemExpandingEIP150Calls, *boost::unit_test::precondition( dev::test::run_not_express ) * +BOOST_AUTO_TEST_CASE( + stChangedEIP150, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP150singleCodeGasPrices, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemExpandingEIP150Calls, *boost::unit_test::precondition( dev::test::run_not_express ) * boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stEIP150Specific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP150Specific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // EIP158 Tests -BOOST_AUTO_TEST_CASE( stEIP158Specific, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stNonZeroCallsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroCallsTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroCallsRevert, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stCodeSizeLimit, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stCreateTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stRevertTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEIP158Specific, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stNonZeroCallsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroCallsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroCallsRevert, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stCodeSizeLimit, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stCreateTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stRevertTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Metropolis Tests -BOOST_AUTO_TEST_CASE( stStackTests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stStaticCall, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stReturnDataTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroKnowledge, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stZeroKnowledge2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stStackTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stStaticCall, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stReturnDataTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroKnowledge, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stZeroKnowledge2, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_CASE( stCodeCopyTest ) {} -BOOST_AUTO_TEST_CASE( stBugs, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stBugs, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Constantinople Tests -BOOST_AUTO_TEST_CASE( stShift, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( stShift, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Stress Tests -BOOST_AUTO_TEST_CASE( stAttackTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stMemoryStressTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stQuadraticComplexityTest, *boost::unit_test::precondition( dev::test::run_not_express ) * +BOOST_AUTO_TEST_CASE( + stAttackTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stMemoryStressTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stQuadraticComplexityTest, *boost::unit_test::precondition( dev::test::run_not_express ) * boost::unit_test::precondition( dev::test::run_not_express ) ) {} // Invalid Opcode Tests -BOOST_AUTO_TEST_CASE( stBadOpcode, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( stBadOpcode, *boost::unit_test::precondition( dev::test::run_not_express ) ) { } // New Tests -BOOST_AUTO_TEST_CASE( stArgsZeroOneBalance, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( stEWASMTests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stArgsZeroOneBalance, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + stEWASMTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_SUITE_END() diff --git a/test/tools/jsontests/TransactionTests.cpp b/test/tools/jsontests/TransactionTests.cpp index 96b19dd67..f75791cca 100644 --- a/test/tools/jsontests/TransactionTests.cpp +++ b/test/tools/jsontests/TransactionTests.cpp @@ -103,7 +103,8 @@ json_spirit::mObject FillTransactionTest( json_spirit::mObject const& _o ) { "transaction from RLP signature is invalid" ) ); // TODO Remove SealEngine from tests too! - se->verifyTransaction( se->chainParams(), ImportRequirements::Everything, txFromFields, 0, bh, 0 ); + se->verifyTransaction( + se->chainParams(), ImportRequirements::Everything, txFromFields, 0, bh, 0 ); if ( expectSection.count( "sender" ) > 0 ) { string expectSender = toString( expectSection["sender"].get_str() ); BOOST_CHECK_MESSAGE( toString( txFromFields.sender() ) == expectSender, @@ -162,7 +163,8 @@ void TestTransactionTest( json_spirit::mObject const& _o ) { txFromRlp = Transaction( rlp.data(), CheckTransaction::Everything ); bool onExperimentalAndZeroSig = onExperimental && txFromRlp.hasZeroSignature(); // TODO Remove SealEngine from tests too! - se->verifyTransaction( se->chainParams(), ImportRequirements::Everything, txFromRlp, 0, bh, 0 ); + se->verifyTransaction( + se->chainParams(), ImportRequirements::Everything, txFromRlp, 0, bh, 0 ); if ( !( txFromRlp.signature().isValid() || onExperimentalAndZeroSig ) ) BOOST_THROW_EXCEPTION( Exception() << errinfo_comment( testname + diff --git a/test/tools/jsontests/vm.cpp b/test/tools/jsontests/vm.cpp index 939dd07da..704b3f01b 100644 --- a/test/tools/jsontests/vm.cpp +++ b/test/tools/jsontests/vm.cpp @@ -50,13 +50,13 @@ CreateResult FakeExtVM::create( u256 _endowment, u256& io_gas, bytesConstRef _init, Instruction, u256, OnOpFunc const& ) { Address address = right160( sha3( rlpList( myAddress, get< 1 >( addresses[myAddress] ) ) ) ); callcreates.emplace_back( _endowment, gasPrice, io_gas, _init.toBytes() ); - return {EVMC_SUCCESS, {}, address}; + return { EVMC_SUCCESS, {}, address }; } CallResult FakeExtVM::call( CallParameters& _p ) { Transaction t( _p.valueTransfer, gasPrice, _p.gas, _p.receiveAddress, _p.data.toVector() ); callcreates.push_back( t ); - return {EVMC_SUCCESS, {}}; // Return empty output. + return { EVMC_SUCCESS, {} }; // Return empty output. } h256 FakeExtVM::blockHash( u256 _number ) { @@ -92,7 +92,8 @@ mObject FakeExtVM::exportEnv() { return ret; } -EnvInfo FakeExtVM::importEnv( mObject const& _o, LastBlockHashesFace const& _lastBlockHashes, time_t _committedBlockTimestamp ) { +EnvInfo FakeExtVM::importEnv( mObject const& _o, LastBlockHashesFace const& _lastBlockHashes, + time_t _committedBlockTimestamp ) { // cant use BOOST_REQUIRE, because this function is used outside boost test (createRandomTest) assert( _o.count( "currentGasLimit" ) > 0 ); assert( _o.count( "currentDifficulty" ) > 0 ); @@ -313,7 +314,8 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo BOOST_REQUIRE_MESSAGE( testInput.count( "expect" ) == 0, testname + " expect set!" ); TestLastBlockHashes lastBlockHashes( h256s( 256, h256() ) ); - eth::EnvInfo env = FakeExtVM::importEnv( testInput.at( "env" ).get_obj(), lastBlockHashes, 0 ); + eth::EnvInfo env = + FakeExtVM::importEnv( testInput.at( "env" ).get_obj(), lastBlockHashes, 0 ); FakeExtVM fev( env ); fev.importState( testInput.at( "pre" ).get_obj() ); @@ -336,7 +338,7 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo auto vm = eth::VMFactory::create(); auto vmtrace = Options::get().vmtrace ? fev.simpleTrace() : OnOpFunc{}; { - Listener::ExecTimeGuard guard{i.first}; + Listener::ExecTimeGuard guard{ i.first }; auto gas = static_cast< int64_t >( fev.gas ); output = vm->exec( fev.gas, fev, vmtrace ); gas -= static_cast< int64_t >( fev.gas ); @@ -368,9 +370,9 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo BOOST_REQUIRE_MESSAGE( testInput.count( "expect" ) == 1, testname + " multiple expect set!" ); State postState = State(); - postState.setStorageLimit(1000000000); + postState.setStorageLimit( 1000000000 ); State expectState = State(); - expectState.setStorageLimit(1000000000); + expectState.setStorageLimit( 1000000000 ); AccountMaskMap expectStateMap; ImportTest::importState( mValue( fev.exportState() ).get_obj(), postState ); ImportTest::importState( @@ -390,9 +392,9 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo testInput.count( "expect" ) == 1, testname + " multiple expect set!" ); State postState = State(); - postState.setStorageLimit(1000000000); + postState.setStorageLimit( 1000000000 ); State expectState = State(); - expectState.setStorageLimit(1000000000); + expectState.setStorageLimit( 1000000000 ); AccountMaskMap expectStateMap; // json_spirit::mObject const& debug_var = testOutput.at("post").get_obj(); @@ -447,7 +449,8 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo testname + " logs field is not a string." ); // use all patches here ("1") - dev::test::FakeExtVM test( eth::EnvInfo{BlockHeader{}, lastBlockHashes, 1, 0, 0} ); + dev::test::FakeExtVM test( + eth::EnvInfo{ BlockHeader{}, lastBlockHashes, 1, 0, 0 } ); test.importState( testInput.at( "post" ).get_obj() ); test.importCallCreates( testInput.at( "callcreates" ).get_array() ); @@ -456,9 +459,9 @@ json_spirit::mValue VmTestSuite::doTests( json_spirit::mValue const& _input, boo BOOST_CHECK_EQUAL( toInt( testInput.at( "gas" ) ), fev.gas ); State postState = State(); - postState.setStorageLimit(1000000000); + postState.setStorageLimit( 1000000000 ); State expectState = State(); - expectState.setStorageLimit(1000000000); + expectState.setStorageLimit( 1000000000 ); mObject mPostState = fev.exportState(); ImportTest::importState( mPostState, postState ); ImportTest::importState( testInput.at( "post" ).get_obj(), expectState ); @@ -505,21 +508,20 @@ class VmTestFixture { BOOST_FIXTURE_TEST_SUITE( VMTests, VmTestFixture ) BOOST_AUTO_TEST_CASE( vmArithmeticTest ) {} -BOOST_AUTO_TEST_CASE( vmBitwiseLogicOperation, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( vmBlockInfoTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( vmEnvironmentalInfo, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + vmBitwiseLogicOperation, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + vmBlockInfoTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + vmEnvironmentalInfo, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_CASE( vmIOandFlowOperations ) {} BOOST_AUTO_TEST_CASE( vmLogTest ) {} -BOOST_AUTO_TEST_CASE( vmPerformance, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + vmPerformance, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_CASE( vmPushDupSwapTest ) {} -BOOST_AUTO_TEST_CASE( vmRandomTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} -BOOST_AUTO_TEST_CASE( vmSha3Test, - *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( + vmRandomTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} +BOOST_AUTO_TEST_CASE( vmSha3Test, *boost::unit_test::precondition( dev::test::run_not_express ) ) {} BOOST_AUTO_TEST_CASE( vmSystemOperations ) {} BOOST_AUTO_TEST_CASE( vmTests ) {} diff --git a/test/tools/jsontests/vm.h b/test/tools/jsontests/vm.h index 4c0c510cd..0d24d83c4 100644 --- a/test/tools/jsontests/vm.h +++ b/test/tools/jsontests/vm.h @@ -76,8 +76,8 @@ class FakeExtVM : public eth::ExtVMFace { void reset( u256 _myBalance, u256 _myNonce, std::map< u256, u256 > const& _storage ); u256 doPosts(); json_spirit::mObject exportEnv(); - static dev::eth::EnvInfo importEnv( - json_spirit::mObject const& _o, eth::LastBlockHashesFace const& _lastBlockHashes, time_t _committedBlockTimestamp ); + static dev::eth::EnvInfo importEnv( json_spirit::mObject const& _o, + eth::LastBlockHashesFace const& _lastBlockHashes, time_t _committedBlockTimestamp ); json_spirit::mObject exportState(); void importState( json_spirit::mObject const& _object ); json_spirit::mObject exportExec(); @@ -94,7 +94,7 @@ class FakeExtVM : public eth::ExtVMFace { u256 gas; u256 execGas; - mutable Logger m_logger{createLogger( VerbosityTrace, "EVM" )}; + mutable Logger m_logger{ createLogger( VerbosityTrace, "EVM" ) }; }; class VmTestSuite : public TestSuite { diff --git a/test/tools/libtesteth/BlockChainHelper.cpp b/test/tools/libtesteth/BlockChainHelper.cpp index 3098b54e1..d563f44f6 100644 --- a/test/tools/libtesteth/BlockChainHelper.cpp +++ b/test/tools/libtesteth/BlockChainHelper.cpp @@ -99,7 +99,7 @@ void TestBlock::initBlockFromJsonHeader( mObject const& _blockHeader, mObject co m_state = std::unique_ptr< State >( new State( 0, m_tempDirState.get()->path(), h256{}, BaseState::Empty, 0, 1000000000 ) ); ImportTest::importState( _stateObj, *m_state ); - m_state->createStateCopyAndClearCaches().commit(dev::eth::CommitBehaviour::KeepEmptyAccounts ); + m_state->createStateCopyAndClearCaches().commit( dev::eth::CommitBehaviour::KeepEmptyAccounts ); json_spirit::mObject state = _stateObj; dev::test::replaceCodeInState( state ); @@ -360,7 +360,7 @@ void TestBlock::verify( TestBlockChain const& _bc ) const { if ( ( m_blockHeader.number() >= daoHardfork && m_blockHeader.number() <= daoHardfork + 9 ) || m_blockHeader.number() == 0 ) { - string exWhat{_e.what()}; + string exWhat{ _e.what() }; string exExpect = "InvalidTransactionsRoot"; BOOST_REQUIRE_MESSAGE( exWhat.find( exExpect ) != string::npos, TestOutputHelper::get().testName() + @@ -472,8 +472,7 @@ void TestBlockChain::reset( TestBlock const& _genesisBlock ) { } bool TestBlockChain::addBlock( TestBlock const& _block ) { - - SchainPatch::useLatestBlockTimestamp(m_blockChain->info().timestamp()); + SchainPatch::useLatestBlockTimestamp( m_blockChain->info().timestamp() ); while ( true ) { try { @@ -497,7 +496,7 @@ bool TestBlockChain::addBlock( TestBlock const& _block ) { State st( block.state() ); m_lastBlock.setState( st ); - SchainPatch::useLatestBlockTimestamp(m_blockChain->info().timestamp()); + SchainPatch::useLatestBlockTimestamp( m_blockChain->info().timestamp() ); return true; } diff --git a/test/tools/libtesteth/FillJsonFunctions.cpp b/test/tools/libtesteth/FillJsonFunctions.cpp index 142344bc0..3b42f2983 100644 --- a/test/tools/libtesteth/FillJsonFunctions.cpp +++ b/test/tools/libtesteth/FillJsonFunctions.cpp @@ -61,7 +61,9 @@ json_spirit::mObject fillJsonWithStateChange( // Sort the vector by address field skale::ChangeLog changeLog = _changeLog; std::sort( changeLog.begin(), changeLog.end(), - []( const skale::Change& lhs, const skale::Change& rhs ) { return lhs.address < rhs.address; } ); + []( const skale::Change& lhs, const skale::Change& rhs ) { + return lhs.address < rhs.address; + } ); std::ostringstream log; json_spirit::mObject o; diff --git a/test/tools/libtesteth/ImportTest.cpp b/test/tools/libtesteth/ImportTest.cpp index 9555cec56..ca8e4598a 100644 --- a/test/tools/libtesteth/ImportTest.cpp +++ b/test/tools/libtesteth/ImportTest.cpp @@ -60,8 +60,8 @@ ImportTest::ImportTest( json_spirit::mObject const& _input, json_spirit::mObject m_statePost( 0 ), m_testInputObject( _input ), m_testOutputObject( _output ) { - m_statePre.setStorageLimit(1000000000); - m_statePost.setStorageLimit(1000000000); + m_statePre.setStorageLimit( 1000000000 ); + m_statePost.setStorageLimit( 1000000000 ); importEnv( _input.at( "env" ).get_obj() ); importTransaction( _input.at( "transaction" ).get_obj() ); importState( _input.at( "pre" ).get_obj(), m_statePre ); @@ -93,7 +93,7 @@ void ImportTest::makeBlockchainTestFromStateTest( set< eth::Network > const& _ne State s = State( 0 ); AccountMaskMap m; - StateAndMap smap{s, m}; + StateAndMap smap{ s, m }; vector< size_t > stateIndexesToPrint; json_spirit::mArray expetSectionArray; @@ -102,18 +102,18 @@ void ImportTest::makeBlockchainTestFromStateTest( set< eth::Network > const& _ne trDup.netId = net; // Calculate the block reward - ChainParams const chainParams{genesisInfo( net )}; + ChainParams const chainParams{ genesisInfo( net ) }; EVMSchedule const schedule = chainParams.makeEvmSchedule( 0, 1 ); // u256 const blockReward = chainParams.blockReward(schedule); - TrExpectSection search{trDup, smap}; + TrExpectSection search{ trDup, smap }; for ( auto const& exp : m_testInputObject.at( "expect" ).get_array() ) { TrExpectSection* search2 = &search; checkGeneralTestSectionSearch( exp.get_obj(), stateIndexesToPrint, "", search2 ); throw std::logic_error( "Skale state does not support addresses list" ); } // for exp - } // for net + } // for net testObj["expect"] = expetSectionArray; @@ -157,14 +157,14 @@ set< eth::Network > ImportTest::getAllNetworksFromExpectSections( BOOST_REQUIRE( exp.get_obj().count( "network" ) > 0 ); if ( exp.get_obj().at( "network" ).type() == json_spirit::str_type ) requireJsonFields( exp.get_obj(), "expect", - {{"network", jsonVType::str_type}, {"result", jsonVType::obj_type}} ); + { { "network", jsonVType::str_type }, { "result", jsonVType::obj_type } } ); else requireJsonFields( exp.get_obj(), "expect", - {{"network", jsonVType::array_type}, {"result", jsonVType::obj_type}} ); + { { "network", jsonVType::array_type }, { "result", jsonVType::obj_type } } ); } else if ( _testType == testType::StateTest ) requireJsonFields( exp.get_obj(), "expect", - {{"indexes", jsonVType::obj_type}, {"network", jsonVType::array_type}, - {"result", jsonVType::obj_type}} ); + { { "indexes", jsonVType::obj_type }, { "network", jsonVType::array_type }, + { "result", jsonVType::obj_type } } ); ImportTest::parseJsonStrValueIntoSet( exp.get_obj().at( "network" ), allNetworks ); } @@ -209,7 +209,7 @@ bytes ImportTest::executeTest( bool _isFilling ) { if ( statePreIsChanged ) { // revert changes in m_statePre m_statePre = State( 0 ); - m_statePre.setStorageLimit(1000000000); + m_statePre.setStorageLimit( 1000000000 ); importState( m_testInputObject.at( "pre" ).get_obj(), m_statePre ); } @@ -261,7 +261,8 @@ std::tuple< State, ImportTest::ExecOutput, skale::ChangeLog > ImportTest::execut StandardTrace st; st.setShowMnemonics(); st.setOptions( Options::get().jsontraceOptions ); - out = initialState.execute( _env, se->chainParams(), _tr, Permanence::Committed, st.onOp() ); + out = initialState.execute( + _env, se->chainParams(), _tr, Permanence::Committed, st.onOp() ); cout << st.json(); cout << "{\"stateRoot\": \"Is not supported\"}"; } else @@ -295,9 +296,9 @@ std::tuple< State, ImportTest::ExecOutput, skale::ChangeLog > ImportTest::execut json_spirit::mObject ImportTest::makeAllFieldsHex( json_spirit::mObject const& _input, bool _isHeader ) { - static const set< string > hashes{"bloom", "coinbase", "hash", "mixHash", "parentHash", + static const set< string > hashes{ "bloom", "coinbase", "hash", "mixHash", "parentHash", "receiptTrie", "stateRoot", "transactionsTrie", "uncleHash", "currentCoinbase", - "previousHash", "to", "address", "caller", "origin", "secretKey", "data", "extraData"}; + "previousHash", "to", "address", "caller", "origin", "secretKey", "data", "extraData" }; json_spirit::mObject output = _input; @@ -343,9 +344,10 @@ json_spirit::mObject ImportTest::makeAllFieldsHex( void ImportTest::importEnv( json_spirit::mObject const& _o ) { requireJsonFields( _o, "env", - {{"currentCoinbase", jsonVType::str_type}, {"currentDifficulty", jsonVType::str_type}, - {"currentGasLimit", jsonVType::str_type}, {"currentNumber", jsonVType::str_type}, - {"currentTimestamp", jsonVType::str_type}, {"previousHash", jsonVType::str_type}} ); + { { "currentCoinbase", jsonVType::str_type }, { "currentDifficulty", jsonVType::str_type }, + { "currentGasLimit", jsonVType::str_type }, { "currentNumber", jsonVType::str_type }, + { "currentTimestamp", jsonVType::str_type }, + { "previousHash", jsonVType::str_type } } ); auto gasLimit = toInt( _o.at( "currentGasLimit" ) ); BOOST_REQUIRE( gasLimit <= std::numeric_limits< int64_t >::max() ); BlockHeader header; @@ -372,7 +374,7 @@ void ImportTest::importState( validation::validateAccountMaskObj( accountMaskJson ); } std::string jsondata = json_spirit::write_string( ( json_spirit::mValue ) o, false ); - _state.populateFrom(jsonToAccountMap(jsondata, 0, &o_mask ) ); + _state.populateFrom( jsonToAccountMap( jsondata, 0, &o_mask ) ); } void ImportTest::importState( json_spirit::mObject const& _o, State& _state ) { @@ -380,8 +382,8 @@ void ImportTest::importState( json_spirit::mObject const& _o, State& _state ) { BOOST_REQUIRE_MESSAGE( account.second.type() == jsonVType::obj_type, "State account is required to be json Object!" ); requireJsonFields( account.second.get_obj(), account.first, - {{"balance", jsonVType::str_type}, {"code", jsonVType::str_type}, - {"nonce", jsonVType::str_type}, {"storage", jsonVType::obj_type}} ); + { { "balance", jsonVType::str_type }, { "code", jsonVType::str_type }, + { "nonce", jsonVType::str_type }, { "storage", jsonVType::obj_type } } ); } AccountMaskMap mask; @@ -391,10 +393,10 @@ void ImportTest::importState( json_spirit::mObject const& _o, State& _state ) { void ImportTest::importTransaction( json_spirit::mObject const& _o, eth::Transaction& o_tr ) { if ( _o.count( "secretKey" ) > 0 ) { requireJsonFields( _o, "transaction", - {{"data", jsonVType::str_type}, {"gasLimit", jsonVType::str_type}, - {"gasPrice", jsonVType::str_type}, {"nonce", jsonVType::str_type}, - {"secretKey", jsonVType::str_type}, {"to", jsonVType::str_type}, - {"value", jsonVType::str_type}} ); + { { "data", jsonVType::str_type }, { "gasLimit", jsonVType::str_type }, + { "gasPrice", jsonVType::str_type }, { "nonce", jsonVType::str_type }, + { "secretKey", jsonVType::str_type }, { "to", jsonVType::str_type }, + { "value", jsonVType::str_type } } ); if ( bigint( _o.at( "nonce" ).get_str() ) >= c_max256plus1 ) BOOST_THROW_EXCEPTION( ValueTooLarge() << errinfo_comment( @@ -420,10 +422,11 @@ void ImportTest::importTransaction( json_spirit::mObject const& _o, eth::Transac o_tr.ignoreExternalGas(); } else { requireJsonFields( _o, "transaction", - {{"data", jsonVType::str_type}, {"gasLimit", jsonVType::str_type}, - {"gasPrice", jsonVType::str_type}, {"nonce", jsonVType::str_type}, - {"v", jsonVType::str_type}, {"r", jsonVType::str_type}, {"s", jsonVType::str_type}, - {"to", jsonVType::str_type}, {"value", jsonVType::str_type}} ); + { { "data", jsonVType::str_type }, { "gasLimit", jsonVType::str_type }, + { "gasPrice", jsonVType::str_type }, { "nonce", jsonVType::str_type }, + { "v", jsonVType::str_type }, { "r", jsonVType::str_type }, + { "s", jsonVType::str_type }, { "to", jsonVType::str_type }, + { "value", jsonVType::str_type } } ); RLPStream transactionRLPStream = createRLPStreamFromTransactionFields( _o ); RLP transactionRLP( transactionRLPStream.out() ); @@ -449,16 +452,17 @@ void ImportTest::importTransaction( json_spirit::mObject const& _o, eth::Transac void ImportTest::importTransaction( json_spirit::mObject const& o_tr ) { if ( o_tr.count( "secretKey" ) ) requireJsonFields( o_tr, "transaction", - {{"data", jsonVType::array_type}, {"gasLimit", jsonVType::array_type}, - {"gasPrice", jsonVType::str_type}, {"nonce", jsonVType::str_type}, - {"secretKey", jsonVType::str_type}, {"to", jsonVType::str_type}, - {"value", jsonVType::array_type}} ); + { { "data", jsonVType::array_type }, { "gasLimit", jsonVType::array_type }, + { "gasPrice", jsonVType::str_type }, { "nonce", jsonVType::str_type }, + { "secretKey", jsonVType::str_type }, { "to", jsonVType::str_type }, + { "value", jsonVType::array_type } } ); else requireJsonFields( o_tr, "transaction", - {{"data", jsonVType::array_type}, {"gasLimit", jsonVType::array_type}, - {"gasPrice", jsonVType::str_type}, {"nonce", jsonVType::str_type}, - {"v", jsonVType::str_type}, {"r", jsonVType::str_type}, {"s", jsonVType::str_type}, - {"to", jsonVType::str_type}, {"value", jsonVType::array_type}} ); + { { "data", jsonVType::array_type }, { "gasLimit", jsonVType::array_type }, + { "gasPrice", jsonVType::str_type }, { "nonce", jsonVType::str_type }, + { "v", jsonVType::str_type }, { "r", jsonVType::str_type }, + { "s", jsonVType::str_type }, { "to", jsonVType::str_type }, + { "value", jsonVType::array_type } } ); // Parse extended transaction size_t dataVectorSize = o_tr.at( "data" ).get_array().size(); @@ -530,16 +534,20 @@ int ImportTest::compareStates( State const& _stateExpect, State const& _statePos if ( _statePost.addressInUse( accountAddress ) ) { if ( addressOptions.hasBalance() ) - CHECK( ( _stateExpect.balance( accountAddress ) == _statePost.balance( accountAddress ) ), + CHECK( ( _stateExpect.balance( accountAddress ) == + _statePost.balance( accountAddress ) ), TestOutputHelper::get().testName() + " Check State: " - << accountAddress << ": incorrect balance " << _statePost.balance( accountAddress ) - << ", expected " << _stateExpect.balance( accountAddress ) ); + << accountAddress << ": incorrect balance " + << _statePost.balance( accountAddress ) << ", expected " + << _stateExpect.balance( accountAddress ) ); if ( addressOptions.hasNonce() ) - CHECK( ( _stateExpect.getNonce( accountAddress ) == _statePost.getNonce( accountAddress ) ), + CHECK( ( _stateExpect.getNonce( accountAddress ) == + _statePost.getNonce( accountAddress ) ), TestOutputHelper::get().testName() + " Check State: " - << accountAddress << ": incorrect nonce " << _statePost.getNonce( accountAddress ) - << ", expected " << _stateExpect.getNonce( accountAddress ) ); + << accountAddress << ": incorrect nonce " + << _statePost.getNonce( accountAddress ) << ", expected " + << _stateExpect.getNonce( accountAddress ) ); if ( addressOptions.hasStorage() ) { map< h256, pair< u256, u256 > > stateStorage = _statePost.storage( accountAddress ); @@ -553,9 +561,10 @@ int ImportTest::compareStates( State const& _stateExpect, State const& _statePos << "] = " << toCompactHexPrefixed( s.second.second ) ); // Check for unexpected storage values - map< h256, pair< u256, u256 > > expectedStorage = _stateExpect.storage( accountAddress ); + map< h256, pair< u256, u256 > > expectedStorage = + _stateExpect.storage( accountAddress ); for ( auto const& s : _statePost.storage( accountAddress ) ) { - if (s.second.second == 0 && expectedStorage.count( s.first ) == 0 ) { + if ( s.second.second == 0 && expectedStorage.count( s.first ) == 0 ) { // take into account fact that storage() in skaled historically // can return zero values of storage, which could just be omitted // since Ethereum default value for storage is zero anyway @@ -572,7 +581,7 @@ int ImportTest::compareStates( State const& _stateExpect, State const& _statePos } if ( addressOptions.hasCode() ) - CHECK( ( _stateExpect.code( accountAddress ) == _statePost.code( accountAddress) ), + CHECK( ( _stateExpect.code( accountAddress ) == _statePost.code( accountAddress ) ), TestOutputHelper::get().testName() + " Check State: " << accountAddress << ": incorrect code '" << toHexPrefixed( _statePost.code( accountAddress ) ) << "', expected '" @@ -633,13 +642,13 @@ bool ImportTest::checkGeneralTestSectionSearch( json_spirit::mObject const& _exp vector< size_t >& _errorTransactions, string const& _network, TrExpectSection* _search ) const { if ( _expects.count( "result" ) ) { requireJsonFields( _expects, "expect", - {{"indexes", jsonVType::obj_type}, {"network", jsonVType::array_type}, - {"result", jsonVType::obj_type}} ); + { { "indexes", jsonVType::obj_type }, { "network", jsonVType::array_type }, + { "result", jsonVType::obj_type } } ); } else { // Expect section in filled test requireJsonFields( _expects, "expect", - {{"indexes", jsonVType::obj_type}, {"hash", jsonVType::str_type}, - {"logs", jsonVType::str_type}} ); + { { "indexes", jsonVType::obj_type }, { "hash", jsonVType::str_type }, + { "logs", jsonVType::str_type } } ); } vector< int > d; @@ -658,7 +667,7 @@ bool ImportTest::checkGeneralTestSectionSearch( json_spirit::mObject const& _exp if ( !Options::get().singleTestNet.empty() ) { // skip this check if we execute transactions only on another specified network - if ( !network.count( Options::get().singleTestNet ) && !network.count( string{"ALL"} ) ) + if ( !network.count( Options::get().singleTestNet ) && !network.count( string{ "ALL" } ) ) return false; } diff --git a/test/tools/libtesteth/ImportTest.h b/test/tools/libtesteth/ImportTest.h index ed4f1c298..f72ad274d 100644 --- a/test/tools/libtesteth/ImportTest.h +++ b/test/tools/libtesteth/ImportTest.h @@ -112,7 +112,7 @@ class ImportTest { json_spirit::mObject const& m_testInputObject; json_spirit::mObject& m_testOutputObject; - Logger m_logger{createLogger( VerbosityInfo, "state" )}; + Logger m_logger{ createLogger( VerbosityInfo, "state" ) }; }; template < class T > diff --git a/test/tools/libtesteth/Options.cpp b/test/tools/libtesteth/Options.cpp index 5f6074367..f37ddfacd 100644 --- a/test/tools/libtesteth/Options.cpp +++ b/test/tools/libtesteth/Options.cpp @@ -133,7 +133,7 @@ Options::Options( int argc, const char** argv ) { // For some reason boost is confused by -- separator. This extra parser "skips" the --. auto skipDoubleDash = []( const std::string& s ) -> std::pair< std::string, std::string > { if ( s == "--" ) - return {"--", {}}; + return { "--", {} }; return {}; }; @@ -155,7 +155,7 @@ Options::Options( int argc, const char** argv ) { setDatabaseKind( DatabaseKind::LevelDB ); // default to LevelDB in the interest of reduced // test execution time for ( auto i = 0; i < argc; ++i ) { - auto arg = std::string{argv[i]}; + auto arg = std::string{ argv[i] }; auto throwIfNoArgumentFollows = [&i, &argc, &arg]() { if ( i + 1 >= argc ) BOOST_THROW_EXCEPTION( @@ -202,7 +202,7 @@ Options::Options( int argc, const char** argv ) { } else if ( arg == "--jsontrace" ) { throwIfNoArgumentFollows(); jsontrace = true; - auto arg = std::string{argv[++i]}; + auto arg = std::string{ argv[++i] }; Json::Value value; Json::Reader().parse( arg, value ); StandardTrace::DebugOptions op; @@ -226,10 +226,10 @@ Options::Options( int argc, const char** argv ) { else if ( arg == "--singletest" ) { throwIfNoArgumentFollows(); singleTest = true; - auto name1 = std::string{argv[++i]}; + auto name1 = std::string{ argv[++i] }; if ( i + 1 < argc ) // two params { - auto name2 = std::string{argv[++i]}; + auto name2 = std::string{ argv[++i] }; if ( name2[0] == '-' ) // not param, another option { singleTestName = std::move( name1 ); @@ -242,7 +242,7 @@ Options::Options( int argc, const char** argv ) { singleTestName = std::move( name1 ); } else if ( arg == "--singlenet" ) { throwIfNoArgumentFollows(); - singleTestNet = std::string{argv[++i]}; + singleTestNet = std::string{ argv[++i] }; ImportTest::checkAllowedNetwork( singleTestNet ); } else if ( arg == "--fulloutput" ) fulloutput = true; @@ -251,7 +251,7 @@ Options::Options( int argc, const char** argv ) { verbosity = std::max( verbosity, atoi( argv[++i] ) ); } else if ( arg == "--options" ) { throwIfNoArgumentFollows(); - boost::filesystem::path file( std::string{argv[++i]} ); + boost::filesystem::path file( std::string{ argv[++i] } ); if ( boost::filesystem::exists( file ) ) randomCodeOptionsPath = file; else { @@ -264,7 +264,7 @@ Options::Options( int argc, const char** argv ) { } else if ( arg == "-t" ) { throwIfAfterSeparator(); throwIfNoArgumentFollows(); - rCurrentTestSuite = std::string{argv[++i]}; + rCurrentTestSuite = std::string{ argv[++i] }; } else if ( arg == "-d" ) { throwIfNoArgumentFollows(); trDataIndex = atoi( argv[++i] ); @@ -276,7 +276,7 @@ Options::Options( int argc, const char** argv ) { trValueIndex = atoi( argv[++i] ); } else if ( arg == "--testpath" ) { throwIfNoArgumentFollows(); - testpath = std::string{argv[++i]}; + testpath = std::string{ argv[++i] }; } else if ( arg == "--statediff" ) { statediff = true; verbosity = VerbosityTrace; @@ -294,7 +294,7 @@ Options::Options( int argc, const char** argv ) { createRandomTest = true; if ( i + 1 < argc ) // two params { - auto options = std::string{argv[++i]}; + auto options = std::string{ argv[++i] }; if ( options[0] == '-' ) // not param, another option i--; else { diff --git a/test/tools/libtesteth/Stats.cpp b/test/tools/libtesteth/Stats.cpp index 2350415e6..733228cf6 100644 --- a/test/tools/libtesteth/Stats.cpp +++ b/test/tools/libtesteth/Stats.cpp @@ -41,7 +41,7 @@ void Stats::testStarted( std::string const& _name ) { } void Stats::testFinished( int64_t _gasUsed ) { - m_stats.push_back( {clock::now() - m_tp, _gasUsed, m_currentSuite + "/" + m_currentTest} ); + m_stats.push_back( { clock::now() - m_tp, _gasUsed, m_currentSuite + "/" + m_currentTest } ); } std::ostream& operator<<( std::ostream& out, Stats::clock::duration const& d ) { @@ -81,7 +81,7 @@ Stats::~Stats() { out << "\n"; } else if ( !Options::get().statsOutFile.empty() ) { // Output stats to file - std::ofstream file{Options::get().statsOutFile}; + std::ofstream file{ Options::get().statsOutFile }; for ( auto&& s : m_stats ) { auto usecs = std::chrono::duration_cast< std::chrono::microseconds >( s.duration ).count(); diff --git a/test/tools/libtesteth/TestHelper.cpp b/test/tools/libtesteth/TestHelper.cpp index 76a04fb93..19bf9dddc 100644 --- a/test/tools/libtesteth/TestHelper.cpp +++ b/test/tools/libtesteth/TestHelper.cpp @@ -112,7 +112,7 @@ void mine( BlockHeader& _bi, SealEngineFace* _sealer, bool _verify ) { _sealer->verify( JustSeal, _bi ); } -void simulateMining( Client& client, size_t numBlocks, const dev::Address &address ) { +void simulateMining( Client& client, size_t numBlocks, const dev::Address& address ) { const auto balanceBefore = client.balanceAt( address ); State state = client.state(); u256 reward = 0; @@ -121,9 +121,9 @@ void simulateMining( Client& client, size_t numBlocks, const dev::Address &addre } state.addBalance( address, reward ); state.commit(); - state.getOriginalDb()->createBlockSnap(1); + state.getOriginalDb()->createBlockSnap( 1 ); const auto balanceAfter = client.balanceAt( address ); - balanceAfter > balanceBefore; // make compiler happy + balanceAfter > balanceBefore; // make compiler happy assert( balanceAfter > balanceBefore ); } @@ -173,13 +173,13 @@ string netIdToString( eth::Network _netId ) { eth::Network stringToNetId( string const& _netname ) { // Networks that used in .json tests - static vector< eth::Network > const networks{ - {eth::Network::FrontierTest, eth::Network::HomesteadTest, eth::Network::EIP150Test, - eth::Network::EIP158Test, eth::Network::ByzantiumTest, eth::Network::ConstantinopleTest, - eth::Network::ConstantinopleFixTest, eth::Network::IstanbulTest, - eth::Network::FrontierToHomesteadAt5, eth::Network::HomesteadToDaoAt5, - eth::Network::HomesteadToEIP150At5, eth::Network::EIP158ToByzantiumAt5, - eth::Network::ByzantiumToConstantinopleFixAt5, eth::Network::TransitionnetTest}}; + static vector< eth::Network > const networks{ { eth::Network::FrontierTest, + eth::Network::HomesteadTest, eth::Network::EIP150Test, eth::Network::EIP158Test, + eth::Network::ByzantiumTest, eth::Network::ConstantinopleTest, + eth::Network::ConstantinopleFixTest, eth::Network::IstanbulTest, + eth::Network::FrontierToHomesteadAt5, eth::Network::HomesteadToDaoAt5, + eth::Network::HomesteadToEIP150At5, eth::Network::EIP158ToByzantiumAt5, + eth::Network::ByzantiumToConstantinopleFixAt5, eth::Network::TransitionnetTest } }; for ( auto const& net : networks ) if ( netIdToString( net ) == _netname ) @@ -210,10 +210,10 @@ bool isDisabledNetwork( eth::Network _net ) { set< eth::Network > const& getNetworks() { // Networks for the test case execution when filling the tests - static set< eth::Network > const networks{ - {eth::Network::FrontierTest, eth::Network::HomesteadTest, eth::Network::EIP150Test, - eth::Network::EIP158Test, eth::Network::ByzantiumTest, eth::Network::ConstantinopleTest, - eth::Network::ConstantinopleFixTest, eth::Network::IstanbulTest}}; + static set< eth::Network > const networks{ { eth::Network::FrontierTest, + eth::Network::HomesteadTest, eth::Network::EIP150Test, eth::Network::EIP158Test, + eth::Network::ByzantiumTest, eth::Network::ConstantinopleTest, + eth::Network::ConstantinopleFixTest, eth::Network::IstanbulTest } }; return networks; } @@ -326,7 +326,7 @@ int64_t toPositiveInt64( const json_spirit::mValue& _v ) { } if ( n < 0 ) - throw std::out_of_range{"unexpected negative value: " + std::to_string( n )}; + throw std::out_of_range{ "unexpected negative value: " + std::to_string( n ) }; return n; } @@ -390,9 +390,9 @@ string replaceCode( string const& _code ) { } void replaceCodeInState( json_spirit::mObject& _o ) { - json_spirit::mObject& fieldsObj = _o.count( "alloc" ) ? - _o["alloc"].get_obj() : - _o.count( "accounts" ) ? _o["accounts"].get_obj() : _o; + json_spirit::mObject& fieldsObj = _o.count( "alloc" ) ? _o["alloc"].get_obj() : + _o.count( "accounts" ) ? _o["accounts"].get_obj() : + _o; for ( auto& account : fieldsObj ) { auto obj = account.second.get_obj(); if ( obj.count( "code" ) && obj["code"].type() == json_spirit::str_type ) @@ -597,7 +597,7 @@ void requireJsonFields( json_spirit::mObject const& _o, string const& _section, } string prepareVersionString() { - return string{"testeth "} + skale_get_buildinfo()->project_version; + return string{ "testeth " } + skale_get_buildinfo()->project_version; } // A simple C++ implementation of the Levenshtein distance algorithm to measure the amount of @@ -735,7 +735,6 @@ void Listener::notifySuiteStarted( string const& _name ) { } void Listener::notifyTestStarted( string const& _name ) { - if ( g_listener ) g_listener->testStarted( _name ); } diff --git a/test/tools/libtesteth/TestHelper.h b/test/tools/libtesteth/TestHelper.h index aa9a730d1..2b5974575 100644 --- a/test/tools/libtesteth/TestHelper.h +++ b/test/tools/libtesteth/TestHelper.h @@ -66,7 +66,7 @@ void mine( Client& c, int numBlocks ); * @brief simulateMining gives money to miner but do not create block. Use it only for testing * instead of mine( Client& c, int numBlocks ) */ -void simulateMining( Client& client, size_t numBlocks, const dev::Address &address ); +void simulateMining( Client& client, size_t numBlocks, const dev::Address& address ); void simulateMining( Client& client, size_t numBlocks ); void mineMoney( Client& c, int numBlocks ); void mineTransaction( Client& c, int numBlocks ); @@ -84,7 +84,8 @@ typedef json_spirit::Value_type jsonVType; class ZeroGasPricer : public eth::GasPricer { protected: u256 ask( eth::Block const& ) const override { return 0; } - u256 bid( unsigned = dev::eth::LatestBlock, eth::TransactionPriority = eth::TransactionPriority::Medium ) const override { + u256 bid( unsigned = dev::eth::LatestBlock, + eth::TransactionPriority = eth::TransactionPriority::Medium ) const override { return 0; } }; @@ -141,8 +142,8 @@ dev::eth::BlockHeader constructHeader( h256 const& _parentHash, h256 const& _sha void updateEthashSeal( dev::eth::BlockHeader& _header, h256 const& _mixHash, dev::eth::Nonce const& _nonce ); RLPStream createRLPStreamFromTransactionFields( json_spirit::mObject const& _tObj ); -json_spirit::mObject fillJsonWithStateChange( State const& _stateOrig, - skale::State const& _statePost, skale::ChangeLog const& _changeLog ); +json_spirit::mObject fillJsonWithStateChange( + State const& _stateOrig, skale::State const& _statePost, skale::ChangeLog const& _changeLog ); json_spirit::mObject fillJsonWithState( State const& _state ); json_spirit::mObject fillJsonWithState( skale::State const& _state, eth::AccountMaskMap const& _map ); diff --git a/test/tools/libtesteth/TestOutputHelper.cpp b/test/tools/libtesteth/TestOutputHelper.cpp index 745896c64..f2e0fed72 100644 --- a/test/tools/libtesteth/TestOutputHelper.cpp +++ b/test/tools/libtesteth/TestOutputHelper.cpp @@ -20,9 +20,9 @@ * Fixture class for boost output when running testeth */ -#include #include #include +#include #include #include @@ -108,5 +108,5 @@ TestOutputHelperFixture::TestOutputHelperFixture() { TestOutputHelperFixture::~TestOutputHelperFixture() { TestOutputHelper::get().finishTest(); // XXX used in Personal test. do it more nicely! - unsetenv("DATA_DIR"); + unsetenv( "DATA_DIR" ); } diff --git a/test/tools/libtesteth/TestSuite.cpp b/test/tools/libtesteth/TestSuite.cpp index b5a680d68..e1ac421e5 100644 --- a/test/tools/libtesteth/TestSuite.cpp +++ b/test/tools/libtesteth/TestSuite.cpp @@ -143,7 +143,7 @@ void TestSuite::runAllTestsInFolder( string const& _testFolder ) const { string() : test::Options::get().singleTestName; vector< fs::path > const compiledFiles = - test::getFiles( getFullPath( _testFolder ), {".json", ".yml"}, filter ); + test::getFiles( getFullPath( _testFolder ), { ".json", ".yml" }, filter ); for ( auto const& file : compiledFiles ) { fs::path const expectedFillerName = getFullPathFiller( _testFolder ) / @@ -177,7 +177,7 @@ void TestSuite::runAllTestsInFolder( string const& _testFolder ) const { // run all tests vector< fs::path > const files = test::getFiles( getFullPathFiller( _testFolder ), - {".json", ".yml"}, filter.empty() ? filter : filter + "Filler" ); + { ".json", ".yml" }, filter.empty() ? filter : filter + "Filler" ); auto& testOutput = test::TestOutputHelper::get(); testOutput.initTest( files.size() ); diff --git a/test/tools/libtesteth/TestUtils.cpp b/test/tools/libtesteth/TestUtils.cpp index 09bdb3a34..5ff74ccd4 100644 --- a/test/tools/libtesteth/TestUtils.cpp +++ b/test/tools/libtesteth/TestUtils.cpp @@ -92,7 +92,7 @@ void ClientBaseFixture::enumerateClients( cerr << "void ClientBaseFixture::enumerateClients. FixedClient now accepts block not sate!" << endl; _state.commit( dev::eth::CommitBehaviour::KeepEmptyAccounts ); // unused variable. remove - // this line + // this line eth::Block b( Block::Null ); b.noteChain( _bc ); FixedClient client( _bc, b ); diff --git a/test/tools/libtesteth/boostTest.cpp b/test/tools/libtesteth/boostTest.cpp index 45fb63b2b..a56044de8 100644 --- a/test/tools/libtesteth/boostTest.cpp +++ b/test/tools/libtesteth/boostTest.cpp @@ -136,7 +136,7 @@ void setCLocale() { // Custom Boost Unit Test Main int main( int argc, const char* argv[] ) { MicroProfileSetEnableAllGroups( true ); - UnsafeRegion::init("."); + UnsafeRegion::init( "." ); std::string const dynamicTestSuiteName = "customTestSuite"; setCLocale(); @@ -154,7 +154,7 @@ int main( int argc, const char* argv[] ) { bool testSuiteFound = false; for ( int i = 0; i < argc; i++ ) { // replace test suite to custom tests - std::string arg = std::string{argv[i]}; + std::string arg = std::string{ argv[i] }; if ( arg == "-t" && i + 1 < argc ) { testSuiteFound = true; argv[i + 1] = ( char* ) dynamicTestSuiteName.c_str(); @@ -193,7 +193,7 @@ int main( int argc, const char* argv[] ) { std::cout << "Running tests using path: " << test::getTestPath() << std::endl; int result = 0; - auto fakeInit = []( int, char* [] ) -> boost::unit_test::test_suite* { return nullptr; }; + auto fakeInit = []( int, char*[] ) -> boost::unit_test::test_suite* { return nullptr; }; if ( opt.jsontrace || opt.vmtrace || opt.statediff ) { // Do not use travis '.' output thread if debug is defined result = unit_test_main( fakeInit, argc, const_cast< char** >( argv ) ); @@ -205,7 +205,7 @@ int main( int argc, const char* argv[] ) { return result; } else { // Initialize travis '.' output thread for log activity - std::atomic_bool stopTravisOut{false}; + std::atomic_bool stopTravisOut{ false }; std::thread outputThread( travisOut, &stopTravisOut ); result = unit_test_main( fakeInit, argc, const_cast< char** >( argv ) ); stopTravisOut = true; diff --git a/test/tools/libtestutils/FixedClient.h b/test/tools/libtestutils/FixedClient.h index 354789c4b..9b8217379 100644 --- a/test/tools/libtestutils/FixedClient.h +++ b/test/tools/libtestutils/FixedClient.h @@ -69,13 +69,14 @@ class FixedClient : public dev::eth::ClientBase { h256 submitTransaction( eth::TransactionSkeleton const&, Secret const& ) override { return {}; }; - h256 importTransaction( eth::Transaction const&, dev::eth::TransactionBroadcast ) override { return {}; } - eth::ExecutionResult call( - Address const&, u256, Address, bytes const&, u256, u256, + h256 importTransaction( eth::Transaction const&, dev::eth::TransactionBroadcast ) override { + return {}; + } + eth::ExecutionResult call( Address const&, u256, Address, bytes const&, u256, u256, #ifdef HISTORIC_STATE - BlockNumber, + BlockNumber, #endif -eth::FudgeFactor ) override { + eth::FudgeFactor ) override { return {}; }; eth::TransactionSkeleton populateTransactionWithDefaults( @@ -84,16 +85,11 @@ eth::FudgeFactor ) override { }; #ifdef HISTORIC_STATE - u256 historicStateBalanceAt(Address, BlockNumber) const override - {return 0;} - u256 historicStateCountAt(Address, BlockNumber) const override - {return 0;} - u256 historicStateAt(Address, u256, BlockNumber) const override - {return 0;} - h256 historicStateRootAt(Address, BlockNumber) const override - {return h256();} - bytes historicStateCodeAt(Address, BlockNumber) const override - {return bytes();}; + u256 historicStateBalanceAt( Address, BlockNumber ) const override { return 0; } + u256 historicStateCountAt( Address, BlockNumber ) const override { return 0; } + u256 historicStateAt( Address, u256, BlockNumber ) const override { return 0; } + h256 historicStateRootAt( Address, BlockNumber ) const override { return h256(); } + bytes historicStateCodeAt( Address, BlockNumber ) const override { return bytes(); }; #endif private: @@ -103,6 +99,5 @@ eth::FudgeFactor ) override { }; - } // namespace test } // namespace dev diff --git a/test/unittests/external-dependencies/boost.cpp b/test/unittests/external-dependencies/boost.cpp index 39d1fbc00..af1f78e13 100644 --- a/test/unittests/external-dependencies/boost.cpp +++ b/test/unittests/external-dependencies/boost.cpp @@ -31,7 +31,8 @@ using namespace boost::multiprecision; BOOST_FIXTURE_TEST_SUITE( boostTests, TestOutputHelperFixture ) // test that reproduces issue https://github.com/ethereum/cpp-ethereum/issues/1977 -BOOST_AUTO_TEST_CASE( u256_overflow_test, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + u256_overflow_test, *boost::unit_test::precondition( dev::test::run_not_express ) ) { dev::u256 a = 14; dev::bigint b = dev::bigint( "115792089237316195423570985008687907853269984665640564039457584007913129639948" ); @@ -39,13 +40,14 @@ BOOST_AUTO_TEST_CASE( u256_overflow_test, *boost::unit_test::precondition( dev:: BOOST_CHECK( a < b ); } -BOOST_AUTO_TEST_CASE( u256_shift_left, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + u256_shift_left, *boost::unit_test::precondition( dev::test::run_not_express ) ) { u256 a = 1; uint64_t amount = 1; auto b = a << amount; BOOST_CHECK_EQUAL( b, 2 ); - auto high_bit = u256{0}; + auto high_bit = u256{ 0 }; bit_set( high_bit, 255 ); BOOST_CHECK_EQUAL( a << 255, high_bit ); BOOST_CHECK_EQUAL( a << uint64_t( 256 ), 0 ); @@ -60,13 +62,15 @@ BOOST_AUTO_TEST_CASE( u256_shift_left, *boost::unit_test::precondition( dev::tes BOOST_CHECK_EQUAL( static_cast< u256 >( bigint( u256( 3 ) ) << 255 ), u256( 1 ) << 255 ); } -BOOST_AUTO_TEST_CASE( u256_shift_left_bug, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + u256_shift_left_bug, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Bug reported: https://github.com/boostorg/multiprecision/issues/31 using uint256 = number< cpp_int_backend< 256, 256, unsigned_magnitude, unchecked, void > >; BOOST_CHECK_EQUAL( uint256( 3 ) << 255, uint256( 1 ) << 255 ); } -BOOST_AUTO_TEST_CASE( u256_logical_shift_right, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + u256_logical_shift_right, *boost::unit_test::precondition( dev::test::run_not_express ) ) { u256 a = 1; uint64_t amount = 1; auto b = a >> amount; @@ -109,7 +113,8 @@ BOOST_AUTO_TEST_CASE( u256_logical_shift_right, *boost::unit_test::precondition( constexpr auto int64_min = std::numeric_limits< int64_t >::min(); static_assert( int64_min >> 1 == int64_min / 2, "I cannot shift!" ); -BOOST_AUTO_TEST_CASE( u256_arithmetic_shift_right, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + u256_arithmetic_shift_right, *boost::unit_test::precondition( dev::test::run_not_express ) ) { s256 a = 1; uint64_t amount = 1; auto b = a >> amount; diff --git a/test/unittests/libdevcore/CommonJS.cpp b/test/unittests/libdevcore/CommonJS.cpp index 4896d9b76..7a8ecf5bf 100644 --- a/test/unittests/libdevcore/CommonJS.cpp +++ b/test/unittests/libdevcore/CommonJS.cpp @@ -36,7 +36,7 @@ BOOST_AUTO_TEST_CASE( test_toJS, *boost::unit_test::precondition( dev::test::run h64 a( "0xbaadf00ddeadbeef" ); u64 b( "0xffff0000bbbaaaa" ); uint64_t c = 38990234243; - bytes d = {0xff, 0x0, 0xef, 0xbc}; + bytes d = { 0xff, 0x0, 0xef, 0xbc }; BOOST_CHECK( toJS( a ) == "0xbaadf00ddeadbeef" ); BOOST_CHECK( toJS( b ) == "0xffff0000bbbaaaa" ); @@ -44,9 +44,10 @@ BOOST_AUTO_TEST_CASE( test_toJS, *boost::unit_test::precondition( dev::test::run BOOST_CHECK( toJS( d ) == "0xff00efbc" ); } -BOOST_AUTO_TEST_CASE( test_jsToBytes, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - bytes a = {0xff, 0xaa, 0xbb, 0xcc}; - bytes b = {0x03, 0x89, 0x90, 0x23, 0x42, 0x43}; +BOOST_AUTO_TEST_CASE( + test_jsToBytes, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + bytes a = { 0xff, 0xaa, 0xbb, 0xcc }; + bytes b = { 0x03, 0x89, 0x90, 0x23, 0x42, 0x43 }; BOOST_CHECK( a == jsToBytes( "0xffaabbcc" ) ); BOOST_CHECK( b == jsToBytes( "38990234243" ) ); BOOST_CHECK( bytes() == jsToBytes( "" ) ); @@ -54,42 +55,46 @@ BOOST_AUTO_TEST_CASE( test_jsToBytes, *boost::unit_test::precondition( dev::test } BOOST_AUTO_TEST_CASE( test_padded, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - bytes a = {0xff, 0xaa}; - BOOST_CHECK( bytes( {0x00, 0x00, 0xff, 0xaa} ) == padded( a, 4 ) ); + bytes a = { 0xff, 0xaa }; + BOOST_CHECK( bytes( { 0x00, 0x00, 0xff, 0xaa } ) == padded( a, 4 ) ); bytes b = {}; - BOOST_CHECK( bytes( {0x00, 0x00, 0x00, 0x00} ) == padded( b, 4 ) ); - bytes c = {0xff, 0xaa, 0xbb, 0xcc}; - BOOST_CHECK( bytes{0xcc} == padded( c, 1 ) ); + BOOST_CHECK( bytes( { 0x00, 0x00, 0x00, 0x00 } ) == padded( b, 4 ) ); + bytes c = { 0xff, 0xaa, 0xbb, 0xcc }; + BOOST_CHECK( bytes{ 0xcc } == padded( c, 1 ) ); } -BOOST_AUTO_TEST_CASE( test_paddedRight, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - bytes a = {0xff, 0xaa}; - BOOST_CHECK( bytes( {0xff, 0xaa, 0x00, 0x00} ) == paddedRight( a, 4 ) ); +BOOST_AUTO_TEST_CASE( + test_paddedRight, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + bytes a = { 0xff, 0xaa }; + BOOST_CHECK( bytes( { 0xff, 0xaa, 0x00, 0x00 } ) == paddedRight( a, 4 ) ); bytes b = {}; - BOOST_CHECK( bytes( {0x00, 0x00, 0x00, 0x00} ) == paddedRight( b, 4 ) ); - bytes c = {0xff, 0xaa, 0xbb, 0xcc}; - BOOST_CHECK( bytes{0xff} == paddedRight( c, 1 ) ); + BOOST_CHECK( bytes( { 0x00, 0x00, 0x00, 0x00 } ) == paddedRight( b, 4 ) ); + bytes c = { 0xff, 0xaa, 0xbb, 0xcc }; + BOOST_CHECK( bytes{ 0xff } == paddedRight( c, 1 ) ); } -BOOST_AUTO_TEST_CASE( test_unpadded, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - bytes a = {0xff, 0xaa, 0x00, 0x00, 0x00}; - BOOST_CHECK( bytes( {0xff, 0xaa} ) == unpadded( a ) ); - bytes b = {0x00, 0x00}; +BOOST_AUTO_TEST_CASE( + test_unpadded, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + bytes a = { 0xff, 0xaa, 0x00, 0x00, 0x00 }; + BOOST_CHECK( bytes( { 0xff, 0xaa } ) == unpadded( a ) ); + bytes b = { 0x00, 0x00 }; BOOST_CHECK( bytes() == unpadded( b ) ); bytes c = {}; BOOST_CHECK( bytes() == unpadded( c ) ); } -BOOST_AUTO_TEST_CASE( test_unpaddedLeft, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - bytes a = {0x00, 0x00, 0x00, 0xff, 0xaa}; - BOOST_CHECK( bytes( {0xff, 0xaa} ) == unpadLeft( a ) ); - bytes b = {0x00, 0x00}; +BOOST_AUTO_TEST_CASE( + test_unpaddedLeft, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + bytes a = { 0x00, 0x00, 0x00, 0xff, 0xaa }; + BOOST_CHECK( bytes( { 0xff, 0xaa } ) == unpadLeft( a ) ); + bytes b = { 0x00, 0x00 }; BOOST_CHECK( bytes() == unpadLeft( b ) ); bytes c = {}; BOOST_CHECK( bytes() == unpadLeft( c ) ); } -BOOST_AUTO_TEST_CASE( test_fromRaw, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + test_fromRaw, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // non ascii characters means empty string h256 a( "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ); BOOST_CHECK( "" == fromRaw( a ) ); @@ -99,7 +104,8 @@ BOOST_AUTO_TEST_CASE( test_fromRaw, *boost::unit_test::precondition( dev::test:: BOOST_CHECK( "AsciiCharacters" == fromRaw( c ) ); } -BOOST_AUTO_TEST_CASE( test_jsToFixed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + test_jsToFixed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { h256 a( "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ); BOOST_CHECK( a == jsToFixed< 32 >( "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) ); @@ -108,7 +114,8 @@ BOOST_AUTO_TEST_CASE( test_jsToFixed, *boost::unit_test::precondition( dev::test BOOST_CHECK_THROW( jsToFixed< 32 >( "NotAHexadecimalOrDecimal" ), std::invalid_argument ); } -BOOST_AUTO_TEST_CASE( test_jsToInt, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + test_jsToInt, *boost::unit_test::precondition( dev::test::run_not_express ) ) { BOOST_CHECK( 43832124 == jsToInt( "43832124" ) ); BOOST_CHECK( 1342356623 == jsToInt( "0x5002bc8f" ) ); BOOST_CHECK( 3483942 == jsToInt( "015224446" ) ); @@ -122,7 +129,8 @@ BOOST_AUTO_TEST_CASE( test_jsToInt, *boost::unit_test::precondition( dev::test:: BOOST_CHECK_THROW( jsToInt< 16 >( "NotAHexadecimalOrDecimal" ), std::invalid_argument ); } -BOOST_AUTO_TEST_CASE( test_jsToU256, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + test_jsToU256, *boost::unit_test::precondition( dev::test::run_not_express ) ) { BOOST_CHECK( u256( "983298932490823474234" ) == jsToU256( "983298932490823474234" ) ); BOOST_CHECK_THROW( jsToU256( "NotAHexadecimalOrDecimal" ), std::invalid_argument ); } diff --git a/test/unittests/libdevcore/FixedHash.cpp b/test/unittests/libdevcore/FixedHash.cpp index 1bec7bbc7..b43ffdf9f 100644 --- a/test/unittests/libdevcore/FixedHash.cpp +++ b/test/unittests/libdevcore/FixedHash.cpp @@ -34,8 +34,8 @@ namespace test { BOOST_FIXTURE_TEST_SUITE( FixedHashTests, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( FixedHashComparisons, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashComparisons, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 4 > h1( sha3( "abcd" ) ); FixedHash< 4 > h2( sha3( "abcd" ) ); FixedHash< 4 > h3( sha3( "aadd" ) ); @@ -52,8 +52,8 @@ BOOST_AUTO_TEST_CASE( FixedHashComparisons, BOOST_CHECK( h6 >= h4 ); } -BOOST_AUTO_TEST_CASE( FixedHashXOR, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashXOR, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 2 > h1( "0xAAAA" ); FixedHash< 2 > h2( "0xBBBB" ); @@ -62,8 +62,7 @@ BOOST_AUTO_TEST_CASE( FixedHashXOR, BOOST_CHECK( h1 == FixedHash< 2 >( "0x1111" ) ); } -BOOST_AUTO_TEST_CASE( FixedHashOR, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( FixedHashOR, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 4 > h1( "0xD3ADB33F" ); FixedHash< 4 > h2( "0xBAADF00D" ); FixedHash< 4 > res( "0xFBADF33F" ); @@ -73,8 +72,8 @@ BOOST_AUTO_TEST_CASE( FixedHashOR, BOOST_CHECK( h1 == res ); } -BOOST_AUTO_TEST_CASE( FixedHashAND, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashAND, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 4 > h1( "0xD3ADB33F" ); FixedHash< 4 > h2( "0xBAADF00D" ); FixedHash< 4 > h3( "0x92aDB00D" ); @@ -84,16 +83,16 @@ BOOST_AUTO_TEST_CASE( FixedHashAND, BOOST_CHECK( h1 = h3 ); } -BOOST_AUTO_TEST_CASE( FixedHashInvert, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashInvert, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 4 > h1( "0xD3ADB33F" ); FixedHash< 4 > h2( "0x2C524CC0" ); BOOST_CHECK( ~h1 == h2 ); } -BOOST_AUTO_TEST_CASE( FixedHashContains, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashContains, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedHash< 4 > h1( "0xD3ADB331" ); FixedHash< 4 > h2( "0x0000B331" ); FixedHash< 4 > h3( "0x0000000C" ); @@ -126,8 +125,8 @@ void incrementSingleIteration( unsigned seed ) { BOOST_CHECK_EQUAL( next, reverse2 ); } -BOOST_AUTO_TEST_CASE( FixedHashIncrement, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + FixedHashIncrement, *boost::unit_test::precondition( dev::test::run_not_express ) ) { incrementSingleIteration( 0 ); incrementSingleIteration( 1 ); incrementSingleIteration( 0xBAD ); diff --git a/test/unittests/libdevcore/LevelDB.cpp b/test/unittests/libdevcore/LevelDB.cpp index d8c955e3e..651dd3d4c 100644 --- a/test/unittests/libdevcore/LevelDB.cpp +++ b/test/unittests/libdevcore/LevelDB.cpp @@ -115,7 +115,7 @@ BOOST_AUTO_TEST_CASE( rotation_test ) { const int rotateInterval = 10; const int nPreserved = ( nPieces - 1 ) * rotateInterval; - auto batcher = make_shared( td.path(), nPieces, false ); + auto batcher = make_shared< batched_io::rotating_db_io >( td.path(), nPieces, false ); db::ManuallyRotatingLevelDB rdb( batcher ); for ( int i = 0; i < nPreserved * 3; ++i ) { @@ -149,7 +149,7 @@ BOOST_AUTO_TEST_CASE( rotation_rewrite_test ) { TransientDirectory td; const int nPieces = 3; - auto batcher = make_shared( td.path(), nPieces, false ); + auto batcher = make_shared< batched_io::rotating_db_io >( td.path(), nPieces, false ); db::ManuallyRotatingLevelDB rdb( batcher ); rdb.insert( string( "a" ), string( "va" ) ); @@ -172,11 +172,11 @@ BOOST_AUTO_TEST_CASE( rotation_rewrite_test ) { BOOST_REQUIRE_EQUAL( rdb.lookup( string( "a" ) ), string( "va_new_new" ) ); } -BOOST_AUTO_TEST_CASE( rotation_circle_test ){ +BOOST_AUTO_TEST_CASE( rotation_circle_test ) { TransientDirectory td; const int nPieces = 3; - auto batcher = make_shared( td.path(), nPieces, false ); + auto batcher = make_shared< batched_io::rotating_db_io >( td.path(), nPieces, false ); db::ManuallyRotatingLevelDB rdb( batcher ); rdb.insert( string( "a" ), string( "va1" ) ); @@ -184,46 +184,46 @@ BOOST_AUTO_TEST_CASE( rotation_circle_test ){ rdb.insert( string( "a" ), string( "va2" ) ); int cnt = 0; - for(int i=0; i( td.path(), nPieces, false ); + auto batcher = make_shared< batched_io::rotating_db_io >( td.path(), nPieces, false ); db::ManuallyRotatingLevelDB rdb( batcher ); - rdb.insert( string( "a" ), to_string(0) ); - for(int i=1; i<=pre_rotate; ++i){ + rdb.insert( string( "a" ), to_string( 0 ) ); + for ( int i = 1; i <= pre_rotate; ++i ) { rdb.rotate(); - rdb.insert( string( "a" ), to_string(i) ); + rdb.insert( string( "a" ), to_string( i ) ); } - BOOST_REQUIRE_EQUAL( rdb.lookup(string("a")), to_string(pre_rotate)); + BOOST_REQUIRE_EQUAL( rdb.lookup( string( "a" ) ), to_string( pre_rotate ) ); } // scope 2 { - auto batcher = make_shared( td.path(), nPieces, false ); + auto batcher = make_shared< batched_io::rotating_db_io >( td.path(), nPieces, false ); db::ManuallyRotatingLevelDB rdb( batcher ); - BOOST_REQUIRE_EQUAL( rdb.lookup(string("a")), to_string(pre_rotate)); + BOOST_REQUIRE_EQUAL( rdb.lookup( string( "a" ) ), to_string( pre_rotate ) ); } - }// for pre_rotate + } // for pre_rotate } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libdevcore/RangeMask.cpp b/test/unittests/libdevcore/RangeMask.cpp index 13540eb55..8c5fcf344 100644 --- a/test/unittests/libdevcore/RangeMask.cpp +++ b/test/unittests/libdevcore/RangeMask.cpp @@ -34,11 +34,10 @@ namespace test { BOOST_FIXTURE_TEST_SUITE( RangeMaskTest, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( constructor, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( constructor, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; - for ( RM r : {RM(), RM( 1, 10 ), RM( Range( 2, 10 ) )} ) { + for ( RM r : { RM(), RM( 1, 10 ), RM( Range( 2, 10 ) ) } ) { BOOST_CHECK( r.empty() ); BOOST_CHECK( !r.contains( 0 ) ); BOOST_CHECK( !r.contains( 1 ) ); @@ -49,8 +48,8 @@ BOOST_AUTO_TEST_CASE( constructor, BOOST_CHECK( !RM( Range( 2, 10 ) ).full() ); } -BOOST_AUTO_TEST_CASE( simple_unions, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + simple_unions, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; RM m( Range( 0, 2000 ) ); @@ -70,8 +69,7 @@ BOOST_AUTO_TEST_CASE( simple_unions, BOOST_CHECK( !m.contains( 258 ) ); } -BOOST_AUTO_TEST_CASE( empty_union, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( empty_union, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; RM m( Range( 0, 2000 ) ); @@ -89,8 +87,8 @@ BOOST_AUTO_TEST_CASE( empty_union, BOOST_CHECK_EQUAL( m.size(), 3 ); } -BOOST_AUTO_TEST_CASE( overlapping_unions, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + overlapping_unions, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; RM m( Range( 0, 2000 ) ); @@ -112,8 +110,7 @@ BOOST_AUTO_TEST_CASE( overlapping_unions, BOOST_CHECK_EQUAL( 70 - 5, m.size() ); } -BOOST_AUTO_TEST_CASE( complement, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( complement, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; RM m( Range( 0, 2000 ) ); @@ -129,8 +126,7 @@ BOOST_AUTO_TEST_CASE( complement, BOOST_CHECK_EQUAL( m.size(), 1000 - 10 ); } -BOOST_AUTO_TEST_CASE( iterator, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( iterator, *boost::unit_test::precondition( dev::test::run_not_express ) ) { using RM = RangeMask; using Range = pair< unsigned, unsigned >; RM m( Range( 0, 2000 ) ); @@ -140,7 +136,7 @@ BOOST_AUTO_TEST_CASE( iterator, vector< unsigned > elements; copy( m.begin(), m.end(), back_inserter( elements ) ); - BOOST_CHECK( elements == ( vector< unsigned >{7, 8, 11, 200, 201, 202, 203, 204} ) ); + BOOST_CHECK( elements == ( vector< unsigned >{ 7, 8, 11, 200, 201, 202, 203, 204 } ) ); } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libdevcore/core.cpp b/test/unittests/libdevcore/core.cpp index 54eb7e81f..f52933e2c 100644 --- a/test/unittests/libdevcore/core.cpp +++ b/test/unittests/libdevcore/core.cpp @@ -36,8 +36,7 @@ using namespace dev::test; BOOST_FIXTURE_TEST_SUITE( CoreLibTests, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( toHex, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( toHex, *boost::unit_test::precondition( dev::test::run_not_express ) ) { dev::bytes b = dev::fromHex( "f0e1d2c3b4a59687" ); BOOST_CHECK_EQUAL( dev::toHex( b ), "f0e1d2c3b4a59687" ); BOOST_CHECK_EQUAL( dev::toHexPrefixed( b ), "0xf0e1d2c3b4a59687" ); @@ -49,15 +48,14 @@ BOOST_AUTO_TEST_CASE( toHex, "0x705a1849c02140e7197fbde82987a9eb623f97e32fc479a3cd8e4b3b52dcc4b2" ); } -BOOST_AUTO_TEST_CASE( toCompactHex, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + toCompactHex, *boost::unit_test::precondition( dev::test::run_not_express ) ) { dev::u256 i( "0x123456789abcdef" ); BOOST_CHECK_EQUAL( dev::toCompactHex( i ), "0123456789abcdef" ); BOOST_CHECK_EQUAL( dev::toCompactHexPrefixed( i ), "0x0123456789abcdef" ); } -BOOST_AUTO_TEST_CASE( byteRef, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( byteRef, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "bytesRef copyTo and toString..."; dev::bytes originalSequence = dev::fromHex( "0102030405060708091011121314151617181920212223242526272829303132" ); @@ -71,8 +69,7 @@ BOOST_AUTO_TEST_CASE( byteRef, out.toBytes() == originalSequence, "Error when h256::ref().copyTo(dev::bytesRef out)" ); } -BOOST_AUTO_TEST_CASE( isHex, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( isHex, *boost::unit_test::precondition( dev::test::run_not_express ) ) { BOOST_CHECK( dev::isHex( "0x" ) ); BOOST_CHECK( dev::isHex( "0xA" ) ); BOOST_CHECK( dev::isHex( "0xAB" ) ); diff --git a/test/unittests/libdevcore/rlp.cpp b/test/unittests/libdevcore/rlp.cpp index f6edca2a0..6676b1c41 100644 --- a/test/unittests/libdevcore/rlp.cpp +++ b/test/unittests/libdevcore/rlp.cpp @@ -221,8 +221,8 @@ BOOST_AUTO_TEST_CASE( EmptyArrayList ) { } } -BOOST_AUTO_TEST_CASE( invalidRLPtest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + invalidRLPtest, *boost::unit_test::precondition( dev::test::run_not_express ) ) { runRlpTest( "invalidRLPTest", "/RLPTests" ); } @@ -234,7 +234,7 @@ BOOST_AUTO_TEST_CASE( rlpRandom ) { fs::path testPath = dev::test::getTestPath(); testPath /= fs::path( "RLPTests/RandomRLPTests" ); - vector< boost::filesystem::path > testFiles = test::getFiles( testPath, {".json"} ); + vector< boost::filesystem::path > testFiles = test::getFiles( testPath, { ".json" } ); for ( auto& path : testFiles ) { try { cnote << "Testing ..." << path.filename(); diff --git a/test/unittests/libdevcore/sharedspace.cpp b/test/unittests/libdevcore/sharedspace.cpp index f3305f609..8c885ad00 100644 --- a/test/unittests/libdevcore/sharedspace.cpp +++ b/test/unittests/libdevcore/sharedspace.cpp @@ -15,18 +15,16 @@ BOOST_FIXTURE_TEST_SUITE( SharedSpaceTests, TestOutputHelperFixture ) BOOST_AUTO_TEST_CASE( All ) { TransientDirectory td; - SharedSpace space(td.path()); + SharedSpace space( td.path() ); space.lock(); - BOOST_ASSERT(!space.try_lock()); + BOOST_ASSERT( !space.try_lock() ); - auto th = std::thread([&space](){ - space.unlock(); - }); + auto th = std::thread( [&space]() { space.unlock(); } ); th.join(); - BOOST_ASSERT(space.try_lock()); - BOOST_ASSERT(!space.try_lock()); + BOOST_ASSERT( space.try_lock() ); + BOOST_ASSERT( !space.try_lock() ); space.unlock(); } diff --git a/test/unittests/libdevcrypto/AES.cpp b/test/unittests/libdevcrypto/AES.cpp index 10545e8a5..e2c7edb3d 100644 --- a/test/unittests/libdevcrypto/AES.cpp +++ b/test/unittests/libdevcrypto/AES.cpp @@ -43,7 +43,8 @@ BOOST_AUTO_TEST_CASE( AesDecrypt, *boost::unit_test::precondition( dev::test::ru BOOST_CHECK( Address( "07746f871de684297923f933279555dda418f8a2" ) == kp.address() ); } -BOOST_AUTO_TEST_CASE( AesDecryptWrongSeed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + AesDecryptWrongSeed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "AesDecryptWrongSeed"; bytes seed = fromHex( "badaead416c20cfd00c2fc9f1788ff9f965a2000799c96a624767cb0e1e90d2d7191efdd92349226742fdc73d1" @@ -53,7 +54,8 @@ BOOST_AUTO_TEST_CASE( AesDecryptWrongSeed, *boost::unit_test::precondition( dev: BOOST_CHECK( Address( "07746f871de684297923f933279555dda418f8a2" ) != kp.address() ); } -BOOST_AUTO_TEST_CASE( AesDecryptWrongPassword, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + AesDecryptWrongPassword, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "AesDecryptWrongPassword"; bytes seed = fromHex( "2dbaead416c20cfd00c2fc9f1788ff9f965a2000799c96a624767cb0e1e90d2d7191efdd92349226742fdc73d1" @@ -63,7 +65,8 @@ BOOST_AUTO_TEST_CASE( AesDecryptWrongPassword, *boost::unit_test::precondition( BOOST_CHECK( Address( "07746f871de684297923f933279555dda418f8a2" ) != kp.address() ); } -BOOST_AUTO_TEST_CASE( AesDecryptFailInvalidSeed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + AesDecryptFailInvalidSeed, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "AesDecryptFailInvalidSeed"; bytes seed = fromHex( "xdbaead416c20cfd00c2fc9f1788ff9f965a2000799c96a624767cb0e1e90d2d7191efdd92349226742fdc73d1" @@ -72,13 +75,15 @@ BOOST_AUTO_TEST_CASE( AesDecryptFailInvalidSeed, *boost::unit_test::precondition BOOST_CHECK( bytes() == aesDecrypt( &seed, "test" ) ); } -BOOST_AUTO_TEST_CASE( AesDecryptFailInvalidSeedSize, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + AesDecryptFailInvalidSeedSize, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "AesDecryptFailInvalidSeedSize"; bytes seed = fromHex( "000102030405060708090a0b0c0d0e0f" ); BOOST_CHECK( bytes() == aesDecrypt( &seed, "test" ) ); } -BOOST_AUTO_TEST_CASE( AesDecryptFailInvalidSeed2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + AesDecryptFailInvalidSeed2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "AesDecryptFailInvalidSeed2"; bytes seed = fromHex( "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f" ); BOOST_CHECK( bytes() == aesDecrypt( &seed, "test" ) ); diff --git a/test/unittests/libdevcrypto/LibSnark.cpp b/test/unittests/libdevcrypto/LibSnark.cpp index 232e46c71..de7c4cd8d 100644 --- a/test/unittests/libdevcrypto/LibSnark.cpp +++ b/test/unittests/libdevcrypto/LibSnark.cpp @@ -82,7 +82,8 @@ BOOST_AUTO_TEST_CASE( ecadd, *boost::unit_test::precondition( run_not_express ) BOOST_AUTO_TEST_CASE( fieldPointInvalid, *boost::unit_test::precondition( run_not_express ) ) { u256 const pMod{ - "21888242871839275222246405745257275088696311157297823662689037894645226208583"}; + "21888242871839275222246405745257275088696311157297823662689037894645226208583" + }; bytes input = toBigEndian( pMod ); BOOST_CHECK( !alt_bn128_G1_add( ref( input ) ).first ); @@ -512,7 +513,7 @@ BOOST_AUTO_TEST_CASE( benchECMULWorstCase1, *boost::unit_test::precondition( run bytes v = fromHex( "1fa111cf23c269b75957c715b762ef37074d341c280d113707ff342211b794571db10707e7cb4ba3c851f6bbb4" "3399701da0c7675ca0f9cfc595774fd055b2fb" ); - u256 const k{"21888242871839275222246405745257275088696311157297823662689037894645226208582"}; + u256 const k{ "21888242871839275222246405745257275088696311157297823662689037894645226208582" }; for ( int i = 0; i < 1000; ++i ) { bool success = false; @@ -531,7 +532,7 @@ BOOST_AUTO_TEST_CASE( benchECMULWorstCase2, *boost::unit_test::precondition( run bytes v = fromHex( "1fa111cf23c269b75957c715b762ef37074d341c280d113707ff342211b794571db10707e7cb4ba3c851f6bbb4" "3399701da0c7675ca0f9cfc595774fd055b2fb" ); - u256 const k{"10944121435919637611123202872628637544348155578648911831344518947322613104291"}; + u256 const k{ "10944121435919637611123202872628637544348155578648911831344518947322613104291" }; for ( int i = 0; i < 1000; ++i ) { bool success = false; @@ -564,7 +565,8 @@ BOOST_AUTO_TEST_CASE( benchECMULIdentity, *boost::unit_test::precondition( run_n BOOST_CHECK_EQUAL( toHex( v ), toHex( w ) ); } -BOOST_AUTO_TEST_CASE( ECMULuseCaseFromRopsten, *boost::unit_test::precondition( run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ECMULuseCaseFromRopsten, *boost::unit_test::precondition( run_not_express ) ) { bytes const input = fromHex( "277a420332215ead37ba61fee84f0d216a345e762af8efd15453697170b3cdc5" "1b312cd37d4ad474fc299c9689fc0f347a2ec2b5b474a41b343142ee5fdd097a" diff --git a/test/unittests/libdevcrypto/SecretStore.cpp b/test/unittests/libdevcrypto/SecretStore.cpp index 513523304..77f3c8066 100644 --- a/test/unittests/libdevcrypto/SecretStore.cpp +++ b/test/unittests/libdevcrypto/SecretStore.cpp @@ -40,8 +40,7 @@ BOOST_AUTO_TEST_SUITE( Crypto ) BOOST_FIXTURE_TEST_SUITE( KeyStore, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( basic_tests, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( basic_tests, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path testPath = test::getTestPath(); testPath /= fs::path( "KeyStoreTests" ); @@ -66,8 +65,8 @@ BOOST_AUTO_TEST_CASE( basic_tests, } } -BOOST_AUTO_TEST_CASE( import_key_from_file, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + import_key_from_file, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Imports a key from an external file. Tests that the imported key is there // and that the external file is not deleted. TransientDirectory importDir; @@ -111,9 +110,9 @@ BOOST_AUTO_TEST_CASE( import_key_from_file, } } -BOOST_AUTO_TEST_CASE( import_secret, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - for ( string const& password : {"foobar", ""} ) { +BOOST_AUTO_TEST_CASE( + import_secret, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + for ( string const& password : { "foobar", "" } ) { TransientDirectory storeDir; string priv = "0202020202020202020202020202020202020202020202020202020202020202"; @@ -137,7 +136,7 @@ BOOST_AUTO_TEST_CASE( import_secret, } BOOST_AUTO_TEST_CASE( import_secret_bytesConstRef ) { - for ( string const& password : {"foobar", ""} ) { + for ( string const& password : { "foobar", "" } ) { TransientDirectory storeDir; string priv = "0202020202020202020202020202020202020202020202020202020202020202"; @@ -161,8 +160,8 @@ BOOST_AUTO_TEST_CASE( import_secret_bytesConstRef ) { } } -BOOST_AUTO_TEST_CASE( wrong_password, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + wrong_password, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TransientDirectory storeDir; SecretStore store( storeDir.path() ); string password = "foobar"; @@ -188,8 +187,7 @@ BOOST_AUTO_TEST_CASE( wrong_password, } } -BOOST_AUTO_TEST_CASE( recode, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( recode, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TransientDirectory storeDir; SecretStore store( storeDir.path() ); string password = "foobar"; @@ -228,8 +226,8 @@ BOOST_AUTO_TEST_CASE( recode, } } -BOOST_AUTO_TEST_CASE( keyImport_PBKDF2SHA256, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + keyImport_PBKDF2SHA256, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Imports a key from an external file. Tests that the imported key is there // and that the external file is not deleted. TransientDirectory importDir; @@ -269,8 +267,8 @@ BOOST_AUTO_TEST_CASE( keyImport_PBKDF2SHA256, fs::remove( importFile ); } -BOOST_AUTO_TEST_CASE( keyImport_Scrypt, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + keyImport_Scrypt, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Imports a key from an external file. Tests that the imported key is there // and that the external file is not deleted. TransientDirectory importDir; diff --git a/test/unittests/libdevcrypto/crypto.cpp b/test/unittests/libdevcrypto/crypto.cpp index 0fd4ab8c5..948186a24 100644 --- a/test/unittests/libdevcrypto/crypto.cpp +++ b/test/unittests/libdevcrypto/crypto.cpp @@ -75,16 +75,15 @@ static CryptoPP::DL_GroupParameters_EC< CryptoPP::ECP >& params() { return s_params; } -BOOST_AUTO_TEST_CASE( sha3general, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( sha3general, *boost::unit_test::precondition( dev::test::run_not_express ) ) { BOOST_REQUIRE_EQUAL( sha3( "" ), h256( "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" ) ); BOOST_REQUIRE_EQUAL( sha3( "hello" ), h256( "1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8" ) ); } -BOOST_AUTO_TEST_CASE( emptySHA3Types, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + emptySHA3Types, *boost::unit_test::precondition( dev::test::run_not_express ) ) { h256 emptySHA3( fromHex( "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" ) ); BOOST_REQUIRE_EQUAL( emptySHA3, EmptySHA3 ); @@ -93,14 +92,13 @@ BOOST_AUTO_TEST_CASE( emptySHA3Types, BOOST_REQUIRE_EQUAL( emptyListSHA3, EmptyListSHA3 ); } -BOOST_AUTO_TEST_CASE( pubkeyOfZero, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + pubkeyOfZero, *boost::unit_test::precondition( dev::test::run_not_express ) ) { auto pub = toPublic( {} ); BOOST_REQUIRE_EQUAL( pub, Public{} ); } -BOOST_AUTO_TEST_CASE( KeyPairMix, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( KeyPairMix, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyPair k = KeyPair::create(); BOOST_REQUIRE( !!k.secret() ); BOOST_REQUIRE( !!k.pub() ); @@ -131,19 +129,19 @@ BOOST_AUTO_TEST_CASE( keypairs ) { BOOST_CHECK_EQUAL( t.sender(), p.address() ); } -BOOST_AUTO_TEST_CASE( KeyPairVerifySecret, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyPairVerifySecret, *boost::unit_test::precondition( dev::test::run_not_express ) ) { auto keyPair = KeyPair::create(); auto* ctx = secp256k1_context_create( SECP256K1_CONTEXT_NONE ); BOOST_CHECK( secp256k1_ec_seckey_verify( ctx, keyPair.secret().data() ) ); secp256k1_context_destroy( ctx ); } -BOOST_AUTO_TEST_CASE( SignAndRecover, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + SignAndRecover, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // This basic test that compares **fixed** results. Useful to test new // implementations or changes to implementations. - auto sec = Secret{sha3( "sec" )}; + auto sec = Secret{ sha3( "sec" ) }; auto msg = sha3( "msg" ); auto sig = sign( sec, msg ); auto expectedSig = @@ -158,8 +156,8 @@ BOOST_AUTO_TEST_CASE( SignAndRecover, BOOST_CHECK_EQUAL( pub.hex(), expectedPub ); } -BOOST_AUTO_TEST_CASE( SignAndRecoverLoop, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + SignAndRecoverLoop, *boost::unit_test::precondition( dev::test::run_not_express ) ) { auto num = 13; auto msg = h256::random(); while ( --num ) { @@ -179,8 +177,8 @@ BOOST_AUTO_TEST_CASE( cryptopp_patch ) { BOOST_REQUIRE_EQUAL( io_text.size(), 0 ); } -BOOST_AUTO_TEST_CASE( verify_secert, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + verify_secert, *boost::unit_test::precondition( dev::test::run_not_express ) ) { Secret empty; KeyPair kNot( empty ); BOOST_REQUIRE( !kNot.address() ); @@ -188,8 +186,8 @@ BOOST_AUTO_TEST_CASE( verify_secert, BOOST_REQUIRE( k.address() ); } -BOOST_AUTO_TEST_CASE( common_encrypt_decrypt, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + common_encrypt_decrypt, *boost::unit_test::precondition( dev::test::run_not_express ) ) { string message( "Now is the time for all good persons to come to the aid of humanity." ); bytes m = asBytes( message ); bytesConstRef bcr( &m ); @@ -206,8 +204,8 @@ BOOST_AUTO_TEST_CASE( common_encrypt_decrypt, BOOST_REQUIRE( plain == asBytes( message ) ); } -BOOST_AUTO_TEST_CASE( sha3_norestart, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + sha3_norestart, *boost::unit_test::precondition( dev::test::run_not_express ) ) { CryptoPP::Keccak_256 ctx; bytes input( asBytes( "test" ) ); ctx.Update( input.data(), 4 ); @@ -237,8 +235,7 @@ BOOST_AUTO_TEST_CASE( sha3_norestart, BOOST_REQUIRE( finalDigest2 != finalDigest3 ); } -BOOST_AUTO_TEST_CASE( ecies_kdf, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( ecies_kdf, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyPair local = KeyPair::create(); KeyPair remote = KeyPair::create(); // nonce @@ -266,8 +263,8 @@ BOOST_AUTO_TEST_CASE( ecies_kdf, BOOST_REQUIRE( key1 == key2 ); } -BOOST_AUTO_TEST_CASE( ecdh_agree_invalid_pubkey, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecdh_agree_invalid_pubkey, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyPair ok = KeyPair::create(); Public pubkey; ~pubkey; // Create a pubkey of all 1s. @@ -275,8 +272,8 @@ BOOST_AUTO_TEST_CASE( ecdh_agree_invalid_pubkey, BOOST_CHECK( !ecdh::agree( ok.secret(), pubkey, z ) ); } -BOOST_AUTO_TEST_CASE( ecdh_agree_invalid_seckey, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecdh_agree_invalid_seckey, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyPair ok = KeyPair::create(); Secret seckey; // "Null" seckey is invalid. BOOST_CHECK( !ecdh::agree( seckey, ok.pub(), seckey ) ); @@ -320,8 +317,8 @@ BOOST_AUTO_TEST_CASE( ecies_sharedMacData ) { BOOST_CHECK_EQUAL( toHex( decrypted ), toHex( original ) ); } -BOOST_AUTO_TEST_CASE( ecies_eckeypair, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecies_eckeypair, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyPair k = KeyPair::create(); string message( "Now is the time for all good persons to come to the aid of humanity." ); @@ -335,8 +332,8 @@ BOOST_AUTO_TEST_CASE( ecies_eckeypair, BOOST_REQUIRE( b == asBytes( original ) ); } -BOOST_AUTO_TEST_CASE( ecdhCryptopp, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecdhCryptopp, *boost::unit_test::precondition( dev::test::run_not_express ) ) { CryptoPP::ECDH< CryptoPP::ECP >::Domain dhLocal( curveOID() ); CryptoPP::SecByteBlock privLocal( dhLocal.PrivateKeyLength() ); CryptoPP::SecByteBlock pubLocal( dhLocal.PublicKeyLength() ); @@ -370,11 +367,11 @@ BOOST_AUTO_TEST_CASE( ecdhCryptopp, // Now use our keys KeyPair a = KeyPair::create(); - _byte_ puba[65] = {0x04}; + _byte_ puba[65] = { 0x04 }; memcpy( &puba[1], a.pub().data(), 64 ); KeyPair b = KeyPair::create(); - _byte_ pubb[65] = {0x04}; + _byte_ pubb[65] = { 0x04 }; memcpy( &pubb[1], b.pub().data(), 64 ); CryptoPP::ECDH< CryptoPP::ECP >::Domain dhA( curveOID() ); @@ -383,8 +380,7 @@ BOOST_AUTO_TEST_CASE( ecdhCryptopp, BOOST_REQUIRE( shared ); } -BOOST_AUTO_TEST_CASE( ecdhe, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( ecdhe, *boost::unit_test::precondition( dev::test::run_not_express ) ) { auto local = KeyPair::create(); auto remote = KeyPair::create(); BOOST_CHECK_NE( local.pub(), remote.pub() ); @@ -402,9 +398,8 @@ BOOST_AUTO_TEST_CASE( ecdhe, BOOST_CHECK_EQUAL( sremote, slocal ); } -BOOST_AUTO_TEST_CASE( ecdhAgree, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - auto sec = Secret{sha3( "ecdhAgree" )}; +BOOST_AUTO_TEST_CASE( ecdhAgree, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + auto sec = Secret{ sha3( "ecdhAgree" ) }; auto pub = toPublic( sec ); Secret sharedSec; BOOST_CHECK( ecdh::agree( sec, pub, sharedSec ) ); @@ -413,8 +408,8 @@ BOOST_AUTO_TEST_CASE( ecdhAgree, BOOST_CHECK_EQUAL( sharedSec.makeInsecure().hex(), expectedSharedSec ); } -BOOST_AUTO_TEST_CASE( handshakeNew, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + handshakeNew, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // authInitiator -> E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || // H(ecdhe-random-pubk) || pubk || nonce || 0x0) authRecipient -> E(remote-pubk, // ecdhe-random-pubk || nonce || 0x0) @@ -605,12 +600,12 @@ BOOST_AUTO_TEST_CASE( handshakeNew, BOOST_REQUIRE_EQUAL( bEgressMac, aIngressMac ); } -BOOST_AUTO_TEST_CASE( ecies_aes128_ctr_unaligned, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecies_aes128_ctr_unaligned, *boost::unit_test::precondition( dev::test::run_not_express ) ) { SecureFixedHash< 16 > encryptK( sha3( "..." ), h128::AlignLeft ); h256 egressMac( sha3( "+++" ) ); // TESTING: send encrypt magic sequence - bytes magic{0x22, 0x40, 0x08, 0x91}; + bytes magic{ 0x22, 0x40, 0x08, 0x91 }; bytes magicCipherAndMac; magicCipherAndMac = encryptSymNoAuth( encryptK, h128(), &magic ); @@ -628,8 +623,8 @@ BOOST_AUTO_TEST_CASE( ecies_aes128_ctr_unaligned, BOOST_REQUIRE( magic == plaintext ); } -BOOST_AUTO_TEST_CASE( ecies_aes128_ctr, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecies_aes128_ctr, *boost::unit_test::precondition( dev::test::run_not_express ) ) { SecureFixedHash< 16 > k( sha3( "0xAAAA" ), h128::AlignLeft ); string m = "AAAAAAAAAAAAAAAA"; bytesConstRef msg( ( _byte_* ) m.data(), m.size() ); @@ -642,8 +637,8 @@ BOOST_AUTO_TEST_CASE( ecies_aes128_ctr, BOOST_REQUIRE_EQUAL( asString( plaintext ), m ); } -BOOST_AUTO_TEST_CASE( cryptopp_aes128_ctr, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + cryptopp_aes128_ctr, *boost::unit_test::precondition( dev::test::run_not_express ) ) { const int aesKeyLen = 16; BOOST_REQUIRE( sizeof( char ) == sizeof( _byte_ ) ); @@ -707,8 +702,8 @@ BOOST_AUTO_TEST_CASE( cryptopp_aes128_ctr, } } -BOOST_AUTO_TEST_CASE( cryptopp_aes128_cbc, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + cryptopp_aes128_cbc, *boost::unit_test::precondition( dev::test::run_not_express ) ) { const int aesKeyLen = 16; BOOST_REQUIRE( sizeof( char ) == sizeof( _byte_ ) ); @@ -750,8 +745,7 @@ BOOST_AUTO_TEST_CASE( cryptopp_aes128_cbc, BOOST_REQUIRE( string192 == plainOriginal ); } -BOOST_AUTO_TEST_CASE( recoverVgt3, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( recoverVgt3, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // base secret Secret secret( sha3( "privacy" ) ); diff --git a/test/unittests/libdevcrypto/hexPrefix.cpp b/test/unittests/libdevcrypto/hexPrefix.cpp index 200d11eda..d9f579efb 100644 --- a/test/unittests/libdevcrypto/hexPrefix.cpp +++ b/test/unittests/libdevcrypto/hexPrefix.cpp @@ -37,8 +37,8 @@ BOOST_AUTO_TEST_SUITE( Crypto ) BOOST_FIXTURE_TEST_SUITE( Basic, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( hexPrefix_test, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + hexPrefix_test, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path testPath = test::getTestPath(); testPath /= fs::path( "BasicTests" ); @@ -61,29 +61,29 @@ BOOST_AUTO_TEST_CASE( hexPrefix_test, } } -BOOST_AUTO_TEST_CASE( base64, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - static char const* const s_tests[][2] = {{"", ""}, {"f", "Zg=="}, {"fo", "Zm8="}, - {"foo", "Zm9v"}, {"foob", "Zm9vYg=="}, {"fooba", "Zm9vYmE="}, {"foobar", "Zm9vYmFy"}, - {"So?

" - "This 4, 5, 6, 7, 8, 9, z, {, |, } tests Base64 encoder. " - "Show me: @, A, B, C, D, E, F, G, H, I, J, K, L, M, " - "N, O, P, Q, R, S, T, U, V, W, X, Y, Z, [, \\, ], ^, _, `, " - "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s.", +BOOST_AUTO_TEST_CASE( base64, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + static char const* const s_tests[][2] = { { "", "" }, { "f", "Zg==" }, { "fo", "Zm8=" }, + { "foo", "Zm9v" }, { "foob", "Zm9vYg==" }, { "fooba", "Zm9vYmE=" }, + { "foobar", "Zm9vYmFy" }, + { "So?

" + "This 4, 5, 6, 7, 8, 9, z, {, |, } tests Base64 encoder. " + "Show me: @, A, B, C, D, E, F, G, H, I, J, K, L, M, " + "N, O, P, Q, R, S, T, U, V, W, X, Y, Z, [, \\, ], ^, _, `, " + "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s.", "U28/PHA+VGhpcyA0LCA1LCA2LCA3LCA4LCA5LCB6LCB7LCB8LCB9IHRlc3RzIEJhc2U2NCBlbmNv" "ZGVyLiBTaG93IG1lOiBALCBBLCBCLCBDLCBELCBFLCBGLCBHLCBILCBJLCBKLCBLLCBMLCBNLCBO" "LCBPLCBQLCBRLCBSLCBTLCBULCBVLCBWLCBXLCBYLCBZLCBaLCBbLCBcLCBdLCBeLCBfLCBgLCBh" - "LCBiLCBjLCBkLCBlLCBmLCBnLCBoLCBpLCBqLCBrLCBsLCBtLCBuLCBvLCBwLCBxLCByLCBzLg=="}}; + "LCBiLCBjLCBkLCBlLCBmLCBnLCBoLCBpLCBqLCBrLCBsLCBtLCBuLCBvLCBwLCBxLCByLCBzLg==" } }; static const auto c_numTests = sizeof( s_tests ) / sizeof( s_tests[0] ); for ( size_t i = 0; i < c_numTests; ++i ) { - auto expectedDecoded = std::string{s_tests[i][0]}; - auto expectedEncoded = std::string{s_tests[i][1]}; + auto expectedDecoded = std::string{ s_tests[i][0] }; + auto expectedEncoded = std::string{ s_tests[i][1] }; auto encoded = toBase64( expectedDecoded ); BOOST_CHECK_EQUAL( expectedEncoded, encoded ); auto decodedBytes = fromBase64( expectedEncoded ); - auto decoded = bytesConstRef{decodedBytes.data(), decodedBytes.size()}.toString(); + auto decoded = bytesConstRef{ decodedBytes.data(), decodedBytes.size() }.toString(); BOOST_CHECK_EQUAL( decoded, expectedDecoded ); } } diff --git a/test/unittests/libdevcrypto/trie.cpp b/test/unittests/libdevcrypto/trie.cpp index d42787fec..7e4d00544 100644 --- a/test/unittests/libdevcrypto/trie.cpp +++ b/test/unittests/libdevcrypto/trie.cpp @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include @@ -67,7 +66,8 @@ BOOST_AUTO_TEST_CASE( fat_trie ) { } } -BOOST_AUTO_TEST_CASE( hex_encoded_securetrie_test, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + hex_encoded_securetrie_test, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testPath = test::getTestPath() / fs::path( "TrieTests" ); cnote << "Testing Secure Trie..."; @@ -128,7 +128,8 @@ BOOST_AUTO_TEST_CASE( hex_encoded_securetrie_test, *boost::unit_test::preconditi } } -BOOST_AUTO_TEST_CASE( trie_test_anyorder, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + trie_test_anyorder, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testPath = test::getTestPath() / fs::path( "TrieTests" ); cnote << "Testing Trie..."; @@ -189,7 +190,8 @@ BOOST_AUTO_TEST_CASE( trie_test_anyorder, *boost::unit_test::precondition( dev:: } } -BOOST_AUTO_TEST_CASE( trie_tests_ordered, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + trie_tests_ordered, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testPath = test::getTestPath() / fs::path( "TrieTests" ); cnote << "Testing Trie..."; @@ -285,7 +287,8 @@ bytes stringMapRlp256( StringMap const& _s ) { return rlp256( bytesMap ); } -BOOST_AUTO_TEST_CASE( moreTrieTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + moreTrieTests, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "Testing Trie more..."; // More tests... { @@ -301,13 +304,13 @@ BOOST_AUTO_TEST_CASE( moreTrieTests, *boost::unit_test::precondition( dev::test: cnote << t; cnote << m; cnote << t.root(); - cnote << stringMapHash256( {{"test", "test"}} ); + cnote << stringMapHash256( { { "test", "test" } } ); t.insert( string( "tesa" ), string( "testy" ) ); cnote << t; cnote << m; cnote << t.root(); - cnote << stringMapHash256( {{"test", "test"}, {"te", "testy"}} ); + cnote << stringMapHash256( { { "test", "test" }, { "te", "testy" } } ); cnote << t.at( string( "test" ) ); cnote << t.at( string( "te" ) ); cnote << t.at( string( "t" ) ); @@ -315,7 +318,7 @@ BOOST_AUTO_TEST_CASE( moreTrieTests, *boost::unit_test::precondition( dev::test: t.remove( string( "te" ) ); cnote << m; cnote << t.root(); - cnote << stringMapHash256( {{"test", "test"}} ); + cnote << stringMapHash256( { { "test", "test" } } ); t.remove( string( "test" ) ); cnote << m; @@ -331,8 +334,8 @@ BOOST_AUTO_TEST_CASE( moreTrieTests, *boost::unit_test::precondition( dev::test: cnote << t; cnote << m; cnote << t.root(); - cnote << stringMapHash256( {{"b", "B"}, {"a", "A"}} ); - bytes r( stringMapRlp256( {{"b", "B"}, {"a", "A"}} ) ); + cnote << stringMapHash256( { { "b", "B" }, { "a", "A" } } ); + bytes r( stringMapRlp256( { { "b", "B" }, { "a", "A" } } ) ); cnote << RLP( r ); } { @@ -351,7 +354,7 @@ BOOST_AUTO_TEST_CASE( moreTrieTests, *boost::unit_test::precondition( dev::test: cnote << RLP( r ); } { - cnote << hex << stringMapHash256( {{"dog", "puppy"}, {"doe", "reindeer"}} ); + cnote << hex << stringMapHash256( { { "dog", "puppy" }, { "doe", "reindeer" } } ); MemTrie t; t.insert( "dog", "puppy" ); t.insert( "doe", "reindeer" ); @@ -440,7 +443,8 @@ std::string randomWord() { } } // namespace -BOOST_AUTO_TEST_CASE( trieLowerBound, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + trieLowerBound, *boost::unit_test::precondition( dev::test::run_not_express ) ) { cnote << "Stress-testing Trie.lower_bound..."; if ( 0 ) { MemoryDB dm; diff --git a/test/unittests/libethashseal/EthashTest.cpp b/test/unittests/libethashseal/EthashTest.cpp index 52be8f137..bc6122259 100644 --- a/test/unittests/libethashseal/EthashTest.cpp +++ b/test/unittests/libethashseal/EthashTest.cpp @@ -117,12 +117,12 @@ BOOST_AUTO_TEST_CASE( epochSeed, *boost::unit_test::precondition( dev::test::run header.setNumber( 30000 ); seed = Ethash::seedHash( header ); BOOST_CHECK_EQUAL( - seed, h256{"290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563"} ); + seed, h256{ "290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563" } ); header.setNumber( 2048 * 30000 ); seed = Ethash::seedHash( header ); BOOST_CHECK_EQUAL( - seed, h256{"20a7678ca7b50829183baac2e1e3c43fa3c4bcbc171b11cf5a9f30bebd172920"} ); + seed, h256{ "20a7678ca7b50829183baac2e1e3c43fa3c4bcbc171b11cf5a9f30bebd172920" } ); } namespace { @@ -190,9 +190,9 @@ BOOST_AUTO_TEST_CASE( ethashEvalHeader ) { // FIXME: Drop this test as ethash library has this test cases in its test suite. for ( auto& t : ethashTestCases ) { - BlockHeader header{fromHex( t.header ), HeaderData}; - h256 headerHash{t.headerHash}; - eth::Nonce nonce{t.nonce}; + BlockHeader header{ fromHex( t.header ), HeaderData }; + h256 headerHash{ t.headerHash }; + eth::Nonce nonce{ t.nonce }; BOOST_REQUIRE_EQUAL( headerHash, header.hash( WithoutSeal ) ); BOOST_REQUIRE_EQUAL( nonce, Ethash::nonce( header ) ); @@ -201,10 +201,10 @@ BOOST_AUTO_TEST_CASE( ethashEvalHeader ) { ethash::hash256_from_bytes( header.hash( WithoutSeal ).data() ), ( uint64_t )( u64 ) nonce ); - h256 mix{result.mix_hash.bytes, h256::ConstructFromPointer}; - h256 final{result.final_hash.bytes, h256::ConstructFromPointer}; + h256 mix{ result.mix_hash.bytes, h256::ConstructFromPointer }; + h256 final{ result.final_hash.bytes, h256::ConstructFromPointer }; - BOOST_REQUIRE_EQUAL( final, h256{t.result} ); + BOOST_REQUIRE_EQUAL( final, h256{ t.result } ); BOOST_REQUIRE_EQUAL( mix, Ethash::mixHash( header ) ); } } diff --git a/test/unittests/libethcore/SealEngineTest.cpp b/test/unittests/libethcore/SealEngineTest.cpp index 4ee30ce56..ce4a1fb6a 100644 --- a/test/unittests/libethcore/SealEngineTest.cpp +++ b/test/unittests/libethcore/SealEngineTest.cpp @@ -45,7 +45,8 @@ class UnsignedTransactionFixture : public TestOutputHelperFixture { ChainOperationParams params; Ethash ethash; BlockHeader header; - Transaction tx{0, 0, 21000, Address( "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" ), bytes(), 0}; + Transaction tx{ 0, 0, 21000, Address( "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" ), bytes(), + 0 }; }; } // namespace @@ -61,15 +62,15 @@ BOOST_AUTO_TEST_CASE( UnsignedTransactionIsValidBeforeExperimental, header.setNumber( 1 ); - SealEngineFace::verifyTransaction( params, ImportRequirements::TransactionSignatures, - tx, 1, header, 0 ); // check that it doesn't throw + SealEngineFace::verifyTransaction( params, ImportRequirements::TransactionSignatures, tx, 1, + header, 0 ); // check that it doesn't throw } BOOST_AUTO_TEST_CASE( UnsignedTransactionIsValidInExperimental ) { header.setNumber( 0x1010 ); - SealEngineFace::verifyTransaction( params, ImportRequirements::TransactionSignatures, - tx, 1, header, 0 ); // check that it doesn't throw + SealEngineFace::verifyTransaction( params, ImportRequirements::TransactionSignatures, tx, 1, + header, 0 ); // check that it doesn't throw } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libethcore/difficulty.cpp b/test/unittests/libethcore/difficulty.cpp index fd26f197d..8e463d1ae 100644 --- a/test/unittests/libethcore/difficulty.cpp +++ b/test/unittests/libethcore/difficulty.cpp @@ -162,8 +162,8 @@ BOOST_AUTO_TEST_CASE( difficultyTestsFrontier ) { testDifficulty( testFileFullName, sealEngine ); } -BOOST_AUTO_TEST_CASE( difficultyTestsRopsten, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + difficultyTestsRopsten, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testFileFullName = test::getTestPath() / fs::path( "BasicTests/difficultyRopsten.json" ); @@ -189,8 +189,8 @@ BOOST_AUTO_TEST_CASE( difficultyTestsHomestead ) { testDifficulty( testFileFullName, sealEngine ); } -BOOST_AUTO_TEST_CASE( difficultyByzantium, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + difficultyByzantium, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testFileFullName = test::getTestPath() / fs::path( "BasicTests/difficultyByzantium.json" ); @@ -203,8 +203,8 @@ BOOST_AUTO_TEST_CASE( difficultyByzantium, testDifficulty( testFileFullName, sealEngine ); } -BOOST_AUTO_TEST_CASE( difficultyTestsMainNetwork, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + difficultyTestsMainNetwork, *boost::unit_test::precondition( dev::test::run_not_express ) ) { fs::path const testFileFullName = test::getTestPath() / fs::path( "BasicTests/difficultyMainNetwork.json" ); @@ -226,10 +226,10 @@ BOOST_AUTO_TEST_CASE( difficultyTestsCustomMainNetwork ) { if ( dev::test::Options::get().filltests ) { int64_t byzantiumBlockNumber = 4370000; - std::vector< int64_t > blockNumberVector = { - byzantiumBlockNumber - 100000, byzantiumBlockNumber, byzantiumBlockNumber + 100000}; - std::vector< u256 > parentDifficultyVector = {1000, 2048, 4000, 1000000}; - std::vector< int > timestampDeltaVector = {0, 1, 8, 10, 13, 20, 100, 800, 1000, 1500}; + std::vector< int64_t > blockNumberVector = { byzantiumBlockNumber - 100000, + byzantiumBlockNumber, byzantiumBlockNumber + 100000 }; + std::vector< u256 > parentDifficultyVector = { 1000, 2048, 4000, 1000000 }; + std::vector< int > timestampDeltaVector = { 0, 1, 8, 10, 13, 20, 100, 800, 1000, 1500 }; int testN = 0; ostringstream finalTest; diff --git a/test/unittests/libethcore/keymanager.cpp b/test/unittests/libethcore/keymanager.cpp index 0e9e8a44e..b6a3fec77 100644 --- a/test/unittests/libethcore/keymanager.cpp +++ b/test/unittests/libethcore/keymanager.cpp @@ -37,15 +37,15 @@ namespace fs = boost::filesystem; BOOST_FIXTURE_TEST_SUITE( KeyManagerTests, TestOutputHelperFixture ) BOOST_AUTO_TEST_CASE( KeyInfoDefaultConstructor, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyInfo kiDefault; BOOST_CHECK_EQUAL( kiDefault.accountName, "" ); BOOST_CHECK( kiDefault.passHash == h256() ); } -BOOST_AUTO_TEST_CASE( KeyInfoConstructor, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyInfoConstructor, *boost::unit_test::precondition( dev::test::run_not_express ) ) { h256 passHash( "0x2a" ); string accountName = "myAccount"; KeyInfo ki( passHash, accountName ); @@ -53,8 +53,8 @@ BOOST_AUTO_TEST_CASE( KeyInfoConstructor, BOOST_CHECK( ki.passHash == h256( "0x2a" ) ); } -BOOST_AUTO_TEST_CASE( KeyManagerConstructor, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyManagerConstructor, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyManager km; BOOST_CHECK_EQUAL( km.keysFile(), km.defaultPath() ); BOOST_CHECK_EQUAL( km.defaultPath(), getDataDir( "ethereum" ) / fs::path( "keys.info" ) ); @@ -63,8 +63,8 @@ BOOST_AUTO_TEST_CASE( KeyManagerConstructor, km.kill( a ); } -BOOST_AUTO_TEST_CASE( KeyManagerKeysFile, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyManagerKeysFile, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyManager km; string password = "hardPassword"; BOOST_CHECK( !km.load( password ) ); @@ -86,8 +86,8 @@ BOOST_AUTO_TEST_CASE( KeyManagerKeysFile, km.kill( a ); } -BOOST_AUTO_TEST_CASE( KeyManagerHints, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyManagerHints, *boost::unit_test::precondition( dev::test::run_not_express ) ) { KeyManager km; string password = "hardPassword"; @@ -105,8 +105,8 @@ BOOST_AUTO_TEST_CASE( KeyManagerHints, km.kill( a ); } -BOOST_AUTO_TEST_CASE( KeyManagerAccounts, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyManagerAccounts, *boost::unit_test::precondition( dev::test::run_not_express ) ) { string password = "hardPassword"; TransientDirectory tmpDir; @@ -120,8 +120,8 @@ BOOST_AUTO_TEST_CASE( KeyManagerAccounts, km.kill( a ); } -BOOST_AUTO_TEST_CASE( KeyManagerKill, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + KeyManagerKill, *boost::unit_test::precondition( dev::test::run_not_express ) ) { string password = "hardPassword"; TransientDirectory tmpDir; KeyPair kp = KeyPair::create(); diff --git a/test/unittests/libethereum/Block.cpp b/test/unittests/libethereum/Block.cpp index ba7236c22..f35389176 100644 --- a/test/unittests/libethereum/Block.cpp +++ b/test/unittests/libethereum/Block.cpp @@ -38,7 +38,8 @@ BOOST_FIXTURE_TEST_SUITE( BlockSuite, TestOutputHelperFixture ) BOOST_FIXTURE_TEST_SUITE( GasPricer, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( bNormalTransactionInput, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + bNormalTransactionInput, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TestBlockChain testBlockchain( TestBlockChain::defaultGenesisBlock( 63000 ) ); TestBlock const& genesisBlock = testBlockchain.testGenesis(); State const& genesisState = genesisBlock.state(); @@ -79,7 +80,8 @@ BOOST_AUTO_TEST_CASE( bBlockNotSyncedToBlockchain ) { BOOST_REQUIRE( testBlockT.transactionQueue().topTransactions( 4 ).size() == 2 ); } -BOOST_AUTO_TEST_CASE( bExceedBlockGasLimit, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + bExceedBlockGasLimit, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TestBlockChain testBlockchain( TestBlockChain::defaultGenesisBlock( 63000 ) ); TestBlock const& genesisBlock = testBlockchain.testGenesis(); State const& genesisState = genesisBlock.state(); @@ -139,7 +141,8 @@ BOOST_AUTO_TEST_CASE( bTemporaryNoGasLeft ) { BOOST_REQUIRE( testBlockT.transactionQueue().topTransactions( 4 ).size() == 3 ); } -BOOST_AUTO_TEST_CASE( bInvalidNonceNoncesAhead, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + bInvalidNonceNoncesAhead, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Add some amount of gas because block limit decreases TestBlockChain testBlockchain( TestBlockChain::defaultGenesisBlock( 63000 + 21000 ) ); TestBlock const& genesisBlock = testBlockchain.testGenesis(); @@ -173,7 +176,8 @@ BOOST_AUTO_TEST_CASE( bInvalidNonceNoncesAhead, *boost::unit_test::precondition( u256( 3 ) ); // nonce starts with 1 } -BOOST_AUTO_TEST_CASE( bInvalidNonceNonceTooLow, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + bInvalidNonceNonceTooLow, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TestBlockChain testBlockchain( TestBlockChain::defaultGenesisBlock( 63000 ) ); TestBlock const& genesisBlock = testBlockchain.testGenesis(); State const& genesisState = genesisBlock.state(); diff --git a/test/unittests/libethereum/BlockChain.cpp b/test/unittests/libethereum/BlockChain.cpp index b4c4175c2..1b3c33a5a 100644 --- a/test/unittests/libethereum/BlockChain.cpp +++ b/test/unittests/libethereum/BlockChain.cpp @@ -295,7 +295,8 @@ BOOST_AUTO_TEST_CASE( updateStats ) { bcRef.garbageCollect( true ); } -BOOST_AUTO_TEST_CASE( invalidJsonThrows, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + invalidJsonThrows, *boost::unit_test::precondition( dev::test::run_not_express ) ) { h256 emptyStateRoot; /* Below, a comma is missing between fields. */ BOOST_CHECK_THROW( diff --git a/test/unittests/libethereum/ClientTest.cpp b/test/unittests/libethereum/ClientTest.cpp index 1399dd290..3c05bd48a 100644 --- a/test/unittests/libethereum/ClientTest.cpp +++ b/test/unittests/libethereum/ClientTest.cpp @@ -26,11 +26,11 @@ #include #include #include -#include -#include +#include #include #include -#include +#include +#include using namespace std; using namespace dev; @@ -39,7 +39,7 @@ using namespace dev::test; using namespace dev::p2p; namespace fs = boost::filesystem; -static size_t rand_port = ( srand(time(nullptr)), 1024 + rand() % 64000 ); +static size_t rand_port = ( srand( time( nullptr ) ), 1024 + rand() % 64000 ); struct FixtureCommon { const string BTRFS_FILE_PATH = "btrfs.file"; @@ -107,12 +107,10 @@ struct FixtureCommon { class TestClientFixture : public TestOutputHelperFixture { public: TestClientFixture( const std::string& _config = "" ) try { - ChainParams chainParams; if ( _config != "" ) { chainParams = chainParams.loadConfig( _config ); - } - else { + } else { chainParams.nodeInfo.port = chainParams.nodeInfo.port6 = rand_port; chainParams.sChain.nodes[0].port = chainParams.sChain.nodes[0].port6 = rand_port; } @@ -133,9 +131,9 @@ class TestClientFixture : public TestOutputHelperFixture { // ), dir, // dir, chainParams, WithExisting::Kill, {"eth"}, testingMode ) ); - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); - setenv("DATA_DIR", m_tmpDir.path().c_str(), 1); + setenv( "DATA_DIR", m_tmpDir.path().c_str(), 1 ); m_ethereum.reset( new eth::ClientTest( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), NULL, monitor, m_tmpDir.path(), WithExisting::Kill ) ); @@ -147,9 +145,7 @@ class TestClientFixture : public TestOutputHelperFixture { // wait for 1st block - because it's always empty std::promise< void > block_promise; auto importHandler = m_ethereum->setOnBlockImport( - [&block_promise]( BlockHeader const& ) { - block_promise.set_value(); - } ); + [&block_promise]( BlockHeader const& ) { block_promise.set_value(); } ); m_ethereum->injectSkaleHost(); m_ethereum->startWorking(); @@ -159,7 +155,7 @@ class TestClientFixture : public TestOutputHelperFixture { m_ethereum->setAuthor( coinbase.address() ); accountHolder.reset( new FixedAccountHolder( [&]() { return m_ethereum.get(); }, {} ) ); - accountHolder->setAccounts( {coinbase} ); + accountHolder->setAccounts( { coinbase } ); } catch ( const std::exception& ex ) { clog( VerbosityError, "TestClientFixture" ) << "CRITICAL " << dev::nested_exception_what( ex ); @@ -170,43 +166,46 @@ class TestClientFixture : public TestOutputHelperFixture { } dev::eth::Client* ethereum() { return m_ethereum.get(); } - dev::KeyPair coinbase{KeyPair::create()}; + dev::KeyPair coinbase{ KeyPair::create() }; - bool getTransactionStatus(const Json::Value& json) { + bool getTransactionStatus( const Json::Value& json ) { try { - { // block + { // block Json::FastWriter fastWriter; std::string s = fastWriter.write( json ); nlohmann::json jo = nlohmann::json::parse( s ); - clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Will compute status of transaction: " ) + cc::j( jo ) + cc::debug( " ..." ) ); - } // block - Transaction tx = tx_from_json(json); - auto txHash = m_ethereum->importTransaction(tx); - clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Mining transaction..." ) ); - dev::eth::mineTransaction(*(m_ethereum), 1); - clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Getting transaction receipt..." ) ); - Json::Value receipt = toJson(m_ethereum->localisedTransactionReceipt(txHash)); - { // block + clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) + << ( cc::debug( "Will compute status of transaction: " ) + cc::j( jo ) + + cc::debug( " ..." ) ); + } // block + Transaction tx = tx_from_json( json ); + auto txHash = m_ethereum->importTransaction( tx ); + clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) + << ( cc::debug( "Mining transaction..." ) ); + dev::eth::mineTransaction( *( m_ethereum ), 1 ); + clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) + << ( cc::debug( "Getting transaction receipt..." ) ); + Json::Value receipt = toJson( m_ethereum->localisedTransactionReceipt( txHash ) ); + { // block Json::FastWriter fastWriter; std::string s = fastWriter.write( receipt ); nlohmann::json jo = nlohmann::json::parse( s ); - clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::debug( "Got transaction receipt: " ) + cc::j( jo ) + cc::debug( " ..." ) ); - } // block + clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) + << ( cc::debug( "Got transaction receipt: " ) + cc::j( jo ) + + cc::debug( " ..." ) ); + } // block bool bStatusFlag = ( receipt["status"] == "0x1" ) ? true : false; - if( bStatusFlag ) - clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) << - ( cc::success( "SUCCESS: Got positive transaction status" ) ); + if ( bStatusFlag ) + clog( VerbosityInfo, "TestClientFixture::getTransactionStatus()" ) + << ( cc::success( "SUCCESS: Got positive transaction status" ) ); else - cerr << "TestClientFixture::getTransactionStatus() ERROR:" << receipt["status"] << endl; + cerr << "TestClientFixture::getTransactionStatus() ERROR:" << receipt["status"] + << endl; return bStatusFlag; - } catch ( std::exception & ex ) { + } catch ( std::exception& ex ) { cerr << "TestClientFixture::getTransactionStatus() ERROR:" << ex.what() << endl; return false; - } catch (...) { + } catch ( ... ) { cerr << "TestClientFixture::getTransactionStatus() Unknown exception" << endl; return false; } @@ -237,10 +236,11 @@ class TestClientSnapshotsFixture : public TestOutputHelperFixture, public Fixtur rv = system( ( "mkdir " + m_tmpDir.path() ).c_str() ); gainRoot(); - rv = system( ( "mount -o user_subvol_rm_allowed " + BTRFS_FILE_PATH + " " + m_tmpDir.path() ) - .c_str() ); + rv = + system( ( "mount -o user_subvol_rm_allowed " + BTRFS_FILE_PATH + " " + m_tmpDir.path() ) + .c_str() ); rv = chown( m_tmpDir.path().c_str(), sudo_uid, sudo_gid ); - ( void )rv; + ( void ) rv; dropRoot(); // btrfs.subvolume.create( ( BTRFS_DIR_PATH + "/vol1" ).c_str() ); @@ -259,19 +259,21 @@ class TestClientSnapshotsFixture : public TestOutputHelperFixture, public Fixtur // ), dir, // dir, chainParams, WithExisting::Kill, {"eth"}, testingMode ) ); std::shared_ptr< SnapshotManager > mgr; - mgr.reset( new SnapshotManager( chainParams, m_tmpDir.path(), { BlockChain::getChainDirName( chainParams ), "vol2", "filestorage"} ) ); + mgr.reset( new SnapshotManager( chainParams, m_tmpDir.path(), + { BlockChain::getChainDirName( chainParams ), "vol2", "filestorage" } ) ); // boost::filesystem::create_directory( // m_tmpDir.path() / "vol1" / "12041" ); // boost::filesystem::create_directory( // m_tmpDir.path() / "vol1" / "12041" / "state" ); - // std::unique_ptr< dev::db::DatabaseFace > db_state( new dev::db::LevelDB( m_tmpDir.path() / "vol1" / "12041" / "state" ) ); - // boost::filesystem::create_directory( + // std::unique_ptr< dev::db::DatabaseFace > db_state( new dev::db::LevelDB( m_tmpDir.path() + // / "vol1" / "12041" / "state" ) ); boost::filesystem::create_directory( // m_tmpDir.path() / "vol1" / "blocks_and_extras" ); - // std::unique_ptr< dev::db::DatabaseFace > db_blocks_and_extras( new dev::db::LevelDB( m_tmpDir.path() / "vol1" / "12041" / "blocks_and_extras" ) ); + // std::unique_ptr< dev::db::DatabaseFace > db_blocks_and_extras( new dev::db::LevelDB( + // m_tmpDir.path() / "vol1" / "12041" / "blocks_and_extras" ) ); - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); - setenv("DATA_DIR", m_tmpDir.path().c_str(), 1); + setenv( "DATA_DIR", m_tmpDir.path().c_str(), 1 ); m_ethereum.reset( new eth::ClientTest( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), mgr, monitor, m_tmpDir.path(), WithExisting::Kill ) ); @@ -283,9 +285,7 @@ class TestClientSnapshotsFixture : public TestOutputHelperFixture, public Fixtur // wait for 1st block - because it's always empty std::promise< void > block_promise; auto importHandler = m_ethereum->setOnBlockImport( - [&block_promise]( BlockHeader const& ) { - block_promise.set_value(); - } ); + [&block_promise]( BlockHeader const& ) { block_promise.set_value(); } ); m_ethereum->injectSkaleHost(); m_ethereum->startWorking(); @@ -308,7 +308,7 @@ class TestClientSnapshotsFixture : public TestOutputHelperFixture, public Fixtur fs::path getTmpDataDir() { return m_tmpDir.path(); } ~TestClientSnapshotsFixture() { - m_ethereum.reset(0); + m_ethereum.reset( 0 ); const char* NC = getenv( "NC" ); if ( NC ) return; @@ -322,7 +322,7 @@ class TestClientSnapshotsFixture : public TestOutputHelperFixture, public Fixtur private: std::unique_ptr< dev::eth::Client > m_ethereum; TransientDirectory m_tmpDir; - dev::KeyPair coinbase{KeyPair::create()}; + dev::KeyPair coinbase{ KeyPair::create() }; }; // genesis config string from solidity @@ -405,7 +405,8 @@ static std::string const c_genesisInfoSkaleTest = std::string() + "nodeName": "Node1", "nodeID": 1112, "bindIP": "127.0.0.1", - "basePort": )E"+std::to_string( rand_port ) + R"E(, + "basePort": )E" + std::to_string( rand_port ) + + R"E(, "logLevel": "trace", "logLevelProposal": "trace", "testSignatures": true @@ -417,7 +418,9 @@ static std::string const c_genesisInfoSkaleTest = std::string() + "emptyBlockIntervalMs": -1, "correctForkInPowPatchTimestamp": 1, "nodes": [ - { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E"+std::to_string( rand_port ) + R"E(, "schainIndex" : 1, "publicKey": "0xfa"} + { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E" + + std::to_string( rand_port ) + + R"E(, "schainIndex" : 1, "publicKey": "0xfa"} ] } }, @@ -451,15 +454,13 @@ BOOST_AUTO_TEST_CASE( transactionWithData ) { Address addr( "0xca4409573a5129a72edf85d6c51e26760fc9c903" ); - bytes data = - jsToBytes( "0x11223344556600770000" ); + bytes data = jsToBytes( "0x11223344556600770000" ); - u256 estimate = testClient - ->estimateGas( addr, 0, addr, data, 10000000, 1000000, - GasEstimationCallback() ) - .first; + u256 estimate = + testClient->estimateGas( addr, 0, addr, data, 10000000, 1000000, GasEstimationCallback() ) + .first; - BOOST_CHECK_EQUAL( estimate, u256( 21000+7*16+3*4 ) ); + BOOST_CHECK_EQUAL( estimate, u256( 21000 + 7 * 16 + 3 * 4 ) ); } BOOST_AUTO_TEST_CASE( constantConsumption ) { @@ -640,25 +641,25 @@ BOOST_AUTO_TEST_CASE( consumptionWithRefunds ) { // data to call method setA(0) bytes data = - jsToBytes( "0xee919d500000000000000000000000000000000000000000000000000000000000000000" ); + jsToBytes( "0xee919d500000000000000000000000000000000000000000000000000000000000000000" ); int64_t maxGas = 100000; u256 estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, + GasEstimationCallback() ) + .first; Json::Value estimateTransaction; - estimateTransaction["from"] = toJS(from ); - estimateTransaction["to"] = toJS (contractAddress); - estimateTransaction["data"] = toJS (data); + estimateTransaction["from"] = toJS( from ); + estimateTransaction["to"] = toJS( contractAddress ); + estimateTransaction["data"] = toJS( data ); - estimateTransaction["gas"] = toJS(estimate - 1); - BOOST_CHECK( !fixture.getTransactionStatus(estimateTransaction) ); + estimateTransaction["gas"] = toJS( estimate - 1 ); + BOOST_CHECK( !fixture.getTransactionStatus( estimateTransaction ) ); fixture.ethereum()->state().getOriginalDb()->createBlockSnap( 2 ); - estimateTransaction["gas"] = toJS(estimate); - BOOST_CHECK( fixture.getTransactionStatus(estimateTransaction) ); + estimateTransaction["gas"] = toJS( estimate ); + BOOST_CHECK( fixture.getTransactionStatus( estimateTransaction ) ); } BOOST_AUTO_TEST_CASE( consumptionWithRefunds2 ) { @@ -698,25 +699,25 @@ BOOST_AUTO_TEST_CASE( consumptionWithRefunds2 ) { // setA(3) already "called" (see "storage" in c_genesisInfoSkaleTest) // data to call getA(3) bytes data = - jsToBytes( "0xd82cf7900000000000000000000000000000000000000000000000000000000000000003" ); + jsToBytes( "0xd82cf7900000000000000000000000000000000000000000000000000000000000000003" ); int64_t maxGas = 100000; u256 estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, + GasEstimationCallback() ) + .first; Json::Value estimateTransaction; - estimateTransaction["from"] = toJS(from); - estimateTransaction["to"] = toJS(contractAddress); - estimateTransaction["data"] = toJS (data); + estimateTransaction["from"] = toJS( from ); + estimateTransaction["to"] = toJS( contractAddress ); + estimateTransaction["data"] = toJS( data ); - estimateTransaction["gas"] = toJS(estimate - 1); - BOOST_CHECK( !fixture.getTransactionStatus(estimateTransaction) ); + estimateTransaction["gas"] = toJS( estimate - 1 ); + BOOST_CHECK( !fixture.getTransactionStatus( estimateTransaction ) ); fixture.ethereum()->state().getOriginalDb()->createBlockSnap( 2 ); - estimateTransaction["gas"] = toJS(estimate); - BOOST_CHECK( fixture.getTransactionStatus(estimateTransaction) ); + estimateTransaction["gas"] = toJS( estimate ); + BOOST_CHECK( fixture.getTransactionStatus( estimateTransaction ) ); } BOOST_AUTO_TEST_CASE( nonLinearConsumption ) { @@ -744,29 +745,29 @@ BOOST_AUTO_TEST_CASE( nonLinearConsumption ) { // data to call method test(100000) bytes data = - jsToBytes( "0xd37165fa00000000000000000000000000000000000000000000000000000000000186a0" ); + jsToBytes( "0xd37165fa00000000000000000000000000000000000000000000000000000000000186a0" ); int64_t maxGas = 100000; u256 estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, + GasEstimationCallback() ) + .first; BOOST_CHECK( estimate < u256( maxGas ) ); maxGas = 50000; estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( + from, 0, contractAddress, data, maxGas, 1000000, GasEstimationCallback() ) + .first; BOOST_CHECK_EQUAL( estimate, u256( maxGas ) ); maxGas = 200000; estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( + from, 0, contractAddress, data, maxGas, 1000000, GasEstimationCallback() ) + .first; BOOST_CHECK_EQUAL( estimate, u256( maxGas ) ); } @@ -814,31 +815,33 @@ BOOST_AUTO_TEST_CASE( consumptionWithReverts ) { // data to call method testRequire(50000) bytes data = - jsToBytes( "0xb8bd717f000000000000000000000000000000000000000000000000000000000000c350" ); + jsToBytes( "0xb8bd717f000000000000000000000000000000000000000000000000000000000000c350" ); u256 estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, + GasEstimationCallback() ) + .first; BOOST_CHECK_EQUAL( estimate, u256( maxGas ) ); // data to call method testRevert(50000) - data = jsToBytes( "0x20987767000000000000000000000000000000000000000000000000000000000000c350" ); + data = + jsToBytes( "0x20987767000000000000000000000000000000000000000000000000000000000000c350" ); estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( + from, 0, contractAddress, data, maxGas, 1000000, GasEstimationCallback() ) + .first; BOOST_CHECK_EQUAL( estimate, u256( maxGas ) ); // data to call method testRequireOff(50000) - data = jsToBytes( "0xfdde8d66000000000000000000000000000000000000000000000000000000000000c350" ); + data = + jsToBytes( "0xfdde8d66000000000000000000000000000000000000000000000000000000000000c350" ); estimate = testClient - ->estimateGas( from, 0, contractAddress, data, maxGas, 1000000, - GasEstimationCallback() ) - .first; + ->estimateGas( + from, 0, contractAddress, data, maxGas, 1000000, GasEstimationCallback() ) + .first; BOOST_CHECK_EQUAL( estimate, u256( 121632 ) ); } @@ -847,8 +850,9 @@ BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( getHistoricNodesData ) -static std::string const c_genesisInfoSkaleIMABLSPublicKeyTest = std::string() + - R"E( +static std::string const c_genesisInfoSkaleIMABLSPublicKeyTest = + std::string() + + R"E( { "sealEngine": "Ethash", "params": { @@ -887,7 +891,8 @@ static std::string const c_genesisInfoSkaleIMABLSPublicKeyTest = std::string() + "nodeName": "Node1", "nodeID": 1112, "bindIP": "127.0.0.1", - "basePort": )E"+std::to_string( rand_port ) + R"E(, + "basePort": )E" + + std::to_string( rand_port ) + R"E(, "logLevel": "trace", "logLevelProposal": "trace", "testSignatures": true @@ -932,7 +937,8 @@ static std::string const c_genesisInfoSkaleIMABLSPublicKeyTest = std::string() + } }, "nodes": [ - { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E"+std::to_string( rand_port ) + R"E(, "schainIndex" : 1, "publicKey": "0xfa"} + { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E" + + std::to_string( rand_port ) + R"E(, "schainIndex" : 1, "publicKey": "0xfa"} ] } }, @@ -953,26 +959,41 @@ BOOST_AUTO_TEST_CASE( initAndUpdateHistoricConfigFields ) { TestClientFixture fixture( c_genesisInfoSkaleIMABLSPublicKeyTest ); ClientTest* testClient = asClientTest( fixture.ethereum() ); - std::array< std::string, 4 > imaBLSPublicKeyOnStartUp = { "12457351342169393659284905310882617316356538373005664536506840512800919345414", "11573096151310346982175966190385407867176668720531590318594794283907348596326", "13929944172721019694880576097738949215943314024940461401664534665129747139387", "7375214420811287025501422512322868338311819657776589198925786170409964211914" }; + std::array< std::string, 4 > imaBLSPublicKeyOnStartUp = { + "12457351342169393659284905310882617316356538373005664536506840512800919345414", + "11573096151310346982175966190385407867176668720531590318594794283907348596326", + "13929944172721019694880576097738949215943314024940461401664534665129747139387", + "7375214420811287025501422512322868338311819657776589198925786170409964211914" + }; BOOST_REQUIRE( testClient->getIMABLSPublicKey() == imaBLSPublicKeyOnStartUp ); - BOOST_REQUIRE( testClient->getHistoricNodePublicKey( 0 ) == "0x3a581d62b12232dade30c3710215a271984841657449d1f474295a13737b778266f57e298f123ae80cbab7cc35ead1b62a387556f94b326d5c65d4a7aa2abcba" ); + BOOST_REQUIRE( testClient->getHistoricNodePublicKey( 0 ) == + "0x3a581d62b12232dade30c3710215a271984841657449d1f474295a13737b778266f57e298f123" + "ae80cbab7cc35ead1b62a387556f94b326d5c65d4a7aa2abcba" ); BOOST_REQUIRE( testClient->getHistoricNodeId( 0 ) == "26" ); BOOST_REQUIRE( testClient->getHistoricNodeIndex( 0 ) == "3" ); testClient->importTransactionsAsBlock( Transactions(), 1000, 4294967294 ); - std::array< std::string, 4 > imaBLSPublicKeyAfterBlock = { "10860211539819517237363395256510340030868592687836950245163587507107792195621", "2419969454136313127863904023626922181546178935031521540751337209075607503568", "3399776985251727272800732947224655319335094876742988846345707000254666193993", "16982202412630419037827505223148517434545454619191931299977913428346639096984" }; + std::array< std::string, 4 > imaBLSPublicKeyAfterBlock = { + "10860211539819517237363395256510340030868592687836950245163587507107792195621", + "2419969454136313127863904023626922181546178935031521540751337209075607503568", + "3399776985251727272800732947224655319335094876742988846345707000254666193993", + "16982202412630419037827505223148517434545454619191931299977913428346639096984" + }; BOOST_REQUIRE( testClient->getIMABLSPublicKey() == imaBLSPublicKeyAfterBlock ); - BOOST_REQUIRE( testClient->getHistoricNodePublicKey( 0 ) == "0x6180cde2cbbcc6b6a17efec4503a7d4316f8612f411ee171587089f770335f484003ad236c534b9afa82befc1f69533723abdb6ec2601e582b72dcfd7919338b" ); + BOOST_REQUIRE( testClient->getHistoricNodePublicKey( 0 ) == + "0x6180cde2cbbcc6b6a17efec4503a7d4316f8612f411ee171587089f770335f484003ad236c534" + "b9afa82befc1f69533723abdb6ec2601e582b72dcfd7919338b" ); BOOST_REQUIRE( testClient->getHistoricNodeId( 0 ) == "30" ); BOOST_REQUIRE( testClient->getHistoricNodeIndex( 0 ) == "0" ); } BOOST_AUTO_TEST_SUITE_END() -static std::string const c_skaleConfigString = R"E( +static std::string const c_skaleConfigString = + R"E( { "sealEngine": "NoProof", "params": { @@ -1002,7 +1023,8 @@ static std::string const c_skaleConfigString = R"E( "nodeName": "TestNode", "nodeID": 1112, "bindIP": "127.0.0.1", - "basePort": )E"+std::to_string( rand_port ) + R"E(, + "basePort": )E" + + std::to_string( rand_port ) + R"E(, "testSignatures": true }, "sChain": { @@ -1011,7 +1033,9 @@ static std::string const c_skaleConfigString = R"E( "snapshotIntervalSec": 10, "emptyBlockIntervalMs": -1, "nodes": [ - { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E"+std::to_string( rand_port ) + R"E(, "ip6": "::1", "basePort6": 1231, "schainIndex" : 1, "publicKey" : "0xfa"} + { "nodeID": 1112, "ip": "127.0.0.1", "basePort": )E" + + std::to_string( rand_port ) + + R"E(, "ip6": "::1", "basePort6": 1231, "schainIndex" : 1, "publicKey" : "0xfa"} ] } }, @@ -1031,7 +1055,8 @@ static std::string const c_skaleConfigString = R"E( BOOST_AUTO_TEST_SUITE( ClientSnapshotsSuite, *boost::unit_test::precondition( option_all_tests ) ) -BOOST_AUTO_TEST_CASE( ClientSnapshotsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ClientSnapshotsTest, *boost::unit_test::precondition( dev::test::run_not_express ) ) { TestClientSnapshotsFixture fixture( c_skaleConfigString ); ClientTest* testClient = asClientTest( fixture.ethereum() ); @@ -1057,7 +1082,8 @@ BOOST_AUTO_TEST_CASE( ClientSnapshotsTest, *boost::unit_test::precondition( dev: BOOST_REQUIRE( testClient->latestBlock().info().stateRoot() == empty_state_root_hash ); std::this_thread::sleep_for( 6000ms ); - BOOST_REQUIRE( fs::exists( fs::path( fixture.getTmpDataDir() ) / "snapshots" / "3" / "snapshot_hash.txt" ) ); + BOOST_REQUIRE( fs::exists( + fs::path( fixture.getTmpDataDir() ) / "snapshots" / "3" / "snapshot_hash.txt" ) ); dev::h256 hash = testClient->hashFromNumber( 3 ); uint64_t timestampFromBlockchain = testClient->blockInfo( hash ).timestamp(); diff --git a/test/unittests/libethereum/ExtVMTest.cpp b/test/unittests/libethereum/ExtVMTest.cpp index 548d30033..9ee4cab4c 100644 --- a/test/unittests/libethereum/ExtVMTest.cpp +++ b/test/unittests/libethereum/ExtVMTest.cpp @@ -27,8 +27,7 @@ using namespace dev; using namespace dev::eth; using namespace dev::test; -using skale:: -State; +using skale::State; class ExtVMConstantinopleFixTestFixture : public TestOutputHelperFixture { public: @@ -49,7 +48,7 @@ class ExtVMConstantinopleFixTestFixture : public TestOutputHelperFixture { } EnvInfo createEnvInfo( BlockHeader const& _header ) const { - return {_header, lastBlockHashes, 1, 0, blockchain.chainID()}; + return { _header, lastBlockHashes, 1, 0, blockchain.chainID() }; } NetworkSelector networkSelector; @@ -59,7 +58,7 @@ class ExtVMConstantinopleFixTestFixture : public TestOutputHelperFixture { BlockChain const& blockchain; h256 preExperimentalBlockHash; h256 experimentalBlockHash; - TestLastBlockHashes lastBlockHashes{{}}; + TestLastBlockHashes lastBlockHashes{ {} }; }; BOOST_FIXTURE_TEST_SUITE( ExtVmSuite, ExtVMConstantinopleFixTestFixture ) @@ -72,8 +71,8 @@ BOOST_AUTO_TEST_CASE( BlockhashOutOfBoundsRetunsZero, TestLastBlockHashes lastBlockHashes( {} ); EnvInfo envInfo( createEnvInfo( block.info() ) ); Address addr( "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" ); - ExtVM extVM( block.mutableState(), envInfo, blockchain.sealEngine()->chainParams(), addr, addr, addr, 0, 0, - {}, {}, {}, 0, 0, false, false ); + ExtVM extVM( block.mutableState(), envInfo, blockchain.sealEngine()->chainParams(), addr, addr, + addr, 0, 0, {}, {}, {}, 0, 0, false, false ); BOOST_CHECK_EQUAL( extVM.blockHash( 100 ), h256() ); } @@ -83,12 +82,13 @@ BOOST_AUTO_TEST_CASE( BlockhashBeforeConstantinopleReliesOnLastHashes, Block block = blockchain.genesisBlock( genesisState ); block.sync( blockchain ); - h256s lastHashes{h256( "0xaaabbbccc" ), h256( "0xdddeeefff" )}; + h256s lastHashes{ h256( "0xaaabbbccc" ), h256( "0xdddeeefff" ) }; TestLastBlockHashes lastBlockHashes( lastHashes ); - EnvInfo envInfo( block.info(), lastBlockHashes, block.info().timestamp(), 0, blockchain.chainID() ); + EnvInfo envInfo( + block.info(), lastBlockHashes, block.info().timestamp(), 0, blockchain.chainID() ); Address addr( "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" ); - ExtVM extVM( block.mutableState(), envInfo, blockchain.sealEngine()->chainParams(), addr, addr, addr, 0, 0, - {}, {}, {}, 0, 0, false, false ); + ExtVM extVM( block.mutableState(), envInfo, blockchain.sealEngine()->chainParams(), addr, addr, + addr, 0, 0, {}, {}, {}, 0, 0, false, false ); h256 hash = extVM.blockHash( 1 ); BOOST_REQUIRE_EQUAL( hash, lastHashes[0] ); } diff --git a/test/unittests/libethereum/GasPricer.cpp b/test/unittests/libethereum/GasPricer.cpp index 70bae8380..d97b78668 100644 --- a/test/unittests/libethereum/GasPricer.cpp +++ b/test/unittests/libethereum/GasPricer.cpp @@ -54,7 +54,8 @@ void executeGasPricerTest( string const& name, double _etherPrice, double _block "ASK Got: " + toString( gp.ask( Block( Block::Null ) ) ) + " Expected: " + toString( _expectedAsk ) ); BOOST_CHECK_MESSAGE( abs( gp.bid( dev::eth::LatestBlock, _txPrio ) - _expectedBid ) < 100000000, - "BID Got: " + toString( gp.bid( dev::eth::LatestBlock, _txPrio ) ) + " Expected: " + toString( _expectedBid ) ); + "BID Got: " + toString( gp.bid( dev::eth::LatestBlock, _txPrio ) ) + + " Expected: " + toString( _expectedBid ) ); } } // namespace test } // namespace dev @@ -66,13 +67,14 @@ BOOST_AUTO_TEST_CASE( trivialGasPricer ) { BOOST_CHECK_EQUAL( gp->ask( Block( Block::Null ) ), DefaultGasPrice ); BOOST_CHECK_EQUAL( gp->bid(), DefaultGasPrice ); - gp->update( BlockChain( eth::ChainParams(), TransientDirectory().path(), false, WithExisting::Kill ) ); + gp->update( + BlockChain( eth::ChainParams(), TransientDirectory().path(), false, WithExisting::Kill ) ); BOOST_CHECK_EQUAL( gp->ask( Block( Block::Null ) ), DefaultGasPrice ); BOOST_CHECK_EQUAL( gp->bid(), DefaultGasPrice ); } -BOOST_AUTO_TEST_CASE( basicGasPricerNoUpdate, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + basicGasPricerNoUpdate, *boost::unit_test::precondition( dev::test::run_not_express ) ) { BasicGasPricer gp( u256( double( ether / 1000 ) / 30.679 ), u256( 15.0 * 1000 ) ); BOOST_CHECK_EQUAL( gp.ask( Block( Block::Null ) ), 103754996057 ); BOOST_CHECK_EQUAL( gp.bid(), 103754996057 ); diff --git a/test/unittests/libethereum/Genesis.cpp b/test/unittests/libethereum/Genesis.cpp index 33c6cafd4..2a12d03e6 100644 --- a/test/unittests/libethereum/Genesis.cpp +++ b/test/unittests/libethereum/Genesis.cpp @@ -43,8 +43,8 @@ namespace js = json_spirit; BOOST_FIXTURE_TEST_SUITE( BasicTests, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( emptySHA3Types, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + emptySHA3Types, *boost::unit_test::precondition( dev::test::run_not_express ) ) { h256 emptyListSHA3( fromHex( "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" ) ); BOOST_REQUIRE_EQUAL( emptyListSHA3, EmptyListSHA3 ); diff --git a/test/unittests/libethereum/InstanceMonitorTest.cpp b/test/unittests/libethereum/InstanceMonitorTest.cpp index 137b70555..e10bea059 100644 --- a/test/unittests/libethereum/InstanceMonitorTest.cpp +++ b/test/unittests/libethereum/InstanceMonitorTest.cpp @@ -13,25 +13,19 @@ using namespace dev::test; namespace fs = boost::filesystem; -class InstanceMonitorMock: public InstanceMonitor { +class InstanceMonitorMock : public InstanceMonitor { public: - explicit InstanceMonitorMock(fs::path const &rotationFlagFilePath, std::shared_ptr statusAndControl) : InstanceMonitor(rotationFlagFilePath, statusAndControl) {}; + explicit InstanceMonitorMock( + fs::path const& rotationFlagFilePath, std::shared_ptr< StatusAndControl > statusAndControl ) + : InstanceMonitor( rotationFlagFilePath, statusAndControl ){}; - fs::path getRotationInfoFilePath() { - return this->rotationInfoFilePath(); - } + fs::path getRotationInfoFilePath() { return this->rotationInfoFilePath(); } - void createFlagFileTest(){ - this->reportExitTimeReached( true ); - } + void createFlagFileTest() { this->reportExitTimeReached( true ); } - void removeFlagFileTest(){ - this->reportExitTimeReached( false ); - } + void removeFlagFileTest() { this->reportExitTimeReached( false ); } - uint64_t getRotationTimestamp() const { - return this->rotationTimestamp(); - } + uint64_t getRotationTimestamp() const { return this->rotationTimestamp(); } }; class InstanceMonitorTestFixture : public TestOutputHelperFixture { @@ -39,27 +33,27 @@ class InstanceMonitorTestFixture : public TestOutputHelperFixture { fs::path rotationFlagDirPath = "test"; InstanceMonitorTestFixture() { - fs::create_directory(rotationFlagDirPath); + fs::create_directory( rotationFlagDirPath ); - statusAndControlFile = std::make_shared(rotationFlagDirPath); - instanceMonitor = new InstanceMonitorMock(rotationFlagDirPath, statusAndControlFile); + statusAndControlFile = std::make_shared< StatusAndControlFile >( rotationFlagDirPath ); + instanceMonitor = new InstanceMonitorMock( rotationFlagDirPath, statusAndControlFile ); rotationFilePath = instanceMonitor->getRotationInfoFilePath(); } InstanceMonitorMock* instanceMonitor; - std::shared_ptr statusAndControlFile; + std::shared_ptr< StatusAndControl > statusAndControlFile; fs::path rotationFilePath; ~InstanceMonitorTestFixture() override { - if (fs::exists(rotationFilePath)) { - fs::remove(rotationFilePath); + if ( fs::exists( rotationFilePath ) ) { + fs::remove( rotationFilePath ); } - if (fs::exists(rotationFlagDirPath/"skaled.status")) { - fs::remove(rotationFlagDirPath/"skaled.status"); + if ( fs::exists( rotationFlagDirPath / "skaled.status" ) ) { + fs::remove( rotationFlagDirPath / "skaled.status" ); } - if (fs::exists(rotationFlagDirPath)) { - fs::remove(rotationFlagDirPath); + if ( fs::exists( rotationFlagDirPath ) ) { + fs::remove( rotationFlagDirPath ); } }; }; @@ -68,22 +62,22 @@ BOOST_FIXTURE_TEST_SUITE( InstanceMonitorSuite, InstanceMonitorTestFixture ) BOOST_AUTO_TEST_CASE( test_initRotationParams ) { uint64_t ts = 100; - BOOST_REQUIRE( !fs::exists(instanceMonitor->getRotationInfoFilePath() ) ); - instanceMonitor->initRotationParams(ts); - BOOST_CHECK_EQUAL(instanceMonitor->getRotationTimestamp(), ts); + BOOST_REQUIRE( !fs::exists( instanceMonitor->getRotationInfoFilePath() ) ); + instanceMonitor->initRotationParams( ts ); + BOOST_CHECK_EQUAL( instanceMonitor->getRotationTimestamp(), ts ); - BOOST_REQUIRE( fs::exists(instanceMonitor->getRotationInfoFilePath() ) ); + BOOST_REQUIRE( fs::exists( instanceMonitor->getRotationInfoFilePath() ) ); - std::ifstream rotateFile(instanceMonitor->getRotationInfoFilePath().string() ); + std::ifstream rotateFile( instanceMonitor->getRotationInfoFilePath().string() ); auto rotateJson = nlohmann::json::parse( rotateFile ); - BOOST_CHECK_EQUAL(rotateJson["timestamp"].get< uint64_t >(), ts); + BOOST_CHECK_EQUAL( rotateJson["timestamp"].get< uint64_t >(), ts ); } BOOST_AUTO_TEST_CASE( test_isTimeToRotate_invalid_file ) { uint64_t currentTime = 100; - std::ofstream rotationInfoFile(instanceMonitor->getRotationInfoFilePath().string() ); + std::ofstream rotationInfoFile( instanceMonitor->getRotationInfoFilePath().string() ); rotationInfoFile << "Broken file"; BOOST_REQUIRE( !instanceMonitor->isTimeToRotate( currentTime ) ); } @@ -93,7 +87,7 @@ BOOST_AUTO_TEST_CASE( test_isTimeToRotate_false ) { uint64_t currentTime = 100; uint64_t finishTime = 200; BOOST_REQUIRE( !instanceMonitor->isTimeToRotate( currentTime ) ); - instanceMonitor->initRotationParams(finishTime); + instanceMonitor->initRotationParams( finishTime ); BOOST_REQUIRE( !instanceMonitor->isTimeToRotate( currentTime ) ); } @@ -102,10 +96,10 @@ BOOST_AUTO_TEST_CASE( test_isTimeToRotate_true ) { BOOST_REQUIRE( !instanceMonitor->isTimeToRotate( currentTime ) ); - instanceMonitor->initRotationParams(100); + instanceMonitor->initRotationParams( 100 ); BOOST_REQUIRE( instanceMonitor->isTimeToRotate( currentTime ) ); - instanceMonitor->initRotationParams(50); + instanceMonitor->initRotationParams( 50 ); BOOST_REQUIRE( instanceMonitor->isTimeToRotate( currentTime ) ); currentTime = 49; @@ -113,20 +107,20 @@ BOOST_AUTO_TEST_CASE( test_isTimeToRotate_true ) { } BOOST_AUTO_TEST_CASE( test_rotation ) { - instanceMonitor->initRotationParams(0); - instanceMonitor->prepareRotation(); + instanceMonitor->initRotationParams( 0 ); + instanceMonitor->prepareRotation(); - BOOST_REQUIRE( statusAndControlFile->getExitState(StatusAndControl::ExitTimeReached) ); - BOOST_REQUIRE( !( fs::exists(instanceMonitor->getRotationInfoFilePath() ) ) ); + BOOST_REQUIRE( statusAndControlFile->getExitState( StatusAndControl::ExitTimeReached ) ); + BOOST_REQUIRE( !( fs::exists( instanceMonitor->getRotationInfoFilePath() ) ) ); } BOOST_AUTO_TEST_CASE( test_create_remove_flag_file ) { instanceMonitor->createFlagFileTest(); - BOOST_REQUIRE( statusAndControlFile->getExitState(StatusAndControl::ExitTimeReached) ); + BOOST_REQUIRE( statusAndControlFile->getExitState( StatusAndControl::ExitTimeReached ) ); instanceMonitor->removeFlagFileTest(); - BOOST_REQUIRE( !( fs::exists(instanceMonitor->getRotationInfoFilePath() ) ) ); - BOOST_REQUIRE( !statusAndControlFile->getExitState(StatusAndControl::ExitTimeReached) ); + BOOST_REQUIRE( !( fs::exists( instanceMonitor->getRotationInfoFilePath() ) ) ); + BOOST_REQUIRE( !statusAndControlFile->getExitState( StatusAndControl::ExitTimeReached ) ); } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libethereum/PrecompiledTest.cpp b/test/unittests/libethereum/PrecompiledTest.cpp index 3483a4699..5ea3f3c81 100644 --- a/test/unittests/libethereum/PrecompiledTest.cpp +++ b/test/unittests/libethereum/PrecompiledTest.cpp @@ -23,16 +23,16 @@ #include #include #include -#include #include #include #include +#include +#include #include #include +#include #include #include -#include -#include #include @@ -59,8 +59,8 @@ std::string stringToHex( std::string inputString ) { BOOST_FIXTURE_TEST_SUITE( PrecompiledTests, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( modexpFermatTheorem, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpFermatTheorem, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -78,8 +78,8 @@ BOOST_AUTO_TEST_CASE( modexpFermatTheorem, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpZeroBase, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpZeroBase, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -96,8 +96,8 @@ BOOST_AUTO_TEST_CASE( modexpZeroBase, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpExtraByteIgnored, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpExtraByteIgnored, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -116,8 +116,8 @@ BOOST_AUTO_TEST_CASE( modexpExtraByteIgnored, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpRightPadding, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpRightPadding, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -151,8 +151,8 @@ BOOST_AUTO_TEST_CASE( modexpMissingValues ) { res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpEmptyValue, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpEmptyValue, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -169,8 +169,8 @@ BOOST_AUTO_TEST_CASE( modexpEmptyValue, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpZeroPowerZero, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpZeroPowerZero, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -188,8 +188,8 @@ BOOST_AUTO_TEST_CASE( modexpZeroPowerZero, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpZeroPowerZeroModZero, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpZeroPowerZeroModZero, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -207,8 +207,8 @@ BOOST_AUTO_TEST_CASE( modexpZeroPowerZeroModZero, res.second.begin(), res.second.end(), expected.begin(), expected.end() ); } -BOOST_AUTO_TEST_CASE( modexpModLengthZero, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpModLengthZero, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "modexp" ); bytes in = fromHex( @@ -223,8 +223,8 @@ BOOST_AUTO_TEST_CASE( modexpModLengthZero, BOOST_REQUIRE( res.second.empty() ); } -BOOST_AUTO_TEST_CASE( modexpCostFermatTheorem, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostFermatTheorem, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -239,8 +239,8 @@ BOOST_AUTO_TEST_CASE( modexpCostFermatTheorem, BOOST_REQUIRE_EQUAL( static_cast< int >( res ), 13056 ); } -BOOST_AUTO_TEST_CASE( modexpCostTooLarge, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostTooLarge, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -251,15 +251,13 @@ BOOST_AUTO_TEST_CASE( modexpCostTooLarge, "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd" ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( - res == - bigint{ - "47428439751604713645494675459558567056699385719046375030561826409641217900517324"}, + BOOST_REQUIRE_MESSAGE( res == bigint{ "47428439751604713645494675459558567056699385719046375030" + "561826409641217900517324" }, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostEmptyExponent, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostEmptyExponent, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -273,11 +271,11 @@ BOOST_AUTO_TEST_CASE( modexpCostEmptyExponent, ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( res == bigint{"12"}, "Got: " + toString( res ) ); + BOOST_REQUIRE_MESSAGE( res == bigint{ "12" }, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostZeroExponent, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostZeroExponent, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -290,11 +288,11 @@ BOOST_AUTO_TEST_CASE( modexpCostZeroExponent, ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( res == bigint{"5"}, "Got: " + toString( res ) ); + BOOST_REQUIRE_MESSAGE( res == bigint{ "5" }, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostApproximated, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostApproximated, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -307,11 +305,11 @@ BOOST_AUTO_TEST_CASE( modexpCostApproximated, ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( res == bigint{"1315"}, "Got: " + toString( res ) ); + BOOST_REQUIRE_MESSAGE( res == bigint{ "1315" }, "Got: " + toString( res ) ); } BOOST_AUTO_TEST_CASE( modexpCostApproximatedPartialByte, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); @@ -325,11 +323,11 @@ BOOST_AUTO_TEST_CASE( modexpCostApproximatedPartialByte, ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( res == bigint{"1285"}, "Got: " + toString( res ) ); + BOOST_REQUIRE_MESSAGE( res == bigint{ "1285" }, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostApproximatedGhost, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostApproximatedGhost, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -342,11 +340,11 @@ BOOST_AUTO_TEST_CASE( modexpCostApproximatedGhost, ); auto res = cost( ref( in ), {}, {} ); - BOOST_REQUIRE_MESSAGE( res == bigint{"40"}, "Got: " + toString( res ) ); + BOOST_REQUIRE_MESSAGE( res == bigint{ "40" }, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostMidRange, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostMidRange, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -363,8 +361,8 @@ BOOST_AUTO_TEST_CASE( modexpCostMidRange, res == ( ( 74 * 74 / 4 + 96 * 74 - 3072 ) * 8 ) / 20, "Got: " + toString( res ) ); } -BOOST_AUTO_TEST_CASE( modexpCostHighRange, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + modexpCostHighRange, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "modexp" ); bytes in = fromHex( @@ -395,10 +393,13 @@ struct PrecompiledTest { }; constexpr PrecompiledTest ecrecoverTests[] = { - {"38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed98873e00000000000000000000000000000" - "0000000000000000000000000000000001b38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed" - "98873e789d1dd423d25f0772d2748d60f7e4b81bb14d086eba8e8e8efb6dcff8a4ae02", - "000000000000000000000000ceaccac640adf55b2028469bd36ba501f28b699d", ""}}; + { "38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9ed98873e0000000000000000000000000000" + "0" + "0000000000000000000000000000000001b38d18acb67d25c8bb9942764b62f18e17054f66a817bd4295423adf9e" + "d" + "98873e789d1dd423d25f0772d2748d60f7e4b81bb14d086eba8e8e8efb6dcff8a4ae02", + "000000000000000000000000ceaccac640adf55b2028469bd36ba501f28b699d", "" } +}; constexpr PrecompiledTest modexpTests[] = { { @@ -905,15 +906,18 @@ constexpr PrecompiledTest modexpTests[] = { "4d11c9ebee1e1d3845099e55504446448027212616167eb36035726daa7698b075286f5379cd3e93cb3e0cf4f9" "cb8d017facbb5550ed32d5ec5400ae57e47e2bf78d1eaeff9480cc765ceff39db500", "nagydani-5-pow0x10001", - }}; + } +}; constexpr PrecompiledTest bn256AddTests[] = { - {"18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9063c909c4720840cb5134cb9f59fa" - "749755796819658d32efc0d288198f3726607c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6a" - "014eed06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7", + { "18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9063c909c4720840cb5134cb9f59f" + "a" + "749755796819658d32efc0d288198f3726607c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6" + "a" + "014eed06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7", "2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703301d1d33be6da8e509df21cc35" "964723180eed7532537db9ae5e7d48f195c915", - "chfast1"}, + "chfast1" }, { "2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703301d1d33be6da8e509df21cc35" "964723180eed7532537db9ae5e7d48f195c91518b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b" @@ -1038,7 +1042,8 @@ constexpr PrecompiledTest bn256AddTests[] = { "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "00000000000000000000000000000000000000", "cdetrio14", - }}; + } +}; constexpr PrecompiledTest bn256ScalarMulTests[] = { { @@ -1184,7 +1189,8 @@ constexpr PrecompiledTest bn256ScalarMulTests[] = { "039730ea8dff1254c0fee9c0ea777d29a9c710b7e616683f194f18c43b43b869073a5ffcc6fc7a28c30723d6e5" "8ce577356982d65b833a5a5c15bf9024b43d98", "cdetrio15", - }}; + } +}; // bn256PairingTests are the test and benchmark data for the bn256 pairing check // precompiled contract. @@ -1477,77 +1483,77 @@ void benchmarkPrecompiled( char const name[], vector_ref< const PrecompiledTest BOOST_AUTO_TEST_CASE( bench_ecrecover, *ut::label( "bench" ) * boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector_ref< const PrecompiledTest > tests{ - ecrecoverTests, sizeof( ecrecoverTests ) / sizeof( ecrecoverTests[0] )}; + vector_ref< const PrecompiledTest > tests{ ecrecoverTests, + sizeof( ecrecoverTests ) / sizeof( ecrecoverTests[0] ) }; benchmarkPrecompiled( "ecrecover", tests, 100000 ); } BOOST_AUTO_TEST_CASE( bench_modexp, *ut::label( "bench" ) * boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector_ref< const PrecompiledTest > tests{ - modexpTests, sizeof( modexpTests ) / sizeof( modexpTests[0] )}; + vector_ref< const PrecompiledTest > tests{ modexpTests, + sizeof( modexpTests ) / sizeof( modexpTests[0] ) }; benchmarkPrecompiled( "modexp", tests, 10000 ); } BOOST_AUTO_TEST_CASE( bench_bn256Add, *ut::label( "bench" ) * boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector_ref< const PrecompiledTest > tests{ - bn256AddTests, sizeof( bn256AddTests ) / sizeof( bn256AddTests[0] )}; + vector_ref< const PrecompiledTest > tests{ bn256AddTests, + sizeof( bn256AddTests ) / sizeof( bn256AddTests[0] ) }; benchmarkPrecompiled( "alt_bn128_G1_add", tests, 1000000 ); } BOOST_AUTO_TEST_CASE( bench_bn256ScalarMul, *ut::label( "bench" ) * boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector_ref< const PrecompiledTest > tests{ - bn256ScalarMulTests, sizeof( bn256ScalarMulTests ) / sizeof( bn256ScalarMulTests[0] )}; + vector_ref< const PrecompiledTest > tests{ bn256ScalarMulTests, + sizeof( bn256ScalarMulTests ) / sizeof( bn256ScalarMulTests[0] ) }; benchmarkPrecompiled( "alt_bn128_G1_mul", tests, 10000 ); } BOOST_AUTO_TEST_CASE( bench_bn256Pairing, *ut::label( "bench" ) * boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector_ref< const PrecompiledTest > tests{ - bn256PairingTests, sizeof( bn256PairingTests ) / sizeof( bn256PairingTests[0] )}; + vector_ref< const PrecompiledTest > tests{ bn256PairingTests, + sizeof( bn256PairingTests ) / sizeof( bn256PairingTests[0] ) }; benchmarkPrecompiled( "alt_bn128_pairing_product", tests, 1000 ); } -BOOST_AUTO_TEST_CASE( ecaddCostBeforeIstanbul, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecaddCostBeforeIstanbul, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "alt_bn128_G1_add" ); - ChainParams chainParams{genesisInfo( eth::Network::IstanbulTransitionTest )}; + ChainParams chainParams{ genesisInfo( eth::Network::IstanbulTransitionTest ) }; auto res = cost( {}, chainParams, 1 ); BOOST_REQUIRE_EQUAL( static_cast< int >( res ), 500 ); } -BOOST_AUTO_TEST_CASE( ecaddCostIstanbul, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecaddCostIstanbul, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "alt_bn128_G1_add" ); - ChainParams chainParams{genesisInfo( eth::Network::IstanbulTransitionTest )}; + ChainParams chainParams{ genesisInfo( eth::Network::IstanbulTransitionTest ) }; auto res = cost( {}, chainParams, 2 ); BOOST_REQUIRE_EQUAL( static_cast< int >( res ), 150 ); } -BOOST_AUTO_TEST_CASE( ecmulBeforeIstanbul, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecmulBeforeIstanbul, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "alt_bn128_G1_mul" ); - ChainParams chainParams{genesisInfo( eth::Network::IstanbulTransitionTest )}; + ChainParams chainParams{ genesisInfo( eth::Network::IstanbulTransitionTest ) }; auto res = cost( {}, chainParams, 1 ); BOOST_REQUIRE_EQUAL( static_cast< int >( res ), 40000 ); } -BOOST_AUTO_TEST_CASE( ecmulCostIstanbul, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ecmulCostIstanbul, *boost::unit_test::precondition( dev::test::run_not_express ) ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "alt_bn128_G1_mul" ); - ChainParams chainParams{genesisInfo( eth::Network::IstanbulTransitionTest )}; + ChainParams chainParams{ genesisInfo( eth::Network::IstanbulTransitionTest ) }; auto res = cost( {}, chainParams, 2 ); @@ -1557,9 +1563,9 @@ BOOST_AUTO_TEST_CASE( ecmulCostIstanbul, BOOST_AUTO_TEST_CASE( ecpairingCost ) { PrecompiledPricer cost = PrecompiledRegistrar::pricer( "alt_bn128_pairing_product" ); - ChainParams chainParams{genesisInfo( eth::Network::IstanbulTransitionTest )}; + ChainParams chainParams{ genesisInfo( eth::Network::IstanbulTransitionTest ) }; - bytes in{fromHex( + bytes in{ fromHex( "0x1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f593034dd2920f673e204fee281" "1c678745fc819b55d3e9d294e45c9b03a76aef41209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b" "4a452003a35bf704bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a416782bb8324af6cf" @@ -1568,7 +1574,7 @@ BOOST_AUTO_TEST_CASE( ecpairingCost ) { "2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411198e9393920d483a7260bfb731" "fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46de" "bd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6d" - "eb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa" )}; + "eb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa" ) }; auto costBeforeIstanbul = cost( ref( in ), chainParams, 1 ); BOOST_CHECK_EQUAL( static_cast< int >( costBeforeIstanbul ), in.size() / 192 * 80000 + 100000 ); @@ -1578,7 +1584,7 @@ BOOST_AUTO_TEST_CASE( ecpairingCost ) { } static std::string const genesisInfoSkaleConfigTest = std::string() + - R"E( + R"E( { "sealEngine": "Ethash", "params": { @@ -1696,19 +1702,20 @@ BOOST_AUTO_TEST_CASE( getConfigVariable ) { chainParams.sealEngineName = NoProof::name(); chainParams.allowFutureBlocks = true; - dev::eth::g_configAccesssor.reset( new skutils::json_config_file_accessor( "../../test/unittests/libethereum/PrecompiledConfig.json" ) ); + dev::eth::g_configAccesssor.reset( new skutils::json_config_file_accessor( + "../../test/unittests/libethereum/PrecompiledConfig.json" ) ); - std::unique_ptr client; + std::unique_ptr< dev::eth::Client > client; dev::TransientDirectory m_tmpDir; - auto monitor = make_shared< InstanceMonitor >("test"); - setenv("DATA_DIR", m_tmpDir.path().c_str(), 1); + auto monitor = make_shared< InstanceMonitor >( "test" ); + setenv( "DATA_DIR", m_tmpDir.path().c_str(), 1 ); client.reset( new eth::ClientTest( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), nullptr, monitor, m_tmpDir.path(), dev::WithExisting::Kill ) ); client->injectSkaleHost(); client->startWorking(); - client->setAuthor( Address("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF") ); + client->setAuthor( Address( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" ) ); ClientTest* testClient = asClientTest( client.get() ); @@ -1718,46 +1725,46 @@ BOOST_AUTO_TEST_CASE( getConfigVariable ) { PrecompiledExecutor exec = PrecompiledRegistrar::executor( "getConfigVariableUint256" ); std::string input = stringToHex( "skaleConfig.sChain.nodes.0.id" ); - input = input.substr(0, 58); // remove 0s in the end + input = input.substr( 0, 58 ); // remove 0s in the end bytes in = fromHex( numberToHex( 29 ) + input ); auto res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( res.first ); - BOOST_REQUIRE( dev::fromBigEndian( res.second ) == 30 ); + BOOST_REQUIRE( dev::fromBigEndian< dev::u256 >( res.second ) == 30 ); input = stringToHex( "skaleConfig.sChain.nodes.0.schainIndex" ); - input = input.substr(0, 76); // remove 0s in the end + input = input.substr( 0, 76 ); // remove 0s in the end in = fromHex( numberToHex( 38 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( res.first ); - BOOST_REQUIRE( dev::fromBigEndian( res.second ) == 13 ); + BOOST_REQUIRE( dev::fromBigEndian< dev::u256 >( res.second ) == 13 ); input = stringToHex( "skaleConfig.sChain.nodes.0.publicKey" ); - input = input.substr(0, 72); // remove 0s in the end + input = input.substr( 0, 72 ); // remove 0s in the end in = fromHex( numberToHex( 36 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( !res.first ); input = stringToHex( "skaleConfig.sChain.nodes.0.unknownField" ); - input = input.substr(0, 78); // remove 0s in the end + input = input.substr( 0, 78 ); // remove 0s in the end in = fromHex( numberToHex( 39 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( !res.first ); input = stringToHex( "skaleConfig.nodeInfo.wallets.ima.n" ); - input = input.substr(0, 68); // remove 0s in the end + input = input.substr( 0, 68 ); // remove 0s in the end in = fromHex( numberToHex( 34 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( res.first ); - BOOST_REQUIRE( dev::fromBigEndian( res.second ) == 1 ); + BOOST_REQUIRE( dev::fromBigEndian< dev::u256 >( res.second ) == 1 ); input = stringToHex( "skaleConfig.nodeInfo.wallets.ima.t" ); - input = input.substr(0, 68); // remove 0s in the end + input = input.substr( 0, 68 ); // remove 0s in the end in = fromHex( numberToHex( 34 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); @@ -1766,15 +1773,17 @@ BOOST_AUTO_TEST_CASE( getConfigVariable ) { exec = PrecompiledRegistrar::executor( "getConfigVariableString" ); input = stringToHex( "skaleConfig.sChain.nodes.0.publicKey" ); - input = input.substr(0, 72); // remove 0s in the end + input = input.substr( 0, 72 ); // remove 0s in the end in = fromHex( numberToHex( 36 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( res.first ); - BOOST_REQUIRE( res.second == fromHex("0x6180cde2cbbcc6b6a17efec4503a7d4316f8612f411ee171587089f770335f484003ad236c534b9afa82befc1f69533723abdb6ec2601e582b72dcfd7919338b") ); + BOOST_REQUIRE( res.second == + fromHex( "0x6180cde2cbbcc6b6a17efec4503a7d4316f8612f411ee171587089f770335f484003" + "ad236c534b9afa82befc1f69533723abdb6ec2601e582b72dcfd7919338b" ) ); input = stringToHex( "skaleConfig.sChain.nodes.0.id" ); - input = input.substr(0, 58); // remove 0s in the end + input = input.substr( 0, 58 ); // remove 0s in the end in = fromHex( numberToHex( 29 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); @@ -1782,14 +1791,14 @@ BOOST_AUTO_TEST_CASE( getConfigVariable ) { BOOST_REQUIRE( !res.first ); input = stringToHex( "skaleConfig.sChain.nodes.0.schainIndex" ); - input = input.substr(0, 76); // remove 0s in the end + input = input.substr( 0, 76 ); // remove 0s in the end in = fromHex( numberToHex( 38 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); BOOST_REQUIRE( !res.first ); input = stringToHex( "skaleConfig.sChain.nodes.0.unknownField" ); - input = input.substr(0, 78); // remove 0s in the end + input = input.substr( 0, 78 ); // remove 0s in the end in = fromHex( numberToHex( 39 ) + input ); res = exec( bytesConstRef( in.data(), in.size() ) ); @@ -1859,9 +1868,9 @@ BOOST_AUTO_TEST_CASE( fileWithHashExtension ) { auto path = dev::getDataDir() / "filestorage" / Address( ownerAddress ).hex() / fileName; bytes in = fromHex( hexAddress + numberToHex( fileName.length() ) + stringToHex( fileName ) + - numberToHex( fileSize ) ); + numberToHex( fileSize ) ); auto res = exec( bytesConstRef( in.data(), in.size() ), m_overlayFS.get() ); - BOOST_REQUIRE( res.first == false); + BOOST_REQUIRE( res.first == false ); m_overlayFS->commit(); BOOST_REQUIRE( !boost::filesystem::exists( path ) ); @@ -1907,7 +1916,7 @@ BOOST_AUTO_TEST_CASE( readMaliciousChunk ) { bytes in = fromHex( hexAddress + numberToHex( fileName.length() ) + stringToHex( fileName ) + numberToHex( 0 ) + numberToHex( fileSize ) ); auto res = exec( bytesConstRef( in.data(), in.size() ), m_overlayFS.get() ); - BOOST_REQUIRE( res.first == false); + BOOST_REQUIRE( res.first == false ); } BOOST_AUTO_TEST_CASE( getFileSize ) { @@ -1931,14 +1940,14 @@ BOOST_AUTO_TEST_CASE( getMaliciousFileSize ) { BOOST_AUTO_TEST_CASE( deleteFile ) { PrecompiledExecutor execCreate = PrecompiledRegistrar::executor( "createFile" ); - bytes inCreate = fromHex( hexAddress + numberToHex( fileName.length() ) + stringToHex( fileName ) + - numberToHex( fileSize ) ); + bytes inCreate = fromHex( hexAddress + numberToHex( fileName.length() ) + + stringToHex( fileName ) + numberToHex( fileSize ) ); execCreate( bytesConstRef( inCreate.data(), inCreate.size() ), m_overlayFS.get() ); m_overlayFS->commit(); PrecompiledExecutor execHash = PrecompiledRegistrar::executor( "calculateFileHash" ); - bytes inHash = fromHex( hexAddress + numberToHex( fileName.length() ) + stringToHex( fileName ) + - numberToHex( fileSize ) ); + bytes inHash = fromHex( hexAddress + numberToHex( fileName.length() ) + + stringToHex( fileName ) + numberToHex( fileSize ) ); execHash( bytesConstRef( inHash.data(), inHash.size() ), m_overlayFS.get() ); m_overlayFS->commit(); @@ -1993,7 +2002,8 @@ BOOST_AUTO_TEST_CASE( calculateFileHash ) { std::string fileHashName = pathToFile.string() + "._hash"; std::ofstream fileHash( fileHashName ); - std::string relativePath = pathToFile.string().substr( pathToFile.string().find( "filestorage" ) ); + std::string relativePath = + pathToFile.string().substr( pathToFile.string().find( "filestorage" ) ); dev::h256 hash = dev::sha256( relativePath ); fileHash << hash; diff --git a/test/unittests/libethereum/SkaleHost.cpp b/test/unittests/libethereum/SkaleHost.cpp index e799ea5eb..51e4eb05e 100644 --- a/test/unittests/libethereum/SkaleHost.cpp +++ b/test/unittests/libethereum/SkaleHost.cpp @@ -870,7 +870,7 @@ BOOST_AUTO_TEST_CASE( gasLimitInBlockProposal ) { wr_state.addBalance( fixture.account2.address(), client->chainParams().gasLimit * 1000 + dev::eth::ether ); wr_state.commit(); - wr_state.getOriginalDb()->createBlockSnap(2); + wr_state.getOriginalDb()->createBlockSnap( 2 ); // 1 txn with max gas Json::Value json; diff --git a/test/unittests/libethereum/StateUnitTests.cpp b/test/unittests/libethereum/StateUnitTests.cpp index e9f306cee..f7729bd09 100644 --- a/test/unittests/libethereum/StateUnitTests.cpp +++ b/test/unittests/libethereum/StateUnitTests.cpp @@ -36,20 +36,19 @@ namespace dev { namespace test { BOOST_FIXTURE_TEST_SUITE( StateUnitTests, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( Basic, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( Basic, *boost::unit_test::precondition( dev::test::run_not_express ) ) { Block s( Block::Null ); } BOOST_AUTO_TEST_CASE( LoadAccountCode ) { - Address addr{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}; + Address addr{ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }; State state( 0 ); State s = state.createStateCopyAndClearCaches(); s.createContract( addr ); - uint8_t codeData[] = {'c', 'o', 'd', 'e'}; + uint8_t codeData[] = { 'c', 'o', 'd', 'e' }; u256 version = 123; - s.setCode( addr, {std::begin( codeData ), std::end( codeData )}, version ); - s.commit(dev::eth::CommitBehaviour::RemoveEmptyAccounts ); + s.setCode( addr, { std::begin( codeData ), std::end( codeData ) }, version ); + s.commit( dev::eth::CommitBehaviour::RemoveEmptyAccounts ); auto& loadedCode = s.code( addr ); BOOST_CHECK( @@ -61,7 +60,7 @@ class AddressRangeTestFixture : public TestOutputHelperFixture { AddressRangeTestFixture() { // get some random addresses and their hashes for ( unsigned i = 0; i < addressCount; ++i ) { - Address addr{i}; + Address addr{ i }; hashToAddress[sha3( addr )] = addr; } @@ -81,10 +80,10 @@ class AddressRangeTestFixture : public TestOutputHelperFixture { BOOST_FIXTURE_TEST_SUITE( StateAddressRangeTests, AddressRangeTestFixture ) -BOOST_AUTO_TEST_CASE( addressesReturnsAllAddresses, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + addressesReturnsAllAddresses, *boost::unit_test::precondition( dev::test::run_not_express ) ) { std::pair< State::AddressMap, h256 > addressesAndNextKey = - state.addresses(h256{}, addressCount * 2 ); + state.addresses( h256{}, addressCount * 2 ); State::AddressMap addresses = addressesAndNextKey.first; BOOST_CHECK_EQUAL( addresses.size(), addressCount ); @@ -95,7 +94,7 @@ BOOST_AUTO_TEST_CASE( addressesReturnsAllAddresses, BOOST_AUTO_TEST_CASE( addressesReturnsNoMoreThanRequested ) { uint maxResults = 3; std::pair< State::AddressMap, h256 > addressesAndNextKey = - state.addresses(h256{}, maxResults ); + state.addresses( h256{}, maxResults ); State::AddressMap& addresses = addressesAndNextKey.first; h256& nextKey = addressesAndNextKey.second; @@ -106,7 +105,7 @@ BOOST_AUTO_TEST_CASE( addressesReturnsNoMoreThanRequested ) { // request next chunk std::pair< State::AddressMap, h256 > addressesAndNextKey2 = - state.addresses(nextKey, maxResults ); + state.addresses( nextKey, maxResults ); State::AddressMap& addresses2 = addressesAndNextKey2.first; BOOST_CHECK_EQUAL( addresses2.size(), maxResults ); auto itHashToAddressEnd2 = std::next( itHashToAddressEnd, maxResults ); @@ -131,15 +130,15 @@ BOOST_AUTO_TEST_CASE( addressesDoesntReturnDeletedInCache ) { } BOOST_AUTO_TEST_CASE( addressesReturnsCreatedInCache, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - State s = state; + State s = state; // create some accounts unsigned createCount = 3; std::map< h256, Address > newHashToAddress; for ( unsigned i = addressCount; i < addressCount + createCount; ++i ) { - Address addr{i}; + Address addr{ i }; newHashToAddress[sha3( addr )] = addr; } diff --git a/test/unittests/libethereum/Transaction.cpp b/test/unittests/libethereum/Transaction.cpp index 3104cc46f..4f5347187 100644 --- a/test/unittests/libethereum/Transaction.cpp +++ b/test/unittests/libethereum/Transaction.cpp @@ -33,8 +33,8 @@ using namespace dev::test; BOOST_FIXTURE_TEST_SUITE( libethereum, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( TransactionGasRequired, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + TransactionGasRequired, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // Transaction data is 0358ac39584bc98a7c979f984b03, 14 bytes Transaction tr( fromHex( "0xf86d800182521c94095e7baea6a6c7c4c2dfeb977efac326af552d870a8e0358ac39584bc98a7c9" @@ -44,25 +44,25 @@ BOOST_AUTO_TEST_CASE( TransactionGasRequired, BOOST_CHECK_EQUAL( tr.baseGasRequired( HomesteadSchedule ), 14 * 68 + 21000 ); BOOST_CHECK_EQUAL( tr.baseGasRequired( IstanbulSchedule ), 14 * 16 + 21000 ); - tr = Transaction ( - fromHex( "0x01f8d18197808504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b018" - "e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697b" - "aef842a00000000000000000000000000000000000000000000000000000000000000003a0000" - "000000000000000000000000000000000000000000000000000000000000780a08ae3a721ee02" - "cf52d85ecec934c6f46ea3e96d6355eb8ccde261e1e419885761a0234565f6d227d8eba0937b0" - "f03cb25f83aeb24c13b7a39a9ef6e80c1ea272a3c" ), - CheckTransaction::None, false, true ); + tr = Transaction( + fromHex( "0x01f8d18197808504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b018" + "e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697b" + "aef842a00000000000000000000000000000000000000000000000000000000000000003a0000" + "000000000000000000000000000000000000000000000000000000000000780a08ae3a721ee02" + "cf52d85ecec934c6f46ea3e96d6355eb8ccde261e1e419885761a0234565f6d227d8eba0937b0" + "f03cb25f83aeb24c13b7a39a9ef6e80c1ea272a3c" ), + CheckTransaction::None, false, true ); BOOST_CHECK_EQUAL( tr.baseGasRequired( HomesteadSchedule ), 14 * 68 + 21000 ); BOOST_CHECK_EQUAL( tr.baseGasRequired( IstanbulSchedule ), 14 * 16 + 21000 ); - tr = Transaction ( - fromHex( "0x02f8d78197808504a817c8008504a817c800827530947d36af85a184e220a656525fcbb9a63" - "b9ab3c12b018e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec8" - "5e40f4cb697baef842a0000000000000000000000000000000000000000000000000000000000" - "0000003a0000000000000000000000000000000000000000000000000000000000000000780a0" - "23927f0e208494bd1fd8876597899d72025167fed902e9c1c417ddd8639bb7b4a02a63ea48f7e" - "94df3a40c4a840ba98da02f13817acb5fe137d40f632e6c8ed367" ), - CheckTransaction::None, false, true ); + tr = Transaction( + fromHex( "0x02f8d78197808504a817c8008504a817c800827530947d36af85a184e220a656525fcbb9a63" + "b9ab3c12b018e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec8" + "5e40f4cb697baef842a0000000000000000000000000000000000000000000000000000000000" + "0000003a0000000000000000000000000000000000000000000000000000000000000000780a0" + "23927f0e208494bd1fd8876597899d72025167fed902e9c1c417ddd8639bb7b4a02a63ea48f7e" + "94df3a40c4a840ba98da02f13817acb5fe137d40f632e6c8ed367" ), + CheckTransaction::None, false, true ); BOOST_CHECK_EQUAL( tr.baseGasRequired( HomesteadSchedule ), 14 * 68 + 21000 ); BOOST_CHECK_EQUAL( tr.baseGasRequired( IstanbulSchedule ), 14 * 16 + 21000 ); } @@ -95,7 +95,8 @@ BOOST_AUTO_TEST_CASE( TransactionWithEmptyRecepient ) { "000003a0000000000000000000000000000000000000000000000000000000000000000780a08d795591e0eb53" "fb374a804ba3f73cf291069549d62316219811c3f7fb8cfad0a07e9d0bd7fabc8f74475624c912b5334dc49224" "b1dede6c802d52a35254bfc457" ); - BOOST_REQUIRE_THROW( Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); + BOOST_REQUIRE_THROW( + Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); txRlp = fromHex( "0x02f8c38197808504a817c8008504a817c80082753080018e0358ac39584bc98a7c979f984b03f85bf85994de" @@ -112,11 +113,12 @@ BOOST_AUTO_TEST_CASE( TransactionWithEmptyRecepient ) { "000000000000000003a0000000000000000000000000000000000000000000000000000000000000000780a0c8" "029a8b702d54c79ef18b557e755a1bfd8a4afcfcf31813790df34a6f740a95a00ceb8fdf611b4c9ff8d007d2a5" "44bc4bfae0e97a03e32b1c8b8208c82cebcafb" ); - BOOST_REQUIRE_THROW( Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); + BOOST_REQUIRE_THROW( + Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); } -BOOST_AUTO_TEST_CASE( TransactionNotReplayProtected, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + TransactionNotReplayProtected, *boost::unit_test::precondition( dev::test::run_not_express ) ) { auto txRlp = fromHex( "0xf86d800182521c94095e7baea6a6c7c4c2dfeb977efac326af552d870a8e0358ac39584bc98a7c979f984b03" "1ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3" @@ -127,31 +129,31 @@ BOOST_AUTO_TEST_CASE( TransactionNotReplayProtected, BOOST_REQUIRE( tx.toBytes() == txRlp ); txRlp = fromHex( - "0x01f8ce8504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b018e0358ac3958" - "4bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a0000000000000" - "0000000000000000000000000000000000000000000000000003a000000000000000000000000000000000" - "0000000000000000000000000000000701a0a3b1de6f2958e1e34db86438bba310637f2e799fe9768a143a" - "d87e47c33d1e6ca00e04ef9fe6bb01176c5a4c5bf4a070662478a320eaaff2895d17451c8d61d472" ); + "0x01f8ce8504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b018e0358ac3958" + "4bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a0000000000000" + "0000000000000000000000000000000000000000000000000003a000000000000000000000000000000000" + "0000000000000000000000000000000701a0a3b1de6f2958e1e34db86438bba310637f2e799fe9768a143a" + "d87e47c33d1e6ca00e04ef9fe6bb01176c5a4c5bf4a070662478a320eaaff2895d17451c8d61d472" ); BOOST_REQUIRE_THROW( Transaction( txRlp, CheckTransaction::None, false, true ), dev::BadCast ); txRlp = fromHex( - "0x02f8d5808504a817c8008504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b" - "018e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842" - "a00000000000000000000000000000000000000000000000000000000000000003a0000000000000000000" - "000000000000000000000000000000000000000000000780a023927f0e208494bd1fd8876597899d720251" - "67fed902e9c1c417ddd8639bb7b4a02a63ea48f7e94df3a40c4a840ba98da02f13817acb5fe137d40f632e" - "6c8ed367" ); + "0x02f8d5808504a817c8008504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b" + "018e0358ac39584bc98a7c979f984b03f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842" + "a00000000000000000000000000000000000000000000000000000000000000003a0000000000000000000" + "000000000000000000000000000000000000000000000780a023927f0e208494bd1fd8876597899d720251" + "67fed902e9c1c417ddd8639bb7b4a02a63ea48f7e94df3a40c4a840ba98da02f13817acb5fe137d40f632e" + "6c8ed367" ); BOOST_REQUIRE_THROW( Transaction( txRlp, CheckTransaction::None, false, true ), dev::BadCast ); } -BOOST_AUTO_TEST_CASE( TransactionChainIDMax64Bit, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + TransactionChainIDMax64Bit, *boost::unit_test::precondition( dev::test::run_not_express ) ) { // recoveryID = 0, v = 36893488147419103265 auto txRlp1 = fromHex( "0xf86e808698852840a46f82d6d894095e7baea6a6c7c4c2dfeb977efac326af552d8780808902000000000000" "0021a098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa01887321be575c8095f" "789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3" ); - Transaction tx1{txRlp1, CheckTransaction::None}; + Transaction tx1{ txRlp1, CheckTransaction::None }; tx1.checkChainId( std::numeric_limits< uint64_t >::max(), false ); // recoveryID = 1, v = 36893488147419103266 @@ -159,7 +161,7 @@ BOOST_AUTO_TEST_CASE( TransactionChainIDMax64Bit, "0xf86e808698852840a46f82d6d894095e7baea6a6c7c4c2dfeb977efac326af552d8780808902000000000000" "0022a098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa01887321be575c8095f" "789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3" ); - Transaction tx2{txRlp2, CheckTransaction::None}; + Transaction tx2{ txRlp2, CheckTransaction::None }; tx2.checkChainId( std::numeric_limits< uint64_t >::max(), false ); txRlp1 = fromHex( @@ -168,7 +170,7 @@ BOOST_AUTO_TEST_CASE( TransactionChainIDMax64Bit, "000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000" "00000000000000000000000000000000000701a0e236de02b843139aebfce593d680c06ce79cfd2f2e7f9dcac9" "fe23b38060591aa0734952245446ad42e47ec996c9a7b02973cbc8dd944c9622714416b2bef122f4" ); - tx1 = Transaction{txRlp1, CheckTransaction::None, false, true}; + tx1 = Transaction{ txRlp1, CheckTransaction::None, false, true }; tx1.checkChainId( std::numeric_limits< uint64_t >::max(), false ); txRlp1 = fromHex( @@ -178,7 +180,7 @@ BOOST_AUTO_TEST_CASE( TransactionChainIDMax64Bit, "00000000000000000000000000000000000000000000000780a0b62465e633b565f2f3632125b452d8df66d4f6" "b48b58f59da6201234e3f9ce75a0467f18ca2b64f3642cb37e7d5470bbac5fbc62c66b23a0ff955b994803fcf3" "74" ); - tx1 = Transaction{txRlp1, CheckTransaction::None, false, true}; + tx1 = Transaction{ txRlp1, CheckTransaction::None, false, true }; tx1.checkChainId( std::numeric_limits< uint64_t >::max(), false ); } @@ -205,7 +207,7 @@ BOOST_AUTO_TEST_CASE( TransactionChainIDBiggerThan64Bit ) { "8827f497375ae5c8a0795eb0b4f36fe712af5e6a8447802c9eb0913a2add86174552bf2e4b0e183feb" ); RLPStream rlpStream; auto tx = Transaction( txRlp1, CheckTransaction::None, false, true ); - auto txBytes = tx.toBytes(IncludeSignature::WithSignature); + auto txBytes = tx.toBytes( IncludeSignature::WithSignature ); BOOST_REQUIRE( txBytes != txRlp1 ); txRlp1 = fromHex( @@ -216,7 +218,7 @@ BOOST_AUTO_TEST_CASE( TransactionChainIDBiggerThan64Bit ) { "4eb34e2500c924a58ccfdc9dbeb4a04afcffcb5d1897df030d45a7eeb3ceb7c7e6fe368fc47865156b4899de32" "01c7" ); tx = Transaction( txRlp1, CheckTransaction::None, false, true ); - txBytes = tx.toBytes(IncludeSignature::WithSignature); + txBytes = tx.toBytes( IncludeSignature::WithSignature ); BOOST_REQUIRE( txBytes != txRlp1 ); } @@ -229,7 +231,7 @@ BOOST_AUTO_TEST_CASE( TransactionReplayProtected ) { tx.checkChainId( 1, false ); BOOST_REQUIRE_THROW( tx.checkChainId( 123, false ), InvalidSignature ); - auto txBytes = tx.toBytes(IncludeSignature::WithSignature); + auto txBytes = tx.toBytes( IncludeSignature::WithSignature ); BOOST_REQUIRE( txBytes == txRlp ); txRlp = fromHex( @@ -241,7 +243,7 @@ BOOST_AUTO_TEST_CASE( TransactionReplayProtected ) { tx = Transaction( txRlp, CheckTransaction::None, false, true ); tx.checkChainId( 151, false ); BOOST_REQUIRE_THROW( tx.checkChainId( 123, false ), InvalidSignature ); - + BOOST_REQUIRE( tx.toBytes() == txRlp ); txRlp = fromHex( @@ -253,13 +255,14 @@ BOOST_AUTO_TEST_CASE( TransactionReplayProtected ) { tx = Transaction( txRlp, CheckTransaction::None, false, true ); tx.checkChainId( 151, false ); BOOST_REQUIRE_THROW( tx.checkChainId( 123, false ), InvalidSignature ); - + BOOST_REQUIRE( tx.toBytes() == txRlp ); } BOOST_AUTO_TEST_CASE( accessList ) { // [ { 'address': HexBytes( "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae" ), - // 'storageKeys': ( "0x0000000000000000000000000000000000000000000000000000000000000003", "0x0000000000000000000000000000000000000000000000000000000000000007" ) } ] + // 'storageKeys': ( "0x0000000000000000000000000000000000000000000000000000000000000003", + // "0x0000000000000000000000000000000000000000000000000000000000000007" ) } ] auto txRlp = fromHex( "0x01f8c38197018504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180f85bf85994de" "0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000" @@ -291,11 +294,12 @@ BOOST_AUTO_TEST_CASE( accessList ) { "0x01f8678197808504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b01808001a01ebdc5" "46c8b85511b7ba831f47c4981069d7af972d10b7dce2c57225cb5df6a7a055ae1e84fea41d37589eb740a0a930" "17a5cd0e9f10ee50f165bf4b1b4c78ddae" ); - BOOST_REQUIRE_THROW( Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); + BOOST_REQUIRE_THROW( + Transaction( txRlp, CheckTransaction::None, false, true ), InvalidTransactionFormat ); } -BOOST_AUTO_TEST_CASE( ExecutionResultOutput, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ExecutionResultOutput, *boost::unit_test::precondition( dev::test::run_not_express ) ) { std::stringstream buffer; ExecutionResult exRes; @@ -462,8 +466,7 @@ BOOST_AUTO_TEST_CASE( GettingSignatureForUnsignedTransactionThrows, BOOST_AUTO_TEST_CASE( StreamRLPWithSignatureForUnsignedTransactionThrows ) { Transaction tx( 0, 0, 10000, Address( "a94f5374fce5edbc8e2a8697c15331677e6ebf0b" ), bytes(), 0 ); - BOOST_REQUIRE_THROW( - tx.toBytes( IncludeSignature::WithSignature ), TransactionIsUnsigned ); + BOOST_REQUIRE_THROW( tx.toBytes( IncludeSignature::WithSignature ), TransactionIsUnsigned ); } BOOST_AUTO_TEST_CASE( CheckLowSForUnsignedTransactionThrows, diff --git a/test/unittests/libethereum/TransactionQueue.cpp b/test/unittests/libethereum/TransactionQueue.cpp index ee0dd8762..fedd68f62 100644 --- a/test/unittests/libethereum/TransactionQueue.cpp +++ b/test/unittests/libethereum/TransactionQueue.cpp @@ -94,39 +94,39 @@ BOOST_AUTO_TEST_CASE( tqPriority ) { Transaction tx5( 0, gasCostHigh, gas, dest, bytes(), 2, sender2 ); txq.import( tx0 ); - BOOST_CHECK( Transactions{tx0} == txq.topTransactions( 256 ) ); + BOOST_CHECK( Transactions{ tx0 } == txq.topTransactions( 256 ) ); txq.import( tx0 ); - BOOST_CHECK( Transactions{tx0} == txq.topTransactions( 256 ) ); + BOOST_CHECK( Transactions{ tx0 } == txq.topTransactions( 256 ) ); txq.import( tx0_1 ); - BOOST_CHECK( Transactions{tx0} == txq.topTransactions( 256 ) ); // no replacement any more! + BOOST_CHECK( Transactions{ tx0 } == txq.topTransactions( 256 ) ); // no replacement any more! txq.import( tx1 ); - BOOST_CHECK( ( Transactions{tx0, tx1} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx0, tx1 } ) == txq.topTransactions( 256 ) ); txq.import( tx2 ); - BOOST_CHECK( ( Transactions{tx2, tx0, tx1} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx0, tx1 } ) == txq.topTransactions( 256 ) ); txq.import( tx3 ); - BOOST_CHECK( ( Transactions{tx2, tx0, tx1, tx3} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx0, tx1, tx3 } ) == txq.topTransactions( 256 ) ); txq.import( tx4 ); - BOOST_CHECK( ( Transactions{tx2, tx0, tx1, tx3, tx4} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx0, tx1, tx3, tx4 } ) == txq.topTransactions( 256 ) ); txq.import( tx5 ); - BOOST_CHECK( ( Transactions{tx2, tx0, tx1, tx3, tx5, tx4} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx0, tx1, tx3, tx5, tx4 } ) == txq.topTransactions( 256 ) ); txq.drop( tx0.sha3() ); // prev BOOST_CHECK( ( Transactions{tx2, tx1, tx3, tx5, tx4} ) == txq.topTransactions( 256 ) ); // now tx4 has nonce increase 1, and goes lower then tx5 and tx3 - BOOST_CHECK( ( Transactions{tx2, tx1, tx4, tx3, tx5} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx1, tx4, tx3, tx5 } ) == txq.topTransactions( 256 ) ); txq.drop( tx1.sha3() ); - BOOST_CHECK( ( Transactions{tx2, tx4, tx3, tx5} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx4, tx3, tx5 } ) == txq.topTransactions( 256 ) ); txq.drop( tx5.sha3() ); - BOOST_CHECK( ( Transactions{tx2, tx4, tx3} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx4, tx3 } ) == txq.topTransactions( 256 ) ); Transaction tx6( 0, gasCostMed, gas, dest, bytes(), 20, sender1 ); txq.import( tx6 ); - BOOST_CHECK( ( Transactions{tx2, tx4, tx3, tx6} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx4, tx3, tx6 } ) == txq.topTransactions( 256 ) ); Transaction tx7( 0, gasCostHigh, gas, dest, bytes(), 2, sender2 ); txq.import( tx7 ); // deterministic signature: hash of tx5 and tx7 will be same - BOOST_CHECK( ( Transactions{tx2, tx4, tx3, tx6} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx2, tx4, tx3, tx6 } ) == txq.topTransactions( 256 ) ); } BOOST_AUTO_TEST_CASE( tqNonceChange ) { @@ -149,29 +149,29 @@ BOOST_AUTO_TEST_CASE( tqNonceChange ) { Transaction tx23( 0, gasCost, gas, dest, bytes(), 3, sender2 ); // 1 insert 0,1,2 for both senders - txq.import( tx20 ); // h = 0 - txq.import( tx21 ); // h = 1 - txq.import( tx22 ); // h = 2 - txq.import( tx10 ); // h = 0 - txq.import( tx11 ); // h = 1 - txq.import( tx12 ); // h = 2 - txq.import( tx13 ); // h = 3 + txq.import( tx20 ); // h = 0 + txq.import( tx21 ); // h = 1 + txq.import( tx22 ); // h = 2 + txq.import( tx10 ); // h = 0 + txq.import( tx11 ); // h = 1 + txq.import( tx12 ); // h = 2 + txq.import( tx13 ); // h = 3 // 2 increase nonce for account 2 txq.dropGood( tx20 ); txq.dropGood( tx21 ); // 3 insert tx with height = 3-2=1 - txq.import( tx23 ); // h = 1 => goes with tx11 + txq.import( tx23 ); // h = 1 => goes with tx11 - Transactions top6 = txq.topTransactions(6); - for(auto tx: top6){ + Transactions top6 = txq.topTransactions( 6 ); + for ( auto tx : top6 ) { std::cout << tx.from() << " " << tx.nonce() << std::endl; } // expected BAD result [tx10], [tx11, tx23], [tx12, tx22], [tx13] !!! - // prev without sort BOOST_REQUIRE( ( Transactions{tx10, tx11, tx22, tx23, tx12, tx13 } ) == top6 ); - // with sort: - BOOST_REQUIRE( ( Transactions{tx10, tx22, tx11, tx23, tx12, tx13 } ) == top6 ); + // prev without sort BOOST_REQUIRE( ( Transactions{tx10, tx11, tx22, tx23, tx12, tx13 } ) == + // top6 ); with sort: + BOOST_REQUIRE( ( Transactions{ tx10, tx22, tx11, tx23, tx12, tx13 } ) == top6 ); } BOOST_AUTO_TEST_CASE( tqFuture ) { @@ -193,10 +193,10 @@ BOOST_AUTO_TEST_CASE( tqFuture ) { txq.import( tx2 ); txq.import( tx3 ); txq.import( tx4 ); - BOOST_CHECK( ( Transactions{tx0, tx1, tx2, tx3, tx4} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx0, tx1, tx2, tx3, tx4 } ) == txq.topTransactions( 256 ) ); txq.setFuture( tx2.sha3() ); - BOOST_CHECK( ( Transactions{tx0, tx1} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx0, tx1 } ) == txq.topTransactions( 256 ) ); // TODO disabled it temporarily!! // Transaction tx2_2( 1, gasCostMed, gas, dest, bytes(), 2, sender ); @@ -226,7 +226,7 @@ BOOST_AUTO_TEST_CASE( tqLimits ) { txq.import( tx3 ); txq.import( tx4 ); txq.import( tx5 ); - BOOST_CHECK( ( Transactions{tx5, tx0, tx1} ) == txq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx5, tx0, tx1 } ) == txq.topTransactions( 256 ) ); } BOOST_AUTO_TEST_CASE( tqImport ) { @@ -234,15 +234,15 @@ BOOST_AUTO_TEST_CASE( tqImport ) { TransactionQueue tq; h256Hash known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 0 ); - + ImportResult ir = tq.import( testTransaction.transaction().toBytes() ); BOOST_REQUIRE( ir == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 1 ); - + ir = tq.import( testTransaction.transaction().toBytes() ); BOOST_REQUIRE( ir == ImportResult::AlreadyKnown ); - + bytes rlp = testTransaction.transaction().toBytes(); rlp.at( 0 ) = 03; ir = tq.import( rlp ); @@ -254,13 +254,13 @@ BOOST_AUTO_TEST_CASE( tqImport ) { TestTransaction testTransaction2 = TestTransaction::defaultTransaction( 1, 2 ); TestTransaction testTransaction3 = TestTransaction::defaultTransaction( 1, 1 ); TestTransaction testTransaction4 = TestTransaction::defaultTransaction( 1, 4 ); - + ir = tq.import( testTransaction2.transaction().toBytes() ); BOOST_REQUIRE( ir == ImportResult::SameNonceAlreadyInQueue ); - + ir = tq.import( testTransaction3.transaction().toBytes() ); BOOST_REQUIRE( ir == ImportResult::AlreadyKnown ); - + ir = tq.import( testTransaction4.transaction().toBytes() ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 1 ); @@ -283,22 +283,22 @@ BOOST_AUTO_TEST_CASE( tqImportFuture ) { TransactionQueue::Status status = tq.status(); BOOST_REQUIRE( status.future == 0 ); - TestTransaction tx1 = TestTransaction::defaultTransaction(4); + TestTransaction tx1 = TestTransaction::defaultTransaction( 4 ); Address sender = tx1.transaction().sender(); - u256 maxNonce = tq.maxNonce(sender); + u256 maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 0 ); - u256 waiting = tq.waiting(sender); + u256 waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 0 ); - + ImportResult ir1 = tq.import( tx1.transaction().toBytes(), IfDropped::Ignore, true ); BOOST_REQUIRE( ir1 == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 1 ); status = tq.status(); BOOST_REQUIRE( status.future == 1 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 1 ); // HACK it's now allowed to repeat future transaction (can put it to current) @@ -308,65 +308,67 @@ BOOST_AUTO_TEST_CASE( tqImportFuture ) { BOOST_REQUIRE( known.size() == 1 ); status = tq.status(); BOOST_REQUIRE( status.future == 1 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 1 ); - + bytes rlp = tx1.transaction().toBytes(); rlp.at( 0 ) = 03; ir1 = tq.import( rlp, IfDropped::Ignore, true ); BOOST_REQUIRE( ir1 == ImportResult::Malformed ); - TestTransaction tx2 = TestTransaction::defaultTransaction(2); + TestTransaction tx2 = TestTransaction::defaultTransaction( 2 ); ImportResult ir2 = tq.import( tx2.transaction().toBytes(), IfDropped::Ignore, true ); BOOST_REQUIRE( ir2 == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 2 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 2 ); BOOST_CHECK( ( Transactions{} ) == tq.topTransactions( 256 ) ); - TestTransaction tx3 = TestTransaction::defaultTransaction(1); + TestTransaction tx3 = TestTransaction::defaultTransaction( 1 ); ImportResult ir3 = tq.import( tx3.transaction().toBytes(), IfDropped::Ignore, true ); BOOST_REQUIRE( ir3 == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 3 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 3 ); BOOST_CHECK( ( Transactions{} ) == tq.topTransactions( 256 ) ); - TestTransaction tx4 = TestTransaction::defaultTransaction(0); + TestTransaction tx4 = TestTransaction::defaultTransaction( 0 ); ImportResult ir4 = tq.import( tx4.transaction().toBytes(), IfDropped::Ignore ); BOOST_REQUIRE( ir4 == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 4 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 4 ); status = tq.status(); BOOST_REQUIRE( status.future == 1 ); BOOST_REQUIRE( status.current == 3 ); - BOOST_CHECK( ( Transactions{ tx4.transaction(), tx3.transaction(), tx2.transaction() } ) == tq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx4.transaction(), tx3.transaction(), tx2.transaction() } ) == + tq.topTransactions( 256 ) ); - TestTransaction tx5 = TestTransaction::defaultTransaction(3); + TestTransaction tx5 = TestTransaction::defaultTransaction( 3 ); ImportResult ir5 = tq.import( tx5.transaction().toBytes(), IfDropped::Ignore ); BOOST_REQUIRE( ir5 == ImportResult::Success ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 5 ); - maxNonce = tq.maxNonce(sender); + maxNonce = tq.maxNonce( sender ); BOOST_REQUIRE( maxNonce == 5 ); - waiting = tq.waiting(sender); + waiting = tq.waiting( sender ); BOOST_REQUIRE( waiting == 5 ); status = tq.status(); BOOST_REQUIRE( status.future == 0 ); BOOST_REQUIRE( status.current == 5 ); - BOOST_CHECK( ( Transactions{ tx4.transaction(), tx3.transaction(), tx2.transaction(), tx5.transaction(), tx1.transaction() } ) == tq.topTransactions( 256 ) ); + BOOST_CHECK( ( Transactions{ tx4.transaction(), tx3.transaction(), tx2.transaction(), + tx5.transaction(), tx1.transaction() } ) == tq.topTransactions( 256 ) ); const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; @@ -375,7 +377,7 @@ BOOST_AUTO_TEST_CASE( tqImportFuture ) { Transaction tx0( 0, gasCostMed, gas, dest, bytes(), 4, sender2 ); ImportResult ir0 = tq.import( tx0, IfDropped::Ignore, true ); BOOST_REQUIRE( ir0 == ImportResult::Success ); - waiting = tq.waiting(dev::toAddress(sender2)); + waiting = tq.waiting( dev::toAddress( sender2 ) ); BOOST_REQUIRE( waiting == 1 ); status = tq.status(); BOOST_REQUIRE( status.future == 1 ); @@ -384,7 +386,7 @@ BOOST_AUTO_TEST_CASE( tqImportFuture ) { BOOST_AUTO_TEST_CASE( dropFromFutureToCurrent ) { TransactionQueue tq; - TestTransaction tx1 = TestTransaction::defaultTransaction(1); + TestTransaction tx1 = TestTransaction::defaultTransaction( 1 ); // put transaction to future ImportResult ir1 = tq.import( tx1.transaction().toBytes(), IfDropped::Ignore, true ); @@ -401,22 +403,22 @@ BOOST_AUTO_TEST_CASE( dropFromFutureToCurrent ) { BOOST_AUTO_TEST_CASE( tqImportFutureLimits ) { dev::eth::TransactionQueue tq( 1024, 2 ); - TestTransaction tx1 = TestTransaction::defaultTransaction(3); + TestTransaction tx1 = TestTransaction::defaultTransaction( 3 ); tq.import( tx1.transaction().toBytes(), IfDropped::Ignore, true ); - TestTransaction tx2 = TestTransaction::defaultTransaction(2); + TestTransaction tx2 = TestTransaction::defaultTransaction( 2 ); tq.import( tx2.transaction().toBytes(), IfDropped::Ignore, true ); - auto waiting = tq.waiting(tx1.transaction().sender()); + auto waiting = tq.waiting( tx1.transaction().sender() ); BOOST_REQUIRE( waiting == 2 ); auto known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 2 ); - TestTransaction tx3 = TestTransaction::defaultTransaction(1); + TestTransaction tx3 = TestTransaction::defaultTransaction( 1 ); ImportResult ir = tq.import( tx3.transaction().toBytes(), IfDropped::Ignore, true ); BOOST_REQUIRE( ir == ImportResult::Success ); - waiting = tq.waiting(tx1.transaction().sender()); + waiting = tq.waiting( tx1.transaction().sender() ); BOOST_REQUIRE( waiting == 2 ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 2 ); @@ -426,15 +428,15 @@ BOOST_AUTO_TEST_CASE( tqImportFutureLimits ) { BOOST_AUTO_TEST_CASE( tqImportFutureLimits2 ) { dev::eth::TransactionQueue tq( 1024, 2 ); - TestTransaction tx1 = TestTransaction::defaultTransaction(3); + TestTransaction tx1 = TestTransaction::defaultTransaction( 3 ); tq.import( tx1.transaction().toBytes(), IfDropped::Ignore, true ); - auto waiting = tq.waiting(tx1.transaction().sender()); + auto waiting = tq.waiting( tx1.transaction().sender() ); BOOST_REQUIRE( waiting == 1 ); auto known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 1 ); auto status = tq.status(); - BOOST_REQUIRE( status.future == 1 ); + BOOST_REQUIRE( status.future == 1 ); const u256 gasCostMed = 20 * szabo; const u256 gas = 25000; @@ -444,27 +446,27 @@ BOOST_AUTO_TEST_CASE( tqImportFutureLimits2 ) { ImportResult ir0 = tq.import( tx0, IfDropped::Ignore, true ); BOOST_REQUIRE( ir0 == ImportResult::Success ); - waiting = tq.waiting(tx1.transaction().sender()); + waiting = tq.waiting( tx1.transaction().sender() ); BOOST_REQUIRE( waiting == 1 ); - waiting = tq.waiting(toAddress(sender2)); + waiting = tq.waiting( toAddress( sender2 ) ); BOOST_REQUIRE( waiting == 1 ); known = tq.knownTransactions(); - BOOST_REQUIRE( known.size() == 2 ); + BOOST_REQUIRE( known.size() == 2 ); status = tq.status(); - BOOST_REQUIRE( status.future == 2 ); + BOOST_REQUIRE( status.future == 2 ); - TestTransaction tx2 = TestTransaction::defaultTransaction(2); + TestTransaction tx2 = TestTransaction::defaultTransaction( 2 ); tq.import( tx2.transaction().toBytes(), IfDropped::Ignore, true ); - waiting = tq.waiting(tx1.transaction().sender()); + waiting = tq.waiting( tx1.transaction().sender() ); BOOST_REQUIRE( waiting == 1 ); - waiting = tq.waiting(toAddress(sender2)); + waiting = tq.waiting( toAddress( sender2 ) ); BOOST_REQUIRE( waiting == 1 ); known = tq.knownTransactions(); BOOST_REQUIRE( known.size() == 2 ); status = tq.status(); - BOOST_REQUIRE( status.future == 2 ); - + BOOST_REQUIRE( status.future == 2 ); + BOOST_CHECK( ( h256Hash{ tx0.sha3(), tx2.transaction().sha3() } ) == known ); } @@ -516,8 +518,9 @@ BOOST_AUTO_TEST_CASE( tqLimit ) { BOOST_AUTO_TEST_CASE( tqLimitBytes ) { TransactionQueue tq( 100, 100, 250, 250 ); - - unsigned maxTxCount = 250 / TestTransaction::defaultTransaction( 1 ).transaction().toBytes().size(); + + unsigned maxTxCount = + 250 / TestTransaction::defaultTransaction( 1 ).transaction().toBytes().size(); TestTransaction testTransaction = TestTransaction::defaultTransaction( 2 ); ImportResult res = tq.import( testTransaction.transaction(), IfDropped::Ignore, true ); @@ -540,7 +543,7 @@ BOOST_AUTO_TEST_CASE( tqLimitBytes ) { BOOST_REQUIRE( tq.status().future == maxTxCount ); for ( size_t i = 1; i < 10; i++ ) { - if (i == 2 || i == 3) + if ( i == 2 || i == 3 ) continue; testTransaction = TestTransaction::defaultTransaction( i ); res = tq.import( testTransaction.transaction() ); @@ -554,7 +557,7 @@ BOOST_AUTO_TEST_CASE( tqLimitBytes ) { BOOST_AUTO_TEST_CASE( tqEqueue ) { TransactionQueue tq; TestTransaction testTransaction = TestTransaction::defaultTransaction(); - + bytes payloadToDecode = testTransaction.transaction().toBytes(); RLPStream rlpStream( 2 ); diff --git a/test/unittests/libevm/VMTest.cpp b/test/unittests/libevm/VMTest.cpp index 521cdc397..bfb49e91f 100644 --- a/test/unittests/libevm/VMTest.cpp +++ b/test/unittests/libevm/VMTest.cpp @@ -17,8 +17,8 @@ along with cpp-ethereum. If not, see . */ -#include #include +#include #include #include #include @@ -51,9 +51,11 @@ BlockHeader initBlockHeader() { class Create2TestFixture : public TestOutputHelperFixture { public: - explicit Create2TestFixture( VMFace* _vm ) : vm{_vm} { state.addBalance( address, 1 * ether ); } + explicit Create2TestFixture( VMFace* _vm ) : vm{ _vm } { + state.addBalance( address, 1 * ether ); + } - virtual ~Create2TestFixture() { } + virtual ~Create2TestFixture() {} void testCreate2worksInConstantinople() { ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, @@ -85,7 +87,7 @@ class Create2TestFixture : public TestOutputHelperFixture { } void testCreate2doesntChangeContractIfAddressExists() { - state.setCode( expectedAddress, bytes{inputData}, 0 ); + state.setCode( expectedAddress, bytes{ inputData }, 0 ); ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, ref( inputData ), ref( code ), sha3( code ), version, depth, isCreate, staticCall ); @@ -168,14 +170,15 @@ class Create2TestFixture : public TestOutputHelperFixture { } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address address{KeyPair::create().address()}; + Address address{ KeyPair::create().address() }; // State state{0}; - State state = State(0).createStateCopyAndClearCaches(); + State state = State( 0 ).createStateCopyAndClearCaches(); std::unique_ptr< SealEngineFace > se{ - ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine()}; - EnvInfo envInfo{blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID}; + ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine() + }; + EnvInfo envInfo{ blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID }; u256 value = 0; u256 gasPrice = 1; @@ -203,20 +206,20 @@ class Create2TestFixture : public TestOutputHelperFixture { class LegacyVMCreate2TestFixture : public Create2TestFixture { public: - LegacyVMCreate2TestFixture() : Create2TestFixture{new LegacyVM} {} + LegacyVMCreate2TestFixture() : Create2TestFixture{ new LegacyVM } {} }; class SkaleInterpreterCreate2TestFixture : public Create2TestFixture { public: SkaleInterpreterCreate2TestFixture() - : Create2TestFixture{new EVMC{evmc_create_interpreter()}} {} + : Create2TestFixture{ new EVMC{ evmc_create_interpreter() } } {} }; class ExtcodehashTestFixture : public TestOutputHelperFixture { public: - explicit ExtcodehashTestFixture( VMFace* _vm ) : vm{_vm} { + explicit ExtcodehashTestFixture( VMFace* _vm ) : vm{ _vm } { state.addBalance( address, 1 * ether ); - state.setCode( extAddress, bytes{extCode}, 0 ); + state.setCode( extAddress, bytes{ extCode }, 0 ); } void testExtcodehashWorksInConstantinople() { @@ -258,7 +261,7 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { } void testExtCodeHashOfNonContractAccount() { - Address addressWithEmptyCode{KeyPair::create().address()}; + Address addressWithEmptyCode{ KeyPair::create().address() }; state.addBalance( addressWithEmptyCode, 1 * ether ); ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, @@ -272,7 +275,7 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { } void testExtCodeHashOfNonExistentAccount() { - Address addressNonExisting{0x1234}; + Address addressNonExisting{ 0x1234 }; ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, addressNonExisting.ref(), ref( code ), sha3( code ), version, depth, isCreate, @@ -284,7 +287,7 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { } void testExtCodeHashOfPrecomileZeroBalance() { - Address addressPrecompile{0x1}; + Address addressPrecompile{ 0x1 }; ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, addressPrecompile.ref(), ref( code ), sha3( code ), version, depth, isCreate, @@ -296,7 +299,7 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { } void testExtCodeHashOfPrecomileNonZeroBalance() { - Address addressPrecompile{0x1}; + Address addressPrecompile{ 0x1 }; state.addBalance( addressPrecompile, 1 * ether ); ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, @@ -318,7 +321,7 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { code = fromHex( "60206000600037600051803f8060005260206000f35050" ); bytes extAddressPrefixed = - bytes{1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc} + extAddress.ref(); + bytes{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc } + extAddress.ref(); ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, ref( extAddressPrefixed ), ref( code ), sha3( code ), version, depth, isCreate, @@ -329,14 +332,15 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { BOOST_REQUIRE( ret.toBytes() == sha3( extCode ).asBytes() ); } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address address{KeyPair::create().address()}; - Address extAddress{KeyPair::create().address()}; - State state{0}; + Address address{ KeyPair::create().address() }; + Address extAddress{ KeyPair::create().address() }; + State state{ 0 }; std::unique_ptr< SealEngineFace > se{ - ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine()}; - EnvInfo envInfo{blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID}; + ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine() + }; + EnvInfo envInfo{ blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID }; u256 value = 0; u256 gasPrice = 1; @@ -362,24 +366,24 @@ class ExtcodehashTestFixture : public TestOutputHelperFixture { class LegacyVMExtcodehashTestFixture : public ExtcodehashTestFixture { public: - LegacyVMExtcodehashTestFixture() : ExtcodehashTestFixture{new LegacyVM} {} + LegacyVMExtcodehashTestFixture() : ExtcodehashTestFixture{ new LegacyVM } {} }; class SkaleInterpreterExtcodehashTestFixture : public ExtcodehashTestFixture { public: SkaleInterpreterExtcodehashTestFixture() - : ExtcodehashTestFixture{new EVMC{evmc_create_interpreter()}} {} + : ExtcodehashTestFixture{ new EVMC{ evmc_create_interpreter() } } {} }; class SstoreTestFixture : public TestOutputHelperFixture { public: - explicit SstoreTestFixture( VMFace* _vm ) : vm{_vm} { + explicit SstoreTestFixture( VMFace* _vm ) : vm{ _vm } { state.addBalance( from, 1 * ether ); state.addBalance( to, 1 * ether ); } - virtual ~SstoreTestFixture() { } + virtual ~SstoreTestFixture() {} void testEip1283Case1() { testGasConsumed( "0x60006000556000600055", 0, 412, 0 ); } @@ -421,30 +425,31 @@ class SstoreTestFixture : public TestOutputHelperFixture { void testGasConsumed( std::string const& _codeStr, u256 const& _originalValue, u256 const& _expectedGasConsumed, u256 const& _expectedRefund ) { - state.setStorageLimit(1000000000); + state.setStorageLimit( 1000000000 ); state.setStorage( to, 0, _originalValue ); state.commit( dev::eth::CommitBehaviour::RemoveEmptyAccounts ); bytes const code = fromHex( _codeStr ); - ExtVM extVm( state, envInfo, se->chainParams(), to, from, from, value, gasPrice, inputData, ref( code ), - sha3( code ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), to, from, from, value, gasPrice, inputData, + ref( code ), sha3( code ), version, depth, isCreate, staticCall ); -// u256 gasBefore = gas; + // u256 gasBefore = gas; owning_bytes_ref ret = vm->exec( gas, extVm, OnOpFunc{} ); -// BOOST_CHECK_EQUAL( gasBefore - gas, _expectedGasConsumed ); -// BOOST_CHECK_EQUAL( extVm.sub.refunds, _expectedRefund ); + // BOOST_CHECK_EQUAL( gasBefore - gas, _expectedGasConsumed ); + // BOOST_CHECK_EQUAL( extVm.sub.refunds, _expectedRefund ); } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address from{KeyPair::create().address()}; - Address to{KeyPair::create().address()}; - State state = State(0).createStateCopyAndClearCaches(); + Address from{ KeyPair::create().address() }; + Address to{ KeyPair::create().address() }; + State state = State( 0 ).createStateCopyAndClearCaches(); std::unique_ptr< SealEngineFace > se{ - ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine()}; - EnvInfo envInfo{blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID}; + ChainParams( genesisInfo( Network::ConstantinopleTest ) ).createSealEngine() + }; + EnvInfo envInfo{ blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID }; u256 value = 0; u256 gasPrice = 1; @@ -460,21 +465,24 @@ class SstoreTestFixture : public TestOutputHelperFixture { class LegacyVMSstoreTestFixture : public SstoreTestFixture { public: - LegacyVMSstoreTestFixture() : SstoreTestFixture{new LegacyVM} {} + LegacyVMSstoreTestFixture() : SstoreTestFixture{ new LegacyVM } {} }; class SkaleInterpreterSstoreTestFixture : public SstoreTestFixture { public: - SkaleInterpreterSstoreTestFixture() : SstoreTestFixture{new EVMC{evmc_create_interpreter()}} {} + SkaleInterpreterSstoreTestFixture() + : SstoreTestFixture{ new EVMC{ evmc_create_interpreter() } } {} }; class ChainIDTestFixture : public TestOutputHelperFixture { public: - explicit ChainIDTestFixture( VMFace* _vm ) : vm{_vm} { state.addBalance( address, 1 * ether ); } + explicit ChainIDTestFixture( VMFace* _vm ) : vm{ _vm } { + state.addBalance( address, 1 * ether ); + } void testChainIDWorksInIstanbul() { - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( code ), sha3( code ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( code ), sha3( code ), version, depth, isCreate, staticCall ); owning_bytes_ref ret = vm->exec( gas, extVm, OnOpFunc{} ); @@ -482,8 +490,8 @@ class ChainIDTestFixture : public TestOutputHelperFixture { } void testChainIDHasCorrectCost() { - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( code ), sha3( code ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( code ), sha3( code ), version, depth, isCreate, staticCall ); bigint gasBefore; bigint gasAfter; @@ -505,20 +513,21 @@ class ChainIDTestFixture : public TestOutputHelperFixture { se.reset( ChainParams( genesisInfo( Network::ConstantinopleFixTest ) ).createSealEngine() ); version = ConstantinopleFixSchedule.accountVersion; - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( code ), sha3( code ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( code ), sha3( code ), version, depth, isCreate, staticCall ); BOOST_REQUIRE_THROW( vm->exec( gas, extVm, OnOpFunc{} ), BadInstruction ); } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address address{KeyPair::create().address()}; - State state{0}; + Address address{ KeyPair::create().address() }; + State state{ 0 }; std::unique_ptr< SealEngineFace > se{ - ChainParams( genesisInfo( Network::IstanbulTest ) ).createSealEngine()}; - EnvInfo envInfo{blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID}; + ChainParams( genesisInfo( Network::IstanbulTest ) ).createSealEngine() + }; + EnvInfo envInfo{ blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID }; u256 value = 0; u256 gasPrice = 1; @@ -538,29 +547,31 @@ class ChainIDTestFixture : public TestOutputHelperFixture { class LegacyVMChainIDTestFixture : public ChainIDTestFixture { public: - LegacyVMChainIDTestFixture() : ChainIDTestFixture{new LegacyVM} {} + LegacyVMChainIDTestFixture() : ChainIDTestFixture{ new LegacyVM } {} }; class SkaleInterpreterChainIDTestFixture : public ChainIDTestFixture { public: SkaleInterpreterChainIDTestFixture() - : ChainIDTestFixture{new EVMC{evmc_create_interpreter()}} {} + : ChainIDTestFixture{ new EVMC{ evmc_create_interpreter() } } {} }; class BalanceFixture : public TestOutputHelperFixture { public: - explicit BalanceFixture( VMFace* _vm ) : vm{_vm} { state.addBalance( address, 1 * ether ); } + explicit BalanceFixture( VMFace* _vm ) : vm{ _vm } { state.addBalance( address, 1 * ether ); } void testSelfBalanceWorksInIstanbul() { - ExtVM extVmSelfBalance( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, staticCall ); + ExtVM extVmSelfBalance( state, envInfo, se->chainParams(), address, address, address, value, + gasPrice, {}, ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, + staticCall ); owning_bytes_ref retSelfBalance = vm->exec( gas, extVmSelfBalance, OnOpFunc{} ); BOOST_REQUIRE_EQUAL( fromBigEndian< u256 >( retSelfBalance ), 1 * ether ); - ExtVM extVmBalance( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( codeBalance ), sha3( codeBalance ), version, depth, isCreate, staticCall ); + ExtVM extVmBalance( state, envInfo, se->chainParams(), address, address, address, value, + gasPrice, {}, ref( codeBalance ), sha3( codeBalance ), version, depth, isCreate, + staticCall ); owning_bytes_ref retBalance = vm->exec( gas, extVmBalance, OnOpFunc{} ); @@ -569,8 +580,9 @@ class BalanceFixture : public TestOutputHelperFixture { } void testSelfBalanceHasCorrectCost() { - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, + staticCall ); bigint gasBefore; bigint gasAfter; @@ -589,8 +601,8 @@ class BalanceFixture : public TestOutputHelperFixture { } void testBalanceHasCorrectCost() { - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( codeBalance ), sha3( codeBalance ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( codeBalance ), sha3( codeBalance ), version, depth, isCreate, staticCall ); bigint gasBefore; bigint gasAfter; @@ -612,20 +624,22 @@ class BalanceFixture : public TestOutputHelperFixture { se.reset( ChainParams( genesisInfo( Network::ConstantinopleFixTest ) ).createSealEngine() ); version = ConstantinopleFixSchedule.accountVersion; - ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( codeSelfBalance ), sha3( codeSelfBalance ), version, depth, isCreate, + staticCall ); BOOST_REQUIRE_THROW( vm->exec( gas, extVm, OnOpFunc{} ), BadInstruction ); } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address address{KeyPair::create().address()}; - State state{0}; + Address address{ KeyPair::create().address() }; + State state{ 0 }; std::unique_ptr< SealEngineFace > se{ - ChainParams( genesisInfo( Network::IstanbulTest ) ).createSealEngine()}; - EnvInfo envInfo{blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID}; + ChainParams( genesisInfo( Network::IstanbulTest ) ).createSealEngine() + }; + EnvInfo envInfo{ blockHeader, lastBlockHashes, 1, 0, se->chainParams().chainID }; u256 value = 0; u256 gasPrice = 1; @@ -651,33 +665,32 @@ class BalanceFixture : public TestOutputHelperFixture { class InstructionTestFixture : public TestOutputHelperFixture { public: - InstructionTestFixture() : vm{new LegacyVM()} { + InstructionTestFixture() : vm{ new LegacyVM() } { ChainParams cp( genesisInfo( Network::IstanbulTest ) ); - cp.sChain._patchTimestamps[static_cast(SchainPatchEnum::PushZeroPatch)] = 1; - SchainPatch::init(cp); + cp.sChain._patchTimestamps[static_cast< size_t >( SchainPatchEnum::PushZeroPatch )] = 1; + SchainPatch::init( cp ); - se.reset(cp.createSealEngine()); - envInfo = std::make_unique ( blockHeader, lastBlockHashes, 1, 0, cp.chainID ); + se.reset( cp.createSealEngine() ); + envInfo = std::make_unique< EnvInfo >( blockHeader, lastBlockHashes, 1, 0, cp.chainID ); state.addBalance( address, 1 * ether ); } void testCode( std::string const& _codeStr ) { - bytes const code = fromHex( _codeStr ); - ExtVM extVm( state, *envInfo, se->chainParams(), address, address, address, value, gasPrice, {}, - ref( code ), sha3( code ), version, depth, isCreate, staticCall ); + ExtVM extVm( state, *envInfo, se->chainParams(), address, address, address, value, gasPrice, + {}, ref( code ), sha3( code ), version, depth, isCreate, staticCall ); owning_bytes_ref ret = vm->exec( gas, extVm, OnOpFunc{} ); } - BlockHeader blockHeader{initBlockHeader()}; + BlockHeader blockHeader{ initBlockHeader() }; LastBlockHashes lastBlockHashes; - Address address{KeyPair::create().address()}; - State state{0}; + Address address{ KeyPair::create().address() }; + State state{ 0 }; std::unique_ptr< SealEngineFace > se; - std::unique_ptr envInfo; + std::unique_ptr< EnvInfo > envInfo; u256 value = 0; u256 gasPrice = 1; @@ -692,12 +705,12 @@ class InstructionTestFixture : public TestOutputHelperFixture { class LegacyVMBalanceFixture : public BalanceFixture { public: - LegacyVMBalanceFixture() : BalanceFixture{new LegacyVM} {} + LegacyVMBalanceFixture() : BalanceFixture{ new LegacyVM } {} }; class SkaleInterpreterBalanceFixture : public BalanceFixture { public: - SkaleInterpreterBalanceFixture() : BalanceFixture{new EVMC{evmc_create_interpreter()}} {} + SkaleInterpreterBalanceFixture() : BalanceFixture{ new EVMC{ evmc_create_interpreter() } } {} }; } // namespace @@ -735,7 +748,7 @@ BOOST_AUTO_TEST_CASE( LegacyVMCreate2collisionWithNonEmptyStorage, // Disable this test since SKALE cleans the storage in a different way // There is now need to ALWAYS clean contract storage, // because the only case when a contract is created on non-empty -//storage is create2 -> selfdestruct -> create2_with_the_same_sed +// storage is create2 -> selfdestruct -> create2_with_the_same_sed // Note: the combination above will cease to exist in Shanhai fork because // there will be no selfdestruct BOOST_AUTO_TEST_CASE( LegacyVMCreate2collisionWithNonEmptyStorageEmptyInitCode ) { @@ -792,71 +805,88 @@ BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE( LegacyVMSstoreSuite, LegacyVMSstoreTestFixture ) -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case1, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case1, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case1(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case2(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case3, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case3, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case3(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case4, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case4, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case4(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case5, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case5, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case5(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case6, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case6, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case6(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case7, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case7, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case7(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case8, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case8, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case8(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case9, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case9, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case9(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case10, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case10, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case10(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case11, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case11, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case11(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case12, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case12, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case12(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case13, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case13, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case13(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case14, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case14, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case14(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case15, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case15, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case15(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case16, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case16, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case16(); } -BOOST_AUTO_TEST_CASE( LegacyVMSstoreEip1283Case17, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMSstoreEip1283Case17, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testEip1283Case17(); } @@ -868,7 +898,8 @@ BOOST_AUTO_TEST_CASE( LegacyVMChainIDworksInIstanbul, testChainIDWorksInIstanbul(); } -BOOST_AUTO_TEST_CASE( LegacyVMChainIDHasCorrectCost, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + LegacyVMChainIDHasCorrectCost, *boost::unit_test::precondition( dev::test::run_not_express ) ) { testChainIDHasCorrectCost(); } @@ -903,10 +934,10 @@ BOOST_FIXTURE_TEST_SUITE( InstructionSuite, InstructionTestFixture ) BOOST_AUTO_TEST_CASE( Push0 ) { string code = "5f"; - BOOST_REQUIRE_NO_THROW( this->testCode(code) ); + BOOST_REQUIRE_NO_THROW( this->testCode( code ) ); u256s stack = vm->stack(); - BOOST_REQUIRE_EQUAL(stack.size(), 1); - BOOST_REQUIRE_EQUAL(stack[0], u256()); + BOOST_REQUIRE_EQUAL( stack.size(), 1 ); + BOOST_REQUIRE_EQUAL( stack[0], u256() ); } BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libskale/HashSnapshot.cpp b/test/unittests/libskale/HashSnapshot.cpp index 77ca9f4fe..8afd131dc 100644 --- a/test/unittests/libskale/HashSnapshot.cpp +++ b/test/unittests/libskale/HashSnapshot.cpp @@ -4,8 +4,8 @@ #include #include -#define private public // TODO refactor SnapshotManager - #include +#define private public // TODO refactor SnapshotManager +#include #undef private #include @@ -40,7 +40,8 @@ namespace dev { namespace test { class SnapshotHashAgentTest { public: - SnapshotHashAgentTest( ChainParams& _chainParams, const std::string& ipToDownloadSnapshotFrom ) { + SnapshotHashAgentTest( + ChainParams& _chainParams, const std::string& ipToDownloadSnapshotFrom ) { std::vector< libff::alt_bn128_Fr > coeffs( _chainParams.sChain.t ); for ( auto& elem : coeffs ) { @@ -64,8 +65,7 @@ class SnapshotHashAgentTest { } } - libBLS::Bls obj = - libBLS::Bls( _chainParams.sChain.t, _chainParams.sChain.nodes.size() ); + libBLS::Bls obj = libBLS::Bls( _chainParams.sChain.t, _chainParams.sChain.nodes.size() ); std::vector< size_t > idx( _chainParams.sChain.t ); for ( size_t i = 0; i < _chainParams.sChain.t; ++i ) { idx[i] = i + 1; @@ -86,7 +86,8 @@ class SnapshotHashAgentTest { isSnapshotMajorityRequired = !ipToDownloadSnapshotFrom.empty(); - this->hashAgent_.reset( new SnapshotHashAgent( _chainParams, _chainParams.nodeInfo.commonBLSPublicKeys, ipToDownloadSnapshotFrom ) ); + this->hashAgent_.reset( new SnapshotHashAgent( + _chainParams, _chainParams.nodeInfo.commonBLSPublicKeys, ipToDownloadSnapshotFrom ) ); } void fillData( const std::vector< dev::h256 >& snapshot_hashes ) { @@ -103,9 +104,7 @@ class SnapshotHashAgentTest { } } - size_t verifyAllData() const { - return this->hashAgent_->verifyAllData(); - } + size_t verifyAllData() const { return this->hashAgent_->verifyAllData(); } std::vector< size_t > getNodesToDownloadSnapshotFrom() { bool res = this->voteForHash(); @@ -166,7 +165,7 @@ class TestIpcServer : public jsonrpc::AbstractServerConnector { class TestIpcClient : public jsonrpc::IClientConnector { public: - explicit TestIpcClient( TestIpcServer& _server ) : m_server{_server} {} + explicit TestIpcClient( TestIpcServer& _server ) : m_server{ _server } {} void SendRPCMessage( const std::string& _message, std::string& _result ) override { m_server.ProcessRequest( _message, _result ); @@ -246,15 +245,17 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo dropRoot(); - int rv = system( ( "dd if=/dev/zero of=" + BTRFS_FILE_PATH + " bs=1M count=" + to_string(200) ).c_str() ); + int rv = + system( ( "dd if=/dev/zero of=" + BTRFS_FILE_PATH + " bs=1M count=" + to_string( 200 ) ) + .c_str() ); rv = system( ( "mkfs.btrfs " + BTRFS_FILE_PATH ).c_str() ); rv = system( ( "mkdir " + BTRFS_DIR_PATH ).c_str() ); gainRoot(); rv = system( ( "mount -o user_subvol_rm_allowed " + BTRFS_FILE_PATH + " " + BTRFS_DIR_PATH ) - .c_str() ); + .c_str() ); rv = chown( BTRFS_DIR_PATH.c_str(), sudo_uid, sudo_gid ); - ( void )rv; + ( void ) rv; dropRoot(); // btrfs.subvolume.create( ( BTRFS_DIR_PATH + "/vol1" ).c_str() ); @@ -284,7 +285,7 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo // true ) ); mgr.reset( new SnapshotManager( chainParams, boost::filesystem::path( BTRFS_DIR_PATH ), - {BlockChain::getChainDirName( chainParams ), "filestorage"} ) ); + { BlockChain::getChainDirName( chainParams ), "filestorage" } ) ); boost::filesystem::create_directory( boost::filesystem::path( BTRFS_DIR_PATH ) / "filestorage" / "test_dir" ); @@ -323,9 +324,9 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo newFileHash << fileHash; // TODO creation order with dependencies, gasPricer etc.. - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); - setenv("DATA_DIR", BTRFS_DIR_PATH.c_str(), 1); + setenv( "DATA_DIR", BTRFS_DIR_PATH.c_str(), 1 ); client.reset( new eth::ClientTest( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), NULL, monitor, boost::filesystem::path( BTRFS_DIR_PATH ), WithExisting::Kill ) ); @@ -339,9 +340,7 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo // wait for 1st block to prevent race conditions in UnsafeRegion std::promise< void > block_promise; auto importHandler = client->setOnBlockImport( - [&block_promise]( BlockHeader const& ) { - block_promise.set_value(); - } ); + [&block_promise]( BlockHeader const& ) { block_promise.set_value(); } ); client->injectSkaleHost(); client->startWorking(); @@ -354,16 +353,16 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo rpc::AdminEthFace /*, rpc::AdminNetFace*/, rpc::DebugFace, rpc::TestFace >; accountHolder.reset( new FixedAccountHolder( [&]() { return client.get(); }, {} ) ); - accountHolder->setAccounts( {coinbase, account2} ); + accountHolder->setAccounts( { coinbase, account2 } ); sessionManager.reset( new rpc::SessionManager() ); adminSession = - sessionManager->newSession( rpc::SessionPermissions{{rpc::Privilege::Admin}} ); + sessionManager->newSession( rpc::SessionPermissions{ { rpc::Privilege::Admin } } ); - auto ethFace = new rpc::Eth( std::string(""), *client, *accountHolder.get() ); + auto ethFace = new rpc::Eth( std::string( "" ), *client, *accountHolder.get() ); gasPricer = make_shared< eth::TrivialGasPricer >( 1000, 1000 ); - client->setGasPricer(gasPricer); + client->setGasPricer( gasPricer ); rpcServer.reset( new FullServer( ethFace /*, new rpc::Net(*web3)*/, new rpc::Web3( /*web3->clientVersion()*/ ), // TODO Add real version? @@ -385,11 +384,11 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo return; gainRoot(); [[maybe_unused]] int rv = system( ( "umount " + BTRFS_DIR_PATH ).c_str() ); - assert(rv == 0); + assert( rv == 0 ); rv = system( ( "rmdir " + BTRFS_DIR_PATH ).c_str() ); - assert(rv == 0); + assert( rv == 0 ); rv = system( ( "rm " + BTRFS_FILE_PATH ).c_str() ); - assert(rv == 0); + assert( rv == 0 ); } string sendingRawShouldFail( string const& _t ) { @@ -402,21 +401,21 @@ struct SnapshotHashingFixture : public TestOutputHelperFixture, public FixtureCo return string(); } - TransientDirectory tempDir; // ! should exist before client! + TransientDirectory tempDir; // ! should exist before client! unique_ptr< Client > client; - dev::KeyPair coinbase{KeyPair::create()}; - dev::KeyPair account2{KeyPair::create()}; + dev::KeyPair coinbase{ KeyPair::create() }; + dev::KeyPair account2{ KeyPair::create() }; unique_ptr< FixedAccountHolder > accountHolder; unique_ptr< rpc::SessionManager > sessionManager; std::shared_ptr< eth::TrivialGasPricer > gasPricer; - KeyManager keyManager{KeyManager::defaultPath(), SecretStore::defaultPath()}; + KeyManager keyManager{ KeyManager::defaultPath(), SecretStore::defaultPath() }; unique_ptr< ModularServer<> > rpcServer; unique_ptr< WebThreeStubClient > rpcClient; std::string adminSession; unique_ptr< SnapshotManager > mgr; }; -} //namespace +} // namespace BOOST_AUTO_TEST_SUITE( SnapshotSigningTestSuite ) @@ -435,14 +434,14 @@ BOOST_AUTO_TEST_CASE( PositiveTest ) { test_agent.fillData( snapshot_hashes ); BOOST_REQUIRE( test_agent.verifyAllData() == 3 ); auto res = test_agent.getNodesToDownloadSnapshotFrom(); - std::vector< size_t > excpected = {0, 1, 2}; + std::vector< size_t > excpected = { 0, 1, 2 }; BOOST_REQUIRE( res == excpected ); BOOST_REQUIRE( test_agent.getVotedHash().first == hash ); - BOOST_REQUIRE( test_agent.getVotedHash().second == - libBLS::Bls::Signing( - libBLS::ThresholdUtils::HashtoG1( - std::make_shared< std::array< uint8_t, 32 > >( hash.asArray() ) ), - test_agent.secret_as_is ) ); + BOOST_REQUIRE( + test_agent.getVotedHash().second == + libBLS::Bls::Signing( libBLS::ThresholdUtils::HashtoG1( + std::make_shared< std::array< uint8_t, 32 > >( hash.asArray() ) ), + test_agent.secret_as_is ) ); } BOOST_AUTO_TEST_CASE( WrongHash ) { @@ -461,7 +460,7 @@ BOOST_AUTO_TEST_CASE( WrongHash ) { test_agent.fillData( snapshot_hashes ); BOOST_REQUIRE( test_agent.verifyAllData() == 6 ); auto res = test_agent.getNodesToDownloadSnapshotFrom(); - std::vector< size_t > excpected = {0, 1, 2, 3, 5}; + std::vector< size_t > excpected = { 0, 1, 2, 3, 5 }; BOOST_REQUIRE( res == excpected ); } @@ -479,7 +478,7 @@ BOOST_AUTO_TEST_CASE( NotEnoughVotes ) { std::vector< dev::h256 > snapshot_hashes( chainParams.sChain.nodes.size(), hash ); snapshot_hashes[2] = dev::h256::random(); test_agent.fillData( snapshot_hashes ); - BOOST_REQUIRE( test_agent.verifyAllData() == 3); + BOOST_REQUIRE( test_agent.verifyAllData() == 3 ); BOOST_REQUIRE_THROW( test_agent.voteForHash(), NotEnoughVotesException ); } @@ -588,28 +587,31 @@ BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( SnapshotPerformanceSuite, *boost::unit_test::disabled() ) BOOST_FIXTURE_TEST_CASE( hashing_speed_db, SnapshotHashingFixture ) { -// *boost::unit_test::disabled() ) { + // *boost::unit_test::disabled() ) { // 21s // dev::db::LevelDB db("/home/dimalit/skaled/big_states/1GR_1.4GB/a77d61c4/12041/state"); // 150s - dev::db::LevelDB db("/home/dimalit/skale-node-tests/big_states/1/da3e7c49/12041/state"); + dev::db::LevelDB db( "/home/dimalit/skale-node-tests/big_states/1/da3e7c49/12041/state" ); auto t1 = std::chrono::high_resolution_clock::now(); auto hash = db.hashBase(); auto t2 = std::chrono::high_resolution_clock::now(); - std::cout << "Hash = " << hash << " Time = " << std::chrono::duration(t2-t1).count() << std::endl; + std::cout << "Hash = " << hash + << " Time = " << std::chrono::duration< double >( t2 - t1 ).count() << std::endl; } -BOOST_FIXTURE_TEST_CASE( hashing_speed_fs, SnapshotHashingFixture) { +BOOST_FIXTURE_TEST_CASE( hashing_speed_fs, SnapshotHashingFixture ) { secp256k1_sha256_t ctx; secp256k1_sha256_initialize( &ctx ); auto t1 = std::chrono::high_resolution_clock::now(); // 140s - with 4k and 1b files both - mgr->proceedFileStorageDirectory("/home/dimalit/skale-node-tests/big_states/10GBF", &ctx, false); + mgr->proceedFileStorageDirectory( + "/home/dimalit/skale-node-tests/big_states/10GBF", &ctx, false ); dev::h256 hash; secp256k1_sha256_finalize( &ctx, hash.data() ); auto t2 = std::chrono::high_resolution_clock::now(); - std::cout << "Hash = " << hash << " Time = " << std::chrono::duration(t2-t1).count() << std::endl; + std::cout << "Hash = " << hash + << " Time = " << std::chrono::duration< double >( t2 - t1 ).count() << std::endl; } diff --git a/test/unittests/libskale/SnapshotManager.cpp b/test/unittests/libskale/SnapshotManager.cpp index a50951bf0..105dc0bef 100644 --- a/test/unittests/libskale/SnapshotManager.cpp +++ b/test/unittests/libskale/SnapshotManager.cpp @@ -113,9 +113,9 @@ struct BtrfsFixture : public FixtureCommon { gainRoot(); rv = system( ( "mount -o user_subvol_rm_allowed " + BTRFS_FILE_PATH + " " + BTRFS_DIR_PATH ) - .c_str() ); + .c_str() ); rv = chown( BTRFS_DIR_PATH.c_str(), sudo_uid, sudo_gid ); - ( void )rv; + ( void ) rv; dropRoot(); // btrfs.subvolume.create( ( BTRFS_DIR_PATH + "/vol1" ).c_str() ); @@ -154,13 +154,13 @@ struct NoBtrfsFixture : public FixtureCommon { } }; -BOOST_AUTO_TEST_SUITE( BtrfsTestSuite, - *boost::unit_test::precondition( dev::test::option_all_tests ) ) +BOOST_AUTO_TEST_SUITE( + BtrfsTestSuite, *boost::unit_test::precondition( dev::test::option_all_tests ) ) BOOST_FIXTURE_TEST_CASE( SimplePositiveTest, BtrfsFixture, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); // add files 1 fs::create_directory( fs::path( BTRFS_DIR_PATH ) / "vol1" / "d11" ); @@ -169,7 +169,7 @@ BOOST_FIXTURE_TEST_CASE( SimplePositiveTest, BtrfsFixture, BOOST_REQUIRE( fs::exists( fs::path( BTRFS_DIR_PATH ) / "vol2" / "d21" ) ); auto latest0 = mgr.getLatestSnapshots(); - std::pair< int, int > expected0 { 0, 0 }; + std::pair< int, int > expected0{ 0, 0 }; BOOST_REQUIRE( latest0 == expected0 ); // create snapshot 1 and check its presense @@ -184,7 +184,7 @@ BOOST_FIXTURE_TEST_CASE( SimplePositiveTest, BtrfsFixture, BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "vol2" / "d21" ) ); auto latest1 = mgr.getLatestSnapshots(); - std::pair< int, int > expected1 { 0, 1 }; + std::pair< int, int > expected1{ 0, 1 }; BOOST_REQUIRE( latest1 == expected1 ); // create snapshot 2 and check files 1 and files 2 @@ -216,12 +216,12 @@ BOOST_FIXTURE_TEST_CASE( SimplePositiveTest, BtrfsFixture, BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "vol2" / "d21" ) ); auto latest2 = mgr.getLatestSnapshots(); - std::pair< int, int > expected2 { 1, 2 }; + std::pair< int, int > expected2{ 1, 2 }; BOOST_REQUIRE( latest2 == expected2 ); mgr.doSnapshot( 3 ); auto latest3 = mgr.getLatestSnapshots(); - std::pair< int, int > expected3 { 2, 3 }; + std::pair< int, int > expected3{ 2, 3 }; BOOST_REQUIRE( latest3 == expected3 ); BOOST_REQUIRE_NO_THROW( mgr.removeSnapshot( 1 ) ); @@ -229,16 +229,17 @@ BOOST_FIXTURE_TEST_CASE( SimplePositiveTest, BtrfsFixture, BOOST_REQUIRE_NO_THROW( mgr.removeSnapshot( 3 ) ); } -BOOST_FIXTURE_TEST_CASE( NoBtrfsTest, NoBtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - BOOST_REQUIRE_THROW( SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ), +BOOST_FIXTURE_TEST_CASE( + NoBtrfsTest, NoBtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + BOOST_REQUIRE_THROW( SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), + { "vol1", "vol2" } ), SnapshotManager::CannotPerformBtrfsOperation ); } -BOOST_FIXTURE_TEST_CASE( BadPathTest, BtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - BOOST_REQUIRE_EXCEPTION( - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ) / "_invalid", {"vol1", "vol2"} ), +BOOST_FIXTURE_TEST_CASE( + BadPathTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), + fs::path( BTRFS_DIR_PATH ) / "_invalid", { "vol1", "vol2" } ), SnapshotManager::InvalidPath, [this]( const SnapshotManager::InvalidPath& ex ) -> bool { return ex.path == fs::path( BTRFS_DIR_PATH ) / "_invalid"; } ); @@ -267,25 +268,28 @@ BOOST_FIXTURE_TEST_CASE( InaccessiblePathTest, BtrfsFixture, dropRoot(); - BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ) / "_no_w", {"vol1"} ), + BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), + fs::path( BTRFS_DIR_PATH ) / "_no_w", { "vol1" } ), SnapshotManager::CannotCreate, [this]( const SnapshotManager::CannotCreate& ex ) -> bool { return ex.path == fs::path( BTRFS_DIR_PATH ) / "_no_w" / "snapshots"; } ); - BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ) / "_no_x", {"vol1"} ), + BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), + fs::path( BTRFS_DIR_PATH ) / "_no_x", { "vol1" } ), SnapshotManager::CannotCreate, [this]( const SnapshotManager::CannotCreate& ex ) -> bool { return ex.path == fs::path( BTRFS_DIR_PATH ) / "_no_x" / "snapshots"; } ); - BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ) / "_no_r", {"vol1"} ), + BOOST_REQUIRE_EXCEPTION( SnapshotManager mgr( dev::eth::ChainParams(), + fs::path( BTRFS_DIR_PATH ) / "_no_r", { "vol1" } ), SnapshotManager::CannotCreate, [this]( const SnapshotManager::CannotCreate& ex ) -> bool { return ex.path == fs::path( BTRFS_DIR_PATH ) / "_no_x" / "snapshots"; } ); } -BOOST_FIXTURE_TEST_CASE( SnapshotTest, BtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); +BOOST_FIXTURE_TEST_CASE( + SnapshotTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); BOOST_REQUIRE_NO_THROW( mgr.doSnapshot( 2 ) ); BOOST_REQUIRE_THROW( mgr.doSnapshot( 2 ), SnapshotManager::SnapshotPresent ); @@ -312,9 +316,9 @@ BOOST_FIXTURE_TEST_CASE( SnapshotTest, BtrfsFixture, BOOST_REQUIRE_THROW( mgr.restoreSnapshot( 2 ), SnapshotManager::CannotPerformBtrfsOperation ); } -BOOST_FIXTURE_TEST_CASE( RestoreTest, BtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); +BOOST_FIXTURE_TEST_CASE( + RestoreTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); BOOST_REQUIRE_THROW( mgr.restoreSnapshot( 2 ), SnapshotManager::SnapshotAbsent ); @@ -328,9 +332,9 @@ BOOST_FIXTURE_TEST_CASE( RestoreTest, BtrfsFixture, BOOST_REQUIRE_THROW( mgr.restoreSnapshot( 2 ), SnapshotManager::CannotPerformBtrfsOperation ); } -BOOST_FIXTURE_TEST_CASE( DiffTest, BtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); +BOOST_FIXTURE_TEST_CASE( + DiffTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); mgr.doSnapshot( 2 ); fs::create_directory( fs::path( BTRFS_DIR_PATH ) / "vol1" / "dir" ); mgr.doSnapshot( 4 ); @@ -361,9 +365,9 @@ BOOST_FIXTURE_TEST_CASE( DiffTest, BtrfsFixture, // TODO Tests to check no files left in /tmp?! -BOOST_FIXTURE_TEST_CASE( ImportTest, BtrfsFixture, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); +BOOST_FIXTURE_TEST_CASE( + ImportTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); BOOST_REQUIRE_THROW( mgr.importDiff( 8 ), SnapshotManager::InvalidPath ); @@ -398,9 +402,9 @@ BOOST_FIXTURE_TEST_CASE( ImportTest, BtrfsFixture, } BOOST_FIXTURE_TEST_CASE( SnapshotRotationTest, BtrfsFixture, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); BOOST_REQUIRE_NO_THROW( mgr.doSnapshot( 1 ) ); sleep( 1 ); @@ -419,9 +423,9 @@ BOOST_FIXTURE_TEST_CASE( SnapshotRotationTest, BtrfsFixture, } BOOST_FIXTURE_TEST_CASE( DiffRotationTest, BtrfsFixture, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); fs::path diff12 = mgr.getDiffPath( 2 ); { @@ -449,9 +453,9 @@ BOOST_FIXTURE_TEST_CASE( DiffRotationTest, BtrfsFixture, } BOOST_FIXTURE_TEST_CASE( RemoveSnapshotTest, BtrfsFixture, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); mgr.doSnapshot( 1 ); mgr.doSnapshot( 2 ); @@ -469,16 +473,16 @@ BOOST_FIXTURE_TEST_CASE( RemoveSnapshotTest, BtrfsFixture, BOOST_FIXTURE_TEST_CASE( CleanupTest, BtrfsFixture, *boost::unit_test::precondition( dev::test::run_not_express ) ) { - SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), {"vol1", "vol2"} ); + SnapshotManager mgr( dev::eth::ChainParams(), fs::path( BTRFS_DIR_PATH ), { "vol1", "vol2" } ); mgr.doSnapshot( 1 ); mgr.doSnapshot( 2 ); mgr.cleanup(); - BOOST_REQUIRE( fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots") ); - BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots" / "1") ); - BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots" / "2") ); + BOOST_REQUIRE( fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots" ) ); + BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots" / "1" ) ); + BOOST_REQUIRE( !fs::exists( fs::path( BTRFS_DIR_PATH ) / "snapshots" / "2" ) ); BOOST_REQUIRE( fs::exists( fs::path( BTRFS_DIR_PATH ) / "diffs" ) ); diff --git a/test/unittests/libskutils/test_skutils_dispatch.cpp b/test/unittests/libskutils/test_skutils_dispatch.cpp index c47f13019..bb06dff49 100644 --- a/test/unittests/libskutils/test_skutils_dispatch.cpp +++ b/test/unittests/libskutils/test_skutils_dispatch.cpp @@ -1,6 +1,6 @@ #include "test_skutils_helper.h" -#include #include +#include static const bool g_bShowDetailedJobLogs = false; // useful for dispatch development only @@ -131,7 +131,8 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { // volatile size_t nCallCountOnce = 0; const uint64_t nOnceJobTimeout = 500; // milliseconds - pLoop->job_add_once( "once uppon a time", + pLoop->job_add_once( + "once uppon a time", [&]() -> void { ++nCallCountOnce; skutils::test::test_log_e( thread_prefix_str() + @@ -140,7 +141,8 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { }, skutils::dispatch::duration_from_milliseconds( nOnceJobTimeout ) ); // - pLoop->job_add_once( "bad job", + pLoop->job_add_once( + "bad job", [&]() -> void { skutils::test::test_log_e( thread_prefix_str() + cc::warn( "bad job invoked, throwing someting" ) ); @@ -157,7 +159,8 @@ BOOST_AUTO_TEST_CASE( loop_functionality_alive ) { skutils::test::test_log_e( thread_prefix_str() + cc::debug( "expecting periodical job to be invoked " ) + cc::size10( nExpectedCallCountPeriodical ) + cc::debug( " time(s), at least" ) ); - pLoop->job_add_periodic( "some periodical work", + pLoop->job_add_periodic( + "some periodical work", [&]() -> void { ++nCallCountPeriodical; skutils::test::test_log_e( thread_prefix_str() + @@ -227,18 +230,19 @@ BOOST_AUTO_TEST_CASE( domain_functionality_alive ) { // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - if( size_t( nExpectedCallCount ) == size_t( nCallCounter ) ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( + thread_prefix_str() + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + if ( size_t( nExpectedCallCount ) == size_t( nCallCounter ) ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // skutils::test::test_log_e( @@ -257,8 +261,8 @@ BOOST_AUTO_TEST_CASE( domain_functionality_alive ) { BOOST_AUTO_TEST_CASE( job_priorities_alive ) { skutils::test::test_print_header_name( "SkUtils/dispatch/job_priorities_alive" ); skutils::test::with_test_environment( [&]() { - size_t g_arrThreadCounts[] = {1, 2, 4 /*, 8, 16, 32, 64*/}; // tests with different count - // of threads + size_t g_arrThreadCounts[] = { 1, 2, 4 /*, 8, 16, 32, 64*/ }; // tests with different count + // of threads for ( const size_t& nThreadCount : g_arrThreadCounts ) { skutils::test::test_log_e( cc::trace( "# " @@ -277,17 +281,17 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { const size_t push_count_at_step_; const size_t sleep_milliseconds_; } g_arrTestDataByPriority[] = { - {"-GOD-------", SKUTILS_DISPATCH_PRIORITY_GOD, 0, 0, false, 10, 1}, - {"-BELOW-GOD-", SKUTILS_DISPATCH_PRIORITY_BELOW_GOD, 0, 0, false, 50, 1}, - {"-ABSOLUTE--", SKUTILS_DISPATCH_PRIORITY_ABSOLUTE, 0, 0, false, 800, 1}, - {"-HIGHEST---", SKUTILS_DISPATCH_PRIORITY_HIGHEST, 0, 0, false, 600, 1}, - {"-HIGH------", SKUTILS_DISPATCH_PRIORITY_HIGH, 0, 0, false, 400, 1}, - {"-NORMAL----", SKUTILS_DISPATCH_PRIORITY_NORMAL, 0, 0, false, 250, 1}, - {"-LOW-------", SKUTILS_DISPATCH_PRIORITY_LOW, 0, 0, false, 80, 1}, - {"-LOWEST----", SKUTILS_DISPATCH_PRIORITY_LOWEST, 0, 0, false, 50, 1}, - {"-TOO-LOW---", SKUTILS_DISPATCH_PRIORITY_LOWEST * 10, 0, 0, false, 40, 1}, - {"-EXTRA-LOW-", SKUTILS_DISPATCH_PRIORITY_LOWEST * 100, 0, 0, false, 30, 1}, - {"-HELL-LOW--", SKUTILS_DISPATCH_PRIORITY_LOWEST * 1000, 0, 0, false, 20, 1}, + { "-GOD-------", SKUTILS_DISPATCH_PRIORITY_GOD, 0, 0, false, 10, 1 }, + { "-BELOW-GOD-", SKUTILS_DISPATCH_PRIORITY_BELOW_GOD, 0, 0, false, 50, 1 }, + { "-ABSOLUTE--", SKUTILS_DISPATCH_PRIORITY_ABSOLUTE, 0, 0, false, 800, 1 }, + { "-HIGHEST---", SKUTILS_DISPATCH_PRIORITY_HIGHEST, 0, 0, false, 600, 1 }, + { "-HIGH------", SKUTILS_DISPATCH_PRIORITY_HIGH, 0, 0, false, 400, 1 }, + { "-NORMAL----", SKUTILS_DISPATCH_PRIORITY_NORMAL, 0, 0, false, 250, 1 }, + { "-LOW-------", SKUTILS_DISPATCH_PRIORITY_LOW, 0, 0, false, 80, 1 }, + { "-LOWEST----", SKUTILS_DISPATCH_PRIORITY_LOWEST, 0, 0, false, 50, 1 }, + { "-TOO-LOW---", SKUTILS_DISPATCH_PRIORITY_LOWEST * 10, 0, 0, false, 40, 1 }, + { "-EXTRA-LOW-", SKUTILS_DISPATCH_PRIORITY_LOWEST * 100, 0, 0, false, 30, 1 }, + { "-HELL-LOW--", SKUTILS_DISPATCH_PRIORITY_LOWEST * 1000, 0, 0, false, 20, 1 }, }; static const size_t cntPriorities = sizeof( g_arrTestDataByPriority ) / sizeof( g_arrTestDataByPriority[0] ); @@ -387,8 +391,7 @@ BOOST_AUTO_TEST_CASE( job_priorities_alive ) { g_bThreadStoppedFlag = true; skutils::test::test_log_e( thread_prefix_str() + cc::debug( "test thread is about to leave..." ) ); - } ) - .detach(); + } ).detach(); // // static const size_t nSleepMilliSeconds = 5000; @@ -596,22 +599,22 @@ BOOST_AUTO_TEST_CASE( domain_timing_functionality_alive ) { // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - if( size_t( nCallCounterOnce ) >= 1 - && size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) - && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) - && size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) - ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( + thread_prefix_str() + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + if ( size_t( nCallCounterOnce ) >= 1 && + size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) && + size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) && + size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // skutils::test::test_log_e( @@ -684,7 +687,8 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + cc::notice( "once job" ) + cc::debug( " to queue" ) ); - skutils::dispatch::once( skutils::dispatch::get_default_queue_id(), + skutils::dispatch::once( + skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallOnce ) ); bInsideCallOnce = true; @@ -699,7 +703,8 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + cc::warn( "periodic job" ) + cc::debug( " to queue" ) ); - skutils::dispatch::repeat( skutils::dispatch::get_default_queue_id(), + skutils::dispatch::repeat( + skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallPeriodic ) ); bInsideCallPeriodic = true; @@ -716,7 +721,8 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // skutils::test::test_log_e( thread_prefix_str() + cc::debug( "adding " ) + cc::note( "async job" ) + cc::debug( " to queue" ) ); - skutils::dispatch::async( skutils::dispatch::get_default_queue_id(), + skutils::dispatch::async( + skutils::dispatch::get_default_queue_id(), [&]() { BOOST_REQUIRE( !bool( bInsideCallAsync ) ); bInsideCallAsync = true; @@ -750,22 +756,22 @@ BOOST_AUTO_TEST_CASE( simple_api ) { // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - if( size_t( nCallCounterOnce ) == 1 - && size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) - && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) - && size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) - ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( thread_prefix_str() + + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + if ( size_t( nCallCounterOnce ) == 1 && + size_t( nCallCounterPeriodic ) >= size_t( nCallCounterPeriodicExpected ) && + size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) && + size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // skutils::test::test_log_e( @@ -881,23 +887,23 @@ BOOST_AUTO_TEST_CASE( auto_queues ) { // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - if( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) - && size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) - && size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) - && size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) - && size_t( nCallCounterSync ) >= size_t( nCallCounterAsync ) - ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( thread_prefix_str() + + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + if ( size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) && + size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) && + size_t( nCallCounterAsync ) >= size_t( nCallCounterAsyncExpected ) && + size_t( nCallCounterSync ) >= size_t( nCallCounterSyncExpected ) && + size_t( nCallCounterSync ) >= size_t( nCallCounterAsync ) ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // skutils::test::test_log_e( thread_prefix_str() + @@ -1017,52 +1023,53 @@ BOOST_AUTO_TEST_CASE( cross_jobs ) { } // // - bool isEverythingOKay = true; // assume good thing + bool isEverythingOKay = true; // assume good thing static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - // - // - // pre-liminary attempt to find out everything is OKay - skutils::test::test_log_e( - thread_prefix_str() + cc::info( "performing preliminary state test..." ) ); - isEverythingOKay = true; // assume good thing - for ( i = 0; i < nQueueCount; ++i ) { - bool bInside = bool( vecInside[i] ); + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( thread_prefix_str() + + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + // + // + // pre-liminary attempt to find out everything is OKay skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "queue " ) + cc::size10( i ) + - cc::debug( " is " ) + - ( ( !bInside ) ? cc::success( "OKay" ) : cc::fatal( "STILL WORKING - FAIL" ) ) ); - if ( bInside ) { - isEverythingOKay = false; - break; + thread_prefix_str() + cc::info( "performing preliminary state test..." ) ); + isEverythingOKay = true; // assume good thing + for ( i = 0; i < nQueueCount; ++i ) { + bool bInside = bool( vecInside[i] ); + skutils::test::test_log_e( thread_prefix_str() + cc::debug( "queue " ) + + cc::size10( i ) + cc::debug( " is " ) + + ( ( !bInside ) ? cc::success( "OKay" ) : + cc::fatal( "STILL WORKING - FAIL" ) ) ); + if ( bInside ) { + isEverythingOKay = false; + break; + } + skutils::dispatch::queue_id_t id_queue_current = + skutils::tools::format( "queue_%zu", i ); + skutils::dispatch::queue_ptr_t pQueue = + skutils::dispatch::get( id_queue_current, false ); + size_t nQueueJobCount = pQueue->async_job_count(); + // BOOST_REQUIRE( nQueueJobCount == 0 ); + skutils::test::test_log_e( + thread_prefix_str() + cc::debug( "worker " ) + cc::bright( id_queue_current ) + + cc::debug( " has " ) + cc::size10( nQueueJobCount ) + + cc::debug( " job(s) unfinished " ) + + ( ( nQueueJobCount == 0 ) ? cc::success( "OKay" ) : + cc::fatal( "FAIL, MUST BE ZERO" ) ) ); } - skutils::dispatch::queue_id_t id_queue_current = - skutils::tools::format( "queue_%zu", i ); - skutils::dispatch::queue_ptr_t pQueue = - skutils::dispatch::get( id_queue_current, false ); - size_t nQueueJobCount = pQueue->async_job_count(); - // BOOST_REQUIRE( nQueueJobCount == 0 ); skutils::test::test_log_e( - thread_prefix_str() + cc::debug( "worker " ) + cc::bright( id_queue_current ) + - cc::debug( " has " ) + cc::size10( nQueueJobCount ) + - cc::debug( " job(s) unfinished " ) + - ( ( nQueueJobCount == 0 ) ? cc::success( "OKay" ) : - cc::fatal( "FAIL, MUST BE ZERO" ) ) ); - } - skutils::test::test_log_e( - thread_prefix_str() + cc::info( "done preliminary state test - " ) + - ( isEverythingOKay ? cc::success( "PASSED" ) : cc::fatal( "FAILED" ) ) ); - if( isEverythingOKay ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + thread_prefix_str() + cc::info( "done preliminary state test - " ) + + ( isEverythingOKay ? cc::success( "PASSED" ) : cc::fatal( "FAILED" ) ) ); + if ( isEverythingOKay ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // if ( !isEverythingOKay ) { @@ -1144,10 +1151,10 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { log_sequence.push_back( s ); skutils::test::test_log_e( thread_prefix_str() + cc::debug( "--- " ) + cc::info( s ) ); }; - auto fnLogSequenceSize = [&]( ) -> size_t { - lock_type lock( mtx ); - size_t n = log_sequence.size(); - return n; + auto fnLogSequenceSize = [&]() -> size_t { + lock_type lock( mtx ); + size_t n = log_sequence.size(); + return n; }; const char g_strLogText_LengthyWork_begin[] = "lengthy work begin"; const char g_strLogText_LengthyWork_end[] = "lengthy work end"; @@ -1304,19 +1311,20 @@ BOOST_AUTO_TEST_CASE( enqueue_while_busy ) { // // static const size_t nSleepSeconds = 5, nWaitRoundCount = 5; - for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) { - skutils::test::test_log_e( thread_prefix_str() - + cc::warn( "waiting for test to complete in round " ) + cc::size10( nWaitRound+1 ) - + cc::warn( " of " ) + cc::size10( nWaitRoundCount ) - + cc::warn( ", will sleep " ) + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); - sleep( nSleepSeconds ); - skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + - cc::size10( nSleepSeconds ) + - cc::warn( " second(s), end of domain life time..." ) ); - size_t n = fnLogSequenceSize(); - if( n >= 10 ) - break; - } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) + for ( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++nWaitRound ) { + skutils::test::test_log_e( thread_prefix_str() + + cc::warn( "waiting for test to complete in round " ) + + cc::size10( nWaitRound + 1 ) + cc::warn( " of " ) + + cc::size10( nWaitRoundCount ) + cc::warn( ", will sleep " ) + + cc::size10( nSleepSeconds ) + cc::warn( " second(s)..." ) ); + sleep( nSleepSeconds ); + skutils::test::test_log_e( thread_prefix_str() + cc::warn( "done sleeping " ) + + cc::size10( nSleepSeconds ) + + cc::warn( " second(s), end of domain life time..." ) ); + size_t n = fnLogSequenceSize(); + if ( n >= 10 ) + break; + } // for( size_t nWaitRound = 0; nWaitRound < nWaitRoundCount; ++ nWaitRound ) // // skutils::test::test_log_e( diff --git a/test/unittests/libskutils/test_skutils_helper.cpp b/test/unittests/libskutils/test_skutils_helper.cpp index 1141a4e81..f7ab5e653 100644 --- a/test/unittests/libskutils/test_skutils_helper.cpp +++ b/test/unittests/libskutils/test_skutils_helper.cpp @@ -316,8 +316,7 @@ void test_server::run_parallel() { run(); test_log_s( cc::info( strScheme_ ) + cc::debug( " network server thread will exit" ) ); thread_is_running_ = false; - } ) - .detach(); + } ).detach(); while ( !thread_is_running_ ) std::this_thread::sleep_for( std::chrono::milliseconds( 10 ) ); test_log_s( @@ -487,8 +486,7 @@ void test_server_ws_base::run() { } test_log_s( cc::info( "Main loop" ) + cc::debug( " finish" ) ); ws_server_thread_is_running_ = false; - } ) - .detach(); + } ).detach(); test_log_s( cc::debug( "Waiting for " ) + cc::note( "test server" ) + cc::debug( " open..." ) ); while ( !bServerOpenComplete ) std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) ); @@ -615,34 +613,26 @@ bool test_server_https::isSSL() const { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -test_server_proxygen::test_server_proxygen( - const char* strBindAddr4, const char* /*strBindAddr6*/, - int nListenPortHTTP4, int /*nListenPortHTTPS4*/, int /*nListenPortHTTP6*/, int /*nListenPortHTTPS6*/, - int32_t threads, int32_t threads_limit - ) - : test_server( "proxygen", nListenPortHTTP4 ) -{ - skutils::http_pg::pg_on_request_handler_t fnHandler = [=]( const nlohmann::json& joIn, - const std::string& strOrigin, int ipVer, const std::string& strDstAddress, int nDstPort ) - -> skutils::result_of_http_request { +test_server_proxygen::test_server_proxygen( const char* strBindAddr4, const char* /*strBindAddr6*/, + int nListenPortHTTP4, int /*nListenPortHTTPS4*/, int /*nListenPortHTTP6*/, + int /*nListenPortHTTPS6*/, int32_t threads, int32_t threads_limit ) + : test_server( "proxygen", nListenPortHTTP4 ) { + skutils::http_pg::pg_on_request_handler_t fnHandler = + [=]( const nlohmann::json& joIn, const std::string& strOrigin, int ipVer, + const std::string& strDstAddress, int nDstPort ) -> skutils::result_of_http_request { skutils::result_of_http_request rslt = - implHandleHttpRequest( - joIn, - strOrigin, - ipVer, - strDstAddress, - nDstPort - ); + implHandleHttpRequest( joIn, strOrigin, ipVer, strDstAddress, nDstPort ); return rslt; }; -// auto& ssl_info = helper_ssl_info(); -// BOOST_REQUIRE( (!ssl_info.strFilePathCert_.empty()) ); -// BOOST_REQUIRE( (!ssl_info.strFilePathCert_.empty()) ); + // auto& ssl_info = helper_ssl_info(); + // BOOST_REQUIRE( (!ssl_info.strFilePathCert_.empty()) ); + // BOOST_REQUIRE( (!ssl_info.strFilePathCert_.empty()) ); skutils::http_pg::pg_accumulate_entries arr_pge = { { 4, strBindAddr4, nListenPortHTTP4, "", "", "" }, -// { 4, strBindAddr4, nListenPortHTTPS4, ssl_info.strFilePathCert_.c_str(), ssl_info.strFilePathCert_.c_str(), "" }, -// { 6, strBindAddr6, nListenPortHTTP6, "", "", "" }, -// { 6, strBindAddr6, nListenPortHTTPS6, ssl_info.strFilePathCert_.c_str(), ssl_info.strFilePathKey_.c_str(), "" }, + // { 4, strBindAddr4, nListenPortHTTPS4, ssl_info.strFilePathCert_.c_str(), + // ssl_info.strFilePathCert_.c_str(), "" }, { 6, strBindAddr6, nListenPortHTTP6, "", + // "", "" }, { 6, strBindAddr6, nListenPortHTTPS6, ssl_info.strFilePathCert_.c_str(), + // ssl_info.strFilePathKey_.c_str(), "" }, }; hProxygenServer_ = skutils::http_pg::pg_start( fnHandler, arr_pge, threads, threads_limit ); std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); @@ -659,8 +649,7 @@ void test_server_proxygen::stop() { std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); } -void test_server_proxygen::run() { -} +void test_server_proxygen::run() {} void test_server_proxygen::run_parallel() { run(); @@ -676,13 +665,11 @@ bool test_server_proxygen::isSSL() const { } skutils::result_of_http_request test_server_proxygen::implHandleHttpRequest( - const nlohmann::json & joIn, - const std::string& strOrigin, - int /*ipVer*/, - const std::string& /*strDstAddress*/, - int /*nDstPort*/ - ) { - test_log_p( cc::ws_tx_inv( "<<< PROXYGEN-TX-POST <<< " ) + cc::u( strOrigin ) + cc::ws_tx( " <<< " ) + cc::j( joIn ) ); + const nlohmann::json& joIn, const std::string& strOrigin, int /*ipVer*/, + const std::string& /*strDstAddress*/, int /*nDstPort*/ +) { + test_log_p( cc::ws_tx_inv( "<<< PROXYGEN-TX-POST <<< " ) + cc::u( strOrigin ) + + cc::ws_tx( " <<< " ) + cc::j( joIn ) ); skutils::result_of_http_request rslt; rslt.isBinary_ = false; rslt.joOut_ = joIn; @@ -1053,7 +1040,8 @@ int close_socket( socket_t sock ) { } template < typename Fn > -socket_t create_socket( int ipVer, const char* host, int port, Fn fn, int socket_flags = 0, bool is_reuse_address = true, bool is_reuse_port = false ) { +socket_t create_socket( int ipVer, const char* host, int port, Fn fn, int socket_flags = 0, + bool is_reuse_address = true, bool is_reuse_port = false ) { #ifdef _WIN32 #define SO_SYNCHRONOUS_NONALERT 0x20 #define SO_OPENTYPE 0x7008 @@ -1097,37 +1085,41 @@ void with_busy_tcp_port( fn_with_busy_tcp_port_worker_t fnWorker, socket_t fd4 = INVALID_SOCKET, fd6 = INVALID_SOCKET; try { if ( isIPv4 ) { // "0.0.0.0" - fd4 = tcp_helpers::create_socket( 4, "127.0.0.1", nSocketListenPort, + fd4 = tcp_helpers::create_socket( + 4, "127.0.0.1", nSocketListenPort, [&]( socket_t sock, struct addrinfo& ai ) -> bool { int ret = 0; - if (::bind( sock, ai.ai_addr, static_cast< int >( ai.ai_addrlen ) ) ) + if ( ::bind( sock, ai.ai_addr, static_cast< int >( ai.ai_addrlen ) ) ) throw std::runtime_error( skutils::tools::format( "Failed to bind IPv4 busy test listener to port %d,error=%d=0x%x", nSocketListenPort, ret, ret ) ); - if (::listen( sock, 5 ) ) // listen through 5 channels + if ( ::listen( sock, 5 ) ) // listen through 5 channels throw std::runtime_error( skutils::tools::format( "Failed to start IPv4 busy test listener to port %d,error=%d=0x%x", nSocketListenPort, ret, ret ) ); return true; - }, 0, is_reuse_address, is_reuse_port ); + }, + 0, is_reuse_address, is_reuse_port ); if ( fd4 == INVALID_SOCKET ) throw std::runtime_error( skutils::tools::format( "Failed to create IPv4 busy test listener on port %d", nSocketListenPort ) ); } if ( isIPv6 ) { // "0:0:0:0:0:0:0:0" - fd6 = tcp_helpers::create_socket( 6, "::1", nSocketListenPort, + fd6 = tcp_helpers::create_socket( + 6, "::1", nSocketListenPort, [&]( socket_t sock, struct addrinfo& ai ) -> bool { int ret = 0; - if (::bind( sock, ai.ai_addr, static_cast< int >( ai.ai_addrlen ) ) ) + if ( ::bind( sock, ai.ai_addr, static_cast< int >( ai.ai_addrlen ) ) ) throw std::runtime_error( skutils::tools::format( "Failed to bind IPv6 busy test listener to port %d,error=%d=0x%x", nSocketListenPort, ret, ret ) ); - if (::listen( sock, 5 ) ) // listen through 5 channels + if ( ::listen( sock, 5 ) ) // listen through 5 channels throw std::runtime_error( skutils::tools::format( "Failed to start IPv6 busy test listener to port %d,error=%d=0x%x", nSocketListenPort, ret, ret ) ); return true; - }, 0, is_reuse_address, is_reuse_port ); + }, + 0, is_reuse_address, is_reuse_port ); if ( fd6 == INVALID_SOCKET ) throw std::runtime_error( skutils::tools::format( "Failed to create IPv6 busy test listener on port %d", nSocketListenPort ) ); @@ -1192,10 +1184,8 @@ void with_test_server( pServer.reset( new test_server_http( nSocketListenPort, false ) ); BOOST_REQUIRE( !pServer->isSSL() ); } else if ( sus == "proxygen" ) { - pServer.reset( new test_server_proxygen( "127.0.0.1", "::1", - nSocketListenPort + 0, nSocketListenPort + 1, nSocketListenPort + 2, nSocketListenPort + 3, - 0, 0 - ) ); + pServer.reset( new test_server_proxygen( "127.0.0.1", "::1", nSocketListenPort + 0, + nSocketListenPort + 1, nSocketListenPort + 2, nSocketListenPort + 3, 0, 0 ) ); } else { test_log_se( cc::error( "Unknown server type: " ) + cc::warn( strServerUrlScheme ) ); throw std::runtime_error( "Unknown server type: " + strServerUrlScheme ); @@ -1384,17 +1374,17 @@ void test_print_header_name( const char* s ) { int g_nDefaultPort = 9696; int g_nDefaultPortProxygen = 8686; -std::vector< std::string > g_vecTestClientNamesA = {"Frodo", "Bilbo", "Sam", "Elrond", "Galadriel", +std::vector< std::string > g_vecTestClientNamesA = { "Frodo", "Bilbo", "Sam", "Elrond", "Galadriel", "Celeborn", "Balrog", "Anduin", "Samwise", "Gandalf", "Legolas", "Aragorn", "Gimli", "Faramir", - "Arwen", "Pippin", "Boromir", "Theoden", "Eowyn"}; -std::vector< std::string > g_vecTestClientNamesB = {"Gollum"}; + "Arwen", "Pippin", "Boromir", "Theoden", "Eowyn" }; +std::vector< std::string > g_vecTestClientNamesB = { "Gollum" }; void test_protocol_server_startup( const char* strProto, int nPort ) { // simply start/stop server std::atomic_bool was_started = false; skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( - [&]( skutils::test::test_server & /*refServer*/ ) -> void { + [&]( skutils::test::test_server& /*refServer*/ ) -> void { was_started = true; skutils::test::test_log_e( cc::success( "WE ARE HERE, SERVER ALIVE" ) ); }, @@ -1432,7 +1422,7 @@ void test_protocol_serial_calls( cc::size10( size_t( cnt_clients ) ) + cc::debug( " client(s)" ) ); skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( - [&]( skutils::test::test_server & /*refServer*/ ) -> void { + [&]( skutils::test::test_server& /*refServer*/ ) -> void { skutils::test::test_log_e( cc::sunny( "Server startup" ) ); for ( size_t i = 0; i < cnt_clients; ++i ) { std::this_thread::sleep_for( @@ -1483,7 +1473,7 @@ void test_protocol_parallel_calls( cc::size10( size_t( cnt_clients ) ) + cc::debug( " client(s)" ) ); skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( - [&]( skutils::test::test_server & /*refServer*/ ) -> void { + [&]( skutils::test::test_server& /*refServer*/ ) -> void { skutils::test::test_log_e( cc::sunny( "Server startup" ) ); skutils::test::with_test_clients( [&]( skutils::test::test_client& refClient ) -> void { @@ -1548,7 +1538,7 @@ void test_protocol_busy_port( const char* strProto, int nPort ) { [&]() -> void { // fn_with_busy_tcp_port_worker_t skutils::test::test_log_e( cc::sunny( "Busy port allocated" ) ); skutils::test::with_test_server( - [&]( skutils::test::test_server & /*refServer*/ ) -> void { + [&]( skutils::test::test_server& /*refServer*/ ) -> void { skutils::test::test_log_e( cc::sunny( "Server startup" ) ); skutils::test::test_log_sf( cc::sunny( "WE SHOULD NOT REACH THIS EXECUTION POINT" ) ); @@ -1575,43 +1565,53 @@ void test_protocol_rest_call( const char* strProto, int nPort, bool tt, bool ft skutils::test::with_test_environment( [&]() -> void { skutils::test::with_test_server( [&]( skutils::test::test_server& /*refServer*/ ) -> void { - std::string strCall( "{ \"id\": \"1234567\", \"method\": \"hello\", \"params\": {} }" ); + std::string strCall( + "{ \"id\": \"1234567\", \"method\": \"hello\", \"params\": {} }" ); nlohmann::json joCall = skutils::test::ensure_call_id_present_copy( nlohmann::json::parse( strCall ) ); - if( tt ) { + if ( tt ) { skutils::test::test_log_e( cc::normal( "\"True test\" part startup" ) ); - std::string strURL = skutils::tools::format( "%s://127.0.0.1:%d", strProto, nPort ); + std::string strURL = + skutils::tools::format( "%s://127.0.0.1:%d", strProto, nPort ); skutils::url u( strURL ); skutils::rest::client restCall( u ); skutils::rest::data_t dataOut = restCall.call( strCall ); - BOOST_REQUIRE( ! dataOut.empty() ); + BOOST_REQUIRE( !dataOut.empty() ); nlohmann::json joResult = nlohmann::json::parse( dataOut.s_ ); - skutils::test::test_log_e( cc::info( "input" ) + cc::debug( "..........." ) + cc::normal( joCall.dump() ) ); - skutils::test::test_log_e( cc::info( "output" ) + cc::debug( ".........." ) + cc::normal( joResult.dump() ) ); + skutils::test::test_log_e( cc::info( "input" ) + cc::debug( "..........." ) + + cc::normal( joCall.dump() ) ); + skutils::test::test_log_e( cc::info( "output" ) + cc::debug( ".........." ) + + cc::normal( joResult.dump() ) ); BOOST_REQUIRE( joCall.dump() == joResult.dump() ); end_1_reached = true; skutils::test::test_log_e( cc::success( "\"True test\" part finish" ) ); } - if( ft ) { + if ( ft ) { skutils::test::test_log_e( cc::normal( "\"False test\" part startup" ) ); - std::string strURL = skutils::tools::format( "%s://127.0.0.1:%d", strProto, nPort + 123 ); // incorrect port + std::string strURL = skutils::tools::format( + "%s://127.0.0.1:%d", strProto, nPort + 123 ); // incorrect port skutils::url u( strURL ); skutils::rest::client restCall( u ); skutils::rest::data_t dataOut = restCall.call( strCall ); - skutils::test::test_log_e( cc::info( "error type" ) + cc::debug( "......" ) + cc::num10( int( dataOut.ei_.et_ ) ) ); - skutils::test::test_log_e( cc::info( "error code" ) + cc::debug( "......" ) + cc::num10( int( dataOut.ei_.ec_ ) ) ); - skutils::test::test_log_e( cc::info( "error text" ) + cc::debug( "......" ) + cc::normal( dataOut.ei_.strError_ ) ); + skutils::test::test_log_e( cc::info( "error type" ) + cc::debug( "......" ) + + cc::num10( int( dataOut.ei_.et_ ) ) ); + skutils::test::test_log_e( cc::info( "error code" ) + cc::debug( "......" ) + + cc::num10( int( dataOut.ei_.ec_ ) ) ); + skutils::test::test_log_e( cc::info( "error text" ) + cc::debug( "......" ) + + cc::normal( dataOut.ei_.strError_ ) ); BOOST_REQUIRE( dataOut.empty() ); - BOOST_REQUIRE( dataOut.ei_.et_ != skutils::http::common_network_exception::error_type::et_no_error ); - BOOST_REQUIRE( ! dataOut.ei_.strError_.empty() ); + BOOST_REQUIRE( + dataOut.ei_.et_ != + skutils::http::common_network_exception::error_type::et_no_error ); + BOOST_REQUIRE( !dataOut.ei_.strError_.empty() ); end_2_reached = true; skutils::test::test_log_e( cc::success( "\"False test\" part finish" ) ); } }, strProto, nPort ); } ); - BOOST_REQUIRE( end_1_reached || (!tt) ); - BOOST_REQUIRE( end_2_reached || (!ft) ); + BOOST_REQUIRE( end_1_reached || ( !tt ) ); + BOOST_REQUIRE( end_2_reached || ( !ft ) ); } }; // namespace test diff --git a/test/unittests/libskutils/test_skutils_helper.h b/test/unittests/libskutils/test_skutils_helper.h index b3955742a..0604a2ca0 100644 --- a/test/unittests/libskutils/test_skutils_helper.h +++ b/test/unittests/libskutils/test_skutils_helper.h @@ -10,12 +10,12 @@ #include #include #include +#include #include +#include #include #include #include -#include -#include #include #include @@ -232,25 +232,21 @@ class test_server_https : public test_server_http_base { class test_server_proxygen : public test_server { skutils::http_pg::wrapped_proxygen_server_handle hProxygenServer_ = nullptr; + public: - test_server_proxygen( const char* strBindAddr4, const char* strBindAddr6, - int nListenPortHTTP4, int nListenPortHTTPS4, int nListenPortHTTP6, int nListenPortHTTPS6, - int32_t threads, int32_t threads_limit - ); + test_server_proxygen( const char* strBindAddr4, const char* strBindAddr6, int nListenPortHTTP4, + int nListenPortHTTPS4, int nListenPortHTTP6, int nListenPortHTTPS6, int32_t threads, + int32_t threads_limit ); virtual ~test_server_proxygen(); void stop() override; void run() override; void run_parallel() override; void check_can_listen() override; virtual bool isSSL() const override; + protected: - skutils::result_of_http_request implHandleHttpRequest( - const nlohmann::json & joIn, - const std::string& strOrigin, - int ipVer, - const std::string& strDstAddress, - int nDstPort - ); + skutils::result_of_http_request implHandleHttpRequest( const nlohmann::json& joIn, + const std::string& strOrigin, int ipVer, const std::string& strDstAddress, int nDstPort ); }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/test/unittests/libskutils/test_skutils_http.cpp b/test/unittests/libskutils/test_skutils_http.cpp index 01e503151..240a9b1d6 100644 --- a/test/unittests/libskutils/test_skutils_http.cpp +++ b/test/unittests/libskutils/test_skutils_http.cpp @@ -1,7 +1,6 @@ -#include #include "test_skutils_helper.h" -#include #include +#include BOOST_AUTO_TEST_SUITE( SkUtils ) BOOST_AUTO_TEST_SUITE( http, *boost::unit_test::precondition( dev::test::option_all_tests ) ) @@ -16,7 +15,8 @@ BOOST_AUTO_TEST_CASE( http_server_startup_sync ) { } BOOST_AUTO_TEST_CASE( proxygen_server_startup ) { skutils::test::test_print_header_name( "SkUtils/proxygen/proxygen_server_startup" ); - skutils::test::test_protocol_server_startup( "proxygen", skutils::test::g_nDefaultPortProxygen ); + skutils::test::test_protocol_server_startup( + "proxygen", skutils::test::g_nDefaultPortProxygen ); } BOOST_AUTO_TEST_CASE( http_single_call ) { @@ -68,7 +68,7 @@ BOOST_AUTO_TEST_CASE( http_busy_port ) { skutils::test::test_print_header_name( "SkUtils/http/http_busy_port" ); skutils::test::test_protocol_busy_port( "http", skutils::test::g_nDefaultPort ); } -//BOOST_AUTO_TEST_CASE( proxygen_busy_port ) { +// BOOST_AUTO_TEST_CASE( proxygen_busy_port ) { // skutils::test::test_print_header_name( "SkUtils/proxygen/proxygen_busy_port" ); // skutils::test::test_protocol_busy_port( "proxygen", skutils::test::g_nDefaultPortProxygen ); //} diff --git a/test/unittests/libskutils/test_skutils_rest.cpp b/test/unittests/libskutils/test_skutils_rest.cpp index dda07a4ee..386446899 100644 --- a/test/unittests/libskutils/test_skutils_rest.cpp +++ b/test/unittests/libskutils/test_skutils_rest.cpp @@ -19,9 +19,10 @@ BOOST_AUTO_TEST_CASE( ws ) { skutils::test::test_protocol_rest_call( "ws", skutils::test::g_nDefaultPort, true, false ); } -//BOOST_AUTO_TEST_CASE( wss ) { +// BOOST_AUTO_TEST_CASE( wss ) { // skutils::test::test_print_header_name( "SkUtils/rest/call/wss" ); -// skutils::test::test_protocol_rest_call( "wss", skutils::test::g_nDefaultPort + 123, true, false ); +// skutils::test::test_protocol_rest_call( "wss", skutils::test::g_nDefaultPort + 123, true, +// false ); //} BOOST_AUTO_TEST_SUITE_END() diff --git a/test/unittests/libskutils/test_skutils_unddos.cpp b/test/unittests/libskutils/test_skutils_unddos.cpp index be1a1a55a..6f11116ed 100644 --- a/test/unittests/libskutils/test_skutils_unddos.cpp +++ b/test/unittests/libskutils/test_skutils_unddos.cpp @@ -1,6 +1,6 @@ #include "test_skutils_helper.h" -#include #include +#include BOOST_AUTO_TEST_SUITE( SkUtils ) BOOST_AUTO_TEST_SUITE( unddos, *boost::unit_test::precondition( dev::test::option_all_tests ) ) @@ -9,12 +9,12 @@ static skutils::unddos::settings compose_test_unddos_settings() { skutils::unddos::settings settings; // skutils::unddos::origin_dos_limits oe1; - oe1.m_originWildcards.push_back("11.11.11.11" ); + oe1.m_originWildcards.push_back( "11.11.11.11" ); oe1.m_defaultMaxCallsPerSec = 3; oe1.m_defaultMaxCallsPerMin = 10; oe1.m_maxWSConn = 2; - oe1.m_banPerSecDuration = skutils::unddos::duration(5 ); - oe1.m_banPerMinDuration = skutils::unddos::duration(10 ); + oe1.m_banPerSecDuration = skutils::unddos::duration( 5 ); + oe1.m_banPerMinDuration = skutils::unddos::duration( 10 ); skutils::unddos::origin_dos_limits oe2; oe2.load_unlim_for_localhost_only(); return settings; @@ -24,34 +24,45 @@ BOOST_AUTO_TEST_CASE( basic_counting ) { skutils::unddos::algorithm unddos; unddos.set_settings( compose_test_unddos_settings() ); skutils::unddos::time_tick_mark ttmNow = skutils::unddos::now_tick_mark(); - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - ++ ttmNow; - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + ++ttmNow; + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); ttmNow += 60; - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); ttmNow += 60; - for( size_t i = 0; i < 10; ++ i ) { - ++ ttmNow; - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + for ( size_t i = 0; i < 10; ++i ) { + ++ttmNow; + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); } - BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_call_from_origin( "11.11.11.11", ttmNow ) != + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); } BOOST_AUTO_TEST_CASE( ws_conn_counting ) { skutils::unddos::algorithm unddos; unddos.set_settings( compose_test_unddos_settings() ); - BOOST_REQUIRE( ! unddos.unregister_ws_conn_for_origin( "11.11.11.11" ) ); - BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); - BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) != skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( !unddos.unregister_ws_conn_for_origin( "11.11.11.11" ) ); + BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) != + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); BOOST_REQUIRE( unddos.unregister_ws_conn_for_origin( "11.11.11.11" ) ); BOOST_REQUIRE( unddos.unregister_ws_conn_for_origin( "11.11.11.11" ) ); - BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); + BOOST_REQUIRE( unddos.register_ws_conn_for_origin( "11.11.11.11" ) == + skutils::unddos::e_high_load_detection_result_t::ehldr_no_error ); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() - diff --git a/test/unittests/libskutils/test_skutils_ws.cpp b/test/unittests/libskutils/test_skutils_ws.cpp index 9d5f9d51f..a3ce34af2 100644 --- a/test/unittests/libskutils/test_skutils_ws.cpp +++ b/test/unittests/libskutils/test_skutils_ws.cpp @@ -1,7 +1,6 @@ -#include #include "test_skutils_helper.h" -#include #include +#include BOOST_AUTO_TEST_SUITE( SkUtils ) BOOST_AUTO_TEST_SUITE( ws, *boost::unit_test::precondition( dev::test::option_all_tests ) ) diff --git a/test/unittests/libtesteth/testHelperTest.cpp b/test/unittests/libtesteth/testHelperTest.cpp index 2ed17b314..2307d1337 100644 --- a/test/unittests/libtesteth/testHelperTest.cpp +++ b/test/unittests/libtesteth/testHelperTest.cpp @@ -29,25 +29,25 @@ using namespace dev::test; BOOST_FIXTURE_TEST_SUITE( TestHelperSuite, TestOutputHelperFixture ) BOOST_AUTO_TEST_SUITE( TranslateNetworks ) -BOOST_AUTO_TEST_CASE( translateNetworks_gteIstanbul, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {">=Istanbul"}; +BOOST_AUTO_TEST_CASE( + translateNetworks_gteIstanbul, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + set< string > networks = { ">=Istanbul" }; networks = test::translateNetworks( networks ); BOOST_CHECK( contains( networks, "Istanbul" ) ); } BOOST_AUTO_TEST_CASE( translateNetworks_gtConstantinople, - + *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {">Constantinople"}; + set< string > networks = { ">Constantinople" }; networks = test::translateNetworks( networks ); BOOST_CHECK( !contains( networks, "Constantinople" ) ); BOOST_CHECK( contains( networks, "ConstantinopleFix" ) ); } -BOOST_AUTO_TEST_CASE( translateNetworks_gtHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {"Frontier", ">Homestead"}; +BOOST_AUTO_TEST_CASE( + translateNetworks_gtHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + set< string > networks = { "Frontier", ">Homestead" }; networks = test::translateNetworks( networks ); BOOST_REQUIRE( networks.count( "Frontier" ) > 0 ); BOOST_REQUIRE( networks.count( "Homestead" ) == 0 ); @@ -57,17 +57,17 @@ BOOST_AUTO_TEST_CASE( translateNetworks_gtHomestead, } } -BOOST_AUTO_TEST_CASE( translateNetworks_geHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {"Frontier", ">=Homestead"}; +BOOST_AUTO_TEST_CASE( + translateNetworks_geHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + set< string > networks = { "Frontier", ">=Homestead" }; networks = test::translateNetworks( networks ); for ( auto const& net : test::getNetworks() ) BOOST_REQUIRE( networks.count( test::netIdToString( net ) ) > 0 ); } -BOOST_AUTO_TEST_CASE( translateNetworks_ltHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {" networks = { " 0 ); for ( auto const& net : test::getNetworks() ) { @@ -76,9 +76,9 @@ BOOST_AUTO_TEST_CASE( translateNetworks_ltHomestead, } } -BOOST_AUTO_TEST_CASE( translateNetworks_ltTest, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {"<=EIP150", " networks = { "<=EIP150", " 0 ); BOOST_REQUIRE( networks.count( "Homestead" ) > 0 ); @@ -87,9 +87,9 @@ BOOST_AUTO_TEST_CASE( translateNetworks_ltTest, BOOST_REQUIRE( networks.count( "Byzantium" ) == 0 ); } -BOOST_AUTO_TEST_CASE( translateNetworks_leHomestead, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {"<=Homestead"}; +BOOST_AUTO_TEST_CASE( + translateNetworks_leHomestead, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + set< string > networks = { "<=Homestead" }; networks = test::translateNetworks( networks ); BOOST_REQUIRE( networks.count( "Frontier" ) > 0 ); BOOST_REQUIRE( networks.count( "Homestead" ) > 0 ); @@ -99,9 +99,9 @@ BOOST_AUTO_TEST_CASE( translateNetworks_leHomestead, } } -BOOST_AUTO_TEST_CASE( translateNetworks_leFrontier, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - set< string > networks = {"<=Frontier"}; +BOOST_AUTO_TEST_CASE( + translateNetworks_leFrontier, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + set< string > networks = { "<=Frontier" }; networks = test::translateNetworks( networks ); BOOST_REQUIRE( networks.count( "Frontier" ) > 0 ); for ( auto const& net : test::getNetworks() ) { @@ -112,90 +112,90 @@ BOOST_AUTO_TEST_CASE( translateNetworks_leFrontier, BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE( TestHelper ) -BOOST_AUTO_TEST_CASE( levenshteinDistance_similar, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_similar, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "someword"; char const* word2 = "soemword"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 2 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_similar2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_similar2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "sOmeWord"; char const* word2 = "someword"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 2 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_similar3, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_similar3, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "sOmeWoRd"; char const* word2 = "someword"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 3 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_similar4, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_similar4, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "sOmeWoRd"; char const* word2 = "soemword"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 5 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_AgtB, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_AgtB, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "someword"; char const* word2 = "other"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 4 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_AgtB2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_AgtB2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "some long sentence here"; char const* word2 = "other shorter phrase"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 14 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_BgtA, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_BgtA, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "other"; char const* word2 = "someword"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 4 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_BgtA2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_BgtA2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "other shorter phrase"; char const* word2 = "some long sentence here"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 14 ); } -BOOST_AUTO_TEST_CASE( levenshteinDistance_different, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + levenshteinDistance_different, *boost::unit_test::precondition( dev::test::run_not_express ) ) { char const* word1 = "abdefg"; char const* word2 = "hijklmn"; size_t distance = test::levenshteinDistance( word1, strlen( word1 ), word2, strlen( word2 ) ); BOOST_CHECK_EQUAL( distance, 6 ); } -BOOST_AUTO_TEST_CASE( getTestSuggestions, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector< string > const testList = { - "test1", "test2", "BlockSuite", "BlockSuite/TestCase", "GeneralBlockchainTests"}; +BOOST_AUTO_TEST_CASE( + getTestSuggestions, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + vector< string > const testList = { "test1", "test2", "BlockSuite", "BlockSuite/TestCase", + "GeneralBlockchainTests" }; auto list = test::testSuggestions( testList, "blocksuit" ); BOOST_CHECK( test::inArray( list, string( "BlockSuite" ) ) ); } -BOOST_AUTO_TEST_CASE( getTestSuggestions2, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { - vector< string > const testList = {"test1", "test2", "BlockSuite", "BlockSuite/TestCase", - "GeneralBlockchainTests", "GeneralStateTests/stExample", "BCGeneralStateTests/stExample"}; +BOOST_AUTO_TEST_CASE( + getTestSuggestions2, *boost::unit_test::precondition( dev::test::run_not_express ) ) { + vector< string > const testList = { "test1", "test2", "BlockSuite", "BlockSuite/TestCase", + "GeneralBlockchainTests", "GeneralStateTests/stExample", "BCGeneralStateTests/stExample" }; auto list = test::testSuggestions( testList, "GeneralStateTests/stExample2" ); BOOST_CHECK( test::inArray( list, string( "GeneralStateTests/stExample" ) ) ); diff --git a/test/unittests/libweb3core/LevelDBHash.cpp b/test/unittests/libweb3core/LevelDBHash.cpp index f7c444dcd..f35a77275 100644 --- a/test/unittests/libweb3core/LevelDBHash.cpp +++ b/test/unittests/libweb3core/LevelDBHash.cpp @@ -9,7 +9,7 @@ BOOST_AUTO_TEST_SUITE( LevelDBHashBase ) BOOST_AUTO_TEST_CASE( hash ) { dev::TransientDirectory td; - std::vector< std::pair< std::string, std::string > > randomKeysValues(123); + std::vector< std::pair< std::string, std::string > > randomKeysValues( 123 ); dev::h256 hash; { @@ -22,7 +22,7 @@ BOOST_AUTO_TEST_CASE( hash ) { for ( size_t i = 0; i < 123; ++i ) { std::string key = dev::h256::random().hex(); std::string value = dev::h256::random().hex(); - db->insert( dev::db::Slice(key), dev::db::Slice(value) ); + db->insert( dev::db::Slice( key ), dev::db::Slice( value ) ); randomKeysValues[i] = { key, value }; } @@ -41,7 +41,7 @@ BOOST_AUTO_TEST_CASE( hash ) { for ( size_t i = 0; i < 123; ++i ) { std::string key = randomKeysValues[i].first; std::string value = randomKeysValues[i].second; - db_copy->insert( dev::db::Slice(key), dev::db::Slice(value) ); + db_copy->insert( dev::db::Slice( key ), dev::db::Slice( value ) ); } db_copy->insert( dev::db::Slice( "PieceUsageBytes" ), dev::db::Slice( "123456789" ) ); db_copy->insert( dev::db::Slice( "ppieceUsageBytes" ), dev::db::Slice( "123456789" ) ); @@ -63,7 +63,7 @@ BOOST_AUTO_TEST_CASE( hash ) { for ( size_t i = 0; i < 123; ++i ) { std::string key = randomKeysValues[i].first; std::string value = randomKeysValues[i].second; - db_copy->insert( dev::db::Slice(key), dev::db::Slice(value) ); + db_copy->insert( dev::db::Slice( key ), dev::db::Slice( value ) ); } db_copy->insert( dev::db::Slice( "PieceUsageBytes" ), dev::db::Slice( "123456789" ) ); @@ -76,9 +76,10 @@ BOOST_AUTO_TEST_CASE( hash ) { std::string lastHashedKey = "start"; bool isContinue = true; while ( isContinue ) { - std::unique_ptr< dev::db::LevelDB > m_db( new dev::db::LevelDB( td.path(), - dev::db::LevelDB::defaultSnapshotReadOptions(), dev::db::LevelDB::defaultWriteOptions(), - dev::db::LevelDB::defaultSnapshotDBOptions() ) ); + std::unique_ptr< dev::db::LevelDB > m_db( + new dev::db::LevelDB( td.path(), dev::db::LevelDB::defaultSnapshotReadOptions(), + dev::db::LevelDB::defaultWriteOptions(), + dev::db::LevelDB::defaultSnapshotDBOptions() ) ); isContinue = m_db->hashBasePartially( &dbCtx, lastHashedKey ); } @@ -99,7 +100,7 @@ BOOST_AUTO_TEST_CASE( hash ) { for ( size_t i = 0; i < 123; ++i ) { std::string key = dev::h256::random().hex(); std::string value = dev::h256::random().hex(); - db_diff->insert( dev::db::Slice(key), dev::db::Slice(value) ); + db_diff->insert( dev::db::Slice( key ), dev::db::Slice( value ) ); } hash_diff = db_diff->hashBase(); diff --git a/test/unittests/libweb3core/memorydb.cpp b/test/unittests/libweb3core/memorydb.cpp index 1e1608b58..7e7e385f6 100644 --- a/test/unittests/libweb3core/memorydb.cpp +++ b/test/unittests/libweb3core/memorydb.cpp @@ -38,8 +38,7 @@ namespace test {} BOOST_FIXTURE_TEST_SUITE( memDB, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( kill, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( kill, *boost::unit_test::precondition( dev::test::run_not_express ) ) { MemoryDB myDB; BOOST_CHECK( myDB.get().empty() ); bytes value = fromHex( "43" ); @@ -50,8 +49,8 @@ BOOST_AUTO_TEST_CASE( kill, BOOST_CHECK( myDB.kill( h256( 42 ) ) ); } -BOOST_AUTO_TEST_CASE( purgeMainMem, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + purgeMainMem, *boost::unit_test::precondition( dev::test::run_not_express ) ) { MemoryDB myDB; BOOST_CHECK( myDB.get().empty() ); string const value = "\x43"; @@ -77,8 +76,8 @@ BOOST_AUTO_TEST_CASE( purgeMainMem, BOOST_CHECK_EQUAL( myDB.get().size(), 0 ); } -BOOST_AUTO_TEST_CASE( purgeMainMem_Refs, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + purgeMainMem_Refs, *boost::unit_test::precondition( dev::test::run_not_express ) ) { MemoryDB myDB; { EnforceRefs enforceRefs( myDB, true ); @@ -133,8 +132,7 @@ BOOST_AUTO_TEST_CASE( purgeMainMem_Refs, BOOST_CHECK_EQUAL( myDB.get().size(), 0 ); } -BOOST_AUTO_TEST_CASE( purgeAuxMem, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( purgeAuxMem, *boost::unit_test::precondition( dev::test::run_not_express ) ) { class AuxMemDB : public MemoryDB { public: std::unordered_map< h256, std::pair< bytes, bool > > getAux() { return m_aux; } @@ -159,8 +157,7 @@ BOOST_AUTO_TEST_CASE( purgeAuxMem, BOOST_CHECK_EQUAL( myDB.getAux().size(), 0 ); } -BOOST_AUTO_TEST_CASE( copy, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( copy, *boost::unit_test::precondition( dev::test::run_not_express ) ) { MemoryDB myDB; BOOST_CHECK( myDB.get().empty() ); bytes value = fromHex( "43" ); @@ -178,8 +175,7 @@ BOOST_AUTO_TEST_CASE( copy, BOOST_CHECK( myDB.keys() != copyToDB.keys() ); } -BOOST_AUTO_TEST_CASE( lookUp, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( lookUp, *boost::unit_test::precondition( dev::test::run_not_express ) ) { MemoryDB myDB; BOOST_CHECK( myDB.get().empty() ); string const value = "\x43"; diff --git a/test/unittests/libweb3jsonrpc/AccountHolder.cpp b/test/unittests/libweb3jsonrpc/AccountHolder.cpp index bdc547071..70aac620b 100644 --- a/test/unittests/libweb3jsonrpc/AccountHolder.cpp +++ b/test/unittests/libweb3jsonrpc/AccountHolder.cpp @@ -34,7 +34,8 @@ namespace test { BOOST_FIXTURE_TEST_SUITE( AccountHolderTest, TestOutputHelperFixture ) -BOOST_AUTO_TEST_CASE( ProxyAccountUseCase, *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + ProxyAccountUseCase, *boost::unit_test::precondition( dev::test::run_not_express ) ) { FixedAccountHolder h = FixedAccountHolder( function< Interface*() >(), vector< KeyPair >() ); BOOST_CHECK( h.allAccounts().empty() ); diff --git a/test/unittests/libweb3jsonrpc/Client.cpp b/test/unittests/libweb3jsonrpc/Client.cpp index 734a80b8a..0d33fd962 100644 --- a/test/unittests/libweb3jsonrpc/Client.cpp +++ b/test/unittests/libweb3jsonrpc/Client.cpp @@ -77,11 +77,11 @@ BOOST_AUTO_TEST_CASE( Personal ) { // dev::WebThreeDirect web3( WebThreeDirect::composeClientVersion( "eth" ), getDataDir(), // string(), // chainParams, WithExisting::Kill, set< string >{"eth"} ); - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); - setenv("DATA_DIR", getDataDir().c_str(), 1); - Client client( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), NULL, monitor, - getDataDir(), WithExisting::Kill, TransactionQueue::Limits{100000, 1024} ); + setenv( "DATA_DIR", getDataDir().c_str(), 1 ); + Client client( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), NULL, + monitor, getDataDir(), WithExisting::Kill, TransactionQueue::Limits{ 100000, 1024 } ); client.injectSkaleHost(); client.startWorking(); @@ -101,7 +101,7 @@ BOOST_AUTO_TEST_CASE( Personal ) { return false; // user input goes here } ); rpc::Personal personal( keyManager, accountHolder, client ); - rpc::Eth eth( std::string(""), client, accountHolder ); + rpc::Eth eth( std::string( "" ), client, accountHolder ); // Create account diff --git a/test/unittests/libweb3jsonrpc/SkaledFixture.cpp b/test/unittests/libweb3jsonrpc/SkaledFixture.cpp index 45b85ddc9..9ee87b266 100644 --- a/test/unittests/libweb3jsonrpc/SkaledFixture.cpp +++ b/test/unittests/libweb3jsonrpc/SkaledFixture.cpp @@ -104,27 +104,27 @@ Json::Value CurlClient::doRequestResponse() { // Accessing JSON data if ( root.isMember( "result" ) ) { return root["result"]; - } else if (root.isMember( "error" )) { + } else if ( root.isMember( "error" ) ) { CHECK( root["error"].isObject() ); auto errorDescription = root["error"]; string description = "JSON-RPC error:"; - if (errorDescription.isMember( "code" )) { + if ( errorDescription.isMember( "code" ) ) { description += errorDescription["code"].asString() + ":"; } - if (errorDescription.isMember( "message" )) { + if ( errorDescription.isMember( "message" ) ) { description += errorDescription["message"].asString() + ":"; }; - throw std::runtime_error( description); + throw std::runtime_error( description ); } else { throw std::runtime_error( "No result or error in response" ); Json::StreamWriterBuilder writer; - writer["indentation"] = " "; // Set indentation level (2 spaces here) + writer["indentation"] = " "; // Set indentation level (2 spaces here) // Convert the Json::Value to a string - std::string output = Json::writeString(writer, root); - throw std::runtime_error( "No result or error in response:" + output); + std::string output = Json::writeString( writer, root ); + throw std::runtime_error( "No result or error in response:" + output ); } } else { // Output error message if parsing fails @@ -453,16 +453,16 @@ void SkaledFixture::doOneTinyTransfersIteration( TransferType _transferType ) { } - cout << 1000.0 * testAccounts.size() * mtmBatchSize / ( getCurrentTimeMs() - begin ) << - " submission tps" << endl; + cout << 1000.0 * testAccounts.size() * mtmBatchSize / ( getCurrentTimeMs() - begin ) + << " submission tps" << endl; for ( auto&& account : testAccounts ) { - waitForTransactionOrBatch(account.second, mtmBatchSize ); + waitForTransactionOrBatch( account.second, mtmBatchSize ); }; - cout << 1000.0 * testAccounts.size() * mtmBatchSize / ( getCurrentTimeMs() - begin ) - << " total tps" << endl; + cout << 1000.0 * testAccounts.size() * mtmBatchSize / ( getCurrentTimeMs() - begin ) + << " total tps" << endl; for ( auto&& account : testAccountsVector ) { checkReceiptStatusAndGetGasUsed( account->getLastTxHash() ); @@ -671,10 +671,10 @@ string SkaledFixture::getTxPayload( Transaction& transaction ) { // this call sends ether a single transfer, or multiple copies of same transfer. // the latter is used in MTM mode testing. For a single transder _batchSize = 1 void SkaledFixture::sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< SkaledAccount > _from, - const string& _to, const u256& _gasPrice, uint64_t _batchSize, TransferType _transferType, + const string& _to, const u256& _gasPrice, uint64_t _batchSize, TransferType _transferType, TransactionWait _wait ) { auto from = _from->getAddressAsString(); - auto accountNonce = _from->computeNonceForNextTransactionOrBatch(_batchSize); + auto accountNonce = _from->computeNonceForNextTransactionOrBatch( _batchSize ); u256 dstBalanceBefore; @@ -713,9 +713,9 @@ void SkaledFixture::sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< Sk ts.gas = 90000; ts.gasPrice = _gasPrice; - vector txHashes; + vector< string > txHashes; - for (uint64_t i = 0; i < _batchSize; i++) { + for ( uint64_t i = 0; i < _batchSize; i++ ) { Transaction transaction( ts ); transaction.forceChainId( chainId ); transaction.forceType( this->transactionType ); @@ -723,8 +723,8 @@ void SkaledFixture::sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< Sk transaction.forceType2Fees( _gasPrice, _gasPrice ); } - if (usePow) { - calculateAndSetPowGas(transaction); + if ( usePow ) { + calculateAndSetPowGas( transaction ); } transaction.sign( _from->getKey() ); @@ -736,8 +736,8 @@ void SkaledFixture::sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< Sk auto txHash = getThreadLocalCurlClient()->eth_sendRawTransaction( payload ); txHashes.push_back( txHash ); } catch ( std::exception& e ) { - cerr << "Exception in eth_sendRawTransaction from: " << transaction.from() << - ": nonce: " << transaction.nonce() << endl; + cerr << "Exception in eth_sendRawTransaction from: " << transaction.from() + << ": nonce: " << transaction.nonce() << endl; cerr << e.what() << endl; throw e; } @@ -753,7 +753,7 @@ void SkaledFixture::sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< Sk ++ts.nonce; } - _from->setLastTxHash( txHashes.back()); + _from->setLastTxHash( txHashes.back() ); } @@ -836,8 +836,8 @@ string SkaledFixture::sendSingleDeployOrSolidityCall( u256 _amount, } -void SkaledFixture::waitForTransactionOrBatch( std::shared_ptr< SkaledAccount > _account, - uint64_t _batchSize) { +void SkaledFixture::waitForTransactionOrBatch( + std::shared_ptr< SkaledAccount > _account, uint64_t _batchSize ) { u256 transactionCount; auto lastSentNonce = _account->getLastSentNonce(); @@ -846,8 +846,7 @@ void SkaledFixture::waitForTransactionOrBatch( std::shared_ptr< SkaledAccount > while ( ( transactionCount = getThreadLocalCurlClient()->eth_getTransactionCount( - _account->getAddressAsString() ) ) < lastSentNonce + 1) { - + _account->getAddressAsString() ) ) < lastSentNonce + 1 ) { if ( this->verifyTransactions ) { CHECK( getTransactionCount( _account->getAddressAsString() ) == transactionCount ) } @@ -861,9 +860,9 @@ void SkaledFixture::waitForTransactionOrBatch( std::shared_ptr< SkaledAccount > } // the count should now be one more than the last transaction nonce - CHECK( transactionCount == lastSentNonce + 1); + CHECK( transactionCount == lastSentNonce + 1 ); - _account->notifyLastTransactionOrBatchCompleted( _batchSize); + _account->notifyLastTransactionOrBatchCompleted( _batchSize ); } void SkaledFixture::splitAccountInHalves( std::shared_ptr< SkaledAccount > _from, @@ -893,8 +892,8 @@ void SkaledFixture::sendTinyTransfer( std::shared_ptr< SkaledAccount > _from, co CHECK( fee <= getBalance( _from->getAddressAsString() ) ) } - sendSingleTransferOrBatch( 1, _from, _from->getAddressAsString(), _gasPrice, - this->mtmBatchSize, _transferType, _wait ); + sendSingleTransferOrBatch( 1, _from, _from->getAddressAsString(), _gasPrice, this->mtmBatchSize, + _transferType, _wait ); } @@ -906,12 +905,11 @@ unique_ptr< WebThreeStubClient > SkaledFixture::rpcClient() const { } void SkaledFixture::calculateAndSetPowGas( Transaction& _t ) const { - for ( u256 i = 1;; i++ ) { _t.forceGasPrice( i ); - h256 hash = dev::sha3( _t.sender().ref() ) ^ - dev::sha3( _t.nonce() ) ^ dev::sha3( _t.gasPrice() ); + h256 hash = + dev::sha3( _t.sender().ref() ) ^ dev::sha3( _t.nonce() ) ^ dev::sha3( _t.gasPrice() ); u256 externalGas = ~u256( 0 ) / u256( hash ) / powDiffuculty; diff --git a/test/unittests/libweb3jsonrpc/SkaledFixture.h b/test/unittests/libweb3jsonrpc/SkaledFixture.h index 13b8a67f7..ea7e46aed 100644 --- a/test/unittests/libweb3jsonrpc/SkaledFixture.h +++ b/test/unittests/libweb3jsonrpc/SkaledFixture.h @@ -22,10 +22,11 @@ Modifications Copyright (C) 2024 SKALE Labs #include "libdevcrypto/AES.h" - #include #include +#include + using namespace std; using namespace dev; using namespace dev::eth; @@ -59,15 +60,14 @@ class SkaledAccount { friend std::shared_ptr< SkaledAccount > std::make_shared< SkaledAccount >(); public: - - void setLastTxHash(const string& _hash) { + void setLastTxHash( const string& _hash ) { std::unique_lock< std::shared_mutex > lock( mutex ); this->lastSentTxHash = _hash; } string getLastTxHash() { std::shared_lock< std::shared_mutex > lock( mutex ); - CHECK(lastSentTxHash) + CHECK( lastSentTxHash ) return lastSentTxHash.value(); } @@ -113,12 +113,9 @@ class SkaledAccount { } - - - // will return the next nonce that can be used for a transaction // if it is a batch, then _batchSize transactions will be sent - u256 computeNonceForNextTransactionOrBatch(uint64_t _batchSize) { + u256 computeNonceForNextTransactionOrBatch( uint64_t _batchSize ) { std::unique_lock< std::shared_mutex > lock( mutex ); @@ -135,11 +132,9 @@ class SkaledAccount { } - u256 computeNonceForNextTx() { - return computeNonceForNextTransactionOrBatch( 1 ); - } + u256 computeNonceForNextTx() { return computeNonceForNextTransactionOrBatch( 1 ); } - void notifyLastTransactionOrBatchCompleted(uint64_t _batchSize) { + void notifyLastTransactionOrBatchCompleted( uint64_t _batchSize ) { std::unique_lock< std::shared_mutex > lock( mutex ); @@ -147,9 +142,9 @@ class SkaledAccount { throw std::runtime_error( "No pending transaction for this account" ); } - CHECK( lastSentNonce == currentTransactionCountOnChain + _batchSize - 1); + CHECK( lastSentNonce == currentTransactionCountOnChain + _batchSize - 1 ); - currentTransactionCountOnChain+= _batchSize; + currentTransactionCountOnChain += _batchSize; lastSentNonce = std::nullopt; } @@ -214,10 +209,10 @@ class SkaledFixture : public TestOutputHelperFixture { void setupFirstKey(); void deployERC20(); - string checkReceiptStatusAndGetGasUsed( string _hash); + string checkReceiptStatusAndGetGasUsed( string _hash ); - void mintERC20(std::shared_ptr< SkaledAccount > _minter, - const string& _address, u256 _amount, u256 _gasPrice, TransactionWait _wait); + void mintERC20( std::shared_ptr< SkaledAccount > _minter, const string& _address, u256 _amount, + u256 _gasPrice, TransactionWait _wait ); void setupTwoToTheNKeys( uint64_t _n ); @@ -245,34 +240,35 @@ class SkaledFixture : public TestOutputHelperFixture { u256 getBalance( const SkaledAccount& _account ) const; - string getTxPayload( Transaction& _transaction); + string getTxPayload( Transaction& _transaction ); void sendSingleTransferOrBatch( u256 _amount, std::shared_ptr< SkaledAccount > _from, - const string& _to, const u256& _gasPrice, uint64_t _batchSize, - TransferType _transferType, TransactionWait _wait); + const string& _to, const u256& _gasPrice, uint64_t _batchSize, TransferType _transferType, + TransactionWait _wait ); void sendSingleTransfer( u256 _amount, std::shared_ptr< SkaledAccount > _from, - const string& _to, const u256& _gasPrice, TransferType _transferType, TransactionWait _wait) { + const string& _to, const u256& _gasPrice, TransferType _transferType, + TransactionWait _wait ) { sendSingleTransferOrBatch( _amount, _from, _to, _gasPrice, 1, _transferType, _wait ); } string sendSingleDeployOrSolidityCall( u256 _amount, std::shared_ptr< SkaledAccount > _from, std::optional< string > _to, const string& _data, const u256& _gasPrice, - TransactionWait _wait); + TransactionWait _wait ); void splitAccountInHalves( std::shared_ptr< SkaledAccount > _from, - std::shared_ptr< SkaledAccount > _to, u256& _gasPrice, TransactionWait _wait); + std::shared_ptr< SkaledAccount > _to, u256& _gasPrice, TransactionWait _wait ); void sendTinyTransfer( std::shared_ptr< SkaledAccount > _from, const u256& _gasPrice, - TransferType _transferType, TransactionWait _wait); + TransferType _transferType, TransactionWait _wait ); unique_ptr< WebThreeStubClient > rpcClient() const; - void calculateAndSetPowGas(Transaction& _t) const; + void calculateAndSetPowGas( Transaction& _t ) const; string skaledEndpoint; string ownerAddressStr; @@ -298,15 +294,14 @@ class SkaledFixture : public TestOutputHelperFixture { TransactionType transactionType = TransactionType::Legacy; - void waitForTransactionOrBatch( std::shared_ptr< SkaledAccount > _account, - uint64_t _batchSize); + void waitForTransactionOrBatch( + std::shared_ptr< SkaledAccount > _account, uint64_t _batchSize ); void waitForTransaction( std::shared_ptr< SkaledAccount > _account ) { waitForTransactionOrBatch( _account, 1 ); } - int timeBetweenTransactionCompletionChecksMs = 1000; // Keccak-256("mint(address,uint256)") diff --git a/test/unittests/libweb3jsonrpc/WebThreeStubClient.cpp b/test/unittests/libweb3jsonrpc/WebThreeStubClient.cpp index e3f221876..fa0a36b5c 100644 --- a/test/unittests/libweb3jsonrpc/WebThreeStubClient.cpp +++ b/test/unittests/libweb3jsonrpc/WebThreeStubClient.cpp @@ -167,8 +167,6 @@ std::string WebThreeStubClient::skale_stats() { } - - std::string WebThreeStubClient::eth_protocolVersion() { Json::Value p; p = Json::nullValue; @@ -407,10 +405,11 @@ std::string WebThreeStubClient::eth_sendTransaction( const Json::Value& param1 ) jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString() ); } -std::string WebThreeStubClient::eth_estimateGas( const Json::Value& param1, const std::string& param2 ) { +std::string WebThreeStubClient::eth_estimateGas( + const Json::Value& param1, const std::string& param2 ) { Json::Value p; p.append( param1 ); - if(!param2.empty()) + if ( !param2.empty() ) p.append( param2 ); Json::Value result = this->CallMethod( "eth_estimateGas", p ); if ( result.isString() ) @@ -432,7 +431,8 @@ std::string WebThreeStubClient::eth_call( const Json::Value& param1, const std:: jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString() ); } -std::string WebThreeStubClient::eth_callEIP1898( const Json::Value& param1, const Json::Value& param2 ) { +std::string WebThreeStubClient::eth_callEIP1898( + const Json::Value& param1, const Json::Value& param2 ) { Json::Value p; p.append( param1 ); p.append( param2 ); @@ -841,7 +841,8 @@ std::string WebThreeStubClient::eth_maxPriorityFeePerGas() { jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString() ); } -Json::Value WebThreeStubClient::eth_createAccessList( const Json::Value& param1, const std::string& param2 ) { +Json::Value WebThreeStubClient::eth_createAccessList( + const Json::Value& param1, const std::string& param2 ) { Json::Value p; p.append( param1 ); p.append( param2 ); @@ -853,7 +854,8 @@ Json::Value WebThreeStubClient::eth_createAccessList( const Json::Value& param1, jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString() ); } -Json::Value WebThreeStubClient::eth_feeHistory( const Json::Value& param1, const std::string& param2, const Json::Value& param3 ) { +Json::Value WebThreeStubClient::eth_feeHistory( + const Json::Value& param1, const std::string& param2, const Json::Value& param3 ) { Json::Value p; if ( param1.isString() ) p.append( param1.asString() ); @@ -1345,7 +1347,8 @@ std::string WebThreeStubClient::debug_preimage( const std::string& param1 ) { jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString() ); } -Json::Value WebThreeStubClient::debug_traceBlockByNumber( const std::string& param1, const Json::Value& param2 ) { +Json::Value WebThreeStubClient::debug_traceBlockByNumber( + const std::string& param1, const Json::Value& param2 ) { Json::Value p; p.append( param1 ); p.append( param2 ); diff --git a/test/unittests/libweb3jsonrpc/WebThreeStubClient.h b/test/unittests/libweb3jsonrpc/WebThreeStubClient.h index d56bac071..34588581a 100644 --- a/test/unittests/libweb3jsonrpc/WebThreeStubClient.h +++ b/test/unittests/libweb3jsonrpc/WebThreeStubClient.h @@ -38,8 +38,8 @@ class WebThreeStubClient : public jsonrpc::Client { std::string eth_blockNumber() noexcept( false ); std::string eth_getBalance( const std::string& param1, const std::string& param2 ) noexcept( false ); - std::string eth_getBalanceEIP1898( const std::string& param1, const Json::Value& param2 ) noexcept( - false ); + std::string eth_getBalanceEIP1898( + const std::string& param1, const Json::Value& param2 ) noexcept( false ); std::string eth_getStorageAt( const std::string& param1, const std::string& param2, const std::string& param3 ) noexcept( false ); std::string eth_getStorageAtEIP1898( const std::string& param1, const std::string& param2, @@ -58,9 +58,11 @@ class WebThreeStubClient : public jsonrpc::Client { false ); std::string eth_sendTransaction( const Json::Value& param1 ) noexcept( false ); std::string eth_call( const Json::Value& param1, const std::string& param2 ) noexcept( false ); - std::string eth_callEIP1898( const Json::Value& param1, const Json::Value& param2 ) noexcept( false ); + std::string eth_callEIP1898( const Json::Value& param1, const Json::Value& param2 ) noexcept( + false ); bool eth_flush() noexcept( false ); - std::string eth_estimateGas( const Json::Value& param1, const std::string& param2 = "latest" ) noexcept( false ); + std::string eth_estimateGas( + const Json::Value& param1, const std::string& param2 = "latest" ) noexcept( false ); Json::Value eth_getBlockByHash( const std::string& param1, bool param2 ) noexcept( false ); Json::Value eth_getBlockByNumber( const std::string& param1, bool param2 ) noexcept( false ); Json::Value eth_getTransactionByHash( const std::string& param1 ) noexcept( false ); @@ -100,8 +102,10 @@ class WebThreeStubClient : public jsonrpc::Client { Json::Value eth_pendingTransactions() noexcept( false ); std::string eth_sendRawTransaction( const std::string& param1 ) noexcept( false ); std::string eth_maxPriorityFeePerGas() noexcept( false ); - Json::Value eth_createAccessList( const Json::Value& param1, const std::string& param2 ) noexcept( false ); - Json::Value eth_feeHistory( const Json::Value& param1, const std::string& param2, const Json::Value& param3 ) noexcept( false ); + Json::Value eth_createAccessList( + const Json::Value& param1, const std::string& param2 ) noexcept( false ); + Json::Value eth_feeHistory( const Json::Value& param1, const std::string& param2, + const Json::Value& param3 ) noexcept( false ); bool eth_notePassword( const std::string& param1 ) noexcept( false ); bool db_put( const std::string& param1, const std::string& param2, const std::string& param3 ) noexcept( false ); @@ -160,7 +164,8 @@ class WebThreeStubClient : public jsonrpc::Client { Json::Value debug_storageRangeAt( const std::string& param1, int param2, const std::string& param3, const std::string& param4, int param5 ) noexcept( false ); std::string debug_preimage( const std::string& param1 ) noexcept( false ); - Json::Value debug_traceBlockByNumber( const std::string & param1, const Json::Value& param2 ) noexcept( false ); + Json::Value debug_traceBlockByNumber( + const std::string& param1, const Json::Value& param2 ) noexcept( false ); Json::Value debug_traceBlockByHash( const std::string& param1, const Json::Value& param2 ) noexcept( false ); Json::Value debug_traceCall( const Json::Value& param1, const std::string& param2, diff --git a/test/unittests/libweb3jsonrpc/genesisGeneration2Config.h b/test/unittests/libweb3jsonrpc/genesisGeneration2Config.h index e13318fc5..b6e19e431 100644 --- a/test/unittests/libweb3jsonrpc/genesisGeneration2Config.h +++ b/test/unittests/libweb3jsonrpc/genesisGeneration2Config.h @@ -942,4 +942,4 @@ static std::string const c_genesisGeneration2ConfigString = R"( } )"; -#endif // GENESISGENERATION2CONFIG_H +#endif // GENESISGENERATION2CONFIG_H diff --git a/test/unittests/libweb3jsonrpc/jsonrpc.cpp b/test/unittests/libweb3jsonrpc/jsonrpc.cpp index e15209f0e..09f974e1b 100644 --- a/test/unittests/libweb3jsonrpc/jsonrpc.cpp +++ b/test/unittests/libweb3jsonrpc/jsonrpc.cpp @@ -22,10 +22,13 @@ #include "WebThreeStubClient.h" +#include "SkaledFixture.h" #include "genesisGeneration2Config.h" #include "libweb3jsonrpc/SkaleFace.h" #include #include +#include +#include #include #include #include @@ -36,14 +39,9 @@ #include #include #include -#include -#include "SkaledFixture.h" -#include -#include -#include -#include "genesisGeneration2Config.h" #include #include +#include #include #include #include @@ -332,7 +330,7 @@ struct JsonRpcFixture : public TestOutputHelperFixture { chainParams.sChain.multiTransactionMode = _mtmEnabled; chainParams.nodeInfo.syncNode = _isSyncNode; - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); setenv( "DATA_DIR", tempDir.path().c_str(), 1 ); @@ -374,8 +372,7 @@ struct JsonRpcFixture : public TestOutputHelperFixture { rpcServer.reset( new FullServer( ethFace, new rpc::Net( chainParams ), new rpc::Web3(), // TODO Add version parameter here? new rpc::AdminEth( *client, *gasPricer, keyManager, *sessionManager ), - new rpc::Debug( *client, nullptr, ""), - new rpc::Test( *client ) ) ); + new rpc::Debug( *client, nullptr, "" ), new rpc::Test( *client ) ) ); // @@ -489,8 +486,8 @@ BOOST_AUTO_TEST_CASE( jsonrpc_gasPrice ) { } -BOOST_AUTO_TEST_CASE( jsonrpc_accounts, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + jsonrpc_accounts, *boost::unit_test::precondition( dev::test::run_not_express ) ) { JsonRpcFixture fixture; std::vector< dev::KeyPair > keys = { KeyPair::create(), KeyPair::create() }; fixture.accountHolder->setAccounts( keys ); @@ -517,8 +514,7 @@ BOOST_AUTO_TEST_CASE( jsonrpc_number ) { } -BOOST_AUTO_TEST_CASE( jsonrpc_netVersion ) -{ +BOOST_AUTO_TEST_CASE( jsonrpc_netVersion ) { std::string _config = c_genesisConfigString; Json::Value ret; Json::Reader().parse( _config, ret ); @@ -815,15 +811,9 @@ BOOST_AUTO_TEST_CASE( eth_signTransaction ) { } - const string skaledConfigFileName = "../../test/historicstate/configs/basic_config.json"; - - - - - BOOST_AUTO_TEST_CASE( simple_contract ) { JsonRpcFixture fixture; dev::eth::simulateMining( *( fixture.client ), 1 ); @@ -1345,14 +1335,17 @@ BOOST_AUTO_TEST_CASE( eth_estimateGas_chainId ) { // } Json::Value testRevert; - testRevert["data"] = "0x6080604052348015600f57600080fd5b50604051633013bad360e21b815246600482015260240160405180910390fdfe"; + testRevert["data"] = + "0x6080604052348015600f57600080fd5b50604051633013bad360e21b81524660048201526024016040518091" + "0390fdfe"; try { fixture.rpcClient->eth_estimateGas( testRevert, "latest" ); - } catch ( jsonrpc::JsonRpcException& ex) { - BOOST_CHECK_EQUAL(ex.GetCode(), 3); - BOOST_CHECK_EQUAL(ex.GetData().asString(), "0xc04eeb4c000000000000000000000000000000000000000000000000000000000000ffff"); - BOOST_CHECK_EQUAL(ex.GetMessage(), "EVM revert instruction without description message"); + } catch ( jsonrpc::JsonRpcException& ex ) { + BOOST_CHECK_EQUAL( ex.GetCode(), 3 ); + BOOST_CHECK_EQUAL( ex.GetData().asString(), + "0xc04eeb4c000000000000000000000000000000000000000000000000000000000000ffff" ); + BOOST_CHECK_EQUAL( ex.GetMessage(), "EVM revert instruction without description message" ); } } @@ -1621,10 +1614,10 @@ BOOST_AUTO_TEST_CASE( call_with_error ) { try { fixture.rpcClient->eth_call( transactionCallObject, "latest" ); - } catch ( jsonrpc::JsonRpcException& ex) { - BOOST_CHECK_EQUAL(ex.GetCode(), 3); - BOOST_CHECK_EQUAL(ex.GetData().asString(), "0x82b42900"); - BOOST_CHECK_EQUAL(ex.GetMessage(), "EVM revert instruction without description message"); + } catch ( jsonrpc::JsonRpcException& ex ) { + BOOST_CHECK_EQUAL( ex.GetCode(), 3 ); + BOOST_CHECK_EQUAL( ex.GetData().asString(), "0x82b42900" ); + BOOST_CHECK_EQUAL( ex.GetMessage(), "EVM revert instruction without description message" ); } } @@ -1676,15 +1669,14 @@ BOOST_AUTO_TEST_CASE( estimate_gas_with_error ) { try { fixture.rpcClient->eth_estimateGas( transactionCallObject, "latest" ); - } catch ( jsonrpc::JsonRpcException& ex) { - BOOST_CHECK_EQUAL(ex.GetCode(), 3); - BOOST_CHECK_EQUAL(ex.GetData().asString(), "0x82b42900"); - BOOST_CHECK_EQUAL(ex.GetMessage(), "EVM revert instruction without description message"); + } catch ( jsonrpc::JsonRpcException& ex ) { + BOOST_CHECK_EQUAL( ex.GetCode(), 3 ); + BOOST_CHECK_EQUAL( ex.GetData().asString(), "0x82b42900" ); + BOOST_CHECK_EQUAL( ex.GetMessage(), "EVM revert instruction without description message" ); } } BOOST_AUTO_TEST_CASE( simplePoWTransaction ) { - u256 ESTIMATE_AFTER_PATCH = u256( 21000 + 1024 * 16 ); u256 ESTIMATE_BEFORE_PATCH = u256( 21000 + 1024 * 68 ); @@ -1747,7 +1739,7 @@ BOOST_AUTO_TEST_CASE( simplePoWTransaction ) { fixture.client->state().getOriginalDb()->createBlockSnap( blockCounter ); blockCounter++; } - } else { // now we are after patch + } else { // now we are after patch BOOST_REQUIRE_EQUAL( gasEstimate, ESTIMATE_AFTER_PATCH ); txHash = fixture.rpcClient->eth_sendTransaction( transact ); goodInfo = fixture.client->blockInfo( fixture.client->hashFromNumber( LatestBlock ) ); @@ -1780,7 +1772,7 @@ BOOST_AUTO_TEST_CASE( recalculateExternalGas ) { ret["accounts"] = accounts; // setup patch - time_t externalGasPatchActivationTimestamp = time(nullptr) + 10; + time_t externalGasPatchActivationTimestamp = time( nullptr ) + 10; ret["skaleConfig"]["sChain"]["ExternalGasPatchTimestamp"] = externalGasPatchActivationTimestamp; Json::FastWriter fastWriter; @@ -1790,40 +1782,49 @@ BOOST_AUTO_TEST_CASE( recalculateExternalGas ) { auto senderAddress = fixture.coinbase.address().hex(); -// // SPDX-License-Identifier: GPL-3.0 - -// pragma solidity >=0.8.2 <0.9.0; - -// /** -// * @title Storage -// * @dev Store & retrieve value in a variable -// * @custom:dev-run-script ./scripts/deploy_with_ethers.ts -// */ -// contract Storage { - -// uint256 number; -// uint256 number1; -// uint256 number2; - -// /** -// * @dev Store value in variable -// * @param num value to store -// */ -// function store(uint256 num) public { -// number = num; -// number1 = num; -// number2 = num; -// } - -// /** -// * @dev Return value -// * @return value of 'number' -// */ -// function retrieve() public view returns (uint256){ -// return number; -// } -// } - std::string bytecode = "608060405234801561001057600080fd5b5061015e806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080fd5b610043610075565b60405161005091906100e7565b60405180910390f35b610073600480360381019061006e91906100ab565b61007e565b005b60008054905090565b80600081905550806001819055508060028190555050565b6000813590506100a581610111565b92915050565b6000602082840312156100c1576100c061010c565b5b60006100cf84828501610096565b91505092915050565b6100e181610102565b82525050565b60006020820190506100fc60008301846100d8565b92915050565b6000819050919050565b600080fd5b61011a81610102565b811461012557600080fd5b5056fea2646970667358221220780703bb6ac2eec922a510d57edcae39b852b578e7f63a263ddb936758dc9c4264736f6c63430008070033"; + // // SPDX-License-Identifier: GPL-3.0 + + // pragma solidity >=0.8.2 <0.9.0; + + // /** + // * @title Storage + // * @dev Store & retrieve value in a variable + // * @custom:dev-run-script ./scripts/deploy_with_ethers.ts + // */ + // contract Storage { + + // uint256 number; + // uint256 number1; + // uint256 number2; + + // /** + // * @dev Store value in variable + // * @param num value to store + // */ + // function store(uint256 num) public { + // number = num; + // number1 = num; + // number2 = num; + // } + + // /** + // * @dev Return value + // * @return value of 'number' + // */ + // function retrieve() public view returns (uint256){ + // return number; + // } + // } + std::string bytecode = + "608060405234801561001057600080fd5b5061015e806100206000396000f3fe60806040523480156100105760" + "0080fd5b50600436106100365760003560e01c80632e64cec11461003b5780636057361d14610059575b600080" + "fd5b610043610075565b60405161005091906100e7565b60405180910390f35b61007360048036038101906100" + "6e91906100ab565b61007e565b005b60008054905090565b806000819055508060018190555080600281905550" + "50565b6000813590506100a581610111565b92915050565b6000602082840312156100c1576100c061010c565b" + "5b60006100cf84828501610096565b91505092915050565b6100e181610102565b82525050565b600060208201" + "90506100fc60008301846100d8565b92915050565b6000819050919050565b600080fd5b61011a81610102565b" + "811461012557600080fd5b5056fea2646970667358221220780703bb6ac2eec922a510d57edcae39b852b578e7" + "f63a263ddb936758dc9c4264736f6c63430008070033"; // deploy contact Json::Value create; @@ -1853,7 +1854,8 @@ BOOST_AUTO_TEST_CASE( recalculateExternalGas ) { txn["to"] = contractAddress; auto ts = toTransactionSkeleton( txn ); - auto t = dev::eth::Transaction( ts, dev::Secret( "7be24de049f2d0d4ecaeaa81564aecf647fa7a4c86264243d77e01da25d859a0" ) ); + auto t = dev::eth::Transaction( + ts, dev::Secret( "7be24de049f2d0d4ecaeaa81564aecf647fa7a4c86264243d77e01da25d859a0" ) ); txHash = fixture.rpcClient->eth_sendRawTransaction( dev::toHex( t.toBytes() ) ); dev::eth::mineTransaction( *( fixture.client ), 1 ); @@ -1864,7 +1866,7 @@ BOOST_AUTO_TEST_CASE( recalculateExternalGas ) { BOOST_REQUIRE( receipt["status"].asString() == "0x1" ); BOOST_REQUIRE( receipt["gasUsed"].asString() == "0x13ef4" ); - sleep(10); + sleep( 10 ); // push new block to update timestamp Json::Value refill; @@ -1890,7 +1892,8 @@ BOOST_AUTO_TEST_CASE( recalculateExternalGas ) { txn["to"] = contractAddress; ts = toTransactionSkeleton( txn ); - t = dev::eth::Transaction( ts, dev::Secret( "8df08814fcfc169aad0015654114be06c28b27bdcdef286cf4dbd5e2950a3ffc" ) ); + t = dev::eth::Transaction( + ts, dev::Secret( "8df08814fcfc169aad0015654114be06c28b27bdcdef286cf4dbd5e2950a3ffc" ) ); txHash = fixture.rpcClient->eth_sendRawTransaction( dev::toHex( t.toBytes() ) ); dev::eth::mineTransaction( *( fixture.client ), 1 ); @@ -1939,7 +1942,8 @@ BOOST_AUTO_TEST_CASE( skipTransactionExecution ) { txn["to"] = "0x5cdb7527ec85022991D4e27F254C438E8337ad7E"; auto ts = toTransactionSkeleton( txn ); - auto t = dev::eth::Transaction( ts, dev::Secret( "08cee1f4bc8c37f88124bb3fc64566ccd35dbeeac84c62300f6b8809cab9ea2f" ) ); + auto t = dev::eth::Transaction( + ts, dev::Secret( "08cee1f4bc8c37f88124bb3fc64566ccd35dbeeac84c62300f6b8809cab9ea2f" ) ); txHash = fixture.rpcClient->eth_sendRawTransaction( dev::toHex( t.toBytes() ) ); BOOST_REQUIRE( txHash == "0x95fb5557db8cc6de0aff3a64c18a6d9378b0d312b24f5d77e8dbf5cc0612d74f" ); @@ -3012,8 +3016,8 @@ BOOST_AUTO_TEST_CASE( powTxnGasLimit ) { "0xc5002ab03e1e7e196b3d0ffa9801e783fcd48d4c6d972f1389ab63f4e2d0bef0"; // gas 1m txPOW2["value"] = 100; - BOOST_REQUIRE_THROW( fixture.rpcClient->eth_sendTransaction( txPOW2 ), jsonrpc::JsonRpcException ); // block gas limit reached - + BOOST_REQUIRE_THROW( fixture.rpcClient->eth_sendTransaction( txPOW2 ), + jsonrpc::JsonRpcException ); // block gas limit reached } BOOST_AUTO_TEST_CASE( EIP1898Calls ) { @@ -3058,8 +3062,10 @@ BOOST_AUTO_TEST_CASE( EIP1898Calls ) { eip1898BadFormed5["requireCanonical"] = 228; - std::array wellFormedCalls = { eip1898WellFormed, eip1898WellFormed1, eip1898WellFormed2, eip1898WellFormed3 }; - std::array badFormedCalls = { eip1898BadFormed, eip1898BadFormed1, eip1898BadFormed2, eip1898BadFormed3, eip1898BadFormed4, eip1898BadFormed5 }; + std::array< Json::Value, 4 > wellFormedCalls = { eip1898WellFormed, eip1898WellFormed1, + eip1898WellFormed2, eip1898WellFormed3 }; + std::array< Json::Value, 6 > badFormedCalls = { eip1898BadFormed, eip1898BadFormed1, + eip1898BadFormed2, eip1898BadFormed3, eip1898BadFormed4, eip1898BadFormed5 }; auto address = fixture.coinbase.address(); @@ -3075,7 +3081,7 @@ BOOST_AUTO_TEST_CASE( EIP1898Calls ) { } - for (const auto& call: wellFormedCalls) { + for ( const auto& call : wellFormedCalls ) { Json::Value transactionCallObject; transactionCallObject["to"] = "0x0000000000000000000000000000000000000005"; transactionCallObject["data"] = "0x0000000000000000000000000000000000000005"; @@ -3130,8 +3136,9 @@ BOOST_AUTO_TEST_CASE( eip2930Transactions ) { // Set chainID = 151 std::string chainID = "0x97"; ret["params"]["chainID"] = chainID; - time_t eip1559PatchActivationTimestamp = time(nullptr) + 10; - ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = eip1559PatchActivationTimestamp; + time_t eip1559PatchActivationTimestamp = time( nullptr ) + 10; + ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = + eip1559PatchActivationTimestamp; Json::FastWriter fastWriter; @@ -3216,7 +3223,8 @@ BOOST_AUTO_TEST_CASE( eip2930Transactions ) { BOOST_REQUIRE( block["transactions"][0]["hash"].asString() == txHash ); BOOST_REQUIRE( block["transactions"][0]["type"] == "0x1" ); - BOOST_REQUIRE( block["transactions"][0]["yParity"].asString() == block["transactions"][0]["v"].asString() ); + BOOST_REQUIRE( block["transactions"][0]["yParity"].asString() == + block["transactions"][0]["v"].asString() ); BOOST_REQUIRE( block["transactions"][0]["accessList"].isArray() ); BOOST_REQUIRE( block["transactions"][0]["accessList"].size() == 0 ); @@ -3328,8 +3336,9 @@ BOOST_AUTO_TEST_CASE( eip1559Transactions ) { // Set chainID = 151 std::string chainID = "0x97"; ret["params"]["chainID"] = chainID; - time_t eip1559PatchActivationTimestamp = time(nullptr) + 10; - ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = eip1559PatchActivationTimestamp; + time_t eip1559PatchActivationTimestamp = time( nullptr ) + 10; + ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = + eip1559PatchActivationTimestamp; Json::FastWriter fastWriter; std::string config = fastWriter.write( ret ); @@ -3430,7 +3439,8 @@ BOOST_AUTO_TEST_CASE( eip1559Transactions ) { BOOST_REQUIRE( block["transactions"][0]["hash"].asString() == txHash ); BOOST_REQUIRE( block["transactions"][0]["type"] == "0x2" ); - BOOST_REQUIRE( block["transactions"][0]["yParity"].asString() == block["transactions"][0]["v"].asString() ); + BOOST_REQUIRE( block["transactions"][0]["yParity"].asString() == + block["transactions"][0]["v"].asString() ); BOOST_REQUIRE( block["transactions"][0]["accessList"].isArray() ); BOOST_REQUIRE( block["transactions"][0].isMember( "chainId" ) ); @@ -3585,15 +3595,16 @@ BOOST_AUTO_TEST_CASE( vInTxnSignature ) { // Set chainID = 151 ret["params"]["chainID"] = "0x97"; - time_t eip1559PatchActivationTimestamp = time(nullptr); - ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = eip1559PatchActivationTimestamp; + time_t eip1559PatchActivationTimestamp = time( nullptr ); + ret["skaleConfig"]["sChain"]["EIP1559TransactionsPatchTimestamp"] = + eip1559PatchActivationTimestamp; Json::FastWriter fastWriter; std::string config = fastWriter.write( ret ); JsonRpcFixture fixture( config ); dev::eth::simulateMining( *( fixture.client ), 20 ); - string senderAddress = toJS(fixture.coinbase.address()); + string senderAddress = toJS( fixture.coinbase.address() ); Json::Value txRefill; txRefill["to"] = "0x5EdF1e852fdD1B0Bc47C0307EF755C76f4B9c251"; @@ -3605,7 +3616,10 @@ BOOST_AUTO_TEST_CASE( vInTxnSignature ) { dev::eth::mineTransaction( *( fixture.client ), 1 ); // send non replay protected txn - txHash = fixture.rpcClient->eth_sendRawTransaction( "0xf864808504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b01801ba0171c7f31feaa0fd7825a5a28d7b535d0b0ee200b27792f66eb7796e7a6a555d7a0081790244f21cefa563b55a7a68ee78f8466738b5827be19faaeff0586fd71be" ); + txHash = fixture.rpcClient->eth_sendRawTransaction( + "0xf864808504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b01801ba0171c7f31feaa0f" + "d7825a5a28d7b535d0b0ee200b27792f66eb7796e7a6a555d7a0081790244f21cefa563b55a7a68ee78f846673" + "8b5827be19faaeff0586fd71be" ); dev::eth::mineTransaction( *( fixture.client ), 1 ); Json::Value txn = fixture.rpcClient->eth_getTransactionByHash( txHash ); @@ -3613,15 +3627,23 @@ BOOST_AUTO_TEST_CASE( vInTxnSignature ) { BOOST_REQUIRE( v < 29 && v > 26 ); // send replay protected legacy txn - txHash = fixture.rpcClient->eth_sendRawTransaction( "0xf866018504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180820151a018b400fc56bc3568e4f23f6f93d538745a5b18054252d6030791c294c9aea9d4a00930492125784fad0a8b38b915e8621f54c53f0878a77f21920c751ec5fd220a" ); + txHash = fixture.rpcClient->eth_sendRawTransaction( + "0xf866018504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180820151a018b400fc56" + "bc3568e4f23f6f93d538745a5b18054252d6030791c294c9aea9d4a00930492125784fad0a8b38b915e8621f54" + "c53f0878a77f21920c751ec5fd220a" ); dev::eth::mineTransaction( *( fixture.client ), 1 ); txn = fixture.rpcClient->eth_getTransactionByHash( txHash ); v = dev::jsToU256( txn["v"].asString() ); - BOOST_REQUIRE( v < 339 && v > 336 ); // 2 * 151 + 35 + BOOST_REQUIRE( v < 339 && v > 336 ); // 2 * 151 + 35 // send type1 txn - txHash = fixture.rpcClient->eth_sendRawTransaction( "0x01f8c38197028504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000000000000000000003a0000000000000000000000000000000000000000000000000000000000000000701a0ee608b7c5df843b4a1988a3e9c24d53019fa674e06a6b2ae0c347a00601c1a84a06ed451f9cc0f4334a180458605ecaa212e58f8436e1a4318e75ae417c72eba2b" ); + txHash = fixture.rpcClient->eth_sendRawTransaction( + "0x01f8c38197028504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180f85bf85994de" + "0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000" + "000000000000000003a0000000000000000000000000000000000000000000000000000000000000000701a0ee" + "608b7c5df843b4a1988a3e9c24d53019fa674e06a6b2ae0c347a00601c1a84a06ed451f9cc0f4334a180458605" + "ecaa212e58f8436e1a4318e75ae417c72eba2b" ); dev::eth::mineTransaction( *( fixture.client ), 1 ); txn = fixture.rpcClient->eth_getTransactionByHash( txHash ); @@ -3629,7 +3651,12 @@ BOOST_AUTO_TEST_CASE( vInTxnSignature ) { BOOST_REQUIRE( v < 2 && v >= 0 ); // send type2 txn - txHash = fixture.rpcClient->eth_sendRawTransaction( "0x02f8c98197038504a817c8018504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000000000000000000000000000000003a0000000000000000000000000000000000000000000000000000000000000000701a0c16ec291a6f4e91476f39e624baf42730b21a805e570fe52334df13d69b63d3fa01c7e9662635512a3bc47d479b17af2df59491e6663823ca13789a86da6dff1a5" ); + txHash = fixture.rpcClient->eth_sendRawTransaction( + "0x02f8c98197038504a817c8018504a817c800827530947d36af85a184e220a656525fcbb9a63b9ab3c12b0180" + "f85bf85994de0b295669a9fd93d5f28d9ec85e40f4cb697baef842a00000000000000000000000000000000000" + "000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000" + "00000701a0c16ec291a6f4e91476f39e624baf42730b21a805e570fe52334df13d69b63d3fa01c7e9662635512" + "a3bc47d479b17af2df59491e6663823ca13789a86da6dff1a5" ); dev::eth::mineTransaction( *( fixture.client ), 1 ); txn = fixture.rpcClient->eth_getTransactionByHash( txHash ); @@ -3830,27 +3857,27 @@ BOOST_AUTO_TEST_CASE( deployment_control_v2 ) { // } string configControllerV2 = - "0x608060405234801561001057600080fd5b506004361061004c576000" - "3560e01c806313f44d1014610051578063a2306c4f14610081578063d0" - "f557f41461009f578063f7e2a91b146100cf575b600080fd5b61006b60" - "048036038101906100669190610189565b6100d9565b60405161007891" - "906101d1565b60405180910390f35b6100896100e0565b604051610096" - "91906101d1565b60405180910390f35b6100b960048036038101906100" - "b491906101ec565b6100f1565b6040516100c691906101d1565b604051" - "80910390f35b6100d761010a565b005b6000919050565b600080549061" - "01000a900460ff1681565b60008060009054906101000a900460ff1690" - "5092915050565b60016000806101000a81548160ff0219169083151502" - "17905550565b600080fd5b600073ffffffffffffffffffffffffffffff" - "ffffffffff82169050919050565b60006101568261012b565b90509190" - "50565b6101668161014b565b811461017157600080fd5b50565b600081" - "3590506101838161015d565b92915050565b6000602082840312156101" - "9f5761019e610126565b5b60006101ad84828501610174565b91505092" - "915050565b60008115159050919050565b6101cb816101b6565b825250" - "50565b60006020820190506101e660008301846101c2565b9291505056" - "5b6000806040838503121561020357610202610126565b5b6000610211" - "85828601610174565b925050602061022285828601610174565b915050" - "925092905056fea2646970667358221220b5f971b16f7bbba22272b220" - "7e02f10abf1682c17fe636c7bf6406c5cae5716064736f6c63430008090033"; + "0x608060405234801561001057600080fd5b506004361061004c576000" + "3560e01c806313f44d1014610051578063a2306c4f14610081578063d0" + "f557f41461009f578063f7e2a91b146100cf575b600080fd5b61006b60" + "048036038101906100669190610189565b6100d9565b60405161007891" + "906101d1565b60405180910390f35b6100896100e0565b604051610096" + "91906101d1565b60405180910390f35b6100b960048036038101906100" + "b491906101ec565b6100f1565b6040516100c691906101d1565b604051" + "80910390f35b6100d761010a565b005b6000919050565b600080549061" + "01000a900460ff1681565b60008060009054906101000a900460ff1690" + "5092915050565b60016000806101000a81548160ff0219169083151502" + "17905550565b600080fd5b600073ffffffffffffffffffffffffffffff" + "ffffffffff82169050919050565b60006101568261012b565b90509190" + "50565b6101668161014b565b811461017157600080fd5b50565b600081" + "3590506101838161015d565b92915050565b6000602082840312156101" + "9f5761019e610126565b5b60006101ad84828501610174565b91505092" + "915050565b60008115159050919050565b6101cb816101b6565b825250" + "50565b60006020820190506101e660008301846101c2565b9291505056" + "5b6000806040838503121561020357610202610126565b5b6000610211" + "85828601610174565b925050602061022285828601610174565b915050" + "925092905056fea2646970667358221220b5f971b16f7bbba22272b220" + "7e02f10abf1682c17fe636c7bf6406c5cae5716064736f6c63430008090033"; std::string _config = c_genesisGeneration2ConfigString; @@ -4042,7 +4069,9 @@ BOOST_AUTO_TEST_CASE( PrecompiledPrintFakeEth, Json::Value printFakeEthCall; - printFakeEthCall["data"] = "0x5C4e11842E8Be09264DC1976943571D7AF6d00f80000000000000000000000000000000000000000000000000000000000000010"; + printFakeEthCall["data"] = + "0x5C4e11842E8Be09264DC1976943571D7AF6d00f8000000000000000000000000000000000000000000000000" + "0000000000000010"; printFakeEthCall["from"] = "0x5C4e11842E8be09264dc1976943571d7Af6d00F9"; printFakeEthCall["to"] = "0000000000000000000000000000000000000006"; @@ -4129,8 +4158,8 @@ BOOST_AUTO_TEST_CASE( mtm_import_sequential_txs ) { Transaction tx3( ts3, ar3.second ); h256 h1 = fixture.client->importTransaction( tx1, TransactionBroadcast::DontBroadcast ); - h256 h2 = fixture.client->importTransaction( tx2, TransactionBroadcast::DontBroadcast); - h256 h3 = fixture.client->importTransaction( tx3, TransactionBroadcast::DontBroadcast); + h256 h2 = fixture.client->importTransaction( tx2, TransactionBroadcast::DontBroadcast ); + h256 h3 = fixture.client->importTransaction( tx3, TransactionBroadcast::DontBroadcast ); BOOST_REQUIRE( h1 ); BOOST_REQUIRE( h2 ); BOOST_REQUIRE( h3 ); @@ -4396,16 +4425,16 @@ BOOST_AUTO_TEST_CASE( skip_invalid_transactions ) { } -BOOST_AUTO_TEST_CASE( eth_signAndSendRawTransaction, - *boost::unit_test::precondition( dev::test::run_not_express ) ) { +BOOST_AUTO_TEST_CASE( + eth_signAndSendRawTransaction, *boost::unit_test::precondition( dev::test::run_not_express ) ) { SkaledFixture fixture( skaledConfigFileName ); fixture.setupFirstKey(); auto firstAccount = fixture.testAccounts.begin()->second; auto gasPrice = fixture.getCurrentGasPrice(); for ( uint64_t i = 0; i < 3; i++ ) { auto dst = SkaledAccount::generate(); - fixture.splitAccountInHalves( firstAccount, dst, gasPrice, - TransactionWait::WAIT_FOR_COMPLETION); + fixture.splitAccountInHalves( + firstAccount, dst, gasPrice, TransactionWait::WAIT_FOR_COMPLETION ); } cout << fixture.rpcClient()->skale_stats() << endl; @@ -4423,10 +4452,9 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthTransfers, fixture.setupFirstKey(); fixture.deployERC20(); - fixture.setupTwoToTheNKeys(12); + fixture.setupTwoToTheNKeys( 12 ); fixture.sendTinyTransfersForAllAccounts( 10, TransferType::NATIVE ); - } BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthMTMTransfers, @@ -4439,17 +4467,14 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthMTMTransfers, fixture.mtmBatchSize = 5; fixture.setupFirstKey(); - fixture.setupTwoToTheNKeys(8); + fixture.setupTwoToTheNKeys( 8 ); fixture.sendTinyTransfersForAllAccounts( 10, TransferType::NATIVE ); - } - - BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthType1Transfers, - *boost::unit_test::precondition( dev::test::run_not_express )) { + *boost::unit_test::precondition( dev::test::run_not_express ) ) { SkaledFixture fixture( skaledConfigFileName ); vector< Secret > accountPieces; @@ -4460,15 +4485,14 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthType1Transfers, fixture.setupFirstKey(); fixture.deployERC20(); - fixture.setupTwoToTheNKeys(12); + fixture.setupTwoToTheNKeys( 12 ); fixture.sendTinyTransfersForAllAccounts( 1000, TransferType::NATIVE ); - } BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthType2Transfers, - *boost::unit_test::precondition( dev::test::run_not_express )) { + *boost::unit_test::precondition( dev::test::run_not_express ) ) { SkaledFixture fixture( skaledConfigFileName ); vector< Secret > accountPieces; @@ -4479,15 +4503,14 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthType2Transfers, fixture.setupFirstKey(); fixture.deployERC20(); - fixture.setupTwoToTheNKeys(12); + fixture.setupTwoToTheNKeys( 12 ); fixture.sendTinyTransfersForAllAccounts( 1000, TransferType::NATIVE ); - } BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthPowTransfers, - *boost::unit_test::precondition( dev::test::run_not_express )) { + *boost::unit_test::precondition( dev::test::run_not_express ) ) { SkaledFixture fixture( skaledConfigFileName ); vector< Secret > accountPieces; @@ -4498,15 +4521,14 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelEthPowTransfers, fixture.setupFirstKey(); fixture.deployERC20(); - fixture.setupTwoToTheNKeys(4); + fixture.setupTwoToTheNKeys( 4 ); fixture.sendTinyTransfersForAllAccounts( 1000, TransferType::NATIVE ); - } BOOST_AUTO_TEST_CASE( perf_sendManyParalelERC20Transfers, - *boost::unit_test::precondition( dev::test::run_not_express )) { + *boost::unit_test::precondition( dev::test::run_not_express ) ) { SkaledFixture fixture( skaledConfigFileName ); vector< Secret > accountPieces; @@ -4517,11 +4539,10 @@ BOOST_AUTO_TEST_CASE( perf_sendManyParalelERC20Transfers, fixture.deployERC20(); - fixture.setupTwoToTheNKeys(12); + fixture.setupTwoToTheNKeys( 12 ); fixture.mintAllKeysWithERC20(); - fixture.sendTinyTransfersForAllAccounts(10, TransferType::ERC20); - + fixture.sendTinyTransfersForAllAccounts( 10, TransferType::ERC20 ); } diff --git a/test/unittests/mapreduce_consensus/ConsensusEngine.cpp b/test/unittests/mapreduce_consensus/ConsensusEngine.cpp index 8c6932c1d..84638ea4d 100644 --- a/test/unittests/mapreduce_consensus/ConsensusEngine.cpp +++ b/test/unittests/mapreduce_consensus/ConsensusEngine.cpp @@ -41,8 +41,8 @@ #include #include -#include #include +#include #include @@ -87,7 +87,6 @@ class TestIpcClient : public jsonrpc::IClientConnector { }; class SingleNodeConsensusFixture : public ConsensusExtFace { - TransientDirectory m_tempDir; protected: @@ -112,15 +111,15 @@ class SingleNodeConsensusFixture : public ConsensusExtFace { ////////////////////////////////////////////// - setenv("DATA_DIR", m_tempDir.path().c_str(), 1); + setenv( "DATA_DIR", m_tempDir.path().c_str(), 1 ); - m_consensus.reset( new ConsensusEngine( - *this, 0, BlockHeader( chainParams.genesisBlock() ).timestamp(), - 0, std::map() ) ); + m_consensus.reset( + new ConsensusEngine( *this, 0, BlockHeader( chainParams.genesisBlock() ).timestamp(), 0, + std::map< std::string, std::uint64_t >() ) ); m_consensus->parseFullConfigAndCreateNode( chainParams.getOriginalJson(), "" ); m_consensusThread = std::thread( [this]() { - sleep(1); + sleep( 1 ); m_consensus->startAll(); m_consensus->bootStrapAll(); } ); @@ -136,7 +135,8 @@ class SingleNodeConsensusFixture : public ConsensusExtFace { } virtual void createBlock( const transactions_vector& _approvedTransactions, uint64_t _timeStamp, - uint32_t _timeStampMs, uint64_t _blockID, u256 _gasPrice, u256 /*_stateRoot*/, uint64_t /*_winningNodeIndex*/ ) override { + uint32_t _timeStampMs, uint64_t _blockID, u256 _gasPrice, u256 /*_stateRoot*/, + uint64_t /*_winningNodeIndex*/ ) override { transaction_promise = decltype( transaction_promise )(); std::cerr << "Block arrived with " << _approvedTransactions.size() << " txns" << std::endl; @@ -152,7 +152,7 @@ class SingleNodeConsensusFixture : public ConsensusExtFace { m_consensusThread.join(); while ( m_consensus->getStatus() != CONSENSUS_EXITED ) { - timespec ms100{0, 100000000}; + timespec ms100{ 0, 100000000 }; nanosleep( &ms100, nullptr ); } } @@ -200,11 +200,10 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { unique_ptr< WebThreeStubClient > rpcClient; unique_ptr< FixedAccountHolder > accountHolder; - dev::KeyPair coinbase{KeyPair::create()}; + dev::KeyPair coinbase{ KeyPair::create() }; public: ConsensusExtFaceFixture() { - ChainParams chainParams; chainParams.sealEngineName = NoProof::name(); chainParams.allowFutureBlocks = true; @@ -214,14 +213,15 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { chainParams.nodeInfo.port = chainParams.nodeInfo.port6 = rand_port; chainParams.sChain.nodes[0].port = chainParams.sChain.nodes[0].port6 = rand_port; - sChainNode node2{u256( 2 ), "127.0.0.12", u256( 11111 ), "::1", u256( 11111 ), u256( 1 ), "0xfa", {"0", "1", "0", "1"}}; + sChainNode node2{ u256( 2 ), "127.0.0.12", u256( 11111 ), "::1", u256( 11111 ), u256( 1 ), + "0xfa", { "0", "1", "0", "1" } }; chainParams.sChain.nodes.push_back( node2 ); ////////////////////////////////////////////// - m_consensus.reset( new ConsensusEngine( - *this, 0, BlockHeader( chainParams.genesisBlock() ).timestamp(), 0 , - std::map())); + m_consensus.reset( + new ConsensusEngine( *this, 0, BlockHeader( chainParams.genesisBlock() ).timestamp(), 0, + std::map< std::string, std::uint64_t >() ) ); m_consensus->parseFullConfigAndCreateNode( chainParams.getOriginalJson(), "" ); m_consensusThread = std::thread( [this]() { @@ -238,12 +238,12 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { // web3.reset( new WebThreeDirect( // "eth tests", "", "", chainParams, WithExisting::Kill, {"eth"}, true ) ); - auto monitor = make_shared< InstanceMonitor >("test"); + auto monitor = make_shared< InstanceMonitor >( "test" ); - setenv("DATA_DIR", m_tempDir.path().c_str(), 1); - client.reset( - new eth::Client( chainParams, ( int ) chainParams.networkID, shared_ptr< GasPricer >(), - NULL, monitor, m_tempDir.path().c_str(), WithExisting::Kill, TransactionQueue::Limits{100000, 1024} ) ); + setenv( "DATA_DIR", m_tempDir.path().c_str(), 1 ); + client.reset( new eth::Client( chainParams, ( int ) chainParams.networkID, + shared_ptr< GasPricer >(), NULL, monitor, m_tempDir.path().c_str(), WithExisting::Kill, + TransactionQueue::Limits{ 100000, 1024 } ) ); client->injectSkaleHost(); client->startWorking(); @@ -251,12 +251,12 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { client->setAuthor( coinbase.address() ); accountHolder.reset( new FixedAccountHolder( [&]() { return client.get(); }, {} ) ); - accountHolder->setAccounts( {coinbase} ); + accountHolder->setAccounts( { coinbase } ); using FullServer = ModularServer< rpc::EthFace, rpc::SkaleFace, rpc::Web3Face, rpc::DebugFace, rpc::TestFace >; - auto ethFace = new rpc::Eth( std::string(""), *client, *accountHolder.get() ); + auto ethFace = new rpc::Eth( std::string( "" ), *client, *accountHolder.get() ); rpcServer.reset( new FullServer( ethFace, new rpc::Skale( *client ), new rpc::Web3( /*web3->clientVersion()*/ ), new rpc::Debug( *client ), // TODO add @@ -266,7 +266,7 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { rpcServer->addConnector( ipcServer ); ipcServer->StartListening(); - auto client = new TestIpcClient{*ipcServer}; + auto client = new TestIpcClient{ *ipcServer }; rpcClient = unique_ptr< WebThreeStubClient >( new WebThreeStubClient( *client ) ); } @@ -286,8 +286,8 @@ class ConsensusExtFaceFixture : public ConsensusExtFace { } virtual void createBlock( const transactions_vector& _approvedTransactions, uint64_t _timeStamp, - uint32_t /* timeStampMs */, uint64_t _blockID, u256 /*_gasPrice */, - u256 /*_stateRoot*/, uint64_t /*_winningNodeIndex*/ ) override { + uint32_t /* timeStampMs */, uint64_t _blockID, u256 /*_gasPrice */, u256 /*_stateRoot*/, + uint64_t /*_winningNodeIndex*/ ) override { ( void ) _timeStamp; ( void ) _blockID; std::cerr << "Block arrived with " << _approvedTransactions.size() << " txns" << std::endl; @@ -398,8 +398,8 @@ BOOST_AUTO_TEST_CASE( gasPriceIncrease ) { v = transactions_vector( 9000 ); size_t i = 0; for ( auto& tx : v ) { - for(size_t j=0; j