diff --git a/tests2/common/api_tests.cmake b/ApiTests.cmake similarity index 100% rename from tests2/common/api_tests.cmake rename to ApiTests.cmake diff --git a/tests2/api_tests/account_by_key_api/CMakeLists.txt b/hived/account_by_key_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/account_by_key_api/CMakeLists.txt rename to hived/account_by_key_api/CMakeLists.txt diff --git a/tests2/api_tests/account_by_key_api/get_key_references.py b/hived/account_by_key_api/get_key_references.py similarity index 100% rename from tests2/api_tests/account_by_key_api/get_key_references.py rename to hived/account_by_key_api/get_key_references.py diff --git a/tests2/api_tests/account_by_key_api/readme.md b/hived/account_by_key_api/readme.md similarity index 100% rename from tests2/api_tests/account_by_key_api/readme.md rename to hived/account_by_key_api/readme.md diff --git a/tests2/api_tests/account_history_api/CMakeLists.txt b/hived/account_history_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/account_history_api/CMakeLists.txt rename to hived/account_history_api/CMakeLists.txt diff --git a/tests2/api_tests/account_history_api/enum_virtual_ops.py b/hived/account_history_api/enum_virtual_ops.py similarity index 100% rename from tests2/api_tests/account_history_api/enum_virtual_ops.py rename to hived/account_history_api/enum_virtual_ops.py diff --git a/tests2/api_tests/account_history_api/get_account_history.py b/hived/account_history_api/get_account_history.py similarity index 100% rename from tests2/api_tests/account_history_api/get_account_history.py rename to hived/account_history_api/get_account_history.py diff --git a/tests2/api_tests/account_history_api/get_ops_in_block.py b/hived/account_history_api/get_ops_in_block.py similarity index 100% rename from tests2/api_tests/account_history_api/get_ops_in_block.py rename to hived/account_history_api/get_ops_in_block.py diff --git a/tests2/api_tests/account_history_api/get_transaction.py b/hived/account_history_api/get_transaction.py similarity index 100% rename from tests2/api_tests/account_history_api/get_transaction.py rename to hived/account_history_api/get_transaction.py diff --git a/tests2/api_tests/account_history_api/readme.md b/hived/account_history_api/readme.md similarity index 100% rename from tests2/api_tests/account_history_api/readme.md rename to hived/account_history_api/readme.md diff --git a/tests2/scripts/api_error_smoketest.py b/hived/api_error_smoketest.py similarity index 100% rename from tests2/scripts/api_error_smoketest.py rename to hived/api_error_smoketest.py diff --git a/tests2/api_tests/condenser_api/CMakeLists.txt b/hived/condenser_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/condenser_api/CMakeLists.txt rename to hived/condenser_api/CMakeLists.txt diff --git a/tests2/api_tests/condenser_api/README.md b/hived/condenser_api/README.md similarity index 100% rename from tests2/api_tests/condenser_api/README.md rename to hived/condenser_api/README.md diff --git a/tests2/api_tests/condenser_api/broadcast_block.py b/hived/condenser_api/broadcast_block.py similarity index 100% rename from tests2/api_tests/condenser_api/broadcast_block.py rename to hived/condenser_api/broadcast_block.py diff --git a/tests2/api_tests/condenser_api/broadcast_transaction.py b/hived/condenser_api/broadcast_transaction.py similarity index 100% rename from tests2/api_tests/condenser_api/broadcast_transaction.py rename to hived/condenser_api/broadcast_transaction.py diff --git a/tests2/api_tests/condenser_api/broadcast_transaction_synchronous.py b/hived/condenser_api/broadcast_transaction_synchronous.py similarity index 100% rename from tests2/api_tests/condenser_api/broadcast_transaction_synchronous.py rename to hived/condenser_api/broadcast_transaction_synchronous.py diff --git a/tests2/api_tests/condenser_api/find_proposals.py b/hived/condenser_api/find_proposals.py similarity index 100% rename from tests2/api_tests/condenser_api/find_proposals.py rename to hived/condenser_api/find_proposals.py diff --git a/tests2/api_tests/condenser_api/get_account_count.py b/hived/condenser_api/get_account_count.py similarity index 100% rename from tests2/api_tests/condenser_api/get_account_count.py rename to hived/condenser_api/get_account_count.py diff --git a/tests2/api_tests/condenser_api/get_account_history.py b/hived/condenser_api/get_account_history.py similarity index 100% rename from tests2/api_tests/condenser_api/get_account_history.py rename to hived/condenser_api/get_account_history.py diff --git a/tests2/api_tests/condenser_api/get_accounts.py b/hived/condenser_api/get_accounts.py similarity index 100% rename from tests2/api_tests/condenser_api/get_accounts.py rename to hived/condenser_api/get_accounts.py diff --git a/tests2/api_tests/condenser_api/get_active_witnesses.py b/hived/condenser_api/get_active_witnesses.py similarity index 100% rename from tests2/api_tests/condenser_api/get_active_witnesses.py rename to hived/condenser_api/get_active_witnesses.py diff --git a/tests2/api_tests/condenser_api/get_block.py b/hived/condenser_api/get_block.py similarity index 100% rename from tests2/api_tests/condenser_api/get_block.py rename to hived/condenser_api/get_block.py diff --git a/tests2/api_tests/condenser_api/get_block_header.py b/hived/condenser_api/get_block_header.py similarity index 100% rename from tests2/api_tests/condenser_api/get_block_header.py rename to hived/condenser_api/get_block_header.py diff --git a/tests2/api_tests/condenser_api/get_chain_properties.py b/hived/condenser_api/get_chain_properties.py similarity index 100% rename from tests2/api_tests/condenser_api/get_chain_properties.py rename to hived/condenser_api/get_chain_properties.py diff --git a/tests2/api_tests/condenser_api/get_config.py b/hived/condenser_api/get_config.py similarity index 100% rename from tests2/api_tests/condenser_api/get_config.py rename to hived/condenser_api/get_config.py diff --git a/tests2/api_tests/condenser_api/get_conversion_requests.py b/hived/condenser_api/get_conversion_requests.py similarity index 100% rename from tests2/api_tests/condenser_api/get_conversion_requests.py rename to hived/condenser_api/get_conversion_requests.py diff --git a/tests2/api_tests/condenser_api/get_current_median_history_price.py b/hived/condenser_api/get_current_median_history_price.py similarity index 100% rename from tests2/api_tests/condenser_api/get_current_median_history_price.py rename to hived/condenser_api/get_current_median_history_price.py diff --git a/tests2/api_tests/condenser_api/get_dynamic_global_properties.py b/hived/condenser_api/get_dynamic_global_properties.py similarity index 100% rename from tests2/api_tests/condenser_api/get_dynamic_global_properties.py rename to hived/condenser_api/get_dynamic_global_properties.py diff --git a/tests2/api_tests/condenser_api/get_escrow.py b/hived/condenser_api/get_escrow.py similarity index 100% rename from tests2/api_tests/condenser_api/get_escrow.py rename to hived/condenser_api/get_escrow.py diff --git a/tests2/api_tests/condenser_api/get_expiring_vesting_delegations.py b/hived/condenser_api/get_expiring_vesting_delegations.py similarity index 100% rename from tests2/api_tests/condenser_api/get_expiring_vesting_delegations.py rename to hived/condenser_api/get_expiring_vesting_delegations.py diff --git a/tests2/api_tests/condenser_api/get_feed_history.py b/hived/condenser_api/get_feed_history.py similarity index 100% rename from tests2/api_tests/condenser_api/get_feed_history.py rename to hived/condenser_api/get_feed_history.py diff --git a/tests2/api_tests/condenser_api/get_hardfork_version.py b/hived/condenser_api/get_hardfork_version.py similarity index 100% rename from tests2/api_tests/condenser_api/get_hardfork_version.py rename to hived/condenser_api/get_hardfork_version.py diff --git a/tests2/api_tests/condenser_api/get_key_references.py b/hived/condenser_api/get_key_references.py similarity index 100% rename from tests2/api_tests/condenser_api/get_key_references.py rename to hived/condenser_api/get_key_references.py diff --git a/tests2/api_tests/condenser_api/get_market_history.py b/hived/condenser_api/get_market_history.py similarity index 100% rename from tests2/api_tests/condenser_api/get_market_history.py rename to hived/condenser_api/get_market_history.py diff --git a/tests2/api_tests/condenser_api/get_market_history_buckets.py b/hived/condenser_api/get_market_history_buckets.py similarity index 100% rename from tests2/api_tests/condenser_api/get_market_history_buckets.py rename to hived/condenser_api/get_market_history_buckets.py diff --git a/tests2/api_tests/condenser_api/get_next_scheduled_hardfork.py b/hived/condenser_api/get_next_scheduled_hardfork.py similarity index 100% rename from tests2/api_tests/condenser_api/get_next_scheduled_hardfork.py rename to hived/condenser_api/get_next_scheduled_hardfork.py diff --git a/tests2/api_tests/condenser_api/get_open_orders.py b/hived/condenser_api/get_open_orders.py similarity index 100% rename from tests2/api_tests/condenser_api/get_open_orders.py rename to hived/condenser_api/get_open_orders.py diff --git a/tests2/api_tests/condenser_api/get_ops_in_block.py b/hived/condenser_api/get_ops_in_block.py similarity index 100% rename from tests2/api_tests/condenser_api/get_ops_in_block.py rename to hived/condenser_api/get_ops_in_block.py diff --git a/tests2/api_tests/condenser_api/get_order_book.py b/hived/condenser_api/get_order_book.py similarity index 100% rename from tests2/api_tests/condenser_api/get_order_book.py rename to hived/condenser_api/get_order_book.py diff --git a/tests2/api_tests/condenser_api/get_owner_history.py b/hived/condenser_api/get_owner_history.py similarity index 100% rename from tests2/api_tests/condenser_api/get_owner_history.py rename to hived/condenser_api/get_owner_history.py diff --git a/tests2/api_tests/condenser_api/get_potential_signatures.py b/hived/condenser_api/get_potential_signatures.py similarity index 100% rename from tests2/api_tests/condenser_api/get_potential_signatures.py rename to hived/condenser_api/get_potential_signatures.py diff --git a/tests2/api_tests/condenser_api/get_recent_trades.py b/hived/condenser_api/get_recent_trades.py similarity index 100% rename from tests2/api_tests/condenser_api/get_recent_trades.py rename to hived/condenser_api/get_recent_trades.py diff --git a/tests2/api_tests/condenser_api/get_recovery_request.py b/hived/condenser_api/get_recovery_request.py similarity index 100% rename from tests2/api_tests/condenser_api/get_recovery_request.py rename to hived/condenser_api/get_recovery_request.py diff --git a/tests2/api_tests/condenser_api/get_required_signatures.py b/hived/condenser_api/get_required_signatures.py similarity index 100% rename from tests2/api_tests/condenser_api/get_required_signatures.py rename to hived/condenser_api/get_required_signatures.py diff --git a/tests2/api_tests/condenser_api/get_reward_fund.py b/hived/condenser_api/get_reward_fund.py similarity index 100% rename from tests2/api_tests/condenser_api/get_reward_fund.py rename to hived/condenser_api/get_reward_fund.py diff --git a/tests2/api_tests/condenser_api/get_savings_withdraw_from.py b/hived/condenser_api/get_savings_withdraw_from.py similarity index 100% rename from tests2/api_tests/condenser_api/get_savings_withdraw_from.py rename to hived/condenser_api/get_savings_withdraw_from.py diff --git a/tests2/api_tests/condenser_api/get_savings_withdraw_to.py b/hived/condenser_api/get_savings_withdraw_to.py similarity index 100% rename from tests2/api_tests/condenser_api/get_savings_withdraw_to.py rename to hived/condenser_api/get_savings_withdraw_to.py diff --git a/tests2/api_tests/condenser_api/get_ticker.py b/hived/condenser_api/get_ticker.py similarity index 100% rename from tests2/api_tests/condenser_api/get_ticker.py rename to hived/condenser_api/get_ticker.py diff --git a/tests2/api_tests/condenser_api/get_trade_history.py b/hived/condenser_api/get_trade_history.py similarity index 100% rename from tests2/api_tests/condenser_api/get_trade_history.py rename to hived/condenser_api/get_trade_history.py diff --git a/tests2/api_tests/condenser_api/get_transaction.py b/hived/condenser_api/get_transaction.py similarity index 100% rename from tests2/api_tests/condenser_api/get_transaction.py rename to hived/condenser_api/get_transaction.py diff --git a/tests2/api_tests/condenser_api/get_transaction_hex.py b/hived/condenser_api/get_transaction_hex.py similarity index 100% rename from tests2/api_tests/condenser_api/get_transaction_hex.py rename to hived/condenser_api/get_transaction_hex.py diff --git a/tests2/api_tests/condenser_api/get_version.py b/hived/condenser_api/get_version.py similarity index 100% rename from tests2/api_tests/condenser_api/get_version.py rename to hived/condenser_api/get_version.py diff --git a/tests2/api_tests/condenser_api/get_vesting_delegations.py b/hived/condenser_api/get_vesting_delegations.py similarity index 100% rename from tests2/api_tests/condenser_api/get_vesting_delegations.py rename to hived/condenser_api/get_vesting_delegations.py diff --git a/tests2/api_tests/condenser_api/get_volume.py b/hived/condenser_api/get_volume.py similarity index 100% rename from tests2/api_tests/condenser_api/get_volume.py rename to hived/condenser_api/get_volume.py diff --git a/tests2/api_tests/condenser_api/get_withdraw_routes.py b/hived/condenser_api/get_withdraw_routes.py similarity index 100% rename from tests2/api_tests/condenser_api/get_withdraw_routes.py rename to hived/condenser_api/get_withdraw_routes.py diff --git a/tests2/api_tests/condenser_api/get_witness_by_account.py b/hived/condenser_api/get_witness_by_account.py similarity index 100% rename from tests2/api_tests/condenser_api/get_witness_by_account.py rename to hived/condenser_api/get_witness_by_account.py diff --git a/tests2/api_tests/condenser_api/get_witness_count.py b/hived/condenser_api/get_witness_count.py similarity index 100% rename from tests2/api_tests/condenser_api/get_witness_count.py rename to hived/condenser_api/get_witness_count.py diff --git a/tests2/api_tests/condenser_api/get_witness_schedule.py b/hived/condenser_api/get_witness_schedule.py similarity index 100% rename from tests2/api_tests/condenser_api/get_witness_schedule.py rename to hived/condenser_api/get_witness_schedule.py diff --git a/tests2/api_tests/condenser_api/get_witnesses.py b/hived/condenser_api/get_witnesses.py similarity index 100% rename from tests2/api_tests/condenser_api/get_witnesses.py rename to hived/condenser_api/get_witnesses.py diff --git a/tests2/api_tests/condenser_api/get_witnesses_by_vote.py b/hived/condenser_api/get_witnesses_by_vote.py similarity index 100% rename from tests2/api_tests/condenser_api/get_witnesses_by_vote.py rename to hived/condenser_api/get_witnesses_by_vote.py diff --git a/tests2/api_tests/condenser_api/list_proposal_votes.py b/hived/condenser_api/list_proposal_votes.py similarity index 100% rename from tests2/api_tests/condenser_api/list_proposal_votes.py rename to hived/condenser_api/list_proposal_votes.py diff --git a/tests2/api_tests/condenser_api/list_proposals.py b/hived/condenser_api/list_proposals.py similarity index 100% rename from tests2/api_tests/condenser_api/list_proposals.py rename to hived/condenser_api/list_proposals.py diff --git a/tests2/api_tests/condenser_api/lookup_account_names.py b/hived/condenser_api/lookup_account_names.py similarity index 100% rename from tests2/api_tests/condenser_api/lookup_account_names.py rename to hived/condenser_api/lookup_account_names.py diff --git a/tests2/api_tests/condenser_api/lookup_accounts.py b/hived/condenser_api/lookup_accounts.py similarity index 100% rename from tests2/api_tests/condenser_api/lookup_accounts.py rename to hived/condenser_api/lookup_accounts.py diff --git a/tests2/api_tests/condenser_api/lookup_witness_accounts.py b/hived/condenser_api/lookup_witness_accounts.py similarity index 100% rename from tests2/api_tests/condenser_api/lookup_witness_accounts.py rename to hived/condenser_api/lookup_witness_accounts.py diff --git a/tests2/api_tests/condenser_api/verify_authority.py b/hived/condenser_api/verify_authority.py similarity index 100% rename from tests2/api_tests/condenser_api/verify_authority.py rename to hived/condenser_api/verify_authority.py diff --git a/tests2/scripts/create_account_list.py b/hived/create_account_list.py similarity index 100% rename from tests2/scripts/create_account_list.py rename to hived/create_account_list.py diff --git a/tests2/api_tests/database_api/CMakeLists.txt b/hived/database_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/database_api/CMakeLists.txt rename to hived/database_api/CMakeLists.txt diff --git a/tests2/api_tests/database_api/README.md b/hived/database_api/README.md similarity index 100% rename from tests2/api_tests/database_api/README.md rename to hived/database_api/README.md diff --git a/tests2/api_tests/database_api/find_account_recovery_requests.py b/hived/database_api/find_account_recovery_requests.py similarity index 100% rename from tests2/api_tests/database_api/find_account_recovery_requests.py rename to hived/database_api/find_account_recovery_requests.py diff --git a/tests2/api_tests/database_api/find_accounts.py b/hived/database_api/find_accounts.py similarity index 100% rename from tests2/api_tests/database_api/find_accounts.py rename to hived/database_api/find_accounts.py diff --git a/tests2/api_tests/database_api/find_change_recovery_account_requests.py b/hived/database_api/find_change_recovery_account_requests.py similarity index 100% rename from tests2/api_tests/database_api/find_change_recovery_account_requests.py rename to hived/database_api/find_change_recovery_account_requests.py diff --git a/tests2/api_tests/database_api/find_decline_voting_rights_requests.py b/hived/database_api/find_decline_voting_rights_requests.py similarity index 100% rename from tests2/api_tests/database_api/find_decline_voting_rights_requests.py rename to hived/database_api/find_decline_voting_rights_requests.py diff --git a/tests2/api_tests/database_api/find_escrows.py b/hived/database_api/find_escrows.py similarity index 100% rename from tests2/api_tests/database_api/find_escrows.py rename to hived/database_api/find_escrows.py diff --git a/tests2/api_tests/database_api/find_hbd_conversion_requests.py b/hived/database_api/find_hbd_conversion_requests.py similarity index 100% rename from tests2/api_tests/database_api/find_hbd_conversion_requests.py rename to hived/database_api/find_hbd_conversion_requests.py diff --git a/tests2/api_tests/database_api/find_limit_orders.py b/hived/database_api/find_limit_orders.py similarity index 100% rename from tests2/api_tests/database_api/find_limit_orders.py rename to hived/database_api/find_limit_orders.py diff --git a/tests2/api_tests/database_api/find_owner_histories.py b/hived/database_api/find_owner_histories.py similarity index 100% rename from tests2/api_tests/database_api/find_owner_histories.py rename to hived/database_api/find_owner_histories.py diff --git a/tests2/api_tests/database_api/find_proposals.py b/hived/database_api/find_proposals.py similarity index 100% rename from tests2/api_tests/database_api/find_proposals.py rename to hived/database_api/find_proposals.py diff --git a/tests2/api_tests/database_api/find_savings_withdrawals.py b/hived/database_api/find_savings_withdrawals.py similarity index 100% rename from tests2/api_tests/database_api/find_savings_withdrawals.py rename to hived/database_api/find_savings_withdrawals.py diff --git a/tests2/api_tests/database_api/find_smt_contributions.py b/hived/database_api/find_smt_contributions.py similarity index 100% rename from tests2/api_tests/database_api/find_smt_contributions.py rename to hived/database_api/find_smt_contributions.py diff --git a/tests2/api_tests/database_api/find_smt_token_emissions.py b/hived/database_api/find_smt_token_emissions.py similarity index 100% rename from tests2/api_tests/database_api/find_smt_token_emissions.py rename to hived/database_api/find_smt_token_emissions.py diff --git a/tests2/api_tests/database_api/find_smt_tokens.py b/hived/database_api/find_smt_tokens.py similarity index 100% rename from tests2/api_tests/database_api/find_smt_tokens.py rename to hived/database_api/find_smt_tokens.py diff --git a/tests2/api_tests/database_api/find_vesting_delegation_expirations.py b/hived/database_api/find_vesting_delegation_expirations.py similarity index 100% rename from tests2/api_tests/database_api/find_vesting_delegation_expirations.py rename to hived/database_api/find_vesting_delegation_expirations.py diff --git a/tests2/api_tests/database_api/find_vesting_delegations.py b/hived/database_api/find_vesting_delegations.py similarity index 100% rename from tests2/api_tests/database_api/find_vesting_delegations.py rename to hived/database_api/find_vesting_delegations.py diff --git a/tests2/api_tests/database_api/find_votes.py b/hived/database_api/find_votes.py similarity index 100% rename from tests2/api_tests/database_api/find_votes.py rename to hived/database_api/find_votes.py diff --git a/tests2/api_tests/database_api/find_withdraw_vesting_routes.py b/hived/database_api/find_withdraw_vesting_routes.py similarity index 100% rename from tests2/api_tests/database_api/find_withdraw_vesting_routes.py rename to hived/database_api/find_withdraw_vesting_routes.py diff --git a/tests2/api_tests/database_api/find_witnesses.py b/hived/database_api/find_witnesses.py similarity index 100% rename from tests2/api_tests/database_api/find_witnesses.py rename to hived/database_api/find_witnesses.py diff --git a/tests2/api_tests/database_api/get_active_witnesses.py b/hived/database_api/get_active_witnesses.py similarity index 100% rename from tests2/api_tests/database_api/get_active_witnesses.py rename to hived/database_api/get_active_witnesses.py diff --git a/tests2/api_tests/database_api/get_config.py b/hived/database_api/get_config.py similarity index 100% rename from tests2/api_tests/database_api/get_config.py rename to hived/database_api/get_config.py diff --git a/tests2/api_tests/database_api/get_current_price_feed.py b/hived/database_api/get_current_price_feed.py similarity index 100% rename from tests2/api_tests/database_api/get_current_price_feed.py rename to hived/database_api/get_current_price_feed.py diff --git a/tests2/api_tests/database_api/get_dynamic_global_properties.py b/hived/database_api/get_dynamic_global_properties.py similarity index 100% rename from tests2/api_tests/database_api/get_dynamic_global_properties.py rename to hived/database_api/get_dynamic_global_properties.py diff --git a/tests2/api_tests/database_api/get_feed_history.py b/hived/database_api/get_feed_history.py similarity index 100% rename from tests2/api_tests/database_api/get_feed_history.py rename to hived/database_api/get_feed_history.py diff --git a/tests2/api_tests/database_api/get_hardfork_properties.py b/hived/database_api/get_hardfork_properties.py similarity index 100% rename from tests2/api_tests/database_api/get_hardfork_properties.py rename to hived/database_api/get_hardfork_properties.py diff --git a/tests2/api_tests/database_api/get_nai_pool.py b/hived/database_api/get_nai_pool.py similarity index 100% rename from tests2/api_tests/database_api/get_nai_pool.py rename to hived/database_api/get_nai_pool.py diff --git a/tests2/api_tests/database_api/get_order_book.py b/hived/database_api/get_order_book.py similarity index 100% rename from tests2/api_tests/database_api/get_order_book.py rename to hived/database_api/get_order_book.py diff --git a/tests2/api_tests/database_api/get_potential_signatures.py b/hived/database_api/get_potential_signatures.py similarity index 100% rename from tests2/api_tests/database_api/get_potential_signatures.py rename to hived/database_api/get_potential_signatures.py diff --git a/tests2/api_tests/database_api/get_required_signatures.py b/hived/database_api/get_required_signatures.py similarity index 100% rename from tests2/api_tests/database_api/get_required_signatures.py rename to hived/database_api/get_required_signatures.py diff --git a/tests2/api_tests/database_api/get_reward_funds.py b/hived/database_api/get_reward_funds.py similarity index 100% rename from tests2/api_tests/database_api/get_reward_funds.py rename to hived/database_api/get_reward_funds.py diff --git a/tests2/api_tests/database_api/get_transaction_hex.py b/hived/database_api/get_transaction_hex.py similarity index 100% rename from tests2/api_tests/database_api/get_transaction_hex.py rename to hived/database_api/get_transaction_hex.py diff --git a/tests2/api_tests/database_api/get_version.py b/hived/database_api/get_version.py similarity index 100% rename from tests2/api_tests/database_api/get_version.py rename to hived/database_api/get_version.py diff --git a/tests2/api_tests/database_api/get_witness_schedule.py b/hived/database_api/get_witness_schedule.py similarity index 100% rename from tests2/api_tests/database_api/get_witness_schedule.py rename to hived/database_api/get_witness_schedule.py diff --git a/tests2/api_tests/database_api/list_account_recovery_requests.py b/hived/database_api/list_account_recovery_requests.py similarity index 100% rename from tests2/api_tests/database_api/list_account_recovery_requests.py rename to hived/database_api/list_account_recovery_requests.py diff --git a/tests2/api_tests/database_api/list_accounts.py b/hived/database_api/list_accounts.py similarity index 100% rename from tests2/api_tests/database_api/list_accounts.py rename to hived/database_api/list_accounts.py diff --git a/tests2/api_tests/database_api/list_change_recovery_account_requests.py b/hived/database_api/list_change_recovery_account_requests.py similarity index 100% rename from tests2/api_tests/database_api/list_change_recovery_account_requests.py rename to hived/database_api/list_change_recovery_account_requests.py diff --git a/tests2/api_tests/database_api/list_decline_voting_rights_requests.py b/hived/database_api/list_decline_voting_rights_requests.py similarity index 100% rename from tests2/api_tests/database_api/list_decline_voting_rights_requests.py rename to hived/database_api/list_decline_voting_rights_requests.py diff --git a/tests2/api_tests/database_api/list_escrows.py b/hived/database_api/list_escrows.py similarity index 100% rename from tests2/api_tests/database_api/list_escrows.py rename to hived/database_api/list_escrows.py diff --git a/tests2/api_tests/database_api/list_hbd_conversion_requests.py b/hived/database_api/list_hbd_conversion_requests.py similarity index 100% rename from tests2/api_tests/database_api/list_hbd_conversion_requests.py rename to hived/database_api/list_hbd_conversion_requests.py diff --git a/tests2/api_tests/database_api/list_limit_orders.py b/hived/database_api/list_limit_orders.py similarity index 100% rename from tests2/api_tests/database_api/list_limit_orders.py rename to hived/database_api/list_limit_orders.py diff --git a/tests2/api_tests/database_api/list_owner_histories.py b/hived/database_api/list_owner_histories.py similarity index 100% rename from tests2/api_tests/database_api/list_owner_histories.py rename to hived/database_api/list_owner_histories.py diff --git a/tests2/api_tests/database_api/list_proposal_votes.py b/hived/database_api/list_proposal_votes.py similarity index 100% rename from tests2/api_tests/database_api/list_proposal_votes.py rename to hived/database_api/list_proposal_votes.py diff --git a/tests2/api_tests/database_api/list_proposals.py b/hived/database_api/list_proposals.py similarity index 100% rename from tests2/api_tests/database_api/list_proposals.py rename to hived/database_api/list_proposals.py diff --git a/tests2/api_tests/database_api/list_savings_withdrawals.py b/hived/database_api/list_savings_withdrawals.py similarity index 100% rename from tests2/api_tests/database_api/list_savings_withdrawals.py rename to hived/database_api/list_savings_withdrawals.py diff --git a/tests2/api_tests/database_api/list_smt_contributions.py b/hived/database_api/list_smt_contributions.py similarity index 100% rename from tests2/api_tests/database_api/list_smt_contributions.py rename to hived/database_api/list_smt_contributions.py diff --git a/tests2/api_tests/database_api/list_smt_token_emissions.py b/hived/database_api/list_smt_token_emissions.py similarity index 100% rename from tests2/api_tests/database_api/list_smt_token_emissions.py rename to hived/database_api/list_smt_token_emissions.py diff --git a/tests2/api_tests/database_api/list_smt_tokens.py b/hived/database_api/list_smt_tokens.py similarity index 100% rename from tests2/api_tests/database_api/list_smt_tokens.py rename to hived/database_api/list_smt_tokens.py diff --git a/tests2/api_tests/database_api/list_vesting_delegation_expirations.py b/hived/database_api/list_vesting_delegation_expirations.py similarity index 100% rename from tests2/api_tests/database_api/list_vesting_delegation_expirations.py rename to hived/database_api/list_vesting_delegation_expirations.py diff --git a/tests2/api_tests/database_api/list_vesting_delegations.py b/hived/database_api/list_vesting_delegations.py similarity index 100% rename from tests2/api_tests/database_api/list_vesting_delegations.py rename to hived/database_api/list_vesting_delegations.py diff --git a/tests2/api_tests/database_api/list_votes.py b/hived/database_api/list_votes.py similarity index 100% rename from tests2/api_tests/database_api/list_votes.py rename to hived/database_api/list_votes.py diff --git a/tests2/api_tests/database_api/list_withdraw_vesting_routes.py b/hived/database_api/list_withdraw_vesting_routes.py similarity index 100% rename from tests2/api_tests/database_api/list_withdraw_vesting_routes.py rename to hived/database_api/list_withdraw_vesting_routes.py diff --git a/tests2/api_tests/database_api/list_witness_votes.py b/hived/database_api/list_witness_votes.py similarity index 100% rename from tests2/api_tests/database_api/list_witness_votes.py rename to hived/database_api/list_witness_votes.py diff --git a/tests2/api_tests/database_api/list_witnesses.py b/hived/database_api/list_witnesses.py similarity index 100% rename from tests2/api_tests/database_api/list_witnesses.py rename to hived/database_api/list_witnesses.py diff --git a/tests2/api_tests/database_api/verify_account_authority.py b/hived/database_api/verify_account_authority.py similarity index 100% rename from tests2/api_tests/database_api/verify_account_authority.py rename to hived/database_api/verify_account_authority.py diff --git a/tests2/api_tests/database_api/verify_authority.py b/hived/database_api/verify_authority.py similarity index 100% rename from tests2/api_tests/database_api/verify_authority.py rename to hived/database_api/verify_authority.py diff --git a/tests2/api_tests/database_api/verify_signatures.py b/hived/database_api/verify_signatures.py similarity index 100% rename from tests2/api_tests/database_api/verify_signatures.py rename to hived/database_api/verify_signatures.py diff --git a/tests2/api_tests/get_ops_in_block.py b/hived/get_ops_in_block.py similarity index 100% rename from tests2/api_tests/get_ops_in_block.py rename to hived/get_ops_in_block.py diff --git a/tests2/api_tests/jsonrpc_api/CMakeLists.txt b/hived/jsonrpc_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/jsonrpc_api/CMakeLists.txt rename to hived/jsonrpc_api/CMakeLists.txt diff --git a/tests2/api_tests/jsonrpc_api/README.md b/hived/jsonrpc_api/README.md similarity index 100% rename from tests2/api_tests/jsonrpc_api/README.md rename to hived/jsonrpc_api/README.md diff --git a/tests2/api_tests/jsonrpc_api/get_methods.py b/hived/jsonrpc_api/get_methods.py similarity index 100% rename from tests2/api_tests/jsonrpc_api/get_methods.py rename to hived/jsonrpc_api/get_methods.py diff --git a/tests2/api_tests/jsonrpc_api/get_signature.py b/hived/jsonrpc_api/get_signature.py similarity index 100% rename from tests2/api_tests/jsonrpc_api/get_signature.py rename to hived/jsonrpc_api/get_signature.py diff --git a/tests2/api_tests/list_account.py b/hived/list_account.py similarity index 100% rename from tests2/api_tests/list_account.py rename to hived/list_account.py diff --git a/tests2/api_tests/market_history_api/CMakeLists.txt b/hived/market_history_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/market_history_api/CMakeLists.txt rename to hived/market_history_api/CMakeLists.txt diff --git a/tests2/api_tests/market_history_api/README.md b/hived/market_history_api/README.md similarity index 100% rename from tests2/api_tests/market_history_api/README.md rename to hived/market_history_api/README.md diff --git a/tests2/api_tests/market_history_api/get_market_history.py b/hived/market_history_api/get_market_history.py similarity index 100% rename from tests2/api_tests/market_history_api/get_market_history.py rename to hived/market_history_api/get_market_history.py diff --git a/tests2/api_tests/market_history_api/get_market_history_buckets.py b/hived/market_history_api/get_market_history_buckets.py similarity index 100% rename from tests2/api_tests/market_history_api/get_market_history_buckets.py rename to hived/market_history_api/get_market_history_buckets.py diff --git a/tests2/api_tests/market_history_api/get_order_book.py b/hived/market_history_api/get_order_book.py similarity index 100% rename from tests2/api_tests/market_history_api/get_order_book.py rename to hived/market_history_api/get_order_book.py diff --git a/tests2/api_tests/market_history_api/get_recent_trades.py b/hived/market_history_api/get_recent_trades.py similarity index 100% rename from tests2/api_tests/market_history_api/get_recent_trades.py rename to hived/market_history_api/get_recent_trades.py diff --git a/tests2/api_tests/market_history_api/get_ticker.py b/hived/market_history_api/get_ticker.py similarity index 100% rename from tests2/api_tests/market_history_api/get_ticker.py rename to hived/market_history_api/get_ticker.py diff --git a/tests2/api_tests/market_history_api/get_trade_history.py b/hived/market_history_api/get_trade_history.py similarity index 100% rename from tests2/api_tests/market_history_api/get_trade_history.py rename to hived/market_history_api/get_trade_history.py diff --git a/tests2/api_tests/market_history_api/get_volume.py b/hived/market_history_api/get_volume.py similarity index 100% rename from tests2/api_tests/market_history_api/get_volume.py rename to hived/market_history_api/get_volume.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/account_history_api/account_history_api_test.yaml b/hived/pyresttest_api_tests/account_history_api/account_history_api_test.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/account_history_api/account_history_api_test.yaml rename to hived/pyresttest_api_tests/account_history_api/account_history_api_test.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/account_history_api/get_account_history.json.pat b/hived/pyresttest_api_tests/account_history_api/get_account_history.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/account_history_api/get_account_history.json.pat rename to hived/pyresttest_api_tests/account_history_api/get_account_history.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/account_history_api/get_ops_in_block.json.pat b/hived/pyresttest_api_tests/account_history_api/get_ops_in_block.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/account_history_api/get_ops_in_block.json.pat rename to hived/pyresttest_api_tests/account_history_api/get_ops_in_block.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/account_history_api/request_template.json b/hived/pyresttest_api_tests/account_history_api/request_template.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/account_history_api/request_template.json rename to hived/pyresttest_api_tests/account_history_api/request_template.json diff --git a/tests2/functional/python_tests/pyresttest_api_tests/basic_smoketest.yaml b/hived/pyresttest_api_tests/basic_smoketest.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/basic_smoketest.yaml rename to hived/pyresttest_api_tests/basic_smoketest.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/comparator_appbase_ops.py b/hived/pyresttest_api_tests/comparator_appbase_ops.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/comparator_appbase_ops.py rename to hived/pyresttest_api_tests/comparator_appbase_ops.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/comparator_contain.py b/hived/pyresttest_api_tests/comparator_contain.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/comparator_contain.py rename to hived/pyresttest_api_tests/comparator_contain.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/comparator_equal.py b/hived/pyresttest_api_tests/comparator_equal.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/comparator_equal.py rename to hived/pyresttest_api_tests/comparator_equal.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_appbase.json b/hived/pyresttest_api_tests/compare_state/compare_block_appbase.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_appbase.json rename to hived/pyresttest_api_tests/compare_state/compare_block_appbase.json diff --git a/tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_appbase.yaml b/hived/pyresttest_api_tests/compare_state/compare_block_appbase.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_appbase.yaml rename to hived/pyresttest_api_tests/compare_state/compare_block_appbase.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_old.json b/hived/pyresttest_api_tests/compare_state/compare_block_old.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_old.json rename to hived/pyresttest_api_tests/compare_state/compare_block_old.json diff --git a/tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_old.yaml b/hived/pyresttest_api_tests/compare_state/compare_block_old.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/compare_state/compare_block_old.yaml rename to hived/pyresttest_api_tests/compare_state/compare_block_old.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/compare_state_history.sh b/hived/pyresttest_api_tests/compare_state_history.sh similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/compare_state_history.sh rename to hived/pyresttest_api_tests/compare_state_history.sh diff --git a/tests2/functional/python_tests/pyresttest_api_tests/condenser_api/find_proposals.json.pat b/hived/pyresttest_api_tests/condenser_api/find_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/condenser_api/find_proposals.json.pat rename to hived/pyresttest_api_tests/condenser_api/find_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/condenser_api/list_proposals.json.pat b/hived/pyresttest_api_tests/condenser_api/list_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/condenser_api/list_proposals.json.pat rename to hived/pyresttest_api_tests/condenser_api/list_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/condenser_api/list_voter_proposals.json.pat b/hived/pyresttest_api_tests/condenser_api/list_voter_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/condenser_api/list_voter_proposals.json.pat rename to hived/pyresttest_api_tests/condenser_api/list_voter_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/condenser_api/request_template.json b/hived/pyresttest_api_tests/condenser_api/request_template.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/condenser_api/request_template.json rename to hived/pyresttest_api_tests/condenser_api/request_template.json diff --git a/tests2/functional/python_tests/pyresttest_api_tests/condenser_api/sps_via_condenser_test.yaml b/hived/pyresttest_api_tests/condenser_api/sps_via_condenser_test.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/condenser_api/sps_via_condenser_test.yaml rename to hived/pyresttest_api_tests/condenser_api/sps_via_condenser_test.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/database_api_test.yaml b/hived/pyresttest_api_tests/database_api/database_api_test.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/database_api_test.yaml rename to hived/pyresttest_api_tests/database_api/database_api_test.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_config.json.pat b/hived/pyresttest_api_tests/database_api/get_config.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_config.json.pat rename to hived/pyresttest_api_tests/database_api/get_config.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_current_price_feed.json.pat b/hived/pyresttest_api_tests/database_api/get_current_price_feed.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_current_price_feed.json.pat rename to hived/pyresttest_api_tests/database_api/get_current_price_feed.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_dynamic_global_properties.json.pat b/hived/pyresttest_api_tests/database_api/get_dynamic_global_properties.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_dynamic_global_properties.json.pat rename to hived/pyresttest_api_tests/database_api/get_dynamic_global_properties.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_feed_history.json.pat b/hived/pyresttest_api_tests/database_api/get_feed_history.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_feed_history.json.pat rename to hived/pyresttest_api_tests/database_api/get_feed_history.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_hardfork_properties.json.pat b/hived/pyresttest_api_tests/database_api/get_hardfork_properties.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_hardfork_properties.json.pat rename to hived/pyresttest_api_tests/database_api/get_hardfork_properties.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_reward_funds.json.pat b/hived/pyresttest_api_tests/database_api/get_reward_funds.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_reward_funds.json.pat rename to hived/pyresttest_api_tests/database_api/get_reward_funds.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/get_witness_schedule.json.pat b/hived/pyresttest_api_tests/database_api/get_witness_schedule.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/get_witness_schedule.json.pat rename to hived/pyresttest_api_tests/database_api/get_witness_schedule.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/list_witnesses.json.pat b/hived/pyresttest_api_tests/database_api/list_witnesses.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/list_witnesses.json.pat rename to hived/pyresttest_api_tests/database_api/list_witnesses.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/database_api/request_template.json b/hived/pyresttest_api_tests/database_api/request_template.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/database_api/request_template.json rename to hived/pyresttest_api_tests/database_api/request_template.json diff --git a/tests2/common/jsonsocket.py b/hived/pyresttest_api_tests/jsonsocket.py similarity index 100% rename from tests2/common/jsonsocket.py rename to hived/pyresttest_api_tests/jsonsocket.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/list_account.py b/hived/pyresttest_api_tests/list_account.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/list_account.py rename to hived/pyresttest_api_tests/list_account.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/run_api_tests.sh b/hived/pyresttest_api_tests/run_api_tests.sh similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/run_api_tests.sh rename to hived/pyresttest_api_tests/run_api_tests.sh diff --git a/tests2/functional/python_tests/pyresttest_api_tests/sps_api/find_proposals.json.pat b/hived/pyresttest_api_tests/sps_api/find_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/sps_api/find_proposals.json.pat rename to hived/pyresttest_api_tests/sps_api/find_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/sps_api/list_proposals.json.pat b/hived/pyresttest_api_tests/sps_api/list_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/sps_api/list_proposals.json.pat rename to hived/pyresttest_api_tests/sps_api/list_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/sps_api/list_voter_proposals.json.pat b/hived/pyresttest_api_tests/sps_api/list_voter_proposals.json.pat similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/sps_api/list_voter_proposals.json.pat rename to hived/pyresttest_api_tests/sps_api/list_voter_proposals.json.pat diff --git a/tests2/functional/python_tests/pyresttest_api_tests/sps_api/request_template.json b/hived/pyresttest_api_tests/sps_api/request_template.json similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/sps_api/request_template.json rename to hived/pyresttest_api_tests/sps_api/request_template.json diff --git a/tests2/functional/python_tests/pyresttest_api_tests/sps_api/sps_api_test.yaml b/hived/pyresttest_api_tests/sps_api/sps_api_test.yaml similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/sps_api/sps_api_test.yaml rename to hived/pyresttest_api_tests/sps_api/sps_api_test.yaml diff --git a/tests2/functional/python_tests/pyresttest_api_tests/test_ah_get_account_history.py b/hived/pyresttest_api_tests/test_ah_get_account_history.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/test_ah_get_account_history.py rename to hived/pyresttest_api_tests/test_ah_get_account_history.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/test_ah_get_ops_in_block.py b/hived/pyresttest_api_tests/test_ah_get_ops_in_block.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/test_ah_get_ops_in_block.py rename to hived/pyresttest_api_tests/test_ah_get_ops_in_block.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/validator_ex.py b/hived/pyresttest_api_tests/validator_ex.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/validator_ex.py rename to hived/pyresttest_api_tests/validator_ex.py diff --git a/tests2/api_tests/rc_api/CMakeLists.txt b/hived/rc_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/rc_api/CMakeLists.txt rename to hived/rc_api/CMakeLists.txt diff --git a/tests2/api_tests/rc_api/find_rc_accounts.py b/hived/rc_api/find_rc_accounts.py similarity index 100% rename from tests2/api_tests/rc_api/find_rc_accounts.py rename to hived/rc_api/find_rc_accounts.py diff --git a/tests2/api_tests/rc_api/get_resource_params.py b/hived/rc_api/get_resource_params.py similarity index 100% rename from tests2/api_tests/rc_api/get_resource_params.py rename to hived/rc_api/get_resource_params.py diff --git a/tests2/api_tests/rc_api/get_resource_pool.py b/hived/rc_api/get_resource_pool.py similarity index 100% rename from tests2/api_tests/rc_api/get_resource_pool.py rename to hived/rc_api/get_resource_pool.py diff --git a/tests2/api_tests/rc_api/readme.md b/hived/rc_api/readme.md similarity index 100% rename from tests2/api_tests/rc_api/readme.md rename to hived/rc_api/readme.md diff --git a/tests2/api_tests/reputation_api/CMakeLists.txt b/hived/reputation_api/CMakeLists.txt similarity index 100% rename from tests2/api_tests/reputation_api/CMakeLists.txt rename to hived/reputation_api/CMakeLists.txt diff --git a/tests2/api_tests/reputation_api/get_account_reputations.py b/hived/reputation_api/get_account_reputations.py similarity index 100% rename from tests2/api_tests/reputation_api/get_account_reputations.py rename to hived/reputation_api/get_account_reputations.py diff --git a/tests2/api_tests/reputation_api/readme.md b/hived/reputation_api/readme.md similarity index 100% rename from tests2/api_tests/reputation_api/readme.md rename to hived/reputation_api/readme.md diff --git a/tests2/api_tests/sps_api_plugin.py b/hived/sps_api_plugin.py similarity index 100% rename from tests2/api_tests/sps_api_plugin.py rename to hived/sps_api_plugin.py diff --git a/tests2/api_tests/test_ah_get_account_history.py b/hived/test_ah_get_account_history.py similarity index 100% rename from tests2/api_tests/test_ah_get_account_history.py rename to hived/test_ah_get_account_history.py diff --git a/tests2/scripts/test_ah_get_account_history.sh b/hived/test_ah_get_account_history.sh similarity index 100% rename from tests2/scripts/test_ah_get_account_history.sh rename to hived/test_ah_get_account_history.sh diff --git a/tests2/api_tests/test_ah_get_ops_in_block.py b/hived/test_ah_get_ops_in_block.py similarity index 100% rename from tests2/api_tests/test_ah_get_ops_in_block.py rename to hived/test_ah_get_ops_in_block.py diff --git a/tests2/scripts/test_ah_get_ops_in_block.sh b/hived/test_ah_get_ops_in_block.sh similarity index 100% rename from tests2/scripts/test_ah_get_ops_in_block.sh rename to hived/test_ah_get_ops_in_block.sh diff --git a/tests2/hivemind/scripts/api_error_smoketest.py b/hivemind/api_error_smoketest.py similarity index 100% rename from tests2/hivemind/scripts/api_error_smoketest.py rename to hivemind/api_error_smoketest.py diff --git a/tests2/hivemind/api_tests/block_api/CMakeLists.txt b/hivemind/block_api/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/block_api/CMakeLists.txt rename to hivemind/block_api/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/block_api/get_block.py b/hivemind/block_api/get_block.py similarity index 100% rename from tests2/hivemind/api_tests/block_api/get_block.py rename to hivemind/block_api/get_block.py diff --git a/tests2/hivemind/api_tests/block_api/get_block_header.py b/hivemind/block_api/get_block_header.py similarity index 100% rename from tests2/hivemind/api_tests/block_api/get_block_header.py rename to hivemind/block_api/get_block_header.py diff --git a/tests2/hivemind/api_tests/block_api/readme.md b/hivemind/block_api/readme.md similarity index 100% rename from tests2/hivemind/api_tests/block_api/readme.md rename to hivemind/block_api/readme.md diff --git a/tests2/hivemind/api_tests/bridge/CMakeLists.txt b/hivemind/bridge/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/bridge/CMakeLists.txt rename to hivemind/bridge/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/bridge/README.md b/hivemind/bridge/README.md similarity index 100% rename from tests2/hivemind/api_tests/bridge/README.md rename to hivemind/bridge/README.md diff --git a/tests2/hivemind/api_tests/bridge/account_notifications.py b/hivemind/bridge/account_notifications.py similarity index 100% rename from tests2/hivemind/api_tests/bridge/account_notifications.py rename to hivemind/bridge/account_notifications.py diff --git a/tests2/hivemind/api_tests/bridge/get_community.py b/hivemind/bridge/get_community.py similarity index 100% rename from tests2/hivemind/api_tests/bridge/get_community.py rename to hivemind/bridge/get_community.py diff --git a/tests2/hivemind/api_tests/bridge/get_ranked_posts.py b/hivemind/bridge/get_ranked_posts.py similarity index 100% rename from tests2/hivemind/api_tests/bridge/get_ranked_posts.py rename to hivemind/bridge/get_ranked_posts.py diff --git a/tests2/hivemind/api_tests/bridge/list_all_subscriptions.py b/hivemind/bridge/list_all_subscriptions.py similarity index 100% rename from tests2/hivemind/api_tests/bridge/list_all_subscriptions.py rename to hivemind/bridge/list_all_subscriptions.py diff --git a/tests2/hivemind/api_tests/bridge/list_community_roles.py b/hivemind/bridge/list_community_roles.py similarity index 100% rename from tests2/hivemind/api_tests/bridge/list_community_roles.py rename to hivemind/bridge/list_community_roles.py diff --git a/tests2/hivemind/api_tests/condenser_api/CMakeLists.txt b/hivemind/condenser_api/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/CMakeLists.txt rename to hivemind/condenser_api/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/condenser_api/get_account_reputations.py b/hivemind/condenser_api/get_account_reputations.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_account_reputations.py rename to hivemind/condenser_api/get_account_reputations.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_account_votes.py b/hivemind/condenser_api/get_account_votes.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_account_votes.py rename to hivemind/condenser_api/get_account_votes.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_active_votes.py b/hivemind/condenser_api/get_active_votes.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_active_votes.py rename to hivemind/condenser_api/get_active_votes.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_blog.py b/hivemind/condenser_api/get_blog.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_blog.py rename to hivemind/condenser_api/get_blog.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_blog_authors.py b/hivemind/condenser_api/get_blog_authors.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_blog_authors.py rename to hivemind/condenser_api/get_blog_authors.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_blog_entries.py b/hivemind/condenser_api/get_blog_entries.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_blog_entries.py rename to hivemind/condenser_api/get_blog_entries.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_comment_discussions_by_payout.py b/hivemind/condenser_api/get_comment_discussions_by_payout.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_comment_discussions_by_payout.py rename to hivemind/condenser_api/get_comment_discussions_by_payout.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_content.py b/hivemind/condenser_api/get_content.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_content.py rename to hivemind/condenser_api/get_content.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_content_replies.py b/hivemind/condenser_api/get_content_replies.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_content_replies.py rename to hivemind/condenser_api/get_content_replies.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_active.py b/hivemind/condenser_api/get_discussions_by_active.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_active.py rename to hivemind/condenser_api/get_discussions_by_active.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_author_before_date.py b/hivemind/condenser_api/get_discussions_by_author_before_date.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_author_before_date.py rename to hivemind/condenser_api/get_discussions_by_author_before_date.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_blog.py b/hivemind/condenser_api/get_discussions_by_blog.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_blog.py rename to hivemind/condenser_api/get_discussions_by_blog.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_cashout.py b/hivemind/condenser_api/get_discussions_by_cashout.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_cashout.py rename to hivemind/condenser_api/get_discussions_by_cashout.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_children.py b/hivemind/condenser_api/get_discussions_by_children.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_children.py rename to hivemind/condenser_api/get_discussions_by_children.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_comments.py b/hivemind/condenser_api/get_discussions_by_comments.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_comments.py rename to hivemind/condenser_api/get_discussions_by_comments.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_created.py b/hivemind/condenser_api/get_discussions_by_created.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_created.py rename to hivemind/condenser_api/get_discussions_by_created.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_feed.py b/hivemind/condenser_api/get_discussions_by_feed.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_feed.py rename to hivemind/condenser_api/get_discussions_by_feed.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_hot.py b/hivemind/condenser_api/get_discussions_by_hot.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_hot.py rename to hivemind/condenser_api/get_discussions_by_hot.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_promoted.py b/hivemind/condenser_api/get_discussions_by_promoted.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_promoted.py rename to hivemind/condenser_api/get_discussions_by_promoted.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_trending.py b/hivemind/condenser_api/get_discussions_by_trending.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_trending.py rename to hivemind/condenser_api/get_discussions_by_trending.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_discussions_by_votes.py b/hivemind/condenser_api/get_discussions_by_votes.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_discussions_by_votes.py rename to hivemind/condenser_api/get_discussions_by_votes.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_feed.py b/hivemind/condenser_api/get_feed.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_feed.py rename to hivemind/condenser_api/get_feed.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_feed_entries.py b/hivemind/condenser_api/get_feed_entries.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_feed_entries.py rename to hivemind/condenser_api/get_feed_entries.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_follow_count.py b/hivemind/condenser_api/get_follow_count.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_follow_count.py rename to hivemind/condenser_api/get_follow_count.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_followers.py b/hivemind/condenser_api/get_followers.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_followers.py rename to hivemind/condenser_api/get_followers.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_following.py b/hivemind/condenser_api/get_following.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_following.py rename to hivemind/condenser_api/get_following.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_post_discussions_by_payout.py b/hivemind/condenser_api/get_post_discussions_by_payout.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_post_discussions_by_payout.py rename to hivemind/condenser_api/get_post_discussions_by_payout.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_reblogged_by.py b/hivemind/condenser_api/get_reblogged_by.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_reblogged_by.py rename to hivemind/condenser_api/get_reblogged_by.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_replies_by_last_update.py b/hivemind/condenser_api/get_replies_by_last_update.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_replies_by_last_update.py rename to hivemind/condenser_api/get_replies_by_last_update.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_tags_used_by_author.py b/hivemind/condenser_api/get_tags_used_by_author.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_tags_used_by_author.py rename to hivemind/condenser_api/get_tags_used_by_author.py diff --git a/tests2/hivemind/api_tests/condenser_api/get_trending_tags.py b/hivemind/condenser_api/get_trending_tags.py similarity index 100% rename from tests2/hivemind/api_tests/condenser_api/get_trending_tags.py rename to hivemind/condenser_api/get_trending_tags.py diff --git a/tests2/hivemind/api_tests/database_api/CMakeLists.txt b/hivemind/database_api/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/database_api/CMakeLists.txt rename to hivemind/database_api/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/database_api/find_comments.py b/hivemind/database_api/find_comments.py similarity index 100% rename from tests2/hivemind/api_tests/database_api/find_comments.py rename to hivemind/database_api/find_comments.py diff --git a/tests2/hivemind/api_tests/database_api/list_comments.py b/hivemind/database_api/list_comments.py similarity index 100% rename from tests2/hivemind/api_tests/database_api/list_comments.py rename to hivemind/database_api/list_comments.py diff --git a/tests2/hivemind/api_tests/follow_api/CMakeLists.txt b/hivemind/follow_api/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/follow_api/CMakeLists.txt rename to hivemind/follow_api/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/follow_api/get_account_reputations.py b/hivemind/follow_api/get_account_reputations.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_account_reputations.py rename to hivemind/follow_api/get_account_reputations.py diff --git a/tests2/hivemind/api_tests/follow_api/get_blog.py b/hivemind/follow_api/get_blog.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_blog.py rename to hivemind/follow_api/get_blog.py diff --git a/tests2/hivemind/api_tests/follow_api/get_blog_entries.py b/hivemind/follow_api/get_blog_entries.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_blog_entries.py rename to hivemind/follow_api/get_blog_entries.py diff --git a/tests2/hivemind/api_tests/follow_api/get_follow_count.py b/hivemind/follow_api/get_follow_count.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_follow_count.py rename to hivemind/follow_api/get_follow_count.py diff --git a/tests2/hivemind/api_tests/follow_api/get_followers.py b/hivemind/follow_api/get_followers.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_followers.py rename to hivemind/follow_api/get_followers.py diff --git a/tests2/hivemind/api_tests/follow_api/get_following.py b/hivemind/follow_api/get_following.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_following.py rename to hivemind/follow_api/get_following.py diff --git a/tests2/hivemind/api_tests/follow_api/get_reblogged_by.py b/hivemind/follow_api/get_reblogged_by.py similarity index 100% rename from tests2/hivemind/api_tests/follow_api/get_reblogged_by.py rename to hivemind/follow_api/get_reblogged_by.py diff --git a/tests2/hivemind/api_tests/follow_api/readme.md b/hivemind/follow_api/readme.md similarity index 100% rename from tests2/hivemind/api_tests/follow_api/readme.md rename to hivemind/follow_api/readme.md diff --git a/tests2/hivemind/api_tests/list_comment.py b/hivemind/list_comment.py similarity index 100% rename from tests2/hivemind/api_tests/list_comment.py rename to hivemind/list_comment.py diff --git a/tests2/hivemind/api_tests/tags_api/CMakeLists.txt b/hivemind/tags_api/CMakeLists.txt similarity index 100% rename from tests2/hivemind/api_tests/tags_api/CMakeLists.txt rename to hivemind/tags_api/CMakeLists.txt diff --git a/tests2/hivemind/api_tests/tags_api/README.md b/hivemind/tags_api/README.md similarity index 100% rename from tests2/hivemind/api_tests/tags_api/README.md rename to hivemind/tags_api/README.md diff --git a/tests2/hivemind/api_tests/tags_api/get_active_votes.py b/hivemind/tags_api/get_active_votes.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_active_votes.py rename to hivemind/tags_api/get_active_votes.py diff --git a/tests2/hivemind/api_tests/tags_api/get_comment_discussions_by_payout.py b/hivemind/tags_api/get_comment_discussions_by_payout.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_comment_discussions_by_payout.py rename to hivemind/tags_api/get_comment_discussions_by_payout.py diff --git a/tests2/hivemind/api_tests/tags_api/get_content_replies.py b/hivemind/tags_api/get_content_replies.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_content_replies.py rename to hivemind/tags_api/get_content_replies.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussion.py b/hivemind/tags_api/get_discussion.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussion.py rename to hivemind/tags_api/get_discussion.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_active.py b/hivemind/tags_api/get_discussions_by_active.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_active.py rename to hivemind/tags_api/get_discussions_by_active.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_author_before_date.py b/hivemind/tags_api/get_discussions_by_author_before_date.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_author_before_date.py rename to hivemind/tags_api/get_discussions_by_author_before_date.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_blog.py b/hivemind/tags_api/get_discussions_by_blog.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_blog.py rename to hivemind/tags_api/get_discussions_by_blog.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_cashout.py b/hivemind/tags_api/get_discussions_by_cashout.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_cashout.py rename to hivemind/tags_api/get_discussions_by_cashout.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_children.py b/hivemind/tags_api/get_discussions_by_children.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_children.py rename to hivemind/tags_api/get_discussions_by_children.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_comments.py b/hivemind/tags_api/get_discussions_by_comments.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_comments.py rename to hivemind/tags_api/get_discussions_by_comments.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_created.py b/hivemind/tags_api/get_discussions_by_created.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_created.py rename to hivemind/tags_api/get_discussions_by_created.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_feed.py b/hivemind/tags_api/get_discussions_by_feed.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_feed.py rename to hivemind/tags_api/get_discussions_by_feed.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_hot.py b/hivemind/tags_api/get_discussions_by_hot.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_hot.py rename to hivemind/tags_api/get_discussions_by_hot.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_promoted.py b/hivemind/tags_api/get_discussions_by_promoted.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_promoted.py rename to hivemind/tags_api/get_discussions_by_promoted.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_trending.py b/hivemind/tags_api/get_discussions_by_trending.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_trending.py rename to hivemind/tags_api/get_discussions_by_trending.py diff --git a/tests2/hivemind/api_tests/tags_api/get_discussions_by_votes.py b/hivemind/tags_api/get_discussions_by_votes.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_discussions_by_votes.py rename to hivemind/tags_api/get_discussions_by_votes.py diff --git a/tests2/hivemind/api_tests/tags_api/get_post_discussions_by_payout.py b/hivemind/tags_api/get_post_discussions_by_payout.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_post_discussions_by_payout.py rename to hivemind/tags_api/get_post_discussions_by_payout.py diff --git a/tests2/hivemind/api_tests/tags_api/get_replies_by_last_update.py b/hivemind/tags_api/get_replies_by_last_update.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_replies_by_last_update.py rename to hivemind/tags_api/get_replies_by_last_update.py diff --git a/tests2/hivemind/api_tests/tags_api/get_tags_used_by_author.py b/hivemind/tags_api/get_tags_used_by_author.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_tags_used_by_author.py rename to hivemind/tags_api/get_tags_used_by_author.py diff --git a/tests2/hivemind/api_tests/tags_api/get_trending_tags.py b/hivemind/tags_api/get_trending_tags.py similarity index 100% rename from tests2/hivemind/api_tests/tags_api/get_trending_tags.py rename to hivemind/tags_api/get_trending_tags.py diff --git a/tests2/hivemind/api_tests/test_list_votes.py b/hivemind/test_list_votes.py similarity index 100% rename from tests2/hivemind/api_tests/test_list_votes.py rename to hivemind/test_list_votes.py diff --git a/tests2/hivemind/api_tests/test_list_votes2.py b/hivemind/test_list_votes2.py similarity index 100% rename from tests2/hivemind/api_tests/test_list_votes2.py rename to hivemind/test_list_votes2.py diff --git a/tests2/functional/python_tests/pyresttest_api_tests/jsonsocket.py b/jsonsocket.py similarity index 100% rename from tests2/functional/python_tests/pyresttest_api_tests/jsonsocket.py rename to jsonsocket.py diff --git a/tests2/common/testbase.py b/testbase.py similarity index 100% rename from tests2/common/testbase.py rename to testbase.py diff --git a/tests2/.dockerignore b/tests2/.dockerignore deleted file mode 100644 index 0fedcb79e5fcfa73f1414eb940c00eeeec8c2093..0000000000000000000000000000000000000000 --- a/tests2/.dockerignore +++ /dev/null @@ -1,13 +0,0 @@ -smoketest/README.md -smoketest/Dockerfile -smoketest/docker_build_and_run.sh -README.md -CMakeLists.txt -db_fixture -tests -plugin_tests -undo_data -generate_empty_blocks -*.cpp -*.hpp -__pycache__ diff --git a/tests2/CMakeLists.txt b/tests2/CMakeLists.txt deleted file mode 100644 index cb33e39d2f1044d79ce1d67eeddf47641cf26f36..0000000000000000000000000000000000000000 --- a/tests2/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -include(common/api_tests.cmake) - -ENABLE_TESTING() - -IF ( BUILD_HIVE_TESTNET ) - add_subdirectory(unit) - add_subdirectory(functional) -ELSE ( BUILD_HIVE_TESTNET ) - add_subdirectory(api_tests) -ENDIF ( BUILD_HIVE_TESTNET ) \ No newline at end of file diff --git a/tests2/README.md b/tests2/README.md deleted file mode 100644 index 2a4cbab152f38ff1610a5a6a8b2421eb508f27e3..0000000000000000000000000000000000000000 --- a/tests2/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Automated Testing Documentation - -## To Create Test Environment Container - -From the root of the repository: - - docker build --rm=false \ - -t steemitinc/ci-test-environment:latest \ - -f tests/scripts/Dockerfile.testenv . - -## To Run The Tests - -(Also in the root of the repository.) - - docker build --rm=false \ - -t steemitinc/hive-test \ - -f Dockerfile.test . - -## To Troubleshoot Failing Tests - - docker run -ti \ - steemitinc/ci-test-environment:latest \ - /bin/bash - -Then, inside the container: - -(These steps are taken from `/Dockerfile.test` in the -repository root.) - - git clone https://github.com/steemit/hive.git \ - /usr/local/src/hive - cd /usr/local/src/hive - git checkout <branch> # e.g. 123-feature - git submodule update --init --recursive - mkdir build - cd build - cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DBUILD_HIVE_TESTNET=ON \ - -DLOW_MEMORY_NODE=OFF \ - -DCLEAR_VOTES=ON \ - .. - make -j$(nproc) chain_test - ./tests/chain_test - cd /usr/local/src/hive - doxygen - programs/build_helpers/check_reflect.py diff --git a/tests2/api_tests/.gitignore b/tests2/api_tests/.gitignore deleted file mode 100644 index 397b4a7624e35fa60563a9c03b1213d93f7b6546..0000000000000000000000000000000000000000 --- a/tests2/api_tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.log diff --git a/tests2/api_tests/CMakeLists.txt b/tests2/api_tests/CMakeLists.txt deleted file mode 100644 index 678603d745dbb39bd1eec1be97ddda49788f5be2..0000000000000000000000000000000000000000 --- a/tests2/api_tests/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -add_subdirectory(account_by_key_api) -add_subdirectory(account_history_api) -add_subdirectory(condenser_api) -add_subdirectory(database_api) -add_subdirectory(jsonrpc_api) -add_subdirectory(market_history_api) -add_subdirectory(rc_api) -add_subdirectory(reputation_api) diff --git a/tests2/api_tests/README.md b/tests2/api_tests/README.md deleted file mode 100644 index 4c2d4328d5344c691024a26f2c073f06d93fdc17..0000000000000000000000000000000000000000 --- a/tests2/api_tests/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# API list - -- Condenser Api -- Bridge -- Account By Key Api -- Account History Api -- Block Api -- Database Api -- Debug Node Api (NOT TESTED) -- Follow Api -- Jsonrpc -- Market History Api -- Network Broadcast Api (NOT TESTED) -- Rc Api -- Reputation Api -- Rewards Api (NOT TESTED) -- Tags Api -- Transaction Status Api (NOT TESTED) -- Witness Api (NOT TESTED) -- Broadcast Ops (NOT TESTED) -- Broadcast Ops Communities (NOT TESTED) - - -## condenser_api - - -## bridge - -`account_notifications` and `get_ranked_posts` have problems with comparision, but methods work. - -Rest of methods works fine, sometimes with differences at `id`. - -## account_by_key_api -Every method works. - -## account_history_api -`get_transaction` method doesn't work, the rest is fine. - -## block_api -Every method works with good comparision. - -## database_api -Tested every method. They generally works fine, details are described in documentation. Some of them needs longer waiting time to finish. - -## follow_api -Some method are not implemented in APIs, they're not tested also. To have this tests work well we need to have list of exception parameters. - -## jsonrpc_api -As descibed in documentation. `get_methods` throws error, rest is fine. - -## market_history_api -Worked fine, every methods work, no diffs in compares. - -## reputation_api -Currently not working. Waiting for response from Gandalf. - -## tags_api -As in documentation. A lot of methods are deprecated, some have other arguments than in docs. And finally, multiple list arguments are in documentation, but isn't implemented in API. \ No newline at end of file diff --git a/tests2/functional/CMakeLists.txt b/tests2/functional/CMakeLists.txt deleted file mode 100644 index b1d69f4ff5f9f5db1351fba857a96555f5d8b4b1..0000000000000000000000000000000000000000 --- a/tests2/functional/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(python_tests) \ No newline at end of file diff --git a/tests2/functional/__init__.py b/tests2/functional/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tests2/functional/hive_utils/__init__.py b/tests2/functional/hive_utils/__init__.py deleted file mode 100644 index 042563d8618dbbf40e631a8a8c89b4c5622c0a50..0000000000000000000000000000000000000000 --- a/tests2/functional/hive_utils/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .common import * -from .hive_node import * \ No newline at end of file diff --git a/tests2/functional/hive_utils/common.py b/tests2/functional/hive_utils/common.py deleted file mode 100644 index 700bc219befc4514a1d2a83832da343af5a7f24e..0000000000000000000000000000000000000000 --- a/tests2/functional/hive_utils/common.py +++ /dev/null @@ -1,304 +0,0 @@ -# -*- coding: utf-8 -*- - -import logging -DEFAULT_LOG_FORMAT = '%(asctime)-15s - %(name)s - %(levelname)s - %(message)s' -DEFAULT_LOG_LEVEL = logging.INFO - -MODULE_NAME = "hive-utils.common" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(DEFAULT_LOG_LEVEL) - -def send_rpc_query(target_node : str, payload : dict) -> dict: - from requests import post - from json import dumps - resp = post(target_node, data = dumps(payload)) - if resp.status_code != 200: - print(resp.json()) - raise Exception("{} returned non 200 code".format(payload["method"])) - return resp.json() - -def get_random_id() -> str: - from uuid import uuid4 - return str(uuid4()) - -def get_current_block_number(source_node) -> int: - payload = { - "jsonrpc" : "2.0", - "id" : get_random_id(), - "method" : "database_api.get_dynamic_global_properties", - "params" : {} - } - - from requests import post - from json import dumps, loads - - try: - resp = post(source_node, data = dumps(payload)) - if resp.status_code != 200: - return -1 - data = resp.json()["result"] - return int(data["head_block_number"]) - except Exception as ex: - return -1 - -def wait_n_blocks(source_node : str, blocks : int, timeout : int = 60): - from time import sleep - starting_block = get_current_block_number(source_node) - cntr = 0 - while starting_block == -1 and cntr < timeout: - starting_block = get_current_block_number(source_node) - sleep(1) - cntr += 1 - if cntr >= timeout: - raise TimeoutError("Timeout in waiting for blocks. Hived is not running?") - current_block = starting_block - cntr = 0 - while current_block - starting_block < blocks and cntr < timeout: - current_block = get_current_block_number(source_node) - sleep(1) - cntr += 1 - if cntr >= timeout: - raise TimeoutError("Timeout in waiting for blocks. Hived is not running?") - -def debug_generate_blocks(target_node : str, debug_key : str, count : int) -> dict: - if count < 0: - raise ValueError("Count must be a positive non-zero number") - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_generate_blocks", - "params": { - "debug_key": debug_key, - "count": count, - "skip": 0, - "miss_blocks": 0, - "edit_if_needed": True - } - } - return send_rpc_query(target_node, payload) - -def debug_generate_blocks_until(target_node : str, debug_key : str, timestamp : str, generate_sparsely : bool = True) -> dict: - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_generate_blocks_until", - "params": { - "debug_key": debug_key, - "head_block_time": timestamp, - "generate_sparsely": generate_sparsely - } - } - return send_rpc_query(target_node, payload) - -def debug_set_hardfork(target_node : str, hardfork_id : int) -> dict: - if hardfork_id < 0: - raise ValueError( "hardfork_id cannot be negative" ) - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_set_hardfork", - "params": { - "hardfork_id": hardfork_id - } - } - return send_rpc_query(target_node, payload) - -def debug_has_hardfork(target_node : str, hardfork_id : int) -> dict: - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_has_hardfork", - "params": { - "hardfork_id": hardfork_id - } - } - return send_rpc_query(target_node, payload) - -def debug_get_witness_schedule(target_node : str) -> dict: - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_get_witness_schedule", - "params": {} - } - return send_rpc_query(target_node, payload) - -def debug_get_hardfork_property_object(target_node : str) -> dict: - payload = { - "jsonrpc": "2.0", - "id" : get_random_id(), - "method": "debug_node_api.debug_get_hardfork_property_object", - "params": {} - } - return send_rpc_query(target_node, payload) - -def get_date_as_isostr(date): - return date.replace(microsecond=0).isoformat() - - -def get_isostr_start_end_date(now, start_date_delta, end_date_delta): - from datetime import timedelta - - start_date = now + timedelta(days = start_date_delta) - end_date = start_date + timedelta(days = end_date_delta) - - start_date = start_date.replace(microsecond=0).isoformat() - end_date = end_date.replace(microsecond=0).isoformat() - - return start_date, end_date - -def save_screen_cfg(cfg_file_name, log_file_path): - """Creates a config file for screen command. In config file we configure logging path and interval. - - Args: - cfg_file_name -- file name for screen config file, - log_file_path -- path to log file. - """ - with open(cfg_file_name, "w") as cfg: - cfg.write("logfile {0}\n".format(log_file_path)) - cfg.write("deflog on\n") - cfg.write("logfile flush 1\n") - -def save_pid_file(pid_file_name, exec_name, port, start_time): - """Creates PID file which indicate running keosd or nodeos process. - - Args: - pid_file_name -- file name for pid file, - exec_name -- name of the exectutable bound to this pid file, - port -- port number for running executable, - start_time -- execution start time. - """ - with open(pid_file_name, "w") as pid_file: - pid_file.write("{0}-{1}-{2}\n".format(exec_name, port, start_time)) - -def wait_for_string_in_file(log_file_name, string, timeout): - """Blocks program execution until a given string is found in given file. - - Args: - log_file_name -- path to scanned file, - string -- sting to be found, - timout -- block timeout in seconds, after this time exception will be raised. - """ - logger.info("Waiting for string \"{}\" in file {}".format(string, log_file_name)) - step = 1 - to_timeout = 0. - from time import sleep - from os.path import exists - while True: - sleep(step) - to_timeout = to_timeout + step - if timeout is not None and to_timeout >= timeout: - msg = "Timeout during wait for string {0}".format(string) - logger.error(msg) - raise TimeoutError(msg) - if exists(log_file_name): - with open(log_file_name, "r") as log_file: - leave = False - for line in log_file.readlines(): - if string in line: - leave = True - break - if leave: - break - -def get_last_line_of_file(file_name): - """Reads and returns last line of given file. - - Args: - file_name -- path to a file. - """ - last_line = "" - from os import SEEK_CUR, SEEK_END - with open(file_name, "r") as f: - f.seek(-2, SEEK_END) - while f.read(1) != b'\n': - f.seek(-2, SEEK_CUR) - last_line = f.readline().decode() - return last_line - -def kill_process(pid_file_name, proc_name, ip_address, port): - """Attempts to stop a process with given PID listening on port at ip_address. Process data is read from pid_file_name. - - Args: - pid_file_name -- path to pid file, - proc_name -- executable name, - ip_address -- executable ip address, - port -- executable port number. - """ - logger.info("Terminating {0} process running on port {1}".format(proc_name, port)) - pids = [] - pid_name = None - try: - from os import popen, kill, remove - from os.path import exists - with open(pid_file_name, "r") as pid_file: - pid_name = pid_file.readline() - pid_name = pid_name.strip() - if pid_name is not None: - for line in popen("ps ax | grep " + proc_name + " | grep -v grep"): - if pid_name in line: - line = line.strip().split() - pids.append(line[0]) - for pid in pids: - for line in popen("ps --no-header --ppid {0}".format(pid)): - line = line.strip().split() - kill(int(line[0]), 2) - kill(int(pid), 2) - if exists(pid_file_name): - remove(pid_file_name) - logger.info("Done...") - else: - logger.warning("No such process: {0}".format(pid_name)) - except Exception as ex: - logger.error("Process {0} cannot be killed. Reason: {1}".format(proc_name, ex)) - -def detect_process_by_name(proc_name, exec_path, port): - """Checks if process of given name runs on given ip_address and port. - - Args: - proc_name -- process name, - exec_path -- path to executable, - port -- process port. - """ - pids = [] - from os import popen - for line in popen("ps ax | grep " + proc_name + " | grep -v grep"): - if exec_path in line and str(port) in line: - line = line.strip().split() - pids.append(line[0]) - if pids: - return True - return False - - -BLOCK_TYPE_HEADBLOCK = "within_reversible_block" -BLOCK_TYPE_IRREVERSIBLE = "within_irreversible_block" -def block_until_transaction_in_block(node_url, transaction_id, block_type = BLOCK_TYPE_HEADBLOCK, timeout = 60.): - logger.info("Block until transaction_id: {0} is {1}".format(transaction_id, block_type)) - from time import sleep - from requests import post - step = 1. - timeout_cnt = 0. - while True: - query = { - "id" : "{}".format(get_random_id()), - "jsonrpc":"2.0", - "method":"transaction_status_api.find_transaction", - "params": { - "transaction_id": transaction_id - } - } - - response = post(node_url, json=query) - transaction_status = response.get("status", None) - if transaction_status is not None: - if transaction_status == block_type: - logger.info("Transaction id: {0} is {1}".format(transaction_id, block_type)) - return - logger.info("Transaction id: {0} not {1}".format(transaction_id, block_type)) - sleep(step) - timeout_cnt = timeout_cnt + step - if timeout_cnt > timeout: - msg = "Timeout reached during block_until_transaction_in_block" - logger.error(msg) - raise TimeoutError(msg) diff --git a/tests2/functional/hive_utils/hive_node.py b/tests2/functional/hive_utils/hive_node.py deleted file mode 100644 index cb02842408bf68f68b4f610b9151c4b0421b1c22..0000000000000000000000000000000000000000 --- a/tests2/functional/hive_utils/hive_node.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/python3 - -import json -import logging -import sys -import os -import subprocess -import datetime - -from .common import DEFAULT_LOG_FORMAT, DEFAULT_LOG_LEVEL - -from threading import Lock - -MODULE_NAME = "hive-utils.hive-node" - -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(DEFAULT_LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(DEFAULT_LOG_LEVEL) -ch.setFormatter(logging.Formatter(DEFAULT_LOG_FORMAT)) - -logger.addHandler(ch) - -from typing import NamedTuple - -class HiveNode(object): - hived_binary = None - hived_process = None - hived_lock = Lock() - hived_data_dir = None - hived_args = list() - - def __init__(self, binary_path : str, working_dir : str, binary_args : list): - logger.info("New hive node") - if not os.path.exists(binary_path): - raise ValueError("Path to hived binary is not valid.") - if not os.path.isfile(binary_path): - raise ValueError("Path to hived binary must point to file") - self.hived_binary = binary_path - - if not os.path.exists(working_dir): - raise ValueError("Path to data directory is not valid") - if not os.path.isdir(working_dir): - raise ValueError("Data directory is not valid directory") - self.hived_data_dir = working_dir - - if binary_args: - self.hived_args.extend(binary_args) - - def __enter__(self): - self.hived_lock.acquire() - - from subprocess import Popen, PIPE - from time import sleep - - hived_command = [ - self.hived_binary, - "--data-dir={}".format(self.hived_data_dir) - ] - hived_command.extend(self.hived_args) - - self.hived_process = Popen(hived_command, stdout=PIPE, stderr=None) - self.hived_process.poll() - sleep(5) - - if self.hived_process.returncode: - raise Exception("Error during starting node") - - def get_output(self): - out, err = self.hived_process.communicate() - return out - - def __exit__(self, exc, value, tb): - logger.info("Closing node") - from signal import SIGINT, SIGTERM - from time import sleep - - if self.hived_process is not None: - self.hived_process.poll() - if self.hived_process.returncode != 0: - self.hived_process.send_signal(SIGINT) - sleep(7) - self.hived_process.poll() - if self.hived_process.returncode != 0: - self.hived_process.send_signal(SIGTERM) - sleep(7) - self.hived_process.poll() - if self.hived_process.returncode != 0: - raise Exception("Error during stopping node. Manual intervention required.") - self.hived_process = None - self.hived_lock.release() - -class HiveNodeInScreen(object): - def __init__(self, hive_executable, working_dir, config_src_path, run_using_existing_data = False, node_is_steem = False): - self.hive_executable = hive_executable - self.working_dir = working_dir - self.config_src_path = config_src_path - self.node_is_steem = node_is_steem - - # usefull when we want to do a replay - if not run_using_existing_data: - from shutil import rmtree, copy - # remove old data from node - if os.path.exists(self.working_dir): - rmtree(self.working_dir) - os.makedirs(self.working_dir+"/blockchain") - # copy config file to working dir - copy(self.config_src_path, self.working_dir + "/config.ini") - - self.hive_config = self.parse_node_config_file(self.working_dir + "/config.ini") - self.ip_address, self.port = self.hive_config["webserver-http-endpoint"][0].split(":") - self.ip_address = "http://{}".format(self.ip_address) - self.node_running = False - - def get_from_config(self, key): - return self.hive_config.get(key, None) - - def get_node_url(self): - return "{}:{}/".format(self.ip_address, self.port) - - def is_running(self): - return self.node_running - - def parse_node_config_file(self, config_file_name): - ret = dict() - lines = None - with open(config_file_name, "r") as f: - lines = f.readlines() - - for line in lines: - proc_line = line.strip() - if proc_line: - if proc_line.startswith("#"): - continue - k, v = proc_line.split("=", 1) - k = k.strip() - v = v.strip() - if k in ret: - ret[k].append(v) - else: - ret[k] = [v] - return ret - - def run_hive_node(self, additional_params = [], wait_for_blocks = True): - from .common import detect_process_by_name, save_screen_cfg, save_pid_file, wait_n_blocks, wait_for_string_in_file, kill_process - - if detect_process_by_name("hived" if not self.node_is_steem else "steemd", self.hive_executable, self.port): - msg = "{0} process is running on {1}:{2}. Please terminate that process and try again.".format("hive", self.ip_address, self.port) - raise ProcessLookupError(msg) - - logger.info("*** START NODE at {0}:{1} in {2}".format(self.ip_address, self.port, self.working_dir)) - - parameters = [ - self.hive_executable, - "-d", - self.working_dir, - "--advanced-benchmark", - "--sps-remove-threshold", - "-1" - ] - - parameters = parameters + additional_params - - self.pid_file_name = "{0}/run_hive-{1}.pid".format(self.working_dir, self.port) - current_time_str = datetime.datetime.now().strftime("%Y-%m-%d") - log_file_name = "{0}/{1}-{2}-{3}.log".format(self.working_dir, "hive", self.port, current_time_str) - screen_cfg_name = "{0}/hive_screen-{1}.cfg".format(self.working_dir, self.port) - - save_screen_cfg(screen_cfg_name, log_file_name) - screen_params = [ - "screen", - "-m", - "-d", - "-L", - "-c", - screen_cfg_name, - "-S", - "{0}-{1}-{2}".format("hive", self.port, current_time_str) - ] - - parameters = screen_params + parameters - logger.info("Running hived with command: {0}".format(" ".join(parameters))) - - try: - subprocess.Popen(parameters) - save_pid_file(self.pid_file_name, "hive", self.port, current_time_str) - # we will allow for screen to setup and die maybe? - from time import sleep - sleep(5) - # now it should be dead - - if not detect_process_by_name("hived" if not self.node_is_steem else "steemd", self.hive_executable, self.port): - msg = "{0} process is not running on {1}:{2}. Please check logs.".format("hive", self.ip_address, self.port) - raise ProcessLookupError(msg) - - if "--replay-blockchain" in parameters: - wait_for_string_in_file(log_file_name, "start listening for ws requests", None) - else: - if wait_for_blocks: - wait_n_blocks("{}:{}".format(self.ip_address, self.port), 5) - else: - wait_for_string_in_file(log_file_name, "start listening for ws requests", 20.) - self.node_running = True - logger.info("Node at {0}:{1} in {2} is up and running...".format(self.ip_address, self.port, self.working_dir)) - except Exception as ex: - logger.error("Exception during hived run: {0}".format(ex)) - kill_process(self.pid_file_name, "hive" if not self.node_is_steem else "steem", self.ip_address, self.port) - self.node_running = False - - - def stop_hive_node(self): - from .common import kill_process - logger.info("Stopping node at {0}:{1}".format(self.ip_address, self.port)) - kill_process(self.pid_file_name, "hive" if not self.node_is_steem else "steem", self.ip_address, self.port) - self.node_running = False - - def __enter__(self): - self.run_hive_node() - - def __exit__(self, exc, value, tb): - self.stop_hive_node() - -if __name__ == "__main__": - KEEP_GOING = True - - def sigint_handler(signum, frame): - logger.info("Shutting down...") - global KEEP_GOING - from time import sleep - KEEP_GOING = False - sleep(3) - sys.exit(0) - - def main(): - try: - import signal - signal.signal(signal.SIGINT, sigint_handler) - - plugins = ["chain","p2p","webserver","json_rpc","debug_node"] - config = "# Simple config file\n" \ - + "shared-file-size = 1G\n" \ - + "enable-stale-production = true\n" \ - + "p2p-endpoint = 127.0.0.1:2001\n" \ - + "webserver-http-endpoint = 127.0.0.1:8095\n" \ - + "webserver-ws-endpoint = 127.0.0.1:8096\n" \ - + "plugin = witness debug_node {}\n".format(" ".join(plugins)) \ - + "plugin = database_api debug_node_api block_api\n" \ - + "witness = \"initminer\"\n" \ - + "private-key = 5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n\n" \ - + "required-participation = 0" - - binary_path = "/home/dariusz-work/Builds/hive/programs/hived/hived" - work_dir = "/home/dariusz-work/hive-data" - - print(config) - - with open(work_dir + "/config.ini", "w") as conf_file: - conf_file.write(config) - - node = HiveNode(binary_path, work_dir, []) - from time import sleep - from .common import wait_n_blocks, debug_generate_blocks - with node: - print("Waiting 10 blocks") - wait_n_blocks("http://127.0.0.1:8095", 10) - print("Done...") - print(debug_generate_blocks("http://127.0.0.1:8095", "5JHNbFNDg834SFj8CMArV6YW7td4zrPzXveqTfaShmYVuYNeK69", 100)) - while(KEEP_GOING): - sleep(1) - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - sys.exit(1) - - main() - - - diff --git a/tests2/functional/hive_utils/resources/config.ini.in b/tests2/functional/hive_utils/resources/config.ini.in deleted file mode 100644 index b8a0aea5d3820e8fe66f41c14f3f0a1773ee79f5..0000000000000000000000000000000000000000 --- a/tests2/functional/hive_utils/resources/config.ini.in +++ /dev/null @@ -1,101 +0,0 @@ -# Appender definition json: {"appender", "stream", "file"} Can only specify a file OR a stream -log-appender = {"appender":"stderr","stream":"std_error"} {"appender":"p2p","file":"logs/p2p/p2p.log"} - -# Logger definition json: {"name", "level", "appender"} -log-logger = {"name":"default","level":"all","appender":"stderr"} {"name":"p2p","level":"all","appender":"p2p"} - -# Whether to print backtrace on SIGSEGV -backtrace = yes - -# Plugin(s) to enable, may be specified multiple times -plugin = witness database_api account_by_key_api network_broadcast_api condenser_api block_api transaction_status_api debug_node_api - -# Disables automatic account history trimming -history-disable-pruning = 0 - -# The location of the rocksdb database for account history. By default it is $DATA_DIR/blockchain/account-history-rocksdb-storage -account-history-rocksdb-path = "blockchain/account-history-rocksdb-storage" - -# Where to export data (NONE to discard) -block-data-export-file = NONE - -# How often to print out block_log_info (default 1 day) -block-log-info-print-interval-seconds = 86400 - -# Whether to defer printing until block is irreversible -block-log-info-print-irreversible = 1 - -# Where to print (filename or special sink ILOG, STDOUT, STDERR) -block-log-info-print-file = ILOG - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G. If running a full node, increase this value to 200G. -shared-file-size = 8G - -# A 2 precision percentage (0-10000) that defines the threshold for when to autoscale the shared memory file. Setting this to 0 disables autoscaling. Recommended value for consensus node is 9500 (95%). Full node is 9900 (99%) -shared-file-full-threshold = 0 - -# A 2 precision percentage (0-10000) that defines how quickly to scale the shared memory file. When autoscaling occurs the file's size will be increased by this percent. Setting this to 0 disables autoscaling. Recommended value is between 1000-2000 (10-20%) -shared-file-scale-rate = 0 - -# Set the maximum size of cached feed for an account -follow-max-feed-size = 500 - -# Block time (in epoch seconds) when to start calculating feeds -follow-start-feeds = 0 - -# Track market history by grouping orders into buckets of equal size measured in seconds specified as a JSON array of numbers -market-history-bucket-size = [15,60,300,3600,86400] - -# How far back in time to track history for each bucket size, measured in the number of buckets (default: 5760) -market-history-buckets-per-size = 5760 - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = 127.0.0.1:2001 - -# Skip rejecting transactions when account has insufficient RCs. This is not recommended. -rc-skip-reject-not-enough-rc = 0 - -# Generate historical resource credits -rc-compute-historical-rc = 0 - -# Size to batch statsd messages. -statsd-batchsize = 1 - -# Block time (in epoch seconds) when to start calculating promoted content. Should be 1 week prior to current time. -tags-start-promoted = 0 - -# Skip updating tags on startup. Can safely be skipped when starting a previously running node. Should not be skipped when reindexing. -tags-skip-startup-update = 0 - -# Defines the number of blocks from the head block that transaction statuses will be tracked. -transaction-status-block-depth = 64000 - -# Defines the block number the transaction status plugin will begin tracking. -transaction-status-track-after-block = 0 - -# Local http endpoint for webserver requests. -webserver-http-endpoint = 127.0.0.1:8090 - -# Local websocket endpoint for webserver requests. -webserver-ws-endpoint = 127.0.0.1:8090 - -# Number of threads used to handle queries. Default: 32. -webserver-thread-pool-size = 32 - -# Enable block production, even if the chain is stale. -enable-stale-production = 0 - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -witness = "initminer" - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -private-key = 5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n - -# Skip enforcing bandwidth restrictions. Default is true in favor of rc_plugin. -witness-skip-enforce-bandwidth = 1 diff --git a/tests2/functional/python_tests/CMakeLists.txt b/tests2/functional/python_tests/CMakeLists.txt deleted file mode 100644 index ceaf42bc50f38027463360d0460a1496770a165b..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -INCLUDE ( CTest ) -ENABLE_TESTING() - -SET ( python_funtional_tests_prefix functional ) -SET ( hived_path ${CMAKE_BINARY_DIR}/programs/hived/hived ) -SET ( initminer_key 5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n ) - -# It is required to start ctest in ${CMAKE_BINARY_DIR}/tests -# The test are grouped as follow functional/<subdirectory name>/<test_basefile_name> -# example: test script functional/python_tests/dhf_tests/beem_dhf_tests.py will started with ctest as follows: -# ctest functional/dhf_tests/beem_dhf_tests -# To start group of tests use ctest -R -# example: to start all tests in sps_tests group: -# ctest -R functional/dhf_tests/.* -# example: to start all python_functional tests: -# ctest -R functional/.* - -MACRO ( ADD_PYTHON_FUNCTIONAL_TEST test_script_base_name ) - FILE( RELATIVE_PATH tests_subset "${CMAKE_CURRENT_SOURCE_DIR}/.." "${CMAKE_CURRENT_SOURCE_DIR}" ) - SET ( test_name ${python_funtional_tests_prefix}/${tests_subset}/${test_script_base_name} ) - SET ( test_script ${test_script_base_name}.py ) - SET ( working_dir ${CMAKE_CURRENT_SOURCE_DIR} ) - - MESSAGE ( STATUS "Adding ${test_name} to test list" ) - SET ( extra_macro_args ${ARGN} ) - LIST ( LENGTH extra_macro_args num_extra_args ) - SET ( test_parameters ${test_script} ) - - IF ( ${num_extra_args} GREATER 0) - SET ( test_parameters ${test_script} ${extra_macro_args} ) - ENDIF () - - ADD_TEST( NAME ${test_name} COMMAND python3 ${test_parameters} WORKING_DIRECTORY ${working_dir} ) - SET_PROPERTY( TEST "${test_name}" PROPERTY LABELS ${python_funtional_tests_prefix} ${tests_subset} ${test_script_base_name} ) - SET_PROPERTY( TEST "${test_name}" PROPERTY ENVIRONMENT TEST_LOG_DIR=${CMAKE_BINARY_DIR}/tests) - -ENDMACRO( ADD_PYTHON_FUNCTIONAL_TEST ) - -# Add here directories with subsets of tests -ADD_SUBDIRECTORY ( dhf_tests ) -ADD_SUBDIRECTORY ( hived ) diff --git a/tests2/functional/python_tests/cli_wallet/run.py b/tests2/functional/python_tests/cli_wallet/run.py deleted file mode 100755 index 06bcba3e3954c7d71f8a5eb11a41c4b7050523e8..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/run.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import glob -import argparse -import datetime -import subprocess - -from tests.utils.cmd_args import parser -from tests.utils.logger import log - -test_args = [] -summary_file_name = "summary.txt" - -def check_subdirs(_dir): - error = False - tests = sorted(glob.glob(_dir+"/*.py")) - if tests: - for test in tests: - root_error = run_script(test) - if root_error: - error = root_error - return error - - -def run_script(_test, _multiplier = 1, _interpreter = None ): - try: - with open(summary_file_name, "a+") as summary: - interpreter = _interpreter if _interpreter else "python3" - ret_code = subprocess.call(interpreter + " " + _test + " " + test_args, shell=True) - if ret_code == 0: - summary.writelines("Test `{0}` passed.\n".format(_test)) - return False - else: - summary.writelines("Test `{0}` failed.\n".format(_test)) - return True - except Exception as _ex: - log.exception("Exception occures in run_script `{0}`".format(str(_ex))) - return True - - -if __name__ == "__main__": - if os.path.isfile(summary_file_name): - os.remove(summary_file_name) - with open(summary_file_name, "a+") as summary: - summary.writelines("Cli wallet test started at {0}.\n".format(str(datetime.datetime.now())[:-7])) - args = parser.parse_args() - for key, val in args.__dict__.items(): - if val : - test_args.append("--"+key.replace("_","-")+ " ") - test_args.append(val) - test_args = " ".join(test_args) - try: - error = True - if os.path.isdir("./tests"): - error = check_subdirs("./tests") - - except Exception as _ex: - log.exception("Exception occured `{0}`.".format(str(_ex))) - error = True - finally: - if error: - log.error("At least one test has faild. Please check summary.txt file.") - exit(1) - else: - log.info("All tests pass.") - exit(0) diff --git a/tests2/functional/python_tests/cli_wallet/tests/000_create_proposal.py b/tests2/functional/python_tests/cli_wallet/tests/000_create_proposal.py deleted file mode 100755 index 544fcfe1c44b926b59483faa9dbaba12cb13c830..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/000_create_proposal.py +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/python3 - -import time - -#from ... import utils -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - creator, receiver = make_user_for_tests(wallet) - - proposals_before = len(find_creator_proposals(creator, last_message_as_json( wallet.list_proposals(creator, "creator", "asc", 50, "all", "")))) - log.info("proposals_before {0}".format(proposals_before)) - - wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum", "body", "{}", "true") - create_prop = wallet.create_proposal(creator, receiver, "2029-06-02T00:00:00", "2029-08-01T00:00:00", "1.000 TBD", "this is subject", "lorem", "true") - - proposals_after = len(find_creator_proposals(creator, last_message_as_json( wallet.list_proposals(creator, "creator", "asc", 50, "all", "")))) - log.info("proposals_after {0}".format(proposals_after)) - - if not proposals_before + 1 == proposals_after: - raise ArgsCheckException("proposals_before +1 should be equal to proposals_after.") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/001_update_proposal.py b/tests2/functional/python_tests/cli_wallet/tests/001_update_proposal.py deleted file mode 100755 index 13efc658cdcd20635cb08f24fbfdf21a41920165..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/001_update_proposal.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/python3 - -import time - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - creator, receiver = make_user_for_tests(wallet) - - proposals_before = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", "") ))) - log.info("proposals_before {0}".format(proposals_before)) - - wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum", "body", "{}", "true") - wallet.create_proposal(creator, receiver, "2029-06-02T00:00:00", "2029-08-01T00:00:00", "1.000 TBD", "this is subject", "lorem", "true") - - resp = find_creator_proposals(creator, last_message_as_json(wallet.list_proposals(creator, "creator", "asc", 50, "all", ""))) - new_proposal_id = 0 - for r in resp: - if r["id"] > new_proposal_id: - new_proposal_id = r["id"] - - proposals_middle = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", "")))) - log.info("proposals_middle {0}".format(proposals_middle)) - - wallet.update_proposal_votes(creator, [new_proposal_id], "true", "true") - proposals_after = len(find_voter_proposals(creator, last_message_as_json( wallet.list_voter_proposals(creator, "creator", "asc", 20, "all", "") ))) - - log.info("proposals_after {0}".format(proposals_after)) - - if not proposals_before == proposals_middle: - raise ArgsCheckException("proposals_before should be equal to proposals_middle.") - - if not proposals_middle + 1 == proposals_after: - raise ArgsCheckException("proposals_middle +1 should be equal to proposals_after.") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/002_remove_proposal.py b/tests2/functional/python_tests/cli_wallet/tests/002_remove_proposal.py deleted file mode 100755 index 27235a7b49cf68ed33992c2ea95fe36da577b98f..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/002_remove_proposal.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/python3 - -import time - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - creator, receiver = make_user_for_tests(wallet) - - proposals_before = len(find_creator_proposals(creator, last_message_as_json( wallet.list_proposals(creator, "creator", "asc", 20, "all", "")))) - log.info("proposals_before {0}".format(proposals_before)) - - wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum", "body", "{}", "true") - wallet.create_proposal(creator, receiver, "2029-06-02T00:00:00", "2029-08-01T00:00:00", "1.000 TBD", "this is subject", "lorem", "true") - - resp = find_creator_proposals(creator, last_message_as_json(wallet.list_proposals(creator, "creator", "asc", 50, "all", ""))) - new_proposal_id = 0 - for r in resp: - if r["id"] > new_proposal_id: - new_proposal_id = r["id"] - - proposals_middle = len(find_creator_proposals(creator, last_message_as_json(wallet.list_proposals(creator, "creator", "asc", 20, "all", "")))) - log.info("proposals_middle {0}".format(proposals_middle)) - - wallet.remove_proposal(creator, [new_proposal_id], "true", "true") - proposals_after = len(find_creator_proposals(creator, last_message_as_json(wallet.list_proposals(creator, "creator", "asc", 20, "all", "")))) - log.info("proposals_after {0}".format(proposals_after)) - - if not proposals_before + 1 == proposals_middle: - raise ArgsCheckException("proposals_before + 1should be equal to proposals_middle.") - - if not proposals_middle - 1 == proposals_after: - raise ArgsCheckException("proposals_middle - 1 should be equal to proposals_after.") - - if not proposals_before == proposals_after: - raise ArgsCheckException("proposals_middle - 1 should be equal to proposals_after.") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/003_list_proposal.py b/tests2/functional/python_tests/cli_wallet/tests/003_list_proposal.py deleted file mode 100755 index c2475809bac329b9fb8add6fea0f9ad344490bf5..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/003_list_proposal.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/python3 - -from collections import OrderedDict - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - active = ["active", "inactive", "all"] - order_by = ["creator", "start_date", "end_date", "total_votes"] - order_direction = ["asc", "desc"] - - for by in order_by: - for direct in order_direction: - for act in active: - if by == "creator": - start = "" - elif by == "start_date" or by == "end_date": - start = "2019-03-01T00:00:00" - else: - start = 0 - call_args = OrderedDict() - call_args["start"]=start - call_args["order_by"]=by - call_args["order_direction"]=direct - call_args["limit"]=10 - call_args["status"]=act - call_args["last_id"]="" - resp = last_message_as_json(call_and_check(wallet.list_proposals, call_args, "args")) - if not "result" in resp: - raise ArgsCheckException("No `result` in response") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/004_list_voter_proposal.py b/tests2/functional/python_tests/cli_wallet/tests/004_list_voter_proposal.py deleted file mode 100755 index 90da118f19358ccb3f38685872e08ce0330a47a7..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/004_list_voter_proposal.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/python3 - -from collections import OrderedDict - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - active = ["active", "inactive", "all"] - order_by = ["creator", "start_date", "end_date", "total_votes"] - order_direction = ["asc", "desc"] - - for by in order_by: - for direct in order_direction: - for act in active: - call_args = OrderedDict() - call_args["start"]=args.creator - call_args["order_by"]=by - call_args["order_direction"]=direct - call_args["limit"]=10 - call_args["status"]=act - call_args["last_id"]="" - resp = last_message_as_json( call_and_check(wallet.list_voter_proposals, call_args, "args")) - if not "result" in resp: - raise ArgsCheckException("No `result` in response") - - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - - - diff --git a/tests2/functional/python_tests/cli_wallet/tests/005_find_proposals.py b/tests2/functional/python_tests/cli_wallet/tests/005_find_proposals.py deleted file mode 100755 index 64f3bb69c5bd49fbfef2b72c26748b9923ac1a6d..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/005_find_proposals.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/python3 - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - id_sets = [ [1], [2], [3], [1,2], [1,2,3], [2,3], [3,4], [4,5], [1,2,3,4,5,6,7]] - - for ids in id_sets: - call_args = {"id_set":ids} - resp = last_message_as_json(call_and_check(wallet.find_proposals, call_args, "args")) - if not "result" in resp: - raise ArgsCheckException("No `result` in response") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - - - diff --git a/tests2/functional/python_tests/cli_wallet/tests/006_cli_wallet_help.py b/tests2/functional/python_tests/cli_wallet/tests/006_cli_wallet_help.py deleted file mode 100755 index e073a74e40c6580d8df4e5eb3629a652f6dd6841..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/006_cli_wallet_help.py +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/python3 - -import subprocess - -from utils.test_utils import * -from utils.cmd_args import args -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - output = subprocess.run([args.path+"/cli_wallet", "--help"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - output_stdout = output.stdout.decode('utf-8') - args_founded = [ arg for arg in output_stdout.split() if "--" in arg ] - only_args_to_be_founded = ['--help', '--server-rpc-endpoint', '--cert-authority', '--rpc-endpoint', '--rpc-tls-endpoint', '--rpc-tls-certificate', '--rpc-http-endpoint', '--daemon', '--rpc-http-allowip', '--wallet-file', '--chain-id'] - res = list(set(args_founded)^set(only_args_to_be_founded)) - if res: - raise ArgsCheckException("There are some additional argument in cli_wallet `{0}`.".format(res)) - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - - - diff --git a/tests2/functional/python_tests/cli_wallet/tests/007_create_proposal_fail_negative_payment.py b/tests2/functional/python_tests/cli_wallet/tests/007_create_proposal_fail_negative_payment.py deleted file mode 100755 index e6272e36c44e1b5b725ffd711ec158a0712c1d36..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/007_create_proposal_fail_negative_payment.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/python3 - -import time - -#from ... import utils -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - creator, receiver = make_user_for_tests(wallet) - - proposals_before = len(find_creator_proposals(creator, last_message_as_json( wallet.list_proposals(creator, "creator", "asc", 50, "all")))) - log.info("proposals_before {0}".format(proposals_before)) - - wallet.post_comment(creator, "lorem", "", "ipsum", "Lorem Ipsum", "body", "{}", "true") - create_prop = wallet.create_proposal(creator, receiver, "2029-06-02T00:00:00", "2029-08-01T00:00:00", "-1.000 TBD", "this is subject", "lorem", "true") - if not create_prop.find("daily_pay.amount >= 0: Daily pay can't be negative value") != -1: - raise ArgsCheckException("Assertion `{0}` is required.".format("daily_pay.amount >= 0: Daily pay can't be negative value")) - - proposals_after = len(find_creator_proposals(creator, last_message_as_json( wallet.list_proposals(creator, "creator", "asc", 50, "all")))) - log.info("proposals_after {0}".format(proposals_after)) - - if not proposals_before == proposals_after: - raise ArgsCheckException("proposals_before +1 should be equal to proposals_after.") - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/008_list_proposal_fail_invalid_value_for_last_id.py b/tests2/functional/python_tests/cli_wallet/tests/008_list_proposal_fail_invalid_value_for_last_id.py deleted file mode 100755 index 6af4d0fac57d01354a0f25d620569000969857d2..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/008_list_proposal_fail_invalid_value_for_last_id.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python3 - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - error_msg_x = "The value `x` for `_last_id` argument is invalid, it should be integer type." - resp_error_x = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "x") - log.info(resp_error_x) - if resp_error_x.find(error_msg_x) == -1: - raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_x)) - - error_msg_y = "The value `y` for `_last_id` argument is invalid, it should be integer type." - resp_error_y = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "y") - log.info(resp_error_y) - if resp_error_y.find(error_msg_y) == -1: - raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_y)) - - error_msg_10 = "The value `10` for `_last_id` argument is invalid, it should be integer type." - resp_10 = wallet.list_proposals(args.creator, "creator", "asc", 50, "all", "10") - log.info(resp_10) - if resp_10.find(error_msg_10) != -1: - raise ArgsCheckException("There should be no assertion `{0}`.".format(error_msg_10)) - if not "result" in last_message_as_json(resp_10): - raise ArgsCheckException("No `result` in response") - - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/009_list_voter_proposal_fail_invalid_value_for_last_id.py b/tests2/functional/python_tests/cli_wallet/tests/009_list_voter_proposal_fail_invalid_value_for_last_id.py deleted file mode 100755 index 365e261ea2d67fb74c11035cfe88311c555f5093..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/009_list_voter_proposal_fail_invalid_value_for_last_id.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/python3 - -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -if __name__ == "__main__": - try: - init_logger(__file__) - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - error_msg_x = "The value `x` for `_last_id` argument is invalid, it should be integer type." - resp_error_x = wallet.list_voter_proposals(args.creator, "creator", "asc", 50, "all", "x") - log.info(resp_error_x) - if resp_error_x.find(error_msg_x) == -1: - raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_x)) - - error_msg_y = "The value `y` for `_last_id` argument is invalid, it should be integer type." - resp_error_y = wallet.list_voter_proposals(args.creator, "creator", "asc", 50, "all", "y") - log.info(resp_error_y) - if resp_error_y.find(error_msg_y) == -1: - raise ArgsCheckException("Assertion `{0}` is required.".format(error_msg_y)) - - error_msg_10 = "The value `10` for `_last_id` argument is invalid, it should be integer type." - resp_10 = wallet.list_voter_proposals(args.creator, "creator", "asc", 50, "all", "10") - log.info(resp_10) - if resp_10.find(error_msg_10) != -1: - raise ArgsCheckException("There should be no assertion `{0}`.".format(error_msg_10)) - if not "result" in last_message_as_json(resp_10): - raise ArgsCheckException("No `result` in response") - - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/010_delayed_voting.py b/tests2/functional/python_tests/cli_wallet/tests/010_delayed_voting.py deleted file mode 100755 index 0ca01a790437ff8f100916f1a7d0240c6ca4f270..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/010_delayed_voting.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/python3 - -import time -import json - -#from ... import utils -from utils.test_utils import * -from utils.cmd_args import args -from utils.cli_wallet import CliWallet -from utils.logger import log, init_logger - -def get_votes( wallet, account_name ): - - pattern = "get_account" + " \"" + account_name + "\"" - - response = wallet.get_account( account_name ) - - found = response.find( pattern ) - if found == -1: - return 0 - - found += len( pattern ) - sub_response = response[ found : len( response ) ] - - items = json.loads( sub_response ) - - assert( "delayed_votes" in items ) - - dv_items = items["delayed_votes"] - - val = 0 - for item in dv_items: - assert( "val" in item ) - val += int( item[ "val" ] ) - - return val - -if __name__ == "__main__": - try: - init_logger(__file__) - - error = False - wallet = CliWallet( args.path, - args.server_rpc_endpoint, - args.cert_auth, - args.rpc_tls_endpoint, - args.rpc_tls_cert, - args.rpc_http_endpoint, - args.deamon, - args.rpc_allowip, - args.wallet_file, - args.chain_id, - args.wif ) - wallet.set_and_run_wallet() - - creator, receiver = make_user_for_tests(wallet) - log.info( "actors: creator: {0} receiver: ".format( creator, receiver ) ) - - # "delayed_votes": [{ - # "time": "2020-04-02T12:39:33", - # "val": 642832 - # } - # ] - - #=================Adding delayed votes================= - before_val = get_votes( wallet, receiver ) - - #=================Vest liquid again================= - wallet.transfer_to_vesting( creator, receiver, "1.000 TESTS", "true" ) - - #=================Adding delayed votes================= - after_val = get_votes( wallet, receiver ) - - log.info( "before_val: {0} after_val: {1}".format( before_val, after_val ) ) - - #=================Checking changes================= - assert( after_val > before_val ) - - except Exception as _ex: - log.exception(str(_ex)) - error = True - finally: - if error: - log.error("TEST `{0}` failed".format(__file__)) - exit(1) - else: - log.info("TEST `{0}` passed".format(__file__)) - exit(0) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/utils/cli_wallet.py b/tests2/functional/python_tests/cli_wallet/tests/utils/cli_wallet.py deleted file mode 100755 index 8ab04696c8685456716b50f70b4d981b2601b1ef..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/utils/cli_wallet.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/python3 - -import sys -import json -import queue -import requests -import threading -import subprocess - -from .logger import log -from .cmd_args import args -from .test_utils import last_message_as_json, ws_to_http - -class CliWalletException(Exception): - def __init__(self, _message): - self.message = _message - - def __str__(self): - return self.message - -class CliWallet(object): - - class CliWalletArgs(object): - def __init__(self, _path_to_executable, - _server_rpc_endpoint, - _cert_auth, - #_rpc_endpoint, - _rpc_tls_endpoint, - _rpc_tls_cert, - _rpc_http_endpoint, - _deamon, - _rpc_allowip, - _wallet_file, - _chain_id, - _wif ): - self.path = _path_to_executable+'/cli_wallet' - self.server_rpc_endpoint = _server_rpc_endpoint - self.cert_auth = _cert_auth - #self.rpc_endpoint = _rpc_endpoint - self.rpc_tls_endpoint = _rpc_tls_endpoint - self.rpc_tls_cert = _rpc_tls_cert - self.rpc_http_endpoint = _rpc_http_endpoint - self.deamon = _deamon - self.rpc_allowip = _rpc_allowip - self.wallet_file = _wallet_file - self.chain_id = _chain_id - self.wif = _wif - - def args_to_list(self): - test_args = [] - args = {"server_rpc_endpoint": self.server_rpc_endpoint} - args["cert_auth"] = self.cert_auth - #args["rpc_endpoint"] = self.rpc_endpoint - args["rpc_tls_endpoint"] = self.rpc_tls_endpoint - args["rpc_tls_cert"] = self.rpc_tls_cert - args["rpc_http_endpoint"] =self.rpc_http_endpoint - args["deamon"] = self.deamon - args["rpc_allowip"] = self.rpc_allowip - args["wallet_file"] = self.wallet_file - args["chain_id"] = self.chain_id - for key, val in args.items(): - if val : - test_args.append("--"+key.replace("_","-")+ " ") - test_args.append(val) - test_args = " ".join(test_args) - return test_args - - - def __init__(self, _path_to_executable, - _server_rpc_endpoint="ws://127.0.0.1:8090", - _cert_auth="_default", - #_rpc_endpoint="127.0.0.1:8091", - _rpc_tls_endpoint="127.0.0.1:8092", - _rpc_tls_cert="server.pem", - _rpc_http_endpoint="127.0.0.1:8093", - _deamon=False, - _rpc_allowip=[], - _wallet_file="wallet.json", - _chain_id="18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e", - _wif = "5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n"): - - self.cli_args = CliWallet.CliWalletArgs(_path_to_executable, _server_rpc_endpoint, _cert_auth, #_rpc_endpoint, - _rpc_tls_endpoint, _rpc_tls_cert, - _rpc_http_endpoint, _deamon, _rpc_allowip, _wallet_file, _chain_id, _wif ) - self.cli_proc = None - self.response = "" - self.q = queue.Queue() - self.t = threading.Thread(target=self.output_reader, args=()) - - - def __getattr__(self, _method_name): - if self.cli_proc: - self.method_name = _method_name - return self - else: - log.error("Cli_wallet is not set") - raise CliWalletException("Cli_wallet is not set") - - - def __call__(self,*_args): - try: - self.response = "" - self.send_and_read(self.prepare_args(*_args)) - return self.response - except Exception as _ex: - log.exception("Exception `{0}` occuress while calling `{1}` with `{2}` args.".format(str(_ex), self.method_name, list(_args))) - - - def set_and_run_wallet(self): - try: - log.info("Calling cli_wallet with args `{0}`".format([self.cli_args.path+ " " + self.cli_args.args_to_list()])) - self.cli_proc = subprocess.Popen([self.cli_args.path+ " " + self.cli_args.args_to_list()], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, shell=True) - if not self.cli_proc: - raise CliWalletException("Failed to run cli_wallet") - self.t.daemon=True - self.t.start() - self.set_password("{0}".format("testpassword")) - self.unlock("{0}".format("testpassword")) - self.import_key("{0}".format(self.cli_args.wif)) - except Exception as _ex: - log.exception("Exception `{0}` occuress while while running cli_wallet.".format(str(_ex))) - - - #we dont have stansaction status api, so we need to combine... - def wait_for_transaction_approwal(self): - json_resp = last_message_as_json(self.response) - block_num = json_resp["result"]["block_num"] - trans_id = json_resp["result"]["id"] - url = ws_to_http(self.cli_args.server_rpc_endpoint) - idx = -1 - while True: - param = {"jsonrpc":"2.0", "method":"block_api.get_block", "params":{"block_num":block_num+idx}, "id":1} - resp = requests.post(url, json=param) - data = resp.json() - if "result" in data and "block" in data["result"]: - block_transactions = data["result"]["block"]["transaction_ids"] - if trans_id in block_transactions: - log.info("Transaction `{0}` founded in block `{1}`".format(trans_id, block_num+idx)) - break - idx += 1 - - - def check_if_transaction(self): - json_resp = last_message_as_json(self.response) - if "result" in json_resp: - if "id" in json_resp["result"]: - return True - return False - - - def read_output(self, _timeout): - while True: - try: - self.response += self.q.get(block=True, timeout=_timeout) - except queue.Empty: - break - - - def send(self, _data): - self.cli_proc.stdin.write(_data.encode("utf-8")) - self.cli_proc.stdin.flush() - - - def send_and_read(self, _data): - log.info("Sending {0}".format(_data)) - self.send(_data) - self.read_output(3) - - #asserions does not occures after above flush, so we need to send additiona `Enter` - self.send("\n") - self.read_output(0.5) - if self.check_if_transaction(): - self.wait_for_transaction_approwal() - - return self.response - - - def exit_wallet(self): - try: - if not self.cli_proc: - log.info("Cannot exit wallet, because wallet was not set - please run it first by using `run_wallet` metode.") - self.cli_proc.communicate() - return self.cli_proc - except Exception as _ex: - log.exception("Exception `{0}` occuress while while running cli_wallet.".format(str(_ex))) - - - def output_reader(self): - while True: - try: - for line in iter(self.cli_proc.stdout.readline, b''): - self.q.put_nowait(line.decode('utf-8') ) - except queue.Full: - pass - - - def prepare_args(self, *_args): - name = self.method_name - args = _args - prepared_args = name + " " - for arg in args: - if isinstance(arg, int): - prepared_args += str(arg) + " " - elif isinstance(arg, str): - if arg: - prepared_args += "\"{0}\"".format(arg) + " " - else: - prepared_args += '\"\"' + " " - else: - prepared_args += "{0}".format(arg) + " " - return prepared_args + "\n" - diff --git a/tests2/functional/python_tests/cli_wallet/tests/utils/cmd_args.py b/tests2/functional/python_tests/cli_wallet/tests/utils/cmd_args.py deleted file mode 100644 index 1b8cc59c41ab661d60cdb0675dede3537e127db3..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/utils/cmd_args.py +++ /dev/null @@ -1,21 +0,0 @@ -import argparse - -args = None - -parser = argparse.ArgumentParser(description='Hived cli wallet test args.') -parser.add_argument('--path-to-cli' , dest='path' , help ='Path to cli_wallet executable') -parser.add_argument('--creator' , dest='creator' , help ='Account to create proposals with') -parser.add_argument('--wif' , dest='wif' , help ='Private key for creator account', default ="5JNHfZYKGaomSFvd4NUdQ9qMcEAC43kujbfjueTHpVapX1Kzq2n") -parser.add_argument('--server-rpc-endpoint', dest="server_rpc_endpoint", help = "Set server endpoint [=ws://127.0.0.1:8090]", default ="ws://127.0.0.1:8090") -parser.add_argument('--cert-auth' , dest="cert_auth" , help = "Set cert auth [=_default]" , default ="_default") -#this argument causes error -#parser.add_argument('--rpc-endpoint' , dest="rpc_endpoint" , help = "Set rpc endpoint [=127.0.0.1:8091]" , default ="127.0.0.1:8091") -parser.add_argument('--rpc-tls-endpoint' , dest="rpc_tls_endpoint" , help = "Set rpc tle endpont [=127.0.0.1:8092]" , default ="127.0.0.1:8092") -parser.add_argument('--rpc-tls-cert' , dest="rpc_tls_cert" , help = "Set rpc tls cert [=server.pem]" , default ="server.pem") -parser.add_argument('--rpc-http-endpoint' , dest="rpc_http_endpoint" , help = "Set rpc http endpoint [=127.0.0.1:8093]" , default ="127.0.0.1:8093") -parser.add_argument('--deamon' , dest="deamon" , help = "Set to work as deamon [=False]" , default =False) -parser.add_argument('--rpc-allowip' , dest="rpc_allowip" , help = "Set allowed rpc ip [=[]]" , default =[]) -parser.add_argument('--wallet-file' , dest="wallet_file" , help = "Set wallet name [=wallet.json]" , default ="wallet.json") -parser.add_argument('--chain-id' , dest="chain_id" , help = "Set chain id [=18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e]", default ="18dcf0a285365fc58b71f18b3d3fec954aa0c141c44e4e5cb4cf777b9eab274e") - -args = parser.parse_args() \ No newline at end of file diff --git a/tests2/functional/python_tests/cli_wallet/tests/utils/logger.py b/tests2/functional/python_tests/cli_wallet/tests/utils/logger.py deleted file mode 100644 index ac5ef90b74e49cecef750f2896f5a4b808c28e3f..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/utils/logger.py +++ /dev/null @@ -1,33 +0,0 @@ -import os -import sys -import logging -import datetime - -log = logging.getLogger("Cli_wallet") - -def init_logger(_file_name): - global log - log.handlers = [] - formater = '%(asctime)s [%(levelname)s] %(message)s' - stdh = logging.StreamHandler(sys.stdout) - stdh.setFormatter(logging.Formatter(formater)) - log.addHandler(stdh) - log.setLevel(logging.INFO) - - data = os.path.split(_file_name) - if data[0]: - path = data[0] + "/logs/" - else: - path = "./logs/" - file = data[1] - if path and not os.path.exists(path): - os.makedirs(path) - now = str(datetime.datetime.now())[:-7] - now = now.replace(' ', '-') - full_path = path+"/"+now+"_"+file - if not full_path.endswith(".log"): - full_path += (".log") - fileh = logging.FileHandler(full_path) - fileh.setFormatter(logging.Formatter(formater)) - log.addHandler(fileh) - diff --git a/tests2/functional/python_tests/cli_wallet/tests/utils/test_utils.py b/tests2/functional/python_tests/cli_wallet/tests/utils/test_utils.py deleted file mode 100644 index 5f698ea4220d73c8e293f955a0bde9757b7b11f8..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/cli_wallet/tests/utils/test_utils.py +++ /dev/null @@ -1,137 +0,0 @@ -import json -import requests - -from utils.logger import log -from utils.cmd_args import args - -class ArgsCheckException(Exception): - def __init__(self, _message): - self.message = _message - - def __str__(self): - return self.message - -user_name = list("aaaaaaaaaaaa") -creator = "initminer" - -def unifie_to_string(_arg): - if not isinstance(_arg, str): - prepared = str(_arg) - else: - prepared = _arg - prepared = prepared.strip() - prepared = prepared.replace(" ", "") - return prepared - - -def check_call_args(_call_args, _response, _arg_prefix): - splited_response = _response.split() - for idx, line in enumerate(splited_response): - if _arg_prefix in line: - key = line[line.find(_arg_prefix+".")+len(_arg_prefix+"."):-1] - #unifie to string - call = unifie_to_string(_call_args[key]) - spli = unifie_to_string(splited_response[idx+1]) - - if call in spli: - _call_args.pop(key) - else: - log.error("Call arg `{0}` expected `{1}`".format(_call_args[key], str(splited_response[idx+1]))) - raise ArgsCheckException("Incossisten value for `{0}` key".format(key)) - if not _call_args: - break - if _call_args: - raise ArgsCheckException("No all values checked, those `{0}` still remains. ".format(_call_args)) - - -def call_and_check(_func, _call_args, _arg_prefix): - response = _func(*_call_args.values()) - log.info("Call response: {0}".format(response)) - check_call_args(_call_args, response, _arg_prefix) - return response - - -def call_and_check_transaction(_func, _call_args, _arg_prefix, _broadcast): - response = _func(*_call_args.values(), _broadcast) - check_call_args(_call_args, response, _arg_prefix) - - -def last_message_as_json( _message): - if "message:" in _message: - _message = _message[_message.rfind("message:")+len("message:"):] - _message.strip() - o = 0 - #lame... but works - for index, ch in enumerate(_message): - if str(ch) == "{": - o +=1 - continue - if str(ch) == "}": - o -=1 - if o == 0: - _message = _message[:index+1] - break - else: - _message = "{}" - return json.loads(_message) - - -def find_creator_proposals(_creator, _proposal_list): - proposals = [] - if "result" in _proposal_list: - result = _proposal_list["result"] - for rs in result: - if rs["creator"] == _creator: - proposals.append(rs) - return proposals - - -def find_voter_proposals(_voter, _proposal_list): - if "result" in _proposal_list: - result = _proposal_list["result"] - for user, user_propsals in result.items(): - if user == _voter: - return user_propsals - return [] - - -def ws_to_http(_url): - pos = _url.find(":") - return "http" + _url[pos:] - - -def get_valid_hive_account_name(): - http_url = ws_to_http(args.server_rpc_endpoint) - while True: - params = {"jsonrpc":"2.0", "method":"condenser_api.get_accounts", "params":[["".join(user_name)]], "id":1} - resp = requests.post(http_url, json=params) - data = resp.json() - if "result" in data: - if len(data["result"]) == 0: - return ''.join(user_name) - if ord(user_name[0]) >= ord('z'): - for i, _ in enumerate("".join(user_name)): - if user_name[i] >= 'z': - user_name[i] = 'a' - continue - user_name[i] = chr(ord(user_name[i]) + 1) - break - else: - user_name[0] = chr(ord(user_name[0]) + 1) - if len(set(user_name)) == 1 and user_name[0] == 'z': - break - -def make_user_for_tests(_cli_wallet, _value_for_vesting = None, _value_for_transfer_tests = None, _value_for_transfer_tbd = None): - value_for_vesting = _value_for_vesting if _value_for_vesting else "20.000 TESTS" - value_for_transfer_tests = _value_for_transfer_tests if _value_for_transfer_tests else "20.000 TESTS" - value_for_transfer_tbd = _value_for_transfer_tbd if _value_for_transfer_tbd else "20.000 TBD" - - receiver = get_valid_hive_account_name() - - _cli_wallet.create_account( creator, receiver, "{}", "true") - - _cli_wallet.transfer_to_vesting( creator, receiver, value_for_vesting, "true") - _cli_wallet.transfer( creator, receiver, value_for_transfer_tests, "initial transfer", "true" ) - _cli_wallet.transfer( creator, receiver, value_for_transfer_tbd, "initial transfer", "true") - - return creator, receiver diff --git a/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_001.py b/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_001.py deleted file mode 100644 index 7c83f91b04afd40e16e06a1c767bb14e7a84743c..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_001.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "comment_payment_001.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - -MODULE_NAME = "Comment-Payment-Tester" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -def print_comment_rewards(node_client, accounts): - logger.info("Print author rewards...") - from beem.comment import Comment - from prettytable import PrettyTable - last_cashout_time = "" - - table = PrettyTable() - table.field_names = ['author','permlink','last_payout','cashout_time','total_vote_weight','reward_weight','total_payout_value','curator_payout_value','author_rewards','net_votes','percent_hbd','pending_payout_value','total_pending_payout_value'] - ret = [] - for account in accounts: - blog = node_client.rpc.get_content(account["name"], test_utils.get_post_permlink(account["name"])) - row = [] - for key in table.field_names: - row.append(blog[key]) - table.add_row(row) - ret.append(row) - last_cashout_time = blog['cashout_time'] - print(table) - return last_cashout_time, ret - -def compare_tables(before, after): - logger.info("Comparing tables...") - for row in range(len(before)): - for col in range(len(before[row])): - assert before[row][col] == after[row][col], "{} != {}".format(before[row][col], after[row][col]) - -if __name__ == '__main__': - logger.info("Performing comment payment tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("hived_path", help = "Path to hived executable.") - parser.add_argument("replay_hived_path", help = "Path to hived executable performing replay.") - - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - {"name" : "tester005", "private_key" : "5Hy4vEeYmBDvmXipe5JAFPhNwCnx7NfsfyiktBTBURn9Qt1ihcA", "public_key" : "TST7CP7FFjvG55AUeH8riYbfD8NxTTtFH32ekQV4YFXmV6gU8uAg3"} - ] - - before = None - after = None - - balances_before = None - balances_after = None - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is not None and node.is_running(): - logger.info("Connecting to testnet...") - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - logger.info("Publishing feed...") - from beem.witness import Witness - w = Witness("initminer", hive_instance=node_client) - w.feed_publish(1000.000, account="initminer") - hive_utils.common.wait_n_blocks(node_client.rpc.url, 5) - - logger.info("Chain prefix is: {}".format(node_client.prefix)) - logger.info("Chain ID is: {}".format(node_client.get_config()["HIVE_CHAIN_ID"])) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "3000000.000", "TESTS") - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, "10000.000", "TESTS") - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, "10000.000", "TBD") - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - - # create post for valid permlinks - from beem.account import Account - test_utils.create_posts(node_client, accounts) - logger.info("Voting...") - for account in accounts[1:]: - acc = Account(account["name"], hive_instance=node_client) - node_client.vote(100., "@{}/{}".format("tester001", test_utils.get_post_permlink("tester001")),account=acc) - hive_utils.common.wait_n_blocks(node_client.rpc.url, 10) - - last_cashout_time, _ = print_comment_rewards(node_client, accounts) - logger.info("Last block number: {}".format(node_client.get_dynamic_global_properties(False)['head_block_number'])) - logger.info("Accelerating time...") - hive_utils.debug_generate_blocks_until(node_client.rpc.url, wif, last_cashout_time, False) - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 100) - _, before = print_comment_rewards(node_client, accounts) - - logger.info("Balances for accounts at end of the test") - balances_before = test_utils.print_balance(node_client, accounts) - logger.info("Last block number: {}".format(node_client.get_dynamic_global_properties(False)['head_block_number'])) - if node is not None: - node.stop_hive_node() - - logger.info("Attempting replay!!!") - if args.replay_hived_path: - logger.info("Replaying with hived via {} in {} with config {}".format(args.replay_hived_path, - args.hived_working_dir, - args.hived_working_dir + "/config.ini") - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.replay_hived_path, - args.hived_working_dir, - args.hived_working_dir + "/config.ini", - True - ) - if node is not None: - node.run_hive_node(["--enable-stale-production","--replay-blockchain"]) - if node is not None and node.is_running(): - logger.info("Connecting to testnet...") - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - _, after = print_comment_rewards(node_client, accounts) - logger.info("Balances for accounts at end of the replay") - balances_after = test_utils.print_balance(node_client, accounts) - logger.info("Last block number: {}".format(node_client.get_dynamic_global_properties(False)['head_block_number'])) - logger.info("Comparing comment rewards") - compare_tables(before, after) - logger.info("Comparing balances") - compare_tables(balances_before, balances_after) - - if node is not None: - node.stop_hive_node() - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_002.py b/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_002.py deleted file mode 100755 index 9402d85c6bf08715342008a9a489274b7c052ebe..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/comment_payment_test_002.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "comment_payment_001.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - -MODULE_NAME = "Comment-Payment-Tester" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -def compare_files_by_line(file1, file2): - try: - line_cnt = 0 - with open(sys.argv[1], 'r') as src: - with open(sys.argv[2], 'r') as dst: - for line in src: - src_line = line.strip() - dst_line = dst.readline().strip() - assert src_line == dst_line, "On line: {} --> {} != {}".format(line_cnt, src_line, dst_line) - line_cnt += 1 - logger.info("OK. Compared {} lines.".format(line_cnt)) - return True - except Exception as ex: - logger.info("Exception: {}".format(ex)) - return False - -def prepare_work_dir(work_dir_path, block_log_path, config_file_path, overwrite = False): - import os - from shutil import copy, rmtree - logger.info("Preparing working dir {}".format(work_dir_path)) - blockchain_dir = work_dir_path + "/blockchain" - if os.path.exists(work_dir_path): - if os.path.isdir(work_dir_path): - logger.info("Cleaning up working dir {}".format(work_dir_path)) - paths_to_delete = [work_dir_path + "/p2p", work_dir_path + "/logs", blockchain_dir + "/block_log.index", blockchain_dir + "/shared_memory.bin"] - from glob import glob - paths_to_delete.extend(glob(work_dir_path +"/*.log")) - paths_to_delete.extend(glob(work_dir_path +"/*.pid")) - paths_to_delete.extend(glob(work_dir_path +"/*.cfg")) - for path in paths_to_delete: - if os.path.exists(path): - logger.info("Removing {}".format(path)) - if os.path.isdir(path): - rmtree(path) - else: - os.remove(path) - else: - raise RuntimeError("{} is not a directory".format(work_dir_path)) - else: - logger.info("Creating directory {}".format(work_dir_path)) - os.makedirs(work_dir_path) - logger.info("Creating directory {}".format(blockchain_dir)) - os.makedirs(blockchain_dir) - logger.info("Copying files...") - copy(block_log_path, blockchain_dir + "/block_log") - copy(config_file_path, work_dir_path + "/config.ini") - -def perform_replay(node_bin_path, node_work_dir_path): - logger.info("Performing replay with {}".format(node_bin_path)) - node = hive_utils.hive_node.HiveNodeInScreen( - node_bin_path, - node_work_dir_path, - None, - True - ) - if node is not None: - node.run_hive_node(["--enable-stale-production","--replay-blockchain","--cashout-logging-log-path-dir",node_work_dir_path]) - return node - -if __name__ == '__main__': - node = None - try: - logger.info("Performing comment payment tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("reference_node_bin_path", help = "Path to reference hived executable.") - parser.add_argument("test_node_bin_path", help = "Path to test hived executable.") - parser.add_argument("reference_node_work_dir", help = "Path to reference node working dir.") - parser.add_argument("test_node_work_dir", help = "Path to reference node working dir.") - parser.add_argument("block_log_path", help="Path to block log for replay.") - parser.add_argument("--replay-reference-node", type=bool, default=True, help="Replay reference node.") - args = parser.parse_args() - - if args.replay_reference_node: - prepare_work_dir(args.reference_node_work_dir, args.block_log_path, "./resources/config.ini") - - prepare_work_dir(args.test_node_work_dir, args.block_log_path, "./resources/config.ini") - - if args.replay_reference_node: - node = perform_replay(args.reference_node_bin_path, args.reference_node_work_dir) - if node is not None: - node.stop_hive_node() - node = None - - node = perform_replay(args.test_node_bin_path, args.test_node_work_dir) - if node is not None: - node.stop_hive_node() - node = None - - logger.info("Comparing comment cashout logs...") - from glob import glob - files_to_compare = glob(args.reference_node_work_dir + "/*-*.log") - for f in files_to_compare: - file_name = f.split("/")[-1] - if not compare_files_by_line(f, args.reference_node_work_dir + "/" + file_name): - sys.exit(1) - sys.exit(0) - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) \ No newline at end of file diff --git a/tests2/functional/python_tests/comment_payment_tests/resources/config.extended.ini b/tests2/functional/python_tests/comment_payment_tests/resources/config.extended.ini deleted file mode 100644 index 6daf75c7305e1ea7c71ab2f27217cfe6f0e6a36a..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/resources/config.extended.ini +++ /dev/null @@ -1,99 +0,0 @@ -# Appender definition json: {"appender", "stream", "file"} Can only specify a file OR a stream -log-appender = {"appender":"stderr","stream":"std_error"} {"appender":"p2p","file":"logs/p2p/p2p.log"} - -# Logger definition json: {"name", "level", "appender"} -log-logger = {"name":"default","level":"all","appender":"stderr"} {"name":"p2p","level":"all","appender":"p2p"} - -# Whether to print backtrace on SIGSEGV -backtrace = yes - -# Plugin(s) to enable, may be specified multiple times -plugin = witness chain database_api account_by_key_api network_broadcast_api tags_api follow_api condenser_api block_api transaction_status_api debug_node_api rewards_api - -# Disables automatic account history trimming -history-disable-pruning = 0 - -# The location of the rocksdb database for account history. By default it is $DATA_DIR/blockchain/account-history-rocksdb-storage -account-history-rocksdb-path = "blockchain/account-history-rocksdb-storage" - -# Where to export data (NONE to discard) -block-data-export-file = NONE - -# How often to print out block_log_info (default 1 day) -block-log-info-print-interval-seconds = 86400 - -# Whether to defer printing until block is irreversible -block-log-info-print-irreversible = 1 - -# Where to print (filename or special sink ILOG, STDOUT, STDERR) -block-log-info-print-file = ILOG - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G. If running a full node, increase this value to 200G. -shared-file-size = 12G - -# A 2 precision percentage (0-10000) that defines the threshold for when to autoscale the shared memory file. Setting this to 0 disables autoscaling. Recommended value for consensus node is 9500 (95%). Full node is 9900 (99%) -shared-file-full-threshold = 0 - -# A 2 precision percentage (0-10000) that defines how quickly to scale the shared memory file. When autoscaling occurs the file's size will be increased by this percent. Setting this to 0 disables autoscaling. Recommended value is between 1000-2000 (10-20%) -shared-file-scale-rate = 0 - -# Set the maximum size of cached feed for an account -follow-max-feed-size = 500 - -# Block time (in epoch seconds) when to start calculating feeds -follow-start-feeds = 0 - -# Track market history by grouping orders into buckets of equal size measured in seconds specified as a JSON array of numbers -market-history-bucket-size = [15,60,300,3600,86400] - -# How far back in time to track history for each bucket size, measured in the number of buckets (default: 5760) -market-history-buckets-per-size = 5760 - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Skip rejecting transactions when account has insufficient RCs. This is not recommended. -rc-skip-reject-not-enough-rc = 0 - -# Generate historical resource credits -rc-compute-historical-rc = 0 - -# Size to batch statsd messages. -statsd-batchsize = 1 - -# Block time (in epoch seconds) when to start calculating promoted content. Should be 1 week prior to current time. -tags-start-promoted = 0 - -# Skip updating tags on startup. Can safely be skipped when starting a previously running node. Should not be skipped when reindexing. -tags-skip-startup-update = 0 - -# Defines the number of blocks from the head block that transaction statuses will be tracked. -transaction-status-block-depth = 64000 - -# Defines the block number the transaction status plugin will begin tracking. -transaction-status-track-after-block = 0 - -# Local http endpoint for webserver requests. -webserver-http-endpoint = 127.0.0.1:8090 - -# Local websocket endpoint for webserver requests. -webserver-ws-endpoint = 127.0.0.1:8090 - -# Number of threads used to handle queries. Default: 32. -webserver-thread-pool-size = 32 - -# Enable block production, even if the chain is stale. -enable-stale-production = 0 - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) - -# WIF PRIVATE KEY to be used by one or more witnesses or miners - -# Skip enforcing bandwidth restrictions. Default is true in favor of rc_plugin. -witness-skip-enforce-bandwidth = 1 \ No newline at end of file diff --git a/tests2/functional/python_tests/comment_payment_tests/resources/config.ini b/tests2/functional/python_tests/comment_payment_tests/resources/config.ini deleted file mode 100644 index 22f4daff647403430c318784d3b9f5121f6355f8..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/resources/config.ini +++ /dev/null @@ -1,99 +0,0 @@ -# Appender definition json: {"appender", "stream", "file"} Can only specify a file OR a stream -log-appender = {"appender":"stderr","stream":"std_error"} {"appender":"p2p","file":"logs/p2p/p2p.log"} - -# Logger definition json: {"name", "level", "appender"} -log-logger = {"name":"default","level":"all","appender":"stderr"} {"name":"p2p","level":"all","appender":"p2p"} - -# Whether to print backtrace on SIGSEGV -backtrace = yes - -# Plugin(s) to enable, may be specified multiple times -plugin = witness chain database_api account_by_key_api network_broadcast_api condenser_api block_api transaction_status_api debug_node_api comment_cashout_logging - -# Disables automatic account history trimming -history-disable-pruning = 0 - -# The location of the rocksdb database for account history. By default it is $DATA_DIR/blockchain/account-history-rocksdb-storage -account-history-rocksdb-path = "blockchain/account-history-rocksdb-storage" - -# Where to export data (NONE to discard) -block-data-export-file = NONE - -# How often to print out block_log_info (default 1 day) -block-log-info-print-interval-seconds = 86400 - -# Whether to defer printing until block is irreversible -block-log-info-print-irreversible = 1 - -# Where to print (filename or special sink ILOG, STDOUT, STDERR) -block-log-info-print-file = ILOG - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G. If running a full node, increase this value to 200G. -shared-file-size = 8G - -# A 2 precision percentage (0-10000) that defines the threshold for when to autoscale the shared memory file. Setting this to 0 disables autoscaling. Recommended value for consensus node is 9500 (95%). Full node is 9900 (99%) -shared-file-full-threshold = 0 - -# A 2 precision percentage (0-10000) that defines how quickly to scale the shared memory file. When autoscaling occurs the file's size will be increased by this percent. Setting this to 0 disables autoscaling. Recommended value is between 1000-2000 (10-20%) -shared-file-scale-rate = 0 - -# Set the maximum size of cached feed for an account -follow-max-feed-size = 500 - -# Block time (in epoch seconds) when to start calculating feeds -follow-start-feeds = 0 - -# Track market history by grouping orders into buckets of equal size measured in seconds specified as a JSON array of numbers -market-history-bucket-size = [15,60,300,3600,86400] - -# How far back in time to track history for each bucket size, measured in the number of buckets (default: 5760) -market-history-buckets-per-size = 5760 - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Skip rejecting transactions when account has insufficient RCs. This is not recommended. -rc-skip-reject-not-enough-rc = 0 - -# Generate historical resource credits -rc-compute-historical-rc = 0 - -# Size to batch statsd messages. -statsd-batchsize = 1 - -# Block time (in epoch seconds) when to start calculating promoted content. Should be 1 week prior to current time. -tags-start-promoted = 0 - -# Skip updating tags on startup. Can safely be skipped when starting a previously running node. Should not be skipped when reindexing. -tags-skip-startup-update = 0 - -# Defines the number of blocks from the head block that transaction statuses will be tracked. -transaction-status-block-depth = 64000 - -# Defines the block number the transaction status plugin will begin tracking. -transaction-status-track-after-block = 0 - -# Local http endpoint for webserver requests. -webserver-http-endpoint = 127.0.0.1:8090 - -# Local websocket endpoint for webserver requests. -webserver-ws-endpoint = 127.0.0.1:8090 - -# Number of threads used to handle queries. Default: 32. -webserver-thread-pool-size = 32 - -# Enable block production, even if the chain is stale. -enable-stale-production = 0 - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) - -# WIF PRIVATE KEY to be used by one or more witnesses or miners - -# Skip enforcing bandwidth restrictions. Default is true in favor of rc_plugin. -witness-skip-enforce-bandwidth = 1 \ No newline at end of file diff --git a/tests2/functional/python_tests/comment_payment_tests/simulate_curve_payouts.py b/tests2/functional/python_tests/comment_payment_tests/simulate_curve_payouts.py deleted file mode 100644 index 24b26b8246cc15ab660dcf2ee2e345fe49713391..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/simulate_curve_payouts.py +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "simulate_curve_payouts.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - -MODULE_NAME = "Simulate-Curve-Payout-Tester" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -def prepare_work_dir(work_dir_path, block_log_path, config_file_path): - import os - from shutil import copy, rmtree - logger.info("Preparing working dir {}".format(work_dir_path)) - blockchain_dir = work_dir_path + "/blockchain" - if os.path.exists(work_dir_path): - if os.path.isdir(work_dir_path): - logger.info("Cleaning up working dir {}".format(work_dir_path)) - paths_to_delete = [work_dir_path + "/p2p", work_dir_path + "/logs", blockchain_dir + "/block_log.index", blockchain_dir + "/shared_memory.bin"] - from glob import glob - paths_to_delete.extend(glob(work_dir_path +"/*.log")) - paths_to_delete.extend(glob(work_dir_path +"/*.pid")) - paths_to_delete.extend(glob(work_dir_path +"/*.cfg")) - for path in paths_to_delete: - if os.path.exists(path): - logger.info("Removing {}".format(path)) - if os.path.isdir(path): - rmtree(path) - else: - os.remove(path) - else: - raise RuntimeError("{} is not a directory".format(work_dir_path)) - else: - logger.info("Creating directory {}".format(work_dir_path)) - os.makedirs(work_dir_path) - logger.info("Creating directory {}".format(blockchain_dir)) - os.makedirs(blockchain_dir) - logger.info("Copying files [1/2]: block_log") - copy(block_log_path, blockchain_dir + "/block_log") - logger.info("Copying files [2/2]: config.ini") - copy(config_file_path, work_dir_path + "/config.ini") - -def perform_replay(node_bin_path, node_work_dir_path, is_steem_node): - logger.info("Performing replay with {}".format(node_bin_path)) - node = hive_utils.hive_node.HiveNodeInScreen( - node_bin_path, - node_work_dir_path, - None, - True, - is_steem_node - ) - if node is not None: - node.run_hive_node(["--enable-stale-production","--replay-blockchain"]) - return node - -def run_node(node_bin_path, node_work_dir_path, is_steem_node): - logger.info("Running node with {}".format(node_bin_path)) - node = hive_utils.hive_node.HiveNodeInScreen( - node_bin_path, - node_work_dir_path, - None, - True, - is_steem_node - ) - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - return node - -def get_data(node_url): - curves = [ - "quadratic", - "bounded_curation", - "linear", - "square_root", - "convergent_linear", - "convergent_square_root", - ] - - ret = {} - h = Hive(node_url) - rf = h.rpc.get_reward_fund("post") - ret['reward_fund'] = rf - for curve in curves: - ret[curve] = h.rpc.simulate_curve_payouts({"curve" : curve, "var1" : rf["content_constant"]}, api='rewards_api') - - return ret - -if __name__ == '__main__': - node = None - try: - logger.info("Performing comment payment tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("reference_node_bin_path", help = "Path to reference hived executable.") - parser.add_argument("test_node_bin_path", help = "Path to test hived executable.") - parser.add_argument("reference_node_work_dir", help = "Path to reference node working dir.") - parser.add_argument("test_node_work_dir", help = "Path to reference node working dir.") - parser.add_argument("block_log_path", help = "Path to block log for replay.") - parser.add_argument("--ref-node-is-steem", action = 'store_true', default = False, help = "Set this flag if reference node is steem node") - parser.add_argument("--compare-as-text", action = 'store_true', default = False, help = "Compare data as text") - parser.add_argument("--no-replay", action = 'store_true', default = False, help = "Do not perform data replay") - args = parser.parse_args() - - if not args.no_replay: - prepare_work_dir(args.reference_node_work_dir, args.block_log_path, "./resources/config.extended.ini") - prepare_work_dir(args.test_node_work_dir, args.block_log_path, "./resources/config.extended.ini") - - logger.info("Reference node data") - if args.no_replay: - node = run_node(args.reference_node_bin_path, args.reference_node_work_dir, args.ref_node_is_steem) - else: - node = perform_replay(args.reference_node_bin_path, args.reference_node_work_dir, args.ref_node_is_steem) - reference_data = get_data("http://127.0.0.1:8090") - - if node is not None: - node.stop_hive_node() - node = None - - logger.info("Test node data") - if args.no_replay: - node = run_node(args.test_node_bin_path, args.test_node_work_dir, False) - else: - node = perform_replay(args.test_node_bin_path, args.test_node_work_dir, False) - test_data = get_data("http://127.0.0.1:8090") - - if node is not None: - node.stop_hive_node() - node = None - - from json import dumps - if args.compare_as_text: - for k, v in reference_data.items(): - logger.info("Comparing data under key: {}".format(k)) - v1 = dumps(v) - v2 = dumps(test_data[k]) - if v1 != v2: - logger.error("Differences detected in data with key {}: {} != {}".format(k, v1, v2)) - sys.exit(1) - else: - from jsondiff import diff - for k, v in reference_data.items(): - logger.info("Comparing data under key: {}".format(k)) - json_diff = diff(v, test_data[k]) - if json_diff: - logger.error("Differences detected in data with key {}: {}".format(k, dumps(json_diff, sort_keys=True, indent=4))) - sys.exit(1) - - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) \ No newline at end of file diff --git a/tests2/functional/python_tests/comment_payment_tests/test_utils.py b/tests2/functional/python_tests/comment_payment_tests/test_utils.py deleted file mode 100644 index f4948dbc14232d26c02324fc0a5f2b3ad6dfc9e6..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/comment_payment_tests/test_utils.py +++ /dev/null @@ -1,128 +0,0 @@ -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_tester_utils.log" - -MODULE_NAME = "Comment-Payment-Tester.Utils" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - - -def create_accounts(node, creator, accounts): - for account in accounts: - logger.info("Creating account: {}".format(account['name'])) - node.create_account(account['name'], - owner_key=account['public_key'], - active_key=account['public_key'], - posting_key=account['public_key'], - memo_key=account['public_key'], - store_keys = False, - creator=creator, - asset='TESTS' - ) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def transfer_to_vesting(node, from_account, accounts, amount, asset): - from beem.account import Account - for acnt in accounts: - logger.info("Transfer to vesting from {} to {} amount {} {}".format( - from_account, acnt['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer_to_vesting(amount, to = acnt['name'], asset = asset) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def transfer_assets_to_accounts(node, from_account, accounts, amount, asset): - from beem.account import Account - for acnt in accounts: - logger.info("Transfer from {} to {} amount {} {}".format(from_account, - acnt['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer(acnt['name'], amount, asset, memo = "initial transfer") - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def get_post_permlink(account): - return "post-permlink-{}".format(account) - - -def create_posts(node, accounts): - logger.info("Creating posts...") - for acnt in accounts: - logger.info("New post ==> ({},{},{},{},{})".format( - "Post title [{}]".format(acnt['name']), - "Post body [{}]".format(acnt['name']), - acnt['name'], - get_post_permlink(acnt['name']), - "firstpost" - )) - node.post("Post title [{}]".format(acnt['name']), - "Post body [{}]".format(acnt['name']), - author=acnt['name'], - permlink = get_post_permlink(acnt['name']), - reply_identifier=None, - json_metadata=None, - comment_options=None, - community=None, - app=None, - tags="firstpost", - beneficiaries=None, - self_vote=False, - parse_body=False) - hive_utils.common.wait_n_blocks(node.rpc.url, 1) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def print_balance(node, accounts): - import prettytable - from beem.account import Account - table = prettytable.PrettyTable() - table.field_names = [ - "Account", - "balance", - "savings", - "hbd", - "savings_hbd", - "reward_hbd", - "reward_hive", - "reward_vesting", - "reward_vesting_hive", - "vesting_shares", - "delegated_vesting_shares", - "received_vesting_shares", - "curation_rewards", - "posting_rewards" - ] - balances = [] - for acnt in accounts: - ret = Account(acnt['name'], hive_instance=node).json() - data = [ - acnt['name'], - ret['balance']['amount'], - ret['savings_balance']['amount'], - ret['hbd_balance']['amount'], - ret['savings_hbd_balance']['amount'], - ret['reward_hbd_balance']['amount'], - ret['reward_hive_balance']['amount'], - ret['reward_vesting_balance']['amount'], - ret['reward_vesting_hive']['amount'], - ret['vesting_shares']['amount'], - ret['delegated_vesting_shares']['amount'], - ret['received_vesting_shares']['amount'], - ret['curation_rewards'], - ret['posting_rewards'] - ] - balances.append(data) - table.add_row(data) - print(table) - return balances diff --git a/tests2/functional/python_tests/delayed_votes_tests/basic_delayed_votes_test_001.py b/tests2/functional/python_tests/delayed_votes_tests/basic_delayed_votes_test_001.py deleted file mode 100755 index 1cecc4feff5ef23eccf0b5c2b22e79c6d6750000..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/delayed_votes_tests/basic_delayed_votes_test_001.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/python3 - -import requests, sys, json - -#HIVE node must work -url = 'http://127.0.0.1:8090' - -def check( item, positive ): - if positive: - assert( "delayed_votes" in item ) - else: - assert( "delayed_votes" not in item ) - -def check_in_array( content, positive ): - for item in content: - check( item, positive ) - break - -def query( payload, positive ): - result = requests.post( url, data=payload ) - content = result.json()["result"] - - if type( content ) == list: - check_in_array( content, positive ) - else: - assert( "accounts" in content ) - content = content["accounts"] - check_in_array( content, positive ) - -if __name__ == '__main__': - - try: - - query( '{"jsonrpc":"2.0", "method":"condenser_api.get_accounts", "params":[["initminer"] ], "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"condenser_api.get_accounts", "params":[["initminer"], true ], "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"condenser_api.get_accounts", "params":[["initminer"], false ], "id":1}', False ) - print( "test {0} passed ".format( "condenser_api.get_accounts passed" ) ) - - query( '{"jsonrpc":"2.0", "method":"condenser_api.lookup_account_names", "params":[["initminer"]], "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"condenser_api.lookup_account_names", "params":[["initminer"], true ], "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"condenser_api.lookup_account_names", "params":[["initminer"], false ], "id":1}', False ) - print( "test {0} passed ".format( "condenser_api.lookup_account_names" ) ) - - query( '{"jsonrpc":"2.0", "method":"database_api.find_accounts", "params": {"accounts":["initminer"]}, "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"database_api.find_accounts", "params": { "accounts":["initminer"], "delayed_votes_active" : true }, "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"database_api.find_accounts", "params": { "accounts":["initminer"], "delayed_votes_active" : false }, "id":1}', False ) - print( "test {0} passed ".format( "condenser_api.find_accounts passed" ) ) - - query( '{"jsonrpc":"2.0", "method":"database_api.list_accounts", "params": {"start":"initminer", "limit":1, "order":"by_name"}, "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"database_api.list_accounts", "params": {"start":"initminer", "limit":1, "order":"by_name", "delayed_votes_active" : true }, "id":1}', True ) - query( '{"jsonrpc":"2.0", "method":"database_api.list_accounts", "params": {"start":"initminer", "limit":1, "order":"by_name", "delayed_votes_active" : false }, "id":1}', False ) - print( "test {0} passed ".format( "condenser_api.list_accounts passed" ) ) - - print( "TEST PASSED" ) - - sys.exit( 0 ) - - except Exception as ex: - - print( "TEST FAILED" ) - print( ex.content ) - - sys.exit( 1 ) diff --git a/tests2/functional/python_tests/dhf_tests/CMakeLists.txt b/tests2/functional/python_tests/dhf_tests/CMakeLists.txt deleted file mode 100644 index d4cb4947fd90dda2fb3654fe2a834e5b6464606a..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/CMakeLists.txt +++ /dev/null @@ -1,8 +0,0 @@ -SET ( dhf_tests_args initminer initminer ${initminer_key} --run-hived ${hived_path} --working-dir ${CMAKE_BINARY_DIR}/tests/hive-node-data) - -IF ( BUILD_HIVE_TESTNET ) - ADD_PYTHON_FUNCTIONAL_TEST( beem_dhf_tests ${dhf_tests_args} --no-erase-proposal ) - ADD_PYTHON_FUNCTIONAL_TEST( list_proposals_tests ${dhf_tests_args} ) -ELSE ( BUILD_HIVE_TESTNET ) - MESSAGE ( STATUS "DHF functional tests skipped: BUILD_HIVE_TESTNET is required" ) -ENDIF ( BUILD_HIVE_TESTNET ) \ No newline at end of file diff --git a/tests2/functional/python_tests/dhf_tests/beem_dhf_tests.py b/tests2/functional/python_tests/dhf_tests/beem_dhf_tests.py deleted file mode 100755 index 7fec87383f0a919d7f752f66d02b3d81afd979e1..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/beem_dhf_tests.py +++ /dev/null @@ -1,436 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import os -import test_utils - -MODULE_NAME = "Beem-Dhf-Tester" -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" - -MAIN_LOG_PATH = "beem_dhf_tests.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - print("beem library is not installed.") - sys.exit(1) - -def test_create_proposal(node, creator_account, receiver_account, wif, subject): - logger.info("Testing: create_proposal") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - - import datetime - now = datetime.datetime.now() - - start_date, end_date = test_utils.get_start_and_end_date(now, 10, 2) - - from beem.account import Account - try: - creator = Account(creator_account, hive_instance=s) - except Exception as ex: - logger.error("Account: {} not found. {}".format(creator_account, ex)) - raise ex - - try: - receiver = Account(receiver_account, hive_instance=s) - except Exception as ex: - logger.error("Account: {} not found. {}".format(receiver_account, ex)) - raise ex - - ret = s.post("Hivepy proposal title", "Hivepy proposal body", creator["name"], permlink = "hivepy-proposal-title", tags = "proposals") - from beembase.operations import Create_proposal - op = Create_proposal( - **{ - "creator" : creator["name"], - "receiver" : receiver["name"], - "start_date" : start_date, - "end_date" : end_date, - "daily_pay" : "16.000 TBD", - "subject" : subject, - "permlink" : "hivepy-proposal-title" - } - ) - ret = None - try: - ret = s.finalizeOp(op, creator["name"], "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - - assert ret["operations"][0][1]["creator"] == creator["name"] - assert ret["operations"][0][1]["receiver"] == receiver["name"] - assert ret["operations"][0][1]["start_date"] == start_date - assert ret["operations"][0][1]["end_date"] == end_date - assert ret["operations"][0][1]["daily_pay"] == "16.000 TBD" - assert ret["operations"][0][1]["subject"] == subject - assert ret["operations"][0][1]["permlink"] == "hivepy-proposal-title" - -def test_list_proposals(node, account, wif, subject): - logger.info("Testing: list_proposals") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - # list inactive proposals, our proposal shoud be here - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "inactive") - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is not None - - # list active proposals, our proposal shouldnt be here - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "active") - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is None - - # list all proposals, our proposal should be here - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "all") - - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is not None - -def test_find_proposals(node, account, wif, subject): - logger.info("Testing: find_proposals") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - # first we will find our special proposal and get its proposal_id - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "inactive") - - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is not None - proposal_id = int(found["proposal_id"]) - - ret = s.rpc.find_proposals([proposal_id]) - assert ret[0]["subject"] == found["subject"] - -def test_vote_proposal(node, account, wif, subject): - logger.info("Testing: vote_proposal") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - # first we will find our special proposal and get its proposal_id - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "inactive") - - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is not None - proposal_id = int(found["proposal_id"]) - - # now lets vote - from beembase.operations import Update_proposal_votes - op = Update_proposal_votes( - **{ - "voter" : account, - "proposal_ids" : [proposal_id], - "approve" : True - } - ) - - ret = None - try: - ret = s.finalizeOp(op, account, "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - - assert ret["operations"][0][1]["voter"] == account - assert ret["operations"][0][1]["proposal_ids"][0] == proposal_id - assert ret["operations"][0][1]["approve"] == True - hive_utils.common.wait_n_blocks(s.rpc.url, 2) - -def test_list_voter_proposals(node, account, wif, subject): - logger.info("Testing: list_voter_proposals") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - voter_proposals = s.rpc.list_proposal_votes([account], 1000, "by_voter_proposal", "ascending", "inactive") - - found = None - for proposals in voter_proposals: - if proposals["proposal"]["subject"] == subject: - found = proposals - - assert found is not None - -def test_remove_proposal(node, account, wif, subject): - logger.info("Testing: remove_proposal") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - # first we will find our special proposal and get its proposal_id - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "inactive") - - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is not None, "Not found" - proposal_id = int(found["proposal_id"]) - - # remove proposal - print(account) - from beembase.operations import Remove_proposal - op = Remove_proposal( - **{ - 'voter' : account, - 'proposal_owner' : account, - 'proposal_ids' : [proposal_id] - } - ) - - try: - s.finalizeOp(op, account, "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - - # try to find our special proposal - proposals = s.rpc.list_proposals([account], 1000, "by_creator", "ascending", "inactive") - - found = None - for proposal in proposals: - if proposal["subject"] == subject: - found = proposal - - assert found is None, "Not found" - -def test_iterate_results_test(node, creator_account, receiver_account, wif, subject, remove): - logger.info("Testing: test_iterate_results_test") - # test for iterate prosals - # 1 we will create n proposals of which k proposal will have the same value in one of the fields - # 2 then we will list proposals starting from kth proposal with limit set to m < k - # 3 we list proposals again with the same conditiona as in 2, we should get the same set of results - # in real life scenatio pagination scheme with limit set to value lower than "k" will be showing - # the same results and will hang - # 4 then we will use newly introduced last_id field, we should see diferent set of proposals - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - - from beem.account import Account - try: - creator = Account(creator_account, hive_instance=s) - except Exception as ex: - logger.error("Account: {} not found. {}".format(creator_account, ex)) - raise ex - - try: - receiver = Account(receiver_account, hive_instance=s) - except Exception as ex: - logger.error("Account: {} not found. {}".format(receiver_account, ex)) - raise ex - - import datetime - now = datetime.datetime.now() - - # 1 we will create n proposals of which k proposal will have the same value in one of the fields - # here we have 5 proposals with the same start date - start_end_pairs = [ - [1,1], - [2,2], - [4,3], - [5,4], - [5,5], - [5,6], - [5,7], - [5,8], - [6,9] - ] - - from beembase.operations import Create_proposal - for start_end_pair in start_end_pairs: - start_date, end_date = test_utils.get_start_and_end_date(now, start_end_pair[0], start_end_pair[1]) - op = Create_proposal( - **{ - 'creator' : creator["name"], - 'receiver' : receiver["name"], - 'start_date' : start_date, - 'end_date' :end_date, - 'daily_pay' : "16.000 TBD", - 'subject' : subject, - 'permlink' : "hivepy-proposal-title" - } - ) - try: - s.finalizeOp(op, creator["name"], "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - hive_utils.common.wait_n_blocks(node, 5) - - start_date = test_utils.date_to_iso(now + datetime.timedelta(days = 5)) - - # 2 then we will list proposals starting from kth proposal with limit set to m < k - proposals = s.rpc.list_proposals([start_date], 3, "by_start_date", "descending", "all") - assert len(proposals) == 3, "Expected {} elements got {}".format(3, len(proposals)) - ids = [] - for proposal in proposals: - assert proposal["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) - ids.append(proposal["proposal_id"]) - assert len(ids) == 3, "Expected {} elements got {}".format(3, len(ids)) - - # 3 we list proposals again with the same conditiona as in 2, we should get the same set of results - proposals = s.rpc.list_proposals([start_date], 3, "by_start_date", "descending", "all") - assert len(proposals) == 3, "Expected {} elements got {}".format(3, len(proposals)) - oids = [] - for proposal in proposals: - assert proposal["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) - oids.append(proposal["proposal_id"]) - assert len(oids) == 3, "Expected {} elements got {}".format(3, len(oids)) - - # the same set of results check - for id in ids: - assert id in oids, "Id not found in expected results array {}".format(id) - - # 4 then we will use newly introduced last_id field, we should see diferent set of proposals - proposals = s.rpc.list_proposals([start_date], 3, "by_start_date", "descending", "all", oids[-1]) - - start_date, end_date = test_utils.get_start_and_end_date(now, 5, 4) - - assert proposals[-1]["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) - assert proposals[-1]["end_date"] == end_date, "Expected end_date do not match {} != {}".format(end_date, proposals[-1]["end_date"]) - - # remove all created proposals - from beembase.operations import Remove_proposal - if not remove: - start_date = test_utils.date_to_iso(now + datetime.timedelta(days = 6)) - for _ in range(0, 2): - proposals = s.list_proposals([start_date], 5, "by_start_date", "descending", "all") - ids = [] - for proposal in proposals: - ids.append(int(proposal['proposal_id'])) - - op = Remove_proposal( - **{ - "voter" : creator["name"], - "proposal_ids" : ids - } - ) - try: - s.finalizeOp(op, creator["name"], "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - hive_utils.common.wait_n_blocks(node, 3) - -def test_update_proposal(node, creator, wif): - logger.info("Testing: update_proposal") - s = Hive(node = [node], no_broadcast = False, keys = [wif]) - proposals = s.rpc.list_proposals([creator], 1000, "by_creator", "ascending", "all") - print(proposals[0]) - from beembase.operations import Update_proposal - subject = "Some new proposal subject" - op = Update_proposal(**{ - 'proposal_id' : proposals[0]["proposal_id"], - 'creator' : proposals[0]["creator"], - 'daily_pay' : "16.000 TBD", - 'subject' : subject, - 'permlink': proposals[0]["permlink"] - }) - try: - s.finalizeOp(op, creator, "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - hive_utils.common.wait_n_blocks(node, 3) - - proposals = s.rpc.list_proposals([creator], 1000, "by_creator", "ascending", "all") - print(proposals[0]) - assert proposals[0]["subject"] == subject, "Subjects dont match" - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create proposals with") - parser.add_argument("receiver", help = "Account to receive funds") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_true', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - subject = str(uuid4()) - logger.info("Subject of testing proposal is set to: {}".format(subject)) - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - test_create_proposal(node_url, args.creator, args.receiver, wif, subject) - hive_utils.common.wait_n_blocks(node_url, 3) - test_list_proposals(node_url, args.creator, wif, subject) - test_find_proposals(node_url, args.creator, wif, subject) - test_vote_proposal(node_url, args.creator, wif, subject) - test_list_voter_proposals(node_url, args.creator, wif, subject) - hive_utils.common.wait_n_blocks(node_url, 3) - if not args.no_erase_proposal: - test_remove_proposal(node_url, args.creator, wif, subject) - test_iterate_results_test(node_url, args.creator, args.receiver, args.wif, str(uuid4()), args.no_erase_proposal) - hive_utils.common.wait_n_blocks(node_url, 3) - test_update_proposal(node_url, args.creator, wif) - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(2) - diff --git a/tests2/functional/python_tests/dhf_tests/id_collision_test.py b/tests2/functional/python_tests/dhf_tests/id_collision_test.py deleted file mode 100644 index 29158d4f3c07571a6db23403e221268c1dd38734..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/id_collision_test.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/python3 -import sys -sys.path.append("../../") - -from uuid import uuid4 -from time import sleep -import logging -import hive_utils -import threading -import os - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "dhf_id_collision_test.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# we would like to test ID conflict problem and I'd like to have python scripts -# which will be producing 2 transactions containing few proposals (having -# specified some uuid as subject) and next submitted in opposite way to 2 nodes -# (we can also specify some 0,5 delay between). Next the script should iterate -# proposals from all nodes and compare uuids against ID assigned by each node. - -class ProposalsCreatorThread(threading.Thread): - def __init__(self, node_url, proposals, private_key, delay): - threading.Thread.__init__(self) - self.node_url = node_url - self.proposals = proposals - self.private_key = private_key - self.delay = delay - self.log = logging.getLogger(MODULE_NAME + ".ProposalsCreatorThread." + self.node_url) - self.node_client = Hive(node = [self.node_url], keys = [self.private_key]) - - - def run(self): - self.log.info("Sending proposals to node at: {} with delay {}".format(self.node_url, self.delay)) - sleep(self.delay) - from beembase.operations import Create_proposal - for proposal in self.proposals: - self.log.info("New proposal ==> ({},{},{},{},{},{},{})".format( - proposal['creator'], - proposal['receiver'], - proposal['start_date'], - proposal['end_date'], - proposal['daily_pay'], - proposal['subject'], - proposal['permlink'] - )) - op = Create_proposal( - **{ - 'creator' : proposal['creator'], - 'receiver' : proposal['receiver'], - 'start_date' : proposal['start_date'], - 'end_date' : proposal['end_date'], - 'daily_pay' : proposal['daily_pay'], - 'subject' : proposal['subject'], - 'permlink' : proposal['permlink'] - } - ) - self.node_client.finalizeOp(op, proposal['creator'], "active") - - -def get_permlink(account): - return "hivepy-proposal-title-{}".format(account) - - -def list_proposals_by_node(creator, private_key, nodes, subjects): - for idx in range(0, len(nodes)): - node = nodes[idx] - logger.info("Listing proposals using node at {}".format(node)) - s = Hive(node = [node], keys = [private_key]) - proposals = s.rpc.list_proposals([creator], 1000, "by_creator", "ascending", "all") - for subject in subjects: - msg = "Looking for id of proposal with subject {}".format(subject) - for proposal in proposals: - if proposal['subject'] == subject: - msg = msg + " - FOUND ID = {}".format(proposal['id']) - #assert proposal['id'] == results[subject], "ID do not match expected {} got {}".format(results[subject], proposal['id']) - break - logger.info(msg) - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("receiver", help = "Account to receive payment for proposal") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("nodes_url", type=str, nargs="+", help="Url of working hive node") - parser.add_argument("--delays", dest="delays", type=float, nargs="+", help="Delays for each worker/node (default 0)") - parser.add_argument("--proposal-count", dest="proposal_count", type=int, default=1, help="Number of proposals each worker will create.") - - args = parser.parse_args() - - logger.info("Performing ID collision test with nodes {}".format(args.nodes_url)) - - node_client = Hive(node = args.nodes_url, keys = [args.wif]) - logger.info("New post ==> ({},{},{},{},{})".format( - "Hivepy proposal title [{}]".format(args.creator), - "Hivepy proposal body [{}]".format(args.creator), - args.creator, - get_permlink(args.creator), - "proposals" - )) - - node_client.post("Hivepy proposal title [{}]".format(args.creator), - "Hivepy proposal body [{}]".format(args.creator), - args.creator, - permlink = get_permlink(args.creator), - tags = "proposals" - ) - - hive_utils.common.wait_n_blocks(args.nodes_url[0], 5) - - workers = [] - - import datetime - import dateutil.parser - now = node_client.get_dynamic_global_properties().get('time', None) - if now is None: - raise ValueError("Head time is None") - now = dateutil.parser.parse(now) - - start_date = now + datetime.timedelta(days = 1) - end_date = start_date + datetime.timedelta(days = 2) - - start_date_str = start_date.replace(microsecond=0).isoformat() - end_date_str = end_date.replace(microsecond=0).isoformat() - - node_subjects = [] - only_subjects = [] - - logger.info("Creating proposals and workers...") - for idx in range(0, len(args.nodes_url)): - proposals = [] - subjects = [] - for i in range(0, args.proposal_count): - subject = str(uuid4()) - proposal = { - 'creator' : args.creator, - 'receiver' : args.receiver, - 'start_date' : start_date_str, - 'end_date' : end_date_str, - 'daily_pay' : "24.000 TBD", - 'subject' : subject, - 'permlink' : get_permlink(args.creator) - } - proposals.append(proposal) - subjects.append(subject) - only_subjects.append(subject) - node_subjects.append(subjects) - delay = 0. - if args.delays: - delay = args.delays[idx] - worker = ProposalsCreatorThread(args.nodes_url[idx], proposals, args.wif, delay) - workers.append(worker) - - logger.info("Starting workers...") - for worker in workers: - worker.start() - - logger.info("Waiting for workers to join...") - for worker in workers: - worker.join() - - - logger.info("===== QUERY PROPOSALS =====") - logger.info("Gathering proposals ID from the nodes where we send the transactions") - results = {} - for idx in range(0, len(node_subjects)): - node = args.nodes_url[idx] - s = Hive(node = [node], keys = [args.wif]) - proposals = s.rpc.list_proposals([args.creator], 1000, "by_creator", "ascending", "all") - for subject in node_subjects[idx]: - for proposal in proposals: - msg = "Looking for id of proposal sent to {} with subject {}".format(node, subject) - if proposal['subject'] == subject: - msg = msg + " - FOUND ID = {}".format(proposal['id']) - results[subject] = proposal['id'] - break - logger.info(msg) - - logger.info("Checking for all transaction IDs by querying all nodes, IDs should match those gathered from nodes where we send the transactions") - list_proposals_by_node(args.creator, args.wif, args.nodes_url, only_subjects) - - hive_utils.common.wait_n_blocks(args.nodes_url[0], 5) - logger.info("Checking for all transaction IDs by querying all nodes (after some blocks produced)") - list_proposals_by_node(args.creator, args.wif, args.nodes_url, only_subjects) - - - - diff --git a/tests2/functional/python_tests/dhf_tests/list_proposals_tests.py b/tests2/functional/python_tests/dhf_tests/list_proposals_tests.py deleted file mode 100644 index 3a46c4f3948912af67a526e44d3d7e26dc7394b5..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/list_proposals_tests.py +++ /dev/null @@ -1,280 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") - -from uuid import uuid4 -from time import sleep -import logging - -import hive_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_list_proposal.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - - -START_END_SUBJECTS = [ - [1,3,"Subject001"], - [2,3,"Subject002"], - [3,3,"Subject003"], - [4,3,"Subject004"], - [5,3,"Subject005"], - [6,3,"Subject006"], - [7,3,"Subject007"], - [8,3,"Subject008"], - [9,3,"Subject009"] -] - - -def create_proposals(node_client, creator_account, receiver_account): - import datetime - now = datetime.datetime.now() - - start_date, end_date = hive_utils.common.get_isostr_start_end_date(now, 10, 2) - - from beem.account import Account - try: - creator = Account(creator_account, hive_instance=node_client) - except Exception as ex: - logger.error("Account: {} not found. {}".format(creator_account, ex)) - raise ex - - try: - receiver = Account(receiver_account, hive_instance=node_client) - except Exception as ex: - logger.error("Account: {} not found. {}".format(receiver_account, ex)) - raise ex - - logger.info("Creating initial post...") - node_client.post("Hivepy proposal title", "Hivepy proposal body", creator["name"], permlink = "hivepy-proposal-title", tags = "proposals") - - logger.info("Creating proposals...") - from beembase.operations import Create_proposal - for start_end_subject in START_END_SUBJECTS: - start_date, end_date = hive_utils.common.get_isostr_start_end_date(now, start_end_subject[0], start_end_subject[1]) - op = Create_proposal( - **{ - 'creator' : creator["name"], - 'receiver' : receiver["name"], - 'start_date' : start_date, - 'end_date' : end_date, - 'daily_pay' : "16.000 TBD", - 'subject' : start_end_subject[2], - 'permlink' : "hivepy-proposal-title" - } - ) - try: - node_client.finalizeOp(op, creator["name"], "active") - except Exception as ex: - logger.exception("Exception: {}".format(ex)) - raise ex - - hive_utils.common.wait_n_blocks(node_client.rpc.url, 1) - hive_utils.common.wait_n_blocks(node_client.rpc.url, 2) - - -def list_proposals_test(node_client, creator): - logger.info("Testing direction ascending with start field given") - proposals = node_client.rpc.list_proposals([creator], 1000, "by_creator", "ascending", "all") - # we should get len(START_END_SUBJECTS) proposals with wirs proposal with subject Subject001 - # and last with subject Subject009 - assert len(proposals) == len(START_END_SUBJECTS), "Proposals count do not match assumed proposal count {}!={}".format(len(proposals), len(START_END_SUBJECTS)) - assert proposals[0]['subject'] == START_END_SUBJECTS[0][2], "Subject of the first proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[0][2]) - assert proposals[-1]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the last proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - logger.info("Testing direction by_creator ascending with no start field given") - proposals = node_client.rpc.list_proposals([], 1000, "by_creator", "ascending", "all") - # we should get len(START_END_SUBJECTS) proposals with wirs proposal with subject Subject001 - # and last with subject Subject009 - assert len(proposals) == len(START_END_SUBJECTS), "Proposals count do not match assumed proposal count {}!={}".format(len(proposals), len(START_END_SUBJECTS)) - assert proposals[0]['subject'] == START_END_SUBJECTS[0][2], "Subject of the first proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[0][2]) - assert proposals[-1]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the last proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - id_first = proposals[0]['id'] - id_last = proposals[-1]['id'] - - logger.info("Testing direction descending with start field given") - proposals = node_client.rpc.list_proposals([creator], 1000, "by_creator", "descending", "all") - # we should get len(START_END_SUBJECTS) proposals with first proposal with subject Subject009 - # and last with subject Subject001 - assert len(proposals) == len(START_END_SUBJECTS), "Proposals count do not match assumed proposal count {}!={}".format(len(proposals), len(START_END_SUBJECTS)) - assert proposals[0]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the first proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[-1][2]) - assert proposals[-1]['subject'] == START_END_SUBJECTS[0][2], "Subject of the last proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[0][2]) - - logger.info("Testing direction descending bu_creator with no start field given") - proposals = node_client.rpc.list_proposals([], 1000, "by_creator", "descending", "all") - assert len(proposals) == len(START_END_SUBJECTS), "Proposals count do not match assumed proposal count {}!={}".format(len(proposals), len(START_END_SUBJECTS)) - assert proposals[0]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the first proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[-1][2]) - assert proposals[-1]['subject'] == START_END_SUBJECTS[0][2], "Subject of the last proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[0][2]) - - # if all pass we can proceed with other tests - # first we will test empty start string in defferent directions - logger.info("Testing empty start string and ascending direction") - proposals = node_client.rpc.list_proposals([""], 1, "by_start_date", "ascending", "all") - # we shoud get proposal with Subject001 - assert proposals[0]['subject'] == START_END_SUBJECTS[0][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[0][2]) - - logger.info("Testing by_start_date no start string and ascending direction") - proposals = node_client.rpc.list_proposals([], 1, "by_start_date", "ascending", "all") - # we shoud get proposal with Subject001 - assert proposals[0]['subject'] == START_END_SUBJECTS[0][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[0]['subject'], START_END_SUBJECTS[0][2]) - - # now we will test empty start string in descending - logger.info("Testing empty start string and descending direction") - proposals = node_client.rpc.list_proposals([""], 1, "by_start_date", "descending", "all") - assert proposals[0]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - # now we will test no start parameter in descending - logger.info("Testing by_start_data with no start and descending direction") - proposals = node_client.rpc.list_proposals([], 1, "by_start_date", "descending", "all") - assert proposals[0]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - # now we will test empty start string with ascending order and last_id set - - logger.info("Testing empty start string and ascending direction and last_id set") - proposals = node_client.rpc.list_proposals([""], 100, "by_start_date", "ascending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - logger.info("Testing no start parameter and ascending direction and last_id set") - proposals = node_client.rpc.list_proposals([], 100, "by_start_date", "ascending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - # now we will test empty start string with descending order and last_id set - logger.info("Testing empty start string and descending direction and last_id set") - proposals = node_client.rpc.list_proposals([""], 100, "by_start_date", "descending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[0][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[0][2]) - - # now we will test empty start string with descending order and last_id set - logger.info("Testing no start string and descending direction and last_id set") - proposals = node_client.rpc.list_proposals([], 100, "by_start_date", "descending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[0][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[0][2]) - - # now we will test empty start string with ascending order and last_id set - logger.info("Testing not empty start string and ascenging direction and last_id set") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "ascending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[-1][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[-1][2]) - - # now we will test empty start string with descending order and last_id set - logger.info("Testing not empty start string and descending direction and last_id set") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "descending", "all", 5) - assert proposals[0]['id'] == 5, "First proposal should have id == 5, has {}".format(proposals[0]['id']) - assert proposals[-1]['subject'] == START_END_SUBJECTS[0][2], "Subject of the proposal does not match with assumed proposal subject {}!={}".format(proposals[-1]['subject'], START_END_SUBJECTS[0][2]) - - logger.info("Testing not empty start string and ascending direction and last_id set to the last element") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "ascending", "all", id_last) - assert len(proposals) == 1 - assert proposals[0]['id'] == id_last - - logger.info("Testing not empty start string and descending direction and last_id set to the first element") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "descending", "all", id_first) - assert len(proposals) == 1 - assert proposals[0]['id'] == id_first - - logger.info("Testing not empty start string and ascending direction and last_id set to the first element") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "ascending", "all", id_first) - assert len(proposals) == len(START_END_SUBJECTS) - - logger.info("Testing not empty start string and descending direction and last_id set to the last element") - proposals = node_client.rpc.list_proposals([creator], 100, "by_creator", "descending", "all", id_last) - assert len(proposals) == len(START_END_SUBJECTS) - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("receiver", help = "Account to receive payment") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - keys = [wif] - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - create_proposals(node_client, args.creator, args.receiver) - list_proposals_test(node_client, args.creator) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(2) - diff --git a/tests2/functional/python_tests/dhf_tests/list_voter_proposal_test.py b/tests2/functional/python_tests/dhf_tests/list_voter_proposal_test.py deleted file mode 100644 index 935c64e25daaba020e6867502ef0c2526eff80ed..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/list_voter_proposal_test.py +++ /dev/null @@ -1,301 +0,0 @@ -# this test checks implementation of last_id field in list_voter_proposal arguments -#!/usr/bin/python3 - -import sys -sys.path.append("../../") - -from uuid import uuid4 -from time import sleep -import logging -import sys - -import hive_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -def create_accounts(node, creator, account): - logger.info("Creating account: {}".format(account['name'])) - node.create_account(account['name'], - owner_key=account['public_key'], - active_key=account['public_key'], - posting_key=account['public_key'], - memo_key=account['public_key'], - store_keys = False, - creator=creator, - asset='TESTS' - ) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - -# transfer_to_vesting initminer pychol "310.000 TESTS" true -def transfer_to_vesting(node, from_account, account, amount, asset): - from beem.account import Account - logger.info("Transfer to vesting from {} to {} amount {} {}".format( - from_account, account['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer_to_vesting(amount, to = account['name'], asset = asset) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -# transfer initminer pychol "399.000 TESTS" "initial transfer" true -# transfer initminer pychol "398.000 TBD" "initial transfer" true -def transfer_assets_to_accounts(node, from_account, account, amount, asset): - from beem.account import Account - logger.info("Transfer from {} to {} amount {} {}".format(from_account, - account['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer(account['name'], amount, asset, memo = "initial transfer") - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def create_posts(node, account): - logger.info("Creating posts...") - from test_utils import get_permlink - logger.info("New post ==> ({},{},{},{},{})".format( - "Hivepy proposal title [{}]".format(account['name']), - "Hivepy proposal body [{}]".format(account['name']), - account['name'], - get_permlink(account['name']), - "proposals" - )) - node.post("Hivepy proposal title [{}]".format(account['name']), - "Hivepy proposal body [{}]".format(account['name']), - account['name'], - permlink = get_permlink(account['name']), - tags = "proposals") - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def create_proposals(node, account, start_date, end_date, proposal_count): - logger.info("Creating proposals...") - from beembase.operations import Create_proposal - from test_utils import get_permlink - for idx in range(0, proposal_count): - logger.info("New proposal ==> ({},{},{},{},{},{},{})".format( - account['name'], - account['name'], - start_date, - end_date, - "24.000 TBD", - "Proposal from account {} {}/{}".format(account['name'], idx, proposal_count), - get_permlink(account['name']) - )) - op = Create_proposal( - **{ - 'creator' : account['name'], - 'receiver' : account['name'], - 'start_date' : start_date, - 'end_date' : end_date, - 'daily_pay' : "24.000 TBD", - 'subject' : "Proposal from account {}".format(account['name']), - 'permlink' : get_permlink(account['name']) - } - ) - try: - node.finalizeOp(op, account['name'], "active") - except Exception as ex: - logger.error("Exception: {}".format(ex)) - raise ex - hive_utils.common.wait_n_blocks(node.rpc.url, 1) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def list_proposals(node, account): - proposals = node.rpc.list_proposals([account['name']], 1000, "by_creator", "ascending", 'all') - ids = [] - for proposal in proposals: - ids.append(int(proposal.get('id', -1))) - logger.info("Listing proposals: {}".format(ids)) - return ids - - -def vote_proposals(node, account, ids): - logger.info("Voting proposals...") - from beembase.operations import Update_proposal_votes - op = Update_proposal_votes( - **{ - 'voter' : account["name"], - 'proposal_ids' : ids, - 'approve' : True - } - ) - try: - node.finalizeOp(op, account["name"], "active") - except Exception as ex: - logger.error("Exception: {}".format(ex)) - raise ex - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def list_voter_proposals(node, account, limit = 1000, last_id = None): - logger.info("List voted proposals...") - # last_id is not supported!!!! - #voter_proposals = node.rpc.list_proposal_votes([account['name']], limit, 'by_voter_proposal', 'ascending', 'all', last_id) - voter_proposals = node.rpc.list_proposal_votes([account['name']], limit, 'by_voter_proposal', 'ascending', 'all') - ids = [] - for proposal in voter_proposals: - if proposal["voter"] == account['name']: - ids.append(int(proposal['proposal']['proposal_id'])) - return ids - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - #account = {"name" : "tester001", "private_key" : "", "public_key" : ""} - account = {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"} - - assert len(account["private_key"]) != 0, "Private key is empty" - - keys = [wif] - keys.append(account["private_key"]) - - logger.info(keys) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - create_accounts(node_client, args.creator, account) - # tranfer to vesting - transfer_to_vesting(node_client, args.creator, account, "300.000", - "TESTS" - ) - # transfer assets to accounts - transfer_assets_to_accounts(node_client, args.creator, account, - "400.000", "TESTS" - ) - - transfer_assets_to_accounts(node_client, args.creator, account, - "400.000", "TBD" - ) - - # create post for valid permlinks - create_posts(node_client, account) - - import datetime - import dateutil.parser - now = node_client.get_dynamic_global_properties().get('time', None) - if now is None: - raise ValueError("Head time is None") - now = dateutil.parser.parse(now) - - start_date = now + datetime.timedelta(days = 1) - end_date = start_date + datetime.timedelta(days = 2) - - end_date_blocks = start_date + datetime.timedelta(days = 2, hours = 1) - - start_date_str = start_date.replace(microsecond=0).isoformat() - end_date_str = end_date.replace(microsecond=0).isoformat() - - end_date_blocks_str = end_date_blocks.replace(microsecond=0).isoformat() - - # create proposals - each account creates one proposal - create_proposals(node_client, account, start_date_str, end_date_str, 5) - - proposals_ids = list_proposals(node_client, account) - assert len(proposals_ids) == 5 - - # each account is voting on proposal - vote_proposals(node_client, account, proposals_ids) - - logger.info("All") - proposals_ids = list_voter_proposals(node_client, account) - logger.info(proposals_ids) - - logger.info("First three") - proposals_ids = list_voter_proposals(node_client, account, 3) - logger.info(proposals_ids) - - # last_id not supported!!! - #logger.info("Rest") - #proposals_ids = list_voter_proposals(node_client, account, 100, proposals_ids[-1]) - #logger.info(proposals_ids) - - assert len(proposals_ids) == 3, "Expecting 3 proposals" - assert proposals_ids[0] == 0, "Expecting id = 0" - assert proposals_ids[-1] == 2, "Expecting id = 2" - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) \ No newline at end of file diff --git a/tests2/functional/python_tests/dhf_tests/proposal_benchmark_test.py b/tests2/functional/python_tests/dhf_tests/proposal_benchmark_test.py deleted file mode 100644 index 920285374e8d3c3430d15fb63ef789360385f1f2..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_benchmark_test.py +++ /dev/null @@ -1,343 +0,0 @@ -#!/usr/bin/python3 - -#example A: -#"/home/a/hived" Path to hived exe -# "/home/a/data" Path to blockchain directory -# "../../hive_utils/resources/config.ini.in" Path to config.ini.in - usually ./hive_utils/resources/config.ini.in -# 1 - number of proposals for every account -# 200 - number of accounts -# 200000.000- number of HIVE's for every account -# 30000.000- number of HBD's for every account -# 100000.000- number of VEST's for every account -# finally is created 200(1*200) proposals and 200 votes for every proposals -> 40200 objects are created -# ./proposal_benchmark_test.py "/home/a/hived" "/home/a/data" "../../hive_utils/resources/config.ini.in" initminer 1 200 200000.000 30000.000 100000.000 - -#example B: -#"/home/a/hived" Path to hived exe -# "/home/a/data" Path to blockchain directory -# "../../hive_utils/resources/config.ini.in" Path to config.ini.in - usually ./hive_utils/resources/config.ini.in -# 2 - number of proposals for every account -# 300 - number of accounts -# 200000.000- number of HIVE's for every account -# 30000.000- number of HBD's for every account -# 100000.000- number of VEST's for every account -# finally is created 600(2*300) proposals and 300 votes for every proposals -> 180600 objects are created -# ./proposal_benchmark_test.py "/home/a/hived" "/home/a/data" "../../hive_utils/resources/config.ini.in" initminer 2 300 200000.000 30000.000 100000.000 - -#Time[ms] is saved in `r_advanced_benchmark.json` ( position{"op_name": "sps_processor"} ) in directory where this script is called - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import dateutil.parser - -data_size = 100 -delayed_blocks = 1 -delayed_blocks_ex = 3 -SPS_API_SINGLE_QUERY_LIMIT = 1000 -HIVE_PROPOSAL_MAX_IDS_NUMBER = 5 - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_benchmark_test.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - - -# 1. create few proposals. -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - - -# create_account "initminer" "pychol" "" true -def create_accounts(node, creator, accounts): - for account in accounts: - logger.info("Creating account: {}".format(account['name'])) - node.commit.create_account(account['name'], - owner_key=account['public_key'], - active_key=account['public_key'], - posting_key=account['public_key'], - memo_key=account['public_key'], - store_keys = False, - creator=creator, - asset='TESTS') - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - - -# transfer_to_vesting initminer pychol "310.000 TESTS" true -def transfer_to_vesting(node, from_account, accounts, vests ): - for acnt in accounts: - logger.info("Transfer to vesting from {} to {} amount {} {}".format(from_account, acnt['name'], vests, "TESTS")) - node.commit.transfer_to_vesting(vests, to = acnt['name'], - account = from_account, asset='TESTS') - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - - -# transfer initminer pychol "399.000 TESTS" "initial transfer" true -# transfer initminer pychol "398.000 TBD" "initial transfer" true -def transfer_assets_to_accounts(node, from_account, accounts, hives, hbds): - for acnt in accounts: - logger.info("Transfer from {} to {} amount {} {}".format(from_account, acnt['name'], hives, "TESTS")) - node.commit.transfer(acnt['name'], hives, "TESTS", memo = "initial transfer", account = from_account) - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - for acnt in accounts: - logger.info("Transfer from {} to {} amount {} {}".format(from_account, acnt['name'], hbds, "TBD")) - node.commit.transfer(acnt['name'], hbds, "TBD", memo = "initial transfer", account = from_account) - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - -def create_permlink( node, account ): - return "hivepy-proposal-title-{}".format( account ) - -def create_posts(node, accounts): - logger.info("Creating posts...") - i = 0 - for acnt in accounts: - node.commit.post("Hivepy proposal title [{}]".format(acnt['name']), - "Hivepy proposal body [{}]".format(acnt['name']), - acnt['name'], - permlink = create_permlink( node, acnt['name'] ), - tags = "proposals") - i += 1 - if ( i % data_size ) == 0: - hive_utils.hive_tools.wait_for_blocks_produced(delayed_blocks_ex, node.url) - print_progress( i, len( accounts ) ) - - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - -def generate_dates( node ): - logger.info("Generating dates...") - import datetime - - block_time = get_block_time( node ) - now = dateutil.parser.parse( block_time ) - - start_date = now + datetime.timedelta(hours = 2) - end_date = start_date + datetime.timedelta(hours = 1) - #because of HIVE_PROPOSAL_MAINTENANCE_CLEANUP - end_date_delay = end_date + datetime.timedelta(days = 1) - - start_date = start_date.replace(microsecond=0).isoformat() - end_date = end_date.replace(microsecond=0).isoformat() - end_date_delay = end_date_delay.replace(microsecond=0).isoformat() - - return start_date, end_date, end_date_delay - -def print_progress( i, count ): - sys.stdout.write('\r') - sys.stdout.write( " === %d from %d === " % ( i, count ) ) - sys.stdout.flush() - print("") - -def create_proposals(node, accounts, start_date, end_date, nr_proposals): - logger.info("Creating proposals...") - - i = 0 - for cnt in range( nr_proposals ): - for acnt in accounts: - ret = node.commit.create_proposal( - acnt["name"], - acnt["name"], - start_date, - end_date, - "16.000 TBD", - "subject: %d" % (cnt), - create_permlink( node, acnt["name"] ) - ) - i += 1 - if ( i % data_size ) == 0: - hive_utils.hive_tools.wait_for_blocks_produced(delayed_blocks_ex, node.url) - print_progress( i, nr_proposals * len( accounts ) ) - - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - -def list_proposals(node, ids, limit ): - logger.info("Listing proposals...") - - cnt = 0 - start = "" - last_id = None - while cnt < limit: - nr_proposals = ( limit - cnt if limit - cnt <= SPS_API_SINGLE_QUERY_LIMIT else SPS_API_SINGLE_QUERY_LIMIT ) - proposals = node.list_proposals( start, "by_creator", "direction_ascending", nr_proposals, "all", last_id ) - for proposal in proposals: - ids.append( proposal["id"] ) - - if len( proposals ) == 0: - break - cnt += len( proposals ) - last_proposal = proposals[ len( proposals ) - 1 ] - start = last_proposal["creator"] - last_id = last_proposal["id"] - -def list_voter_proposals(node, limit ): - logger.info("Listing voter proposals...") - - res = 0 - cnt = 0 - start = "" - while cnt < limit: - nr_proposals = ( limit - cnt if limit - cnt <= SPS_API_SINGLE_QUERY_LIMIT else SPS_API_SINGLE_QUERY_LIMIT ) - voter_proposals = node.list_voter_proposals( start, "by_creator", "direction_ascending", nr_proposals, "all" ) - res += len( voter_proposals ) - - if len( voter_proposals ) == 0: - break - cnt += len( voter_proposals ) - start = voter_proposals[ len( voter_proposals ) - 1 ]["creator"] - return res - -def vote_proposals(node, ids, accounts ): - logger.info("Voting proposals for %i proposals..." % ( len( ids ) ) ) - - proposal_limit = HIVE_PROPOSAL_MAX_IDS_NUMBER - - i = 0 - i_real = 0 - cnt = 0 - array_length = len( ids ) - proposal_set = [] - - for id in ids: - proposal_set.append( id ) - cnt += 1 - if len( proposal_set ) == proposal_limit or cnt == array_length: - for acnt in accounts: - ret = node.commit.update_proposal_votes( acnt["name"], proposal_set, True) - i += 1 - i_real += len( proposal_set ) - if ( i % data_size ) == 0: - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - print_progress( i_real, len( ids ) * len( accounts ) ) - proposal_set = [] - - hive_utils.common.wait_n_blocks(node.url, delayed_blocks) - -def generate_blocks( node, time, wif ): - logger.info("Generating blocks ...") - - ret = node.debug_generate_blocks_until( wif, time, False ) - print( "Moved %s blocks" % ( ret["blocks"] ) ) - node.debug_generate_blocks( wif, delayed_blocks_ex ) - -def get_block_time( node ): - global_properties = hive_utils.hive_tools.get_dynamic_global_properties( node.url ) - - last_block_number = global_properties.get('result', None) - return last_block_number[ "time" ] - -def get_info( node, message, time ): - block_time = get_block_time( node ) - - print( "%s:" % ( message ) ) - print( "block_time: %s" % ( block_time ) ) - print( "end time : %s" % ( time ) ) - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("path", type=str, help = "Path to hived") - parser.add_argument("dir", type=str, help = "Path to blockchain directory") - parser.add_argument("ini", type=str, help = "Path to config.ini.in - usually ./hive_utils/resources/config.ini.in") - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("nr_proposals", type=int, help = "Nr proposals for every account") - parser.add_argument("nr_accounts", type=int, help = "Nr accounts") - parser.add_argument("hives", type=str, default="200000.000", help = "HIVE's") - parser.add_argument("hbds", type=str, default="30000.000", help = "HBD's") - parser.add_argument("vests", type=str, default="100000.000", help = "VEST's") - - args = parser.parse_args() - - node = hive_utils.hive_node.HiveNodeInScreen( args.path, args.dir, args.ini ) - node_url = node.get_node_url() - wif = node.get_from_config('private-key')[0] - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [] - for i in range( args.nr_accounts ): - accounts.append( {"name" : "", "private_key" : "5JBuekd1sVXXK3wBu6nvPB1LWypZ83BYdu7tGcUNYVd42xQGGh1", "public_key" : "TST5kSj1yTzBz3PDoJ5QUyVVagdgYfs8Y4vVsZG3dqKJU8hg7WmQN"} ) - accounts[ len( accounts ) - 1 ]["name"] = "tester" + str( i ) - - keys = [wif] - #for account in accounts: - keys.append(accounts[0]["private_key"]) - - node.run_hive_node(["--enable-stale-production"]) - try: - if node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, keys = keys) - - create_accounts(node_client, args.creator, accounts) - transfer_to_vesting(node_client, args.creator, accounts, args.vests ) - transfer_assets_to_accounts(node_client, args.creator, accounts, args.hives, args.hbds ) - create_posts(node_client, accounts) - - #total proposals: nr_proposals * accounts - start_date, end_date, end_date_delay = generate_dates( node_client ) - create_proposals( node_client, accounts, start_date, end_date, args.nr_proposals ) - - total_proposals = args.nr_proposals * len(accounts) - - ids = [] - list_proposals( node_client, ids, total_proposals ) - total_proposals = len( ids ) - - #total votes: total proposals * accounts - vote_proposals(node_client, ids, accounts ) - - print( "%s items is ready to be removed" % ( total_proposals * len( accounts ) + total_proposals ) ) - - get_info( node_client, "before movement", end_date_delay ) - generate_blocks( node_client, end_date_delay, wif ) - get_info( node_client, "after movement", end_date_delay ) - - ids = [] - total_votes = total_proposals * len( accounts ) - list_proposals( node_client, ids, total_proposals ) - voter_proposals_number = list_voter_proposals( node_client, total_votes ) - - if len( ids ) == 0 and voter_proposals_number == 0: - print( "***All proposals/votes were removed - test passed***" ) - else: - print( "***There are %i proposals/votes. All proposals should be removed - test failed***" % ( len( ids ) + total_votes ) ) - - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_001.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_001.py deleted file mode 100644 index 5fd88dd7251d44c28241defa74087e3f65f1cf71..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_001.py +++ /dev/null @@ -1,264 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_001.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - - -# 1. create few proposals - in this scenatio all proposals have the same start and end date -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -def create_proposals(node, accounts, start_date, end_date, wif=None): - logger.info("Creating proposals...") - from beembase.operations import Create_proposal - for acnt in accounts: - logger.info("New proposal ==> ({},{},{},{},{},{},{})".format( - acnt['name'], - acnt['name'], - start_date, - end_date, - "24.000 TBD", - "Proposal from account {}".format(acnt['name']), - test_utils.get_permlink(acnt['name']) - )) - op = Create_proposal( - **{ - 'creator' : acnt['name'], - 'receiver' : acnt['name'], - 'start_date' : start_date, - 'end_date' : end_date, - 'daily_pay' : "24.000 TBD", - 'subject' : "Proposal from account {}".format(acnt['name']), - 'permlink' : test_utils.get_permlink(acnt['name']) - } - ) - node.finalizeOp(op, acnt['name'], "active") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - {"name" : "tester005", "private_key" : "5Hy4vEeYmBDvmXipe5JAFPhNwCnx7NfsfyiktBTBURn9Qt1ihcA", "public_key" : "TST7CP7FFjvG55AUeH8riYbfD8NxTTtFH32ekQV4YFXmV6gU8uAg3"} - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - logger.info("Chain prefix is: {}".format(node_client.prefix)) - logger.info("Chain ID is: {}".format(node_client.get_config()["HIVE_CHAIN_ID"])) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", - wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", - wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - import datetime - import dateutil.parser - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = dateutil.parser.parse(now) - - start_date = now + datetime.timedelta(days = 1) - end_date = start_date + datetime.timedelta(days = 2) - - end_date_blocks = start_date + datetime.timedelta(days = 2, hours = 1) - - start_date_str = start_date.replace(microsecond=0).isoformat() - end_date_str = end_date.replace(microsecond=0).isoformat() - - end_date_blocks_str = end_date_blocks.replace(microsecond=0).isoformat() - - # create proposals - each account creates one proposal - create_proposals(node_client, accounts, start_date_str, end_date_str, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, start_date_str, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, start_date_str, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == "390000", "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(start_date_str)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, start_date_str, False) - current_date = start_date - while current_date < end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_str = current_date.replace(microsecond=0).isoformat() - logger.info("Moving to date: {}".format(current_date_str)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_str, False) - - logger.info("Balances for accounts at time: {}".format(current_date_str)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - votes = test_utils.list_proposals(node_client, start_date_str, "active") - for vote in votes: - # should be > 0 for all - assert vote > 0, "All votes counts shoud be greater than 0" - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(end_date_blocks_str)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, end_date_blocks_str, False) - logger.info("Balances for accounts at time: {}".format(end_date_blocks_str)) - balances = test_utils.print_balance(node_client, accounts) - #should be 438.000, 437.904 becouse of rounding - for balance in balances: - assert balance == '437904', "All balances should be equal 437904" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - votes = test_utils.list_proposals(node_client, start_date_str, "expired") - for vote in votes: - # should be > 0 for all - assert vote > 0, "All votes counts shoud be greater than 0" - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_002.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_002.py deleted file mode 100644 index bb63f292e3ab3bab72d499092c60111e47fa4e01..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_002.py +++ /dev/null @@ -1,247 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_002.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - - -# 1. create few proposals - in this scenario proposals have different starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - logger.info("Chain prefix is: {}".format(node_client.prefix)) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 5, '24.000 TBD'], # starts one day from now and lasts five days - ['tester002', 1 + 0, 2, '24.000 TBD'], # starts one day from now and lasts two days - ['tester003', 1 + 2, 1, '24.000 TBD'], # starts three days from now and lasts one day - ['tester004', 1 + 4, 1, '24.000 TBD'] # starts four days from now and lasts one day - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_end_date = test_start_date + datetime.timedelta(days = 6, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # should be '510.000 TBD', '438.000 TBD', '414.000 TBD', '414.000 TBD', - # but because of "rounding" implementation it is - # 509.760 TBD, 437.904 TBD, 413.952 TBD, 413.952 TBD - test_balances = [ - '509760', - '437904', - '413952', - '413952', - ] - - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_003.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_003.py deleted file mode 100644 index 03f4f1ed734d69e3314ef287870a924343530443..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_003.py +++ /dev/null @@ -1,245 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_003.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Greedy baby scenario -# 0. In this scenario we have one proposal with huge daily pay and couple with low daily pay -# all proposals have the same number of votes, greedy proposal is first -# 1. create few proposals - in this scenario proposals have the same starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: Only greedy baby got paid - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 3, '240000.000 TBD'], # starts 1 day from now and lasts 3 days - ['tester002', 1 + 0, 3, '24.000 TBD'], # starts 1 day from now and lasts 3 days - ['tester003', 1 + 0, 3, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester004', 1 + 0, 3, '24.000 TBD'] # starts 1 days from now and lasts 3 day - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_end_date = test_start_date + datetime.timedelta(days = 4, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should 29951.682 be but its 29905.081 due to the roundin implementation - test_balances = [ - '29905081', - '390000', - '390000', - '390000', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_004.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_004.py deleted file mode 100644 index ba731dbb7f4b6a36b692bc5bedfa6c97192733f1..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_004.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_004.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Greedy baby scenario -# 0. In this scenario we have one proposal with huge daily pay and couple with low daily pay -# all proposals have the same number of votes, greedy proposal is last -# 1. create few proposals - in this scenario proposals have the same starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: all got paid. - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 3, '24.000 TBD'], # starts 1 day from now and lasts 3 days - ['tester002', 1 + 0, 3, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester003', 1 + 0, 3, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester004', 1 + 0, 3, '240000.000 TBD'], # starts 1 day from now and lasts 3 days - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_end_date = test_start_date + datetime.timedelta(days = 4, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should be '462.000 TBD', '462.000 TBD', '462.000 TBD', '29735.682 TBD', - # but because of rounding implementation is 461.856 TBD,461.856 TBD,461.856 TBD,29689.513 TBD - - test_balances = [ - '461856', - '461856', - '461856', - '29689513', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_005.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_005.py deleted file mode 100644 index 269219a7d27edeee42b78464930089f447cbd831..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_005.py +++ /dev/null @@ -1,247 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_005.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Greedy baby scenario -# 0. In this scenario we have one proposal with huge daily pay and couple with low daily pay -# all proposals have the same number of votes, greedy proposal is first -# 1. create few proposals - in this scenario proposals have different starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: Only greedy baby got paid - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 3, '240000.000 TBD'], # starts 1 day from now and lasts 3 days - ['tester002', 1 + 0, 1, '24.000 TBD'], # starts 1 day from now and lasts 1 days - ['tester003', 1 + 1, 1, '24.000 TBD'], # starts 2 days from now and lasts 1 day - ['tester004', 1 + 2, 1, '24.000 TBD'] # starts 3 days from now and lasts 1 day - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_end_date = test_start_date + datetime.timedelta(days = 4, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should be '29951.682 TBD', '390.000 TBD', '390.000 TBD', '390.000 TBD', - # but but because of rounding implementation it is 29905.081 TBD,390.000 TBD,390.000 TBD,390.000 TBD - - test_balances = [ - '29905081', - '390000', - '390000', - '390000', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_006.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_006.py deleted file mode 100644 index 1e7565eee3bbaa5f679afdd4927e3471538e7e1b..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_006.py +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_006.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Greedy baby scenario -# 0. In this scenario we have one proposal with huge daily pay and couple with low daily pay -# all proposals have the same number of votes, greedy proposal is last -# 1. create few proposals - in this scenario proposals have different starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: all got paid. - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 1, '24.000 TBD'], # starts 1 day from now and lasts 1 day - ['tester002', 1 + 1, 1, '24.000 TBD'], # starts 2 days from now and lasts 1 day - ['tester003', 1 + 2, 1, '24.000 TBD'], # starts 3 days from now and lasts 1 day - ['tester004', 1 + 0, 3, '240000.000 TBD'], # starts one day from now and lasts 3 days - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_end_date = test_start_date + datetime.timedelta(days = 4, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should be '414.000 TBD', '414.000 TBD', '414.000 TBD', '29879.682 TBD', - # but but because of rounding implementationit is 413.952 TBD,413.952 TBD,413.952 TBD,29833.225 TBD - test_balances = [ - '413952', - '413952', - '413952', - '29833225', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_007.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_007.py deleted file mode 100644 index 5a5a8b0ae0890a924cc618a98b29fc393c09fbc3..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_007.py +++ /dev/null @@ -1,283 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_007.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Unvote proposal during payment -# 1. create few proposals - in this scenario proposals have the same starting and ending dates -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. Unvote one of the proposal duting payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: all got paid. - -def unvote_proposals(node, accounts, debug_key): - logger.info("Unvoting proposals...") - from beembase.operations import Update_proposal_votes - for acnt in accounts: - proposal_set = [0] - logger.info("Account {} unvoted proposals: {}".format(acnt["name"], ",".join(str(x) for x in proposal_set))) - op = Update_proposal_votes( - **{ - 'voter' : acnt["name"], - 'proposal_ids' : proposal_set, - 'approve' : False - } - ) - node.finalizeOp(op, acnt["name"], "active") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "1000000.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 day - ['tester002', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester003', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester004', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 days - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_mid_date = test_start_date + datetime.timedelta(days = 3, hours = 1) - - test_end_date = test_start_date + datetime.timedelta(days = 5, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - test_utils.vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - balances = test_utils.print_balance(node_client, accounts) - for balance in balances: - #should be 390.000 TBD for all - assert balance == '390000', "All balances should be equal to 390.000 TBD" - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_mid_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - unvote_proposals(node_client, accounts, wif) - - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # is should be '463.000 TBD', '486.000 TBD', '486.000 TBD', '486.000 TBD', - # but because of "rounding" implementation it is 462.854 TBD,485.808 TBD,485.808 TBD,485.808 TBD - test_balances = [ - '462854', - '485808', - '485808', - '485808', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_008.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_008.py deleted file mode 100644 index 652bc50cf7202c0c194b17b0bca4133c52d8314a..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_008.py +++ /dev/null @@ -1,273 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_008.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Circular payment -# 1. create few proposals - in this scenario proposals have the same starting and ending dates -# one of the proposals will by paying to the treasury -# 2. vote on them to show differences in asset distribution (depending on collected votes) -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - -# Expected result: all got paid. - -def vote_proposals(node, accounts, wif): - logger.info("Voting proposals...") - from beembase.operations import Update_proposal_votes - for acnt in accounts: - proposal_set = [0,1,2,3,4] - logger.info("Account {} voted for proposals: {}".format(acnt["name"], ",".join(str(x) for x in proposal_set))) - op = Update_proposal_votes( - **{ - 'voter' : acnt["name"], - 'proposal_ids' : proposal_set, - 'approve' : True - } - ) - node.finalizeOp(op, acnt["name"], "active") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "999950.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 day - ['tester002', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester003', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester004', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 days - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - start_date, end_date = test_utils.get_start_and_end_date(now, 1, 4) - proposals.append({'creator' : 'tester001', 'receiver' : 'hive.fund', 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : '96.000 TBD'}) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_mid_date = test_start_date + datetime.timedelta(days = 3, hours = 1) - - test_end_date = test_start_date + datetime.timedelta(days = 5, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # each account is voting on proposal - vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - test_balances = [ - '380000', - '390000', - '390000', - '390000', - ] - balances = test_utils.print_balance(node_client, accounts) - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should be '476.000 TBD', '486.000 TBD', '486.000 TBD', '486.000 TBD', - # but because of rounding implementation it is 475.808 TBD,485.808 TBD,485.808 TBD,485.808 TBD - test_balances = [ - '475808', - '485808', - '485808', - '485808', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_009.py b/tests2/functional/python_tests/dhf_tests/proposal_payment_test_009.py deleted file mode 100644 index eccaa1bdbd5ab549c2b485f56a0f18b5cba8dd1f..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/proposal_payment_test_009.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/python3 - -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging -import test_utils -import os - - -LOG_LEVEL = logging.INFO -LOG_FORMAT = "%(asctime)-15s - %(name)s - %(levelname)s - %(message)s" -MAIN_LOG_PATH = "hdf_proposal_payment_008.log" -log_dir = os.environ.get("TEST_LOG_DIR", None) -if log_dir is not None: - MAIN_LOG_PATH = log_dir + "/" + MAIN_LOG_PATH -else: - MAIN_LOG_PATH = "./" + MAIN_LOG_PATH - - -MODULE_NAME = "DHF-Tests" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -ch = logging.StreamHandler(sys.stdout) -ch.setLevel(LOG_LEVEL) -ch.setFormatter(logging.Formatter(LOG_FORMAT)) - -fh = logging.FileHandler(MAIN_LOG_PATH) -fh.setLevel(LOG_LEVEL) -fh.setFormatter(logging.Formatter(LOG_FORMAT)) - -if not logger.hasHandlers(): - logger.addHandler(ch) - logger.addHandler(fh) - -try: - from beem import Hive -except Exception as ex: - logger.error("beem library is not installed.") - sys.exit(1) - -# Voter proxy test -# 1. create few proposals - in this scenario proposals have the same starting and ending dates -# 2. vote on them to show differences in asset distribution, one voter sets the other as the proxy -# 3. wait for proposal payment phase -# 4. verify (using account history and by checking regular account balance) that given accounts have been correctly paid. - - -def vote_proposals(node, accounts, wif): - logger.info("Voting proposals...") - from beembase.operations import Update_proposal_votes - idx = 0 - for acnt in accounts: - proposal_set = [idx] - logger.info("Account {} voted for proposals: {}".format(acnt["name"], ",".join(str(x) for x in proposal_set))) - op = Update_proposal_votes( - **{ - 'voter' : acnt["name"], - 'proposal_ids' : proposal_set, - 'approve' : True - } - ) - node.finalizeOp(op, acnt["name"], "active") - idx += 1 - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - -if __name__ == '__main__': - logger.info("Performing SPS tests") - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("creator", help = "Account to create test accounts with") - parser.add_argument("treasury", help = "Treasury account") - parser.add_argument("wif", help="Private key for creator account") - parser.add_argument("--node-url", dest="node_url", default="http://127.0.0.1:8090", help="Url of working hive node") - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - parser.add_argument("--working-dir", dest="hived_working_dir", default="/tmp/hived-data/", help = "Path to hived working directory") - parser.add_argument("--config-path", dest="hived_config_path", default="../../hive_utils/resources/config.ini.in",help = "Path to source config.ini file") - parser.add_argument("--no-erase-proposal", action='store_false', dest = "no_erase_proposal", help = "Do not erase proposal created with this test") - - - args = parser.parse_args() - - node = None - - if args.hived_path: - logger.info("Running hived via {} in {} with config {}".format(args.hived_path, - args.hived_working_dir, - args.hived_config_path) - ) - - node = hive_utils.hive_node.HiveNodeInScreen( - args.hived_path, - args.hived_working_dir, - args.hived_config_path - ) - - node_url = args.node_url - wif = args.wif - - if len(wif) == 0: - logger.error("Private-key is not set in config.ini") - sys.exit(1) - - logger.info("Using node at: {}".format(node_url)) - logger.info("Using private-key: {}".format(wif)) - - accounts = [ - # place accounts here in the format: {'name' : name, 'private_key' : private-key, 'public_key' : public-key} - {"name" : "tester001", "private_key" : "5KQeu7SdzxT1DiUzv7jaqwkwv1V8Fi7N8NBZtHugWYXqVFH1AFa", "public_key" : "TST8VfiahQsfS1TLcnBfp4NNfdw67uWweYbbUXymbNiDXVDrzUs7J"}, - {"name" : "tester002", "private_key" : "5KgfcV9bgEen3v9mxkoGw6Rhuf2giDRZTHZjzwisjkrpF4FUh3N", "public_key" : "TST5gQPYm5bs9dRPHpqBy6dU32M8FcoKYFdF4YWEChUarc9FdYHzn"}, - {"name" : "tester003", "private_key" : "5Jz3fcrrgKMbL8ncpzTdQmdRVHdxMhi8qScoxSR3TnAFUcdyD5N", "public_key" : "TST57wy5bXyJ4Z337Bo6RbinR6NyTRJxzond5dmGsP4gZ51yN6Zom"}, - {"name" : "tester004", "private_key" : "5KcmobLVMSAVzETrZxfEGG73Zvi5SKTgJuZXtNgU3az2VK3Krye", "public_key" : "TST8dPte853xAuLMDV7PTVmiNMRwP6itMyvSmaht7J5tVczkDLa5K"}, - ] - - if not accounts: - logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") - sys.exit(1) - - keys = [wif] - for account in accounts: - keys.append(account["private_key"]) - - if node is not None: - node.run_hive_node(["--enable-stale-production"]) - try: - if node is None or node.is_running(): - node_client = Hive(node = [node_url], no_broadcast = False, - keys = keys - ) - - # create accounts - test_utils.create_accounts(node_client, args.creator, accounts) - # tranfer to vesting - test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", - "TESTS" - ) - logger.info("Wait 30 days for full voting power") - hive_utils.debug_generate_blocks(node_client.rpc.url, wif, 30 * 24 * 3600 / 3 + 10) - # transfer assets to accounts - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TESTS", wif - ) - - test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, - "400.000", "TBD", wif - ) - - logger.info("Balances for accounts after initial transfer") - test_utils.print_balance(node_client, accounts) - # transfer assets to treasury - test_utils.transfer_assets_to_treasury(node_client, args.creator, args.treasury, - "999950.000", "TBD", wif - ) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # create post for valid permlinks - test_utils.create_posts(node_client, accounts, wif) - - now = node_client.get_dynamic_global_properties(False).get('time', None) - if now is None: - raise ValueError("Head time is None") - now = test_utils.date_from_iso(now) - - proposal_data = [ - ['tester001', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 day - ['tester002', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester003', 1 + 0, 4, '24.000 TBD'], # starts 1 days from now and lasts 3 day - ['tester004', 1 + 0, 4, '24.000 TBD'], # starts 1 day from now and lasts 3 days - ] - - proposals = [ - # pace proposals here in the format: {'creator' : creator, 'receiver' : receiver, 'start_date' : start-date, 'end_date' : end_date} - - ] - - for pd in proposal_data: - start_date, end_date = test_utils.get_start_and_end_date(now, pd[1], pd[2]) - proposal = {'creator' : pd[0], 'receiver' : pd[0], 'start_date' : start_date, 'end_date' : end_date, 'daily_pay' : pd[3]} - proposals.append(proposal) - - import datetime - test_start_date = now + datetime.timedelta(days = 1) - test_start_date_iso = test_utils.date_to_iso(test_start_date) - - test_mid_date = test_start_date + datetime.timedelta(days = 3, hours = 1) - - test_end_date = test_start_date + datetime.timedelta(days = 5, hours = 1) - test_end_date_iso = test_utils.date_to_iso(test_end_date) - - test_utils.create_proposals(node_client, proposals, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - - # tester01 sets tester02 as its proxy - logger.info("Setting tester002 as a proxy of tester001...") - from beembase.operations import Account_witness_proxy - op = Account_witness_proxy( - **{ - "account" : 'tester001', - "proxy" : 'tester002' - } - ) - node_client.finalizeOp(op, "tester001", "active") - - # each account is voting on proposal - vote_proposals(node_client, accounts, wif) - - # list proposals with inactive status, it shoud be list of pairs id:total_votes - votes = test_utils.list_proposals(node_client, test_start_date_iso, "inactive") - for vote in votes: - #should be 0 for all - assert vote == 0, "All votes should be equal to 0" - - logger.info("Balances for accounts after creating proposals") - test_balances = [ - '390000', - '390000', - '390000', - '390000', - ] - balances = test_utils.print_balance(node_client, accounts) - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - # move forward in time to see if proposals are paid - # moving is made in 1h increments at a time, after each - # increment balance is printed - logger.info("Moving to date: {}".format(test_start_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_start_date_iso, False) - current_date = test_start_date - while current_date < test_end_date: - current_date = current_date + datetime.timedelta(hours = 1) - current_date_iso = test_utils.date_to_iso(current_date) - - logger.info("Moving to date: {}".format(current_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, current_date_iso, False) - - logger.info("Balances for accounts at time: {}".format(current_date_iso)) - test_utils.print_balance(node_client, accounts) - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - votes = test_utils.list_proposals(node_client, test_start_date_iso, "active") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "expired") - votes = test_utils.list_proposals(node_client, test_start_date_iso, "all") - - # move additional hour to ensure that all proposals ended - logger.info("Moving to date: {}".format(test_end_date_iso)) - hive_utils.common.debug_generate_blocks_until(node_client.rpc.url, wif, test_end_date_iso, False) - logger.info("Balances for accounts at time: {}".format(test_end_date_iso)) - balances = test_utils.print_balance(node_client, accounts) - # it should be '390.000 TBD', '486.000 TBD', '486.000 TBD', '486.000 TBD', - # but because of rounding implementation it is 390.000 TBD,485.808 TBD,485.808 TBD,485.808 TBD - test_balances = [ - '390000', - '485808', - '485808', - '485808', - ] - for idx in range(0, len(test_balances)): - assert balances[idx] == test_balances[idx], "Balances dont match {} != {}".format(balances[idx], test_balances[idx]) - - test_utils.print_balance(node_client, [{'name' : args.treasury}]) - - if node is not None: - node.stop_hive_node() - sys.exit(0) - sys.exit(1) - except Exception as ex: - logger.error("Exception: {}".format(ex)) - if node is not None: - node.stop_hive_node() - sys.exit(1) diff --git a/tests2/functional/python_tests/dhf_tests/test_utils.py b/tests2/functional/python_tests/dhf_tests/test_utils.py deleted file mode 100644 index eff1deb677281d28f1de849c9071cc6b1c2322e9..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/dhf_tests/test_utils.py +++ /dev/null @@ -1,192 +0,0 @@ -import sys -sys.path.append("../../") -import hive_utils - -from uuid import uuid4 -from time import sleep -import logging - -LOG_LEVEL = logging.INFO - -MODULE_NAME = "DHF-Tests.DHF-Utils" -logger = logging.getLogger(MODULE_NAME) -logger.setLevel(LOG_LEVEL) - -# create_account "initminer" "pychol" "" true -def create_accounts(node, creator, accounts): - for account in accounts: - logger.info("Creating account: {}".format(account['name'])) - node.create_account(account['name'], - owner_key=account['public_key'], - active_key=account['public_key'], - posting_key=account['public_key'], - memo_key=account['public_key'], - store_keys = False, - creator=creator, - asset='TESTS' - ) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -# transfer_to_vesting initminer pychol "310.000 TESTS" true -def transfer_to_vesting(node, from_account, accounts, amount, asset): - from beem.account import Account - for acnt in accounts: - logger.info("Transfer to vesting from {} to {} amount {} {}".format( - from_account, acnt['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer_to_vesting(amount, to = acnt['name'], asset = asset) - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -# transfer initminer pychol "399.000 TESTS" "initial transfer" true -# transfer initminer pychol "398.000 TBD" "initial transfer" true -def transfer_assets_to_accounts(node, from_account, accounts, amount, asset, wif=None): - from beem.account import Account - for acnt in accounts: - logger.info("Transfer from {} to {} amount {} {}".format(from_account, - acnt['name'], amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer(acnt['name'], amount, asset, memo = "initial transfer") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def transfer_assets_to_treasury(node, from_account, treasury_account, amount, asset, wif=None): - from beem.account import Account - logger.info("Transfer from {} to {} amount {} {}".format(from_account, - treasury_account, amount, asset) - ) - acc = Account(from_account, hive_instance=node) - acc.transfer(treasury_account, amount, asset, memo = "initial transfer") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def get_permlink(account): - return "hivepy-proposal-title-{}".format(account) - - -def create_posts(node, accounts, wif=None): - logger.info("Creating posts...") - for acnt in accounts: - logger.info("New post ==> ({},{},{},{},{})".format( - "Hivepy proposal title [{}]".format(acnt['name']), - "Hivepy proposal body [{}]".format(acnt['name']), - acnt['name'], - get_permlink(acnt['name']), - "proposals" - )) - node.post("Hivepy proposal title [{}]".format(acnt['name']), - "Hivepy proposal body [{}]".format(acnt['name']), - acnt['name'], - permlink = get_permlink(acnt['name']), - tags = "proposals") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def create_proposals(node, proposals, wif=None): - logger.info("Creating proposals...") - from beembase.operations import Create_proposal - for proposal in proposals: - logger.info("New proposal ==> ({},{},{},{},{},{},{})".format( - proposal['creator'], - proposal['receiver'], - proposal['start_date'], - proposal['end_date'], - proposal['daily_pay'], - "Proposal from account {}".format(proposal['creator']), - get_permlink(proposal['creator']) - )) - - op = Create_proposal( - **{ - 'creator' : proposal['creator'], - 'receiver' : proposal['receiver'], - 'start_date' : proposal['start_date'], - 'end_date' : proposal['end_date'], - 'daily_pay' : proposal['daily_pay'], - 'subject' : "Proposal from account {}".format(proposal['creator']), - 'permlink' : get_permlink(proposal['creator']) - } - ) - node.finalizeOp(op, proposal['creator'], "active") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def vote_proposals(node, accounts, wif=None): - logger.info("Voting proposals...") - from beembase.operations import Update_proposal_votes - for acnt in accounts: - proposal_set = [x for x in range(0, len(accounts))] - logger.info("Account {} voted for proposals: {}".format(acnt["name"], ",".join(str(x) for x in proposal_set))) - op = Update_proposal_votes( - **{ - 'voter' : acnt["name"], - 'proposal_ids' : proposal_set, - 'approve' : True - } - ) - node.finalizeOp(op, acnt["name"], "active") - if wif is not None: - hive_utils.debug_generate_blocks(node.rpc.url, wif, 5) - else: - hive_utils.common.wait_n_blocks(node.rpc.url, 5) - - -def list_proposals(node, start_date, status): - proposals = node.rpc.list_proposals([start_date], 1000, "by_start_date", "ascending", status) - ret = [] - votes = [] - for proposal in proposals: - ret.append("{}:{}".format(proposal.get('id', 'Error'), proposal.get('total_votes', 'Error'))) - votes.append(int(proposal.get('total_votes', -1))) - logger.info("Listing proposals with status {} (id:total_votes): {}".format(status, ",".join(ret))) - return votes - - -def print_balance(node, accounts): - from beem.account import Account - balances = [] - balances_str = [] - for acnt in accounts: - ret = Account(acnt['name'], hive_instance=node).json() - hbd = ret.get('hbd_balance', None) - if hbd is not None: - hbd = hbd.get('amount') - balances_str.append("{}:{}".format(acnt['name'], hbd)) - balances.append(hbd) - logger.info("Balances ==> {}".format(",".join(balances_str))) - return balances - - -def date_to_iso(date): - return date.replace(microsecond=0).isoformat() - - -def date_from_iso(date_iso_str): - import dateutil.parser - return dateutil.parser.parse(date_iso_str) - - -def get_start_and_end_date(now, start_days_from_now, end_days_from_start): - from datetime import timedelta - start_date = now + timedelta(days = start_days_from_now) - end_date = start_date + timedelta(days = end_days_from_start) - - assert start_date > now, "Start date must be greater than now" - assert end_date > start_date, "End date must be greater than start date" - - return date_to_iso(start_date), date_to_iso(end_date) \ No newline at end of file diff --git a/tests2/functional/python_tests/hived/CMakeLists.txt b/tests2/functional/python_tests/hived/CMakeLists.txt deleted file mode 100644 index 3322ff15bda50ffe1eb4f12e3aa3798c0d4f6334..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/hived/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -SET ( hived_tests_args --run-hived ${hived_path}) - -IF ( BUILD_HIVE_TESTNET ) - ADD_PYTHON_FUNCTIONAL_TEST( hived_options_tests ${hived_tests_args} ) -ELSE ( BUILD_HIVE_TESTNET ) - MESSAGE ( STATUS "hived functional tests skipped: BUILD_HIVE_TESTNET is required" ) -ENDIF ( BUILD_HIVE_TESTNET ) diff --git a/tests2/functional/python_tests/hived/hived_options_tests.py b/tests2/functional/python_tests/hived/hived_options_tests.py deleted file mode 100755 index 168497275920054e3ef1c9b25443911c978e33d6..0000000000000000000000000000000000000000 --- a/tests2/functional/python_tests/hived/hived_options_tests.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/python3 - -import sys -import tempfile -import json -from pathlib import Path -sys.path.append("../../") -import hive_utils - -def assert_eq(x, y): - assert x == y, "{} != {}".format(x, y) - -if __name__ == '__main__': - import argparse - parser = argparse.ArgumentParser() - parser.add_argument("--run-hived", dest="hived_path", help = "Path to hived executable. Warning: using this option will erase contents of selected hived working directory.") - - args = parser.parse_args() - - node = None - - if args.hived_path: - work_dir = tempfile.gettempdir() - config_file_name = 'config_test.ini' - - node = hive_utils.hive_node.HiveNode( - args.hived_path, - work_dir, - ['--config=' + config_file_name, '--dump-config'] - ) - - with node: - out = node.get_output() - js = json.loads(out) - config_path = Path(work_dir) / config_file_name - assert_eq(Path(js['data-dir']), Path(work_dir)) - assert_eq(Path(js['config']), config_path) diff --git a/tests2/hived/smoketest/Dockerfile b/tests2/hived/smoketest/Dockerfile deleted file mode 100644 index beb3713a01ba74ecdb6753f51476f0a738bbd214..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/Dockerfile +++ /dev/null @@ -1,37 +0,0 @@ -FROM phusion/baseimage:0.9.19 - -ENV LANG=en_US.UTF-8 -ENV WDIR=/usr/local/hive -ENV SMOKETEST=$WDIR/smoketest - -RUN apt-get update -RUN apt-get install -y apt-utils -RUN apt-get install -y libreadline-dev -RUN apt-get install -y python3 -RUN apt-get install -y python3-pip -RUN apt-get install -y net-tools -RUN apt-get install -y cpio -RUN pip3 install --upgrade pip -RUN pip3 install pyresttest - -COPY . $WDIR/ - -RUN apt-get clean -RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* - -#reference: volume points to reference hived -#tested: volume points to tested hived -#ref_blockchain: volume points to reference folder, where blockchain folder exists -#tested_blockchain: volume points to tested folder, where blockchain folder exists -#logs_dir: location where non-empty logs will be copied -VOLUME ["reference", "tested", "ref_blockchain", "tested_blockchain", "logs_dir", "run"] - -EXPOSE 8090 -EXPOSE 8091 - -#CMD pyresttest -CMD cd $SMOKETEST && \ - ./smoketest.sh /reference/hived /tested/hived /ref_blockchain /tested_blockchain $STOP_REPLAY_AT_BLOCK $JOBS $COPY_CONFIG 2>&1 | tee log.txt || \ - find ./ -type f -path */logs/* -not -name logs | cpio -pd /logs_dir && \ - cp log.txt /logs_dir && \ - chmod -R a+rw /logs_dir diff --git a/tests2/hived/smoketest/README.md b/tests2/hived/smoketest/README.md deleted file mode 100644 index c99ceee6baa699a886fd2714227d6feb59fa3fb8..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Quick Basic Test Suit (AKA smoketest) Documentation - -## To Run Smoketest - -From directory of smoketest.sh (example of cmd line, for more see smoketest.sh): - -./smoketest.sh ~/working/hived ~/reference/hived ~/working_blockchain_dir ~/reference_blockchain_dir 3000000 12 - -py scripts generate json response files only if request failed or response is different - look for them in `log` -folder created inside test group. - -## To Add a Test Group - -In directory of smoketest.sh: -1. Create subdirectory with group name. -1. In that subdirectory create test_group.sh which - - Accepts following arguments: JOBS TEST_ADDRESS TEST_PORT REF_ADDRESS REF_PORT BLOCK_LIMIT where: - JOBS is suggested number of parallel jobs to run, - TEST_ADDRESS:TEST_PORT indicate where the tested hived instance listens to API requests, - REF_ADDRESS:REF_PORT ditto for reference instance and - BLOCK_LIMIT is the top number of block to be processed. - - Returns 0 on success, non-zero on failure. - - Create config.ini in test directory or config_ref.ini and config_test.ini for dedicated hived instances. - If no config*.ini files you need manually create them in working directories of hived instances. diff --git a/tests2/hived/smoketest/account_history/config.ini b/tests2/hived/smoketest/account_history/config.ini deleted file mode 100644 index bc7ff432a7a9cf89892b60063b72c94390988350..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/account_history/config.ini +++ /dev/null @@ -1,60 +0,0 @@ -# Plugin(s) to enable, may be specified multiple times -plugin = account_history account_history_api database_api - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. -# account-history-track-account-range = - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. Deprecated in favor of account-history-track-account-range. -# track-account-range = - -# Defines a list of operations which will be explicitly logged. -# account-history-whitelist-ops = - -# Defines a list of operations which will be explicitly logged. Deprecated in favor of history-whitelist-ops. -# whitelist-ops = - -# Defines a list of operations which will be explicitly ignored. -# account-history-blacklist-ops = - -# Defines a list of operations which will be explicitly ignored. Deprecated in favor of history-blacklist-ops. -# blacklist-ops = - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G -shared-file-size = 8G - -# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints. -# checkpoint = - -# flush shared memory changes to disk every N blocks -# flush-state-interval = - -# Database edits to apply on startup (may specify multiple times) -# debug-node-edit-script = - -# The local IP address and port to listen for incoming connections. -# p2p-endpoint = - -# Maxmimum number of incoming connections on P2P endpoint. -# p2p-max-connections = - -# The IP address and port of a remote peer to sync with. Deprecated in favor of p2p-seed-node. -# seed-node = - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Enable block production, even if the chain is stale. -enable-stale-production = false - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -# witness = - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -# private-key = - diff --git a/tests2/hived/smoketest/account_history/test_group.sh b/tests2/hived/smoketest/account_history/test_group.sh deleted file mode 100644 index 1a93188888ad744d058a285cd6a0f9fb1ba9f749..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/account_history/test_group.sh +++ /dev/null @@ -1,118 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo Usage: jobs test_hived_path ref_hived_path test_work_path ref_work_path block_limit [--dont-copy-config] - echo Example: 16 ~/steemit/1/hived ~/steemit/2/hived ~/steemit/1/wdir ~/steemit/2/wdir 5000000 - exit -1 -} - -if [ $# -lt 6 -o $# -gt 7 ] -then - print_help_and_quit -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -SCRIPT_DIR=../scripts -PY_SCRIPT_DIR=../../api_tests -REPLAY_SCRIPT=run_replay.sh -NODE_SCRIPT=open_node.sh -NODE_ADDRESS=0.0.0.0 -TEST_PORT=8090 -REF_PORT=8091 -TEST_NODE=$NODE_ADDRESS:$TEST_PORT -REF_NODE=$NODE_ADDRESS:$REF_PORT -TEST_NODE_OPT=--webserver-http-endpoint=$TEST_NODE -REF_NODE_OPT=--webserver-http-endpoint=$REF_NODE -EXIT_CODE=0 -JOBS=$1 -TEST_HIVED_PATH=$2 -REF_HIVED_PATH=$3 -TEST_WORK_PATH=$4 -REF_WORK_PATH=$5 -BLOCK_LIMIT=$6 -WDIR=$PWD/logs -TEST_HIVED_PID=-1 -REF_HIVED_PID=-1 -export HIVED_NODE_PID=-1 - -function run_replay { - echo Running $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - [ $? -ne 0 ] && echo test group FAILED && exit -1 -} - -function open_node { - echo Running $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 - . $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 -} - -function run_test { - echo Running test $1 - WDIR=$PWD/$1/logs - rm -rf $WDIR - mkdir -p $1 - pushd $PY_SCRIPT_DIR - - echo Running python3 $2 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR $3 - python3 $2 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR $3 - [ $? -ne 0 ] && echo test $1 FAILED && EXIT_CODE=-1 - - popd -} - -run_replay - -open_node "tested" $TEST_HIVED_PATH $TEST_NODE_OPT $TEST_WORK_PATH $TEST_PORT -TEST_HIVED_PID=$HIVED_NODE_PID - -open_node "reference" $REF_HIVED_PATH $REF_NODE_OPT $REF_WORK_PATH $REF_PORT -REF_HIVED_PID=$HIVED_NODE_PID - -function cleanup { - ARG=$1 - if [ $TEST_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $TEST_HIVED_PID & - wait -n $TEST_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $TEST_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - if [ $REF_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $REF_HIVED_PID & - wait -n $REF_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $REF_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - wait - - if [ $ARG -eq 0 ] - then - exit $EXIT_CODE - else - exit $ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -echo TEST_HIVED_PID: $TEST_HIVED_PID REF_HIVED_PID: $REF_HIVED_PID -if [ $TEST_HIVED_PID -ne -1 ] && [ $REF_HIVED_PID -ne -1 ]; then - run_test "account_history" "test_ah_get_account_history.py" - run_test "get_ops_in_block" "test_ah_get_ops_in_block.py" $BLOCK_LIMIT -else - EXIT_CODE=-1 -fi - -cleanup $EXIT_CODE diff --git a/tests2/hived/smoketest/ah_limit_account/config.ini b/tests2/hived/smoketest/ah_limit_account/config.ini deleted file mode 100644 index 86c5791ac513446681f3d83862b1299fb66a3001..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_account/config.ini +++ /dev/null @@ -1,60 +0,0 @@ -# Plugin(s) to enable, may be specified multiple times -plugin = account_history account_history_api database_api - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. -account-history-track-account-range = ["blocktrades", "blocktrades"] - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. Deprecated in favor of account-history-track-account-range. -# track-account-range = - -# Defines a list of operations which will be explicitly logged. -# account-history-whitelist-ops = - - -# Defines a list of operations which will be explicitly logged. Deprecated in favor of history-whitelist-ops. -# whitelist-ops = - -# Defines a list of operations which will be explicitly ignored. -# account-history-blacklist-ops = - -# Defines a list of operations which will be explicitly ignored. Deprecated in favor of history-blacklist-ops. -# blacklist-ops = - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G -shared-file-size = 8G - -# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints. -# checkpoint = - -# flush shared memory changes to disk every N blocks -# flush-state-interval = - -# Database edits to apply on startup (may specify multiple times) -# debug-node-edit-script = - -# The local IP address and port to listen for incoming connections. -# p2p-endpoint = - -# Maxmimum number of incoming connections on P2P endpoint. -# p2p-max-connections = - -# The IP address and port of a remote peer to sync with. Deprecated in favor of p2p-seed-node. -# seed-node = - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Enable block production, even if the chain is stale. -enable-stale-production = false - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -# witness = - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -# private-key = diff --git a/tests2/hived/smoketest/ah_limit_account/test_group.sh b/tests2/hived/smoketest/ah_limit_account/test_group.sh deleted file mode 100644 index fd43463434831763dfc49fdee26da2e37420a167..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_account/test_group.sh +++ /dev/null @@ -1,117 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo Usage: jobs test_hived_path ref_hived_path test_work_path ref_work_path block_limit [--dont-copy-config] - echo Example: 16 ~/steemit/1/hived ~/steemit/2/hived ~/steemit/1/wdir ~/steemit/2/wdir 5000000 - exit -1 -} - -if [ $# -lt 6 -o $# -gt 7 ] -then - print_help_and_quit -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -SCRIPT_DIR=../scripts -PY_SCRIPT_DIR=../../api_tests -REPLAY_SCRIPT=run_replay.sh -NODE_SCRIPT=open_node.sh -NODE_ADDRESS=0.0.0.0 -TEST_PORT=8090 -REF_PORT=8091 -TEST_NODE=$NODE_ADDRESS:$TEST_PORT -REF_NODE=$NODE_ADDRESS:$REF_PORT -TEST_NODE_OPT=--webserver-http-endpoint=$TEST_NODE -REF_NODE_OPT=--webserver-http-endpoint=$REF_NODE -EXIT_CODE=0 -JOBS=$1 -TEST_HIVED_PATH=$2 -REF_HIVED_PATH=$3 -TEST_WORK_PATH=$4 -REF_WORK_PATH=$5 -BLOCK_LIMIT=$6 -WDIR=$PWD/logs -TEST_HIVED_PID=-1 -REF_HIVED_PID=-1 -export HIVED_NODE_PID=-1 - -function run_replay { - echo Running $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - [ $? -ne 0 ] && echo test group FAILED && exit -1 -} - -function open_node { - echo Running $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 - . $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 -} - -function run_test { - echo Running test $1 - WDIR=$PWD/$1/logs - rm -rf $WDIR - mkdir -p $1 - pushd $PY_SCRIPT_DIR - - echo Running python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - [ $? -ne 0 ] && echo test $1 FAILED && EXIT_CODE=-1 - - popd -} - -run_replay - -open_node "tested" $TEST_HIVED_PATH $TEST_NODE_OPT $TEST_WORK_PATH $TEST_PORT -TEST_HIVED_PID=$HIVED_NODE_PID - -open_node "reference" $REF_HIVED_PATH $REF_NODE_OPT $REF_WORK_PATH $REF_PORT -REF_HIVED_PID=$HIVED_NODE_PID - -function cleanup { - ARG=$1 - if [ $TEST_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $TEST_HIVED_PID & - wait -n $TEST_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $TEST_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - if [ $REF_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $REF_HIVED_PID & - wait -n $REF_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $REF_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - wait - - if [ $ARG -eq 0 ] - then - exit $EXIT_CODE - else - exit $ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -echo TEST_HIVED_PID: $TEST_HIVED_PID REF_HIVED_PID: $REF_HIVED_PID -if [ $TEST_HIVED_PID -ne -1 ] && [ $REF_HIVED_PID -ne -1 ]; then - run_test "test_ah_get_account_history.py" -else - EXIT_CODE=-1 -fi - -cleanup $EXIT_CODE diff --git a/tests2/hived/smoketest/ah_limit_account_operation/config.ini b/tests2/hived/smoketest/ah_limit_account_operation/config.ini deleted file mode 100644 index ec759cc3dee048294d6cf450fb7ad28b170232f0..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_account_operation/config.ini +++ /dev/null @@ -1,61 +0,0 @@ -# Plugin(s) to enable, may be specified multiple times -plugin = account_history account_history_api database_api - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. -account-history-track-account-range = ["blocktrades", "blocktrades"] -account-history-track-account-range = ["c", "f"] - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. Deprecated in favor of account-history-track-account-range. -# track-account-range = - -# Defines a list of operations which will be explicitly logged. -account-history-whitelist-ops = account_create_operation, account_update_operation, transfer_operation - - -# Defines a list of operations which will be explicitly logged. Deprecated in favor of history-whitelist-ops. -# whitelist-ops = - -# Defines a list of operations which will be explicitly ignored. -# account-history-blacklist-ops = - -# Defines a list of operations which will be explicitly ignored. Deprecated in favor of history-blacklist-ops. -# blacklist-ops = - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G -shared-file-size = 8G - -# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints. -# checkpoint = - -# flush shared memory changes to disk every N blocks -# flush-state-interval = - -# Database edits to apply on startup (may specify multiple times) -# debug-node-edit-script = - -# The local IP address and port to listen for incoming connections. -# p2p-endpoint = - -# Maxmimum number of incoming connections on P2P endpoint. -# p2p-max-connections = - -# The IP address and port of a remote peer to sync with. Deprecated in favor of p2p-seed-node. -# seed-node = - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Enable block production, even if the chain is stale. -enable-stale-production = false - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -# witness = - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -# private-key = diff --git a/tests2/hived/smoketest/ah_limit_account_operation/test_group.sh b/tests2/hived/smoketest/ah_limit_account_operation/test_group.sh deleted file mode 100644 index fd43463434831763dfc49fdee26da2e37420a167..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_account_operation/test_group.sh +++ /dev/null @@ -1,117 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo Usage: jobs test_hived_path ref_hived_path test_work_path ref_work_path block_limit [--dont-copy-config] - echo Example: 16 ~/steemit/1/hived ~/steemit/2/hived ~/steemit/1/wdir ~/steemit/2/wdir 5000000 - exit -1 -} - -if [ $# -lt 6 -o $# -gt 7 ] -then - print_help_and_quit -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -SCRIPT_DIR=../scripts -PY_SCRIPT_DIR=../../api_tests -REPLAY_SCRIPT=run_replay.sh -NODE_SCRIPT=open_node.sh -NODE_ADDRESS=0.0.0.0 -TEST_PORT=8090 -REF_PORT=8091 -TEST_NODE=$NODE_ADDRESS:$TEST_PORT -REF_NODE=$NODE_ADDRESS:$REF_PORT -TEST_NODE_OPT=--webserver-http-endpoint=$TEST_NODE -REF_NODE_OPT=--webserver-http-endpoint=$REF_NODE -EXIT_CODE=0 -JOBS=$1 -TEST_HIVED_PATH=$2 -REF_HIVED_PATH=$3 -TEST_WORK_PATH=$4 -REF_WORK_PATH=$5 -BLOCK_LIMIT=$6 -WDIR=$PWD/logs -TEST_HIVED_PID=-1 -REF_HIVED_PID=-1 -export HIVED_NODE_PID=-1 - -function run_replay { - echo Running $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - [ $? -ne 0 ] && echo test group FAILED && exit -1 -} - -function open_node { - echo Running $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 - . $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 -} - -function run_test { - echo Running test $1 - WDIR=$PWD/$1/logs - rm -rf $WDIR - mkdir -p $1 - pushd $PY_SCRIPT_DIR - - echo Running python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - [ $? -ne 0 ] && echo test $1 FAILED && EXIT_CODE=-1 - - popd -} - -run_replay - -open_node "tested" $TEST_HIVED_PATH $TEST_NODE_OPT $TEST_WORK_PATH $TEST_PORT -TEST_HIVED_PID=$HIVED_NODE_PID - -open_node "reference" $REF_HIVED_PATH $REF_NODE_OPT $REF_WORK_PATH $REF_PORT -REF_HIVED_PID=$HIVED_NODE_PID - -function cleanup { - ARG=$1 - if [ $TEST_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $TEST_HIVED_PID & - wait -n $TEST_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $TEST_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - if [ $REF_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $REF_HIVED_PID & - wait -n $REF_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $REF_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - wait - - if [ $ARG -eq 0 ] - then - exit $EXIT_CODE - else - exit $ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -echo TEST_HIVED_PID: $TEST_HIVED_PID REF_HIVED_PID: $REF_HIVED_PID -if [ $TEST_HIVED_PID -ne -1 ] && [ $REF_HIVED_PID -ne -1 ]; then - run_test "test_ah_get_account_history.py" -else - EXIT_CODE=-1 -fi - -cleanup $EXIT_CODE diff --git a/tests2/hived/smoketest/ah_limit_operations/config.ini b/tests2/hived/smoketest/ah_limit_operations/config.ini deleted file mode 100644 index ec759cc3dee048294d6cf450fb7ad28b170232f0..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_operations/config.ini +++ /dev/null @@ -1,61 +0,0 @@ -# Plugin(s) to enable, may be specified multiple times -plugin = account_history account_history_api database_api - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. -account-history-track-account-range = ["blocktrades", "blocktrades"] -account-history-track-account-range = ["c", "f"] - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. Deprecated in favor of account-history-track-account-range. -# track-account-range = - -# Defines a list of operations which will be explicitly logged. -account-history-whitelist-ops = account_create_operation, account_update_operation, transfer_operation - - -# Defines a list of operations which will be explicitly logged. Deprecated in favor of history-whitelist-ops. -# whitelist-ops = - -# Defines a list of operations which will be explicitly ignored. -# account-history-blacklist-ops = - -# Defines a list of operations which will be explicitly ignored. Deprecated in favor of history-blacklist-ops. -# blacklist-ops = - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G -shared-file-size = 8G - -# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints. -# checkpoint = - -# flush shared memory changes to disk every N blocks -# flush-state-interval = - -# Database edits to apply on startup (may specify multiple times) -# debug-node-edit-script = - -# The local IP address and port to listen for incoming connections. -# p2p-endpoint = - -# Maxmimum number of incoming connections on P2P endpoint. -# p2p-max-connections = - -# The IP address and port of a remote peer to sync with. Deprecated in favor of p2p-seed-node. -# seed-node = - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Enable block production, even if the chain is stale. -enable-stale-production = false - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -# witness = - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -# private-key = diff --git a/tests2/hived/smoketest/ah_limit_operations/test_group.sh b/tests2/hived/smoketest/ah_limit_operations/test_group.sh deleted file mode 100644 index fd43463434831763dfc49fdee26da2e37420a167..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/ah_limit_operations/test_group.sh +++ /dev/null @@ -1,117 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo Usage: jobs test_hived_path ref_hived_path test_work_path ref_work_path block_limit [--dont-copy-config] - echo Example: 16 ~/steemit/1/hived ~/steemit/2/hived ~/steemit/1/wdir ~/steemit/2/wdir 5000000 - exit -1 -} - -if [ $# -lt 6 -o $# -gt 7 ] -then - print_help_and_quit -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -SCRIPT_DIR=../scripts -PY_SCRIPT_DIR=../../api_tests -REPLAY_SCRIPT=run_replay.sh -NODE_SCRIPT=open_node.sh -NODE_ADDRESS=0.0.0.0 -TEST_PORT=8090 -REF_PORT=8091 -TEST_NODE=$NODE_ADDRESS:$TEST_PORT -REF_NODE=$NODE_ADDRESS:$REF_PORT -TEST_NODE_OPT=--webserver-http-endpoint=$TEST_NODE -REF_NODE_OPT=--webserver-http-endpoint=$REF_NODE -EXIT_CODE=0 -JOBS=$1 -TEST_HIVED_PATH=$2 -REF_HIVED_PATH=$3 -TEST_WORK_PATH=$4 -REF_WORK_PATH=$5 -BLOCK_LIMIT=$6 -WDIR=$PWD/logs -TEST_HIVED_PID=-1 -REF_HIVED_PID=-1 -export HIVED_NODE_PID=-1 - -function run_replay { - echo Running $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - [ $? -ne 0 ] && echo test group FAILED && exit -1 -} - -function open_node { - echo Running $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 - . $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 -} - -function run_test { - echo Running test $1 - WDIR=$PWD/$1/logs - rm -rf $WDIR - mkdir -p $1 - pushd $PY_SCRIPT_DIR - - echo Running python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - [ $? -ne 0 ] && echo test $1 FAILED && EXIT_CODE=-1 - - popd -} - -run_replay - -open_node "tested" $TEST_HIVED_PATH $TEST_NODE_OPT $TEST_WORK_PATH $TEST_PORT -TEST_HIVED_PID=$HIVED_NODE_PID - -open_node "reference" $REF_HIVED_PATH $REF_NODE_OPT $REF_WORK_PATH $REF_PORT -REF_HIVED_PID=$HIVED_NODE_PID - -function cleanup { - ARG=$1 - if [ $TEST_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $TEST_HIVED_PID & - wait -n $TEST_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $TEST_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - if [ $REF_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $REF_HIVED_PID & - wait -n $REF_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $REF_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - wait - - if [ $ARG -eq 0 ] - then - exit $EXIT_CODE - else - exit $ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -echo TEST_HIVED_PID: $TEST_HIVED_PID REF_HIVED_PID: $REF_HIVED_PID -if [ $TEST_HIVED_PID -ne -1 ] && [ $REF_HIVED_PID -ne -1 ]; then - run_test "test_ah_get_account_history.py" -else - EXIT_CODE=-1 -fi - -cleanup $EXIT_CODE diff --git a/tests2/hived/smoketest/docker_build_and_run.sh b/tests2/hived/smoketest/docker_build_and_run.sh deleted file mode 100644 index 963969f7e8ecd42c438da29294612cbeb72be4b0..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/docker_build_and_run.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/bash -#params: -# - ref hived location -# - tested hived location -# - ref blockchain folder location -# - tested blockchain folder location -# - path to directory, where non-empty logs should be generated -# - stop replay at block -# - number of jobs (optional) -# - --dont-copy-config (optional), if passed config.init files are not copied from test directories -# -# WARNING: use absolute paths instead of relative! -# -# sudo ./docker_build_and_run.sh ~/steemit/hive/build/Release/programs/hived ~/steemit/hive/build/Release/programs/hived ~/steemit/hived_data/hivenet ~/steemit/hived_data/hivenet ~/steemit/logs 5000000 12 - -if [ $# -lt 6 -o $# -gt 8 ] -then - echo "Usage: reference_hived_location tested_hived_location ref_blockchain_folder_location tested_blockchain_folder_location" - echo " logs_dir stop_replay_at_block [jobs [--dont-copy-config]" - echo "Example: ~/steemit/ref_hived ~/steemit/hive/build/Release/programs/hived ~/steemit/hivenet ~/steemit/testnet" - echo " ~/steemit/logs 5000000 12" - echo " if <jobs> not passed, <nproc> will be used." - exit -1 -fi - -echo $* - -JOBS=0 - -if [ $# -eq 7 ] -then - JOBS=$7 -fi - -docker build -t smoketest ../ -f Dockerfile -[ $? -ne 0 ] && echo docker build FAILED && exit -1 - -docker system prune -f - -if [ -e $5 ]; then - rm -rf $5/* -else - mkdir -p $5 -fi - -docker run -v $1:/reference -v $2:/tested -v $3:/ref_blockchain -v $4:/tested_blockchain -v $5:/logs_dir -v /run:/run \ - -e STOP_REPLAY_AT_BLOCK=$6 -e JOBS=$JOBS -e COPY_CONFIG=$8 -p 8090:8090 -p 8091:8091 smoketest:latest diff --git a/tests2/hived/smoketest/scripts/open_node.sh b/tests2/hived/smoketest/scripts/open_node.sh deleted file mode 100644 index d00f75cabe73b01276463acfa7e78d6c14ebc9c3..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/scripts/open_node.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -if [ $# -ne 5 ] -then - echo Usage: node_kind hived_path node_options work_path port - echo Example: reference ~/steemit/hive/build/programs/hived/hived --webserver-http-endpoint=127.0.0.1:8090 ~/working 8090 - exit -1 -fi - -function check_pid_port { - echo Checking that hived with pid $1 listens at $2 port. - - NETSTAT_CMD="netstat -tlpn 2> /dev/null" - STAGE1=$(eval $NETSTAT_CMD) - # echo STAGE1: $STAGE1 - STAGE2=$(echo $STAGE1 | grep -o ":$2 [^ ]* LISTEN $1/hived") - ATTEMPT=0 - - while [[ -z $STAGE2 ]] && [ $ATTEMPT -lt 3 ]; do - sleep 3 - STAGE1=$(eval $NETSTAT_CMD) - STAGE2=$(echo $STAGE1 | grep -o ":$2 [^ ]* LISTEN $1/hived") - ((ATTEMPT++)) - done - - if [[ -z $STAGE2 ]]; then - echo FATAL: Could not find hived with pid $1 listening at port $2 using $NETSTAT_CMD command. - echo FATAL: Most probably another hived instance is running and listens at the port. - kill -s SIGINT $1 - return 1 - else - return 0 - fi -} - -PID=-1 -NAME=$1 -HIVED_PATH=$2 -NODE_OPTIONS=$3 -WORK_PATH=$4 -TEST_PORT=$5 - -function cleanup { - if [ $PID -gt 0 ] - then - sleep 0.1 && kill -s SIGINT $PID & - wait $PID - [ $? -eq 0 ] && echo ERROR: $HIVED_PATH exited with error - fi - exit -1 -} - -trap cleanup SIGINT SIGPIPE - -echo Running $NAME hived to listen -$HIVED_PATH $NODE_OPTIONS -d $WORK_PATH & PID=$! - -if [ $PID -le 0 ] -then - echo FATAL: cannot run $HIVED_PATH - exit -1 -fi - -if check_pid_port $PID $TEST_PORT; then - HIVED_NODE_PID=$PID - echo NODE: $HIVED_NODE_PID -fi diff --git a/tests2/hived/smoketest/scripts/run_replay.sh b/tests2/hived/smoketest/scripts/run_replay.sh deleted file mode 100644 index e8becffc1b16a66b063d02518d7be250f4686fb3..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/scripts/run_replay.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -if [ $# -lt 5 -o $# -gt 6 ] -then - echo "Usage: path_to_tested_hived path_to_reference_hived" - echo " path_to_test_blockchain_directory path_to_reference_blockchain_directory" - echo " number_of_blocks_to_replay [--dont-copy-config]" - echo "Example: ~/work/steemit/hive/build/programs/hived/hived ~/master/steemit/hive/build/programs/hived/hived ~/steemit/hive/work1 ~/steemit/hive/work2 2000000" - echo "Note: Run this script from test group directory." - exit -1 -fi - -HIVED_CONFIG=config.ini -HIVED_CONFIG_REF=config_ref.ini -HIVED_CONFIG_TEST=config_test.ini -TEST_HIVED_PATH=$1 -REF_HIVED_PATH=$2 -TEST_WORK_PATH=$3 -REF_WORK_PATH=$4 -BLOCK_LIMIT=$5 -COPY_CONFIG=$6 -RET_VAL1=-1 -RET_VAL2=-1 -EXIT_CODE=0 - -function copy_config { - if [ -e $HIVED_CONFIG ] - then - echo Copying ./$HIVED_CONFIG over $1/$HIVED_CONFIG - cp ./$HIVED_CONFIG $1/$HIVED_CONFIG - [ $? -ne 0 ] && echo FATAL: Failed to copy ./$HIVED_CONFIG over $1/$HIVED_CONFIG file. && exit -1 - elif [ -e $2 ] - then - echo Copying ./$2 over $1/$HIVED_CONFIG - cp ./$2 $1/$HIVED_CONFIG - [ $? -ne 0 ] && echo FATAL: Failed to copy ./$2 over $1/$HIVED_CONFIG file. && exit -1 - else - echo WARNING: missing $HIVED_CONFIG - fi -} - -function cleanup { - ARG=$1 - if [ $REPLAY_PID1 ] - then - if [ $ARG -ne 0 ]; then - sleep 0.1 && kill -s SIGINT $REPLAY_PID1 & - fi - wait -n $REPLAY_PID1 - [ $ARG -ne 0 -a $? -ne 0 ] && echo "FATAL: tested hived failed to replay $BLOCK_LIMIT blocks." && EXIT_CODE=-1 - fi - if [ $REPLAY_PID2 ] - then - if [ $ARG -ne 0 ]; then - sleep 0.1 && kill -s SIGINT $REPLAY_PID2 & - fi - wait -n $REPLAY_PID2 - [ $ARG -ne 0 -a $? -ne 0 ] && echo "FATAL: reference hived failed to replay $BLOCK_LIMIT blocks." && EXIT_CODE=-1 - fi - - if [ $ARG -ne 0 ] - then - EXIT_CODE=$ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -if [ "$COPY_CONFIG" != "--dont-copy-config" ] -then - copy_config $TEST_WORK_PATH $HIVED_CONFIG_TEST - copy_config $REF_WORK_PATH $HIVED_CONFIG_REF -fi - -echo Running "test instance" replay of $BLOCK_LIMIT blocks -( $TEST_HIVED_PATH --replay --stop-replay-at-block $BLOCK_LIMIT -d $TEST_WORK_PATH ) & REPLAY_PID1=$! - -echo Running "reference instance" replay of $BLOCK_LIMIT blocks -( $REF_HIVED_PATH --replay --stop-replay-at-block $BLOCK_LIMIT -d $REF_WORK_PATH ) & REPLAY_PID2=$! - -cleanup $EXIT_CODE diff --git a/tests2/hived/smoketest/smoketest.sh b/tests2/hived/smoketest/smoketest.sh deleted file mode 100644 index d1bd7d96b5fa55374c87dad4273217a9c5487371..0000000000000000000000000000000000000000 --- a/tests2/hived/smoketest/smoketest.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/bash - -EXIT_CODE=0 -GROUP_TOTAL=0 -GROUP_PASSED=0 -GROUP_SKIPPED=0 -GROUP_FAILURE=0 -JOBS=0 -API_TEST_PATH=../../python_scripts/tests/api_tests -BLOCK_SUBPATH=blockchain/block_log -GROUP_TEST_SCRIPT=test_group.sh - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo "Usage: path_to_tested_hived path_to_reference_hived path_to_test_blockchain_directory" - echo " path_to_reference_blockchain_directory number_of_blocks_to_replay [number_of_jobs [--dont-copy-config]]" - echo "Example: ~/work/steemit/hive/build/Release/programs/hived/hived ~/master/steemit/hive/build/Release/programs/hived/hived ~/steemit/hive/work1 ~/steemit/hive/work2 5000000" - echo " Pass absolute, not relative paths;" - echo " if <number_of_jobs> not passed or if is less or zero equal <nproc> will be used;" - echo " if --dont-copy-config is passed config.init files are not copied from test directories." - exit -1 -} - -if [ $# -lt 5 -o $# -gt 7 ] -then - print_help_and_quit -fi - -TEST_HIVED_PATH=$1 -REF_HIVED_PATH=$2 -TEST_WORK_PATH=$3 -REF_WORK_PATH=$4 -BLOCK_LIMIT=$5 - -if [ $# -gt 5 ] -then - JOBS=$6 -fi - -if [ $JOBS -le 0 ] -then - JOBS=$(nproc --all) -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -function check_hived_path { - echo Checking $1... - if [ -x "$1" ] && file "$1" | grep -q "executable" - then - echo OK: $1 is executable file. - else - echo FATAL: $1 is not executable file or found! && exit -1 - fi -} - -function check_work_path { - echo Checking $1... - if [ -e "$1" ] && [ -e "$1/$BLOCK_SUBPATH" ] - then - echo OK: $1/$BLOCK_SUBPATH found. - else - echo FATAL: $1 not found or $BLOCK_SUBPATH not found in $1! && exit -1 - fi -} - -function run_test_group { - echo Running test group $1 - pushd $1 - - if ! [ -x "$GROUP_TEST_SCRIPT" ]; then - echo Skipping subdirectory $1 due to missing $GROUP_TEST_SCRIPT file. - ((GROUP_SKIPPED++)) - popd - return - fi - - echo Running ./$GROUP_TEST_SCRIPT $JOBS $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - ./$GROUP_TEST_SCRIPT $JOBS $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - EXIT_CODE=$? - if [ $EXIT_CODE -ne 0 ] - then - EXIT_CODE=-1 - echo test group $1 FAILED - ((GROUP_FAILURE++)) - else - echo test group $1 PASSED - ((GROUP_PASSED++)) - fi - - popd -} - -function cleanup { - exit $1 -} - -trap cleanup SIGINT SIGPIPE - -check_hived_path $TEST_HIVED_PATH -check_hived_path $REF_HIVED_PATH - -check_work_path $TEST_WORK_PATH -check_work_path $REF_WORK_PATH - -for dir in ./*/ -do - dir=${dir%*/} - run_test_group ${dir##*/} - ((GROUP_TOTAL++)) - [ $EXIT_CODE -gt 0 ] && break -done - -echo TOTAL test groups: $GROUP_TOTAL -echo PASSED test groups: $GROUP_PASSED -echo SKIPPED test groups: $GROUP_SKIPPED -echo FAILED test groups: $GROUP_FAILURE - -exit $EXIT_CODE diff --git a/tests2/hivemind/api_tests/.gitignore b/tests2/hivemind/api_tests/.gitignore deleted file mode 100644 index 397b4a7624e35fa60563a9c03b1213d93f7b6546..0000000000000000000000000000000000000000 --- a/tests2/hivemind/api_tests/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.log diff --git a/tests2/hivemind/api_tests/CMakeLists.txt b/tests2/hivemind/api_tests/CMakeLists.txt deleted file mode 100644 index 8131dd83963d15bfd4a5c11c388cae5aadc371f4..0000000000000000000000000000000000000000 --- a/tests2/hivemind/api_tests/CMakeLists.txt +++ /dev/null @@ -1,24 +0,0 @@ -# Adding python tests to cmake -set(REFERENCE_NODE https://api.hive.blog) -set(TEST_NODE http://127.0.0.1:8090) - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/testbase.py" "${CMAKE_BINARY_DIR}/tests/api_tests/testbase.py" COPYONLY) - -macro(ADD_API_TEST api_name test_name) - set(working_dir ${CMAKE_BINARY_DIR}/tests/api_tests/${api_name}) - configure_file("${CMAKE_CURRENT_SOURCE_DIR}/${test_name}.py" "${working_dir}/${test_name}.py" COPYONLY) - message(STATUS "Adding ${api_name}/${test_name} to test list") - set(extra_macro_args ${ARGN}) - list(LENGTH extra_macro_args num_extra_args) - set(test_parameters ${test_name}.py ${TEST_NODE} ${REFERENCE_NODE} ${working_dir}) - if (${num_extra_args} GREATER 0) - set(test_parameters ${test_name}.py ${TEST_NODE} ${REFERENCE_NODE} ${working_dir} ${extra_macro_args}) - endif() - add_test(NAME "${api_name}/${test_name}" COMMAND python3 ${test_parameters} WORKING_DIRECTORY ${working_dir}) - set_property(TEST "${api_name}/${test_name}" PROPERTY LABELS python_tests ${api_name} ${test_name}) -endmacro(ADD_API_TEST) - -add_subdirectory(follow_api) -add_subdirectory(tags_api) -add_subdirectory(bridge) -add_subdirectory(block_api) diff --git a/tests2/hivemind/api_tests/testbase.py b/tests2/hivemind/api_tests/testbase.py deleted file mode 100755 index 8f03f75860cf9ec9d526f6a7c9870b30968fb1a7..0000000000000000000000000000000000000000 --- a/tests2/hivemind/api_tests/testbase.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/python3 - -import os -import json -import jsondiff -from pathlib import Path - -TEST_NODE_IS_HIVE = True -REFERENCE_NODE_IS_HIVE = True - -# ignore this tags when comparing results from test and reference nodes -TAGS_TO_REMOVE = [ - "timestamp", - "post_id", - "id" -] - -TAGS_TO_RENAME = { - "STEEM_":"HIVE_", - "SBD_":"HBD_" -} - -def rename_tags(data): - for k, v in TAGS_TO_RENAME.items(): - data = rename_tag(data, k, v) - return data - -def rename_tag(data, old, new): - if not isinstance(data, (dict, list)): - return data - if isinstance(data, list): - return [rename_tag(v, old, new) for v in data] - return {k.replace(old, new): rename_tag(v, old, new) for k, v in data.items()} - -def remove_tag(data): - if not isinstance(data, (dict, list)): - return data - if isinstance(data, list): - return [remove_tag(v) for v in data] - return {k: remove_tag(v) for k, v in data.items() if k not in TAGS_TO_REMOVE} - -class SimpleJsonTest(object): - def __init__(self, test_node, ref_node, work_dir): - self._test_node = test_node - self._ref_node = ref_node - self._work_dir = Path(work_dir) - - self.create_work_dir() - - def create_work_dir(self): - if self._work_dir.exists(): - if self._work_dir.is_file(): - os.remove(self._work_dir) - - if not self._work_dir.exists(): - self._work_dir.mkdir(parents = True) - - def create_file_name(self, file_name): - return self._work_dir / Path(file_name) - - def write_to_file(self, dest_file, data, label): - try: - f = dest_file.open( "a" ) - f.write("{} Response:\n".format(label)) - json.dump(data, f, indent=2, sort_keys=True) - f.close() - return True - except: - print( "Cannot open file:", dest_file ) - return False - - def json_pretty_string(self, json_obj): - return json.dumps(json_obj, sort_keys=True, indent=4) - - def compare_results(self, args, print_response = False, test_node_is_hive = TEST_NODE_IS_HIVE, reference_node_is_hive = REFERENCE_NODE_IS_HIVE): - try: - from requests import post - - print("Sending query:\n{}".format(self.json_pretty_string(args))) - - resp1 = post(self._test_node, data=json.dumps(args)) - resp2 = post(self._ref_node, data=json.dumps(args)) - - filename1 = self.create_file_name("ref.log") - filename2 = self.create_file_name("tested.log") - - # we will treat codes != 200 as test failed - if resp1.status_code != 200 or resp2.status_code != 200: - print("One of the nodes returned non 200 return codes. Test node: {}, reference node: {}".format(resp1.status_code, resp2.status_code)) - self.write_to_file(filename1, resp1, self._test_node) - self.write_to_file(filename2, resp2, self._ref_node) - return False - - json1 = resp1.json() - json1 = remove_tag(json1) - if reference_node_is_hive and not test_node_is_hive: - json1 = rename_tags(json1) - - json2 = resp2.json() - json2 = remove_tag(json2) - if test_node_is_hive and not reference_node_is_hive: - json2 = rename_tags(json2) - - if print_response: - print("Response from test node at {}:\n{}".format(self._test_node, self.json_pretty_string(json1))) - print("Response from ref node at {}:\n{}".format(self._ref_node, self.json_pretty_string(json2))) - - json1_error = json1.get("error", None) - json2_error = json2.get("error", None) - - if json1_error is not None: - print("Test node {} returned error code".format(self._test_node)) - self.write_to_file(filename1, json1, self._test_node) - - if json2_error is not None: - print("Reference node {} returned error code".format(self._ref_node)) - self.write_to_file(filename2, json2, self._ref_node) - - if resp1.status_code != resp2.status_code or json1 != json2: - print("Difference detected") - - # if print_response flag is not set print responses to compare, avoid double printing if flag is set to true - if not print_response: - print("Response from test node at {}:\n{}".format(self._test_node, self.json_pretty_string(json1))) - print("Response from ref node at {}:\n{}".format(self._ref_node, self.json_pretty_string(json2))) - - json_diff = jsondiff.diff(json1, json2) - if json_diff: - print("Differences detected in jsons: {}".format(self.json_pretty_string(json_diff))) - - # avoid dobuble write in case of error detected and differences detected. - if json1_error is None: - self.write_to_file(filename1, json1, self._test_node) - if json2_error is None: - self.write_to_file(filename2, json2, self._ref_node) - - print( "Compare break with error") - return False - - print( "Compare finished") - return True - - except Exception as ex: - # treat exception as test failed - print("Exception during sending request: {}".format(ex)) - return False - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser() - - parser.add_argument("api", type = str, help = "Full api name. i.e: database_api.get_block") - parser.add_argument("params", type = str, help = "JSON with parameters") - - parser.add_argument("--test-node", dest = "test_node", type = str, default = "https://api.steem.house", help = "IP address of test node") - parser.add_argument("--test-node-is-hive", dest = "test_node_is_hive", type = bool, default = True, help = "Test node is hive node?") - parser.add_argument("--ref-node", dest = "ref_node", type = str, default = "https://api.steemit.com", help = "IP address of reference node") - parser.add_argument("--ref-node-is-hive", dest = "ref_node_is_hive", type = bool, default = False, help = "Reference node is hive?") - parser.add_argument("--work-dir", dest = "work_dir", type = str, default = "./", help = "Work dir") - parser.add_argument("--print-response", dest = "print_response", type = bool, default = False, help = "Print response from nodes") - - args = parser.parse_args() - tester = SimpleJsonTest(args.test_node, args.ref_node, args.work_dir) - - test_args = { - "jsonrpc": "2.0", - "id": 1, - "method": args.api, - "params": json.loads(args.params) - } - - if tester.compare_results(test_args, args.print_response, args.test_node_is_hive, args.ref_node_is_hive): - exit(0) - exit(1) diff --git a/tests2/hivemind/smoketest/smoketest.sh b/tests2/hivemind/smoketest/smoketest.sh deleted file mode 100644 index d1bd7d96b5fa55374c87dad4273217a9c5487371..0000000000000000000000000000000000000000 --- a/tests2/hivemind/smoketest/smoketest.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/bash - -EXIT_CODE=0 -GROUP_TOTAL=0 -GROUP_PASSED=0 -GROUP_SKIPPED=0 -GROUP_FAILURE=0 -JOBS=0 -API_TEST_PATH=../../python_scripts/tests/api_tests -BLOCK_SUBPATH=blockchain/block_log -GROUP_TEST_SCRIPT=test_group.sh - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo "Usage: path_to_tested_hived path_to_reference_hived path_to_test_blockchain_directory" - echo " path_to_reference_blockchain_directory number_of_blocks_to_replay [number_of_jobs [--dont-copy-config]]" - echo "Example: ~/work/steemit/hive/build/Release/programs/hived/hived ~/master/steemit/hive/build/Release/programs/hived/hived ~/steemit/hive/work1 ~/steemit/hive/work2 5000000" - echo " Pass absolute, not relative paths;" - echo " if <number_of_jobs> not passed or if is less or zero equal <nproc> will be used;" - echo " if --dont-copy-config is passed config.init files are not copied from test directories." - exit -1 -} - -if [ $# -lt 5 -o $# -gt 7 ] -then - print_help_and_quit -fi - -TEST_HIVED_PATH=$1 -REF_HIVED_PATH=$2 -TEST_WORK_PATH=$3 -REF_WORK_PATH=$4 -BLOCK_LIMIT=$5 - -if [ $# -gt 5 ] -then - JOBS=$6 -fi - -if [ $JOBS -le 0 ] -then - JOBS=$(nproc --all) -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -function check_hived_path { - echo Checking $1... - if [ -x "$1" ] && file "$1" | grep -q "executable" - then - echo OK: $1 is executable file. - else - echo FATAL: $1 is not executable file or found! && exit -1 - fi -} - -function check_work_path { - echo Checking $1... - if [ -e "$1" ] && [ -e "$1/$BLOCK_SUBPATH" ] - then - echo OK: $1/$BLOCK_SUBPATH found. - else - echo FATAL: $1 not found or $BLOCK_SUBPATH not found in $1! && exit -1 - fi -} - -function run_test_group { - echo Running test group $1 - pushd $1 - - if ! [ -x "$GROUP_TEST_SCRIPT" ]; then - echo Skipping subdirectory $1 due to missing $GROUP_TEST_SCRIPT file. - ((GROUP_SKIPPED++)) - popd - return - fi - - echo Running ./$GROUP_TEST_SCRIPT $JOBS $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - ./$GROUP_TEST_SCRIPT $JOBS $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - EXIT_CODE=$? - if [ $EXIT_CODE -ne 0 ] - then - EXIT_CODE=-1 - echo test group $1 FAILED - ((GROUP_FAILURE++)) - else - echo test group $1 PASSED - ((GROUP_PASSED++)) - fi - - popd -} - -function cleanup { - exit $1 -} - -trap cleanup SIGINT SIGPIPE - -check_hived_path $TEST_HIVED_PATH -check_hived_path $REF_HIVED_PATH - -check_work_path $TEST_WORK_PATH -check_work_path $REF_WORK_PATH - -for dir in ./*/ -do - dir=${dir%*/} - run_test_group ${dir##*/} - ((GROUP_TOTAL++)) - [ $EXIT_CODE -gt 0 ] && break -done - -echo TOTAL test groups: $GROUP_TOTAL -echo PASSED test groups: $GROUP_PASSED -echo SKIPPED test groups: $GROUP_SKIPPED -echo FAILED test groups: $GROUP_FAILURE - -exit $EXIT_CODE diff --git a/tests2/hivemind/smoketest/votes/config.ini b/tests2/hivemind/smoketest/votes/config.ini deleted file mode 100644 index 856a478c14bfcc4b27260039b1b8f0696cd57b65..0000000000000000000000000000000000000000 --- a/tests2/hivemind/smoketest/votes/config.ini +++ /dev/null @@ -1,60 +0,0 @@ -# Plugin(s) to enable, may be specified multiple times -plugin = database_api - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. -# account-history-track-account-range = - -# Defines a range of accounts to track as a json pair ["from","to"] [from,to] Can be specified multiple times. Deprecated in favor of account-history-track-account-range. -# track-account-range = - -# Defines a list of operations which will be explicitly logged. -# account-history-whitelist-ops = - -# Defines a list of operations which will be explicitly logged. Deprecated in favor of history-whitelist-ops. -# whitelist-ops = - -# Defines a list of operations which will be explicitly ignored. -# account-history-blacklist-ops = - -# Defines a list of operations which will be explicitly ignored. Deprecated in favor of history-blacklist-ops. -# blacklist-ops = - -# the location of the chain shared memory files (absolute path or relative to application data dir) -shared-file-dir = "blockchain" - -# Size of the shared memory file. Default: 54G -shared-file-size = 8G - -# Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints. -# checkpoint = - -# flush shared memory changes to disk every N blocks -# flush-state-interval = - -# Database edits to apply on startup (may specify multiple times) -# debug-node-edit-script = - -# The local IP address and port to listen for incoming connections. -# p2p-endpoint = - -# Maxmimum number of incoming connections on P2P endpoint. -# p2p-max-connections = - -# The IP address and port of a remote peer to sync with. Deprecated in favor of p2p-seed-node. -# seed-node = - -# The IP address and port of a remote peer to sync with. -p2p-seed-node = - -# Enable block production, even if the chain is stale. -enable-stale-production = false - -# Percent of witnesses (0-99) that must be participating in order to produce blocks -required-participation = 0 - -# name of witness controlled by this node (e.g. initwitness ) -# witness = - -# WIF PRIVATE KEY to be used by one or more witnesses or miners -# private-key = - diff --git a/tests2/hivemind/smoketest/votes/test_group.sh b/tests2/hivemind/smoketest/votes/test_group.sh deleted file mode 100644 index 07c3cbb91247a633e117c6287a428447cefdf8d2..0000000000000000000000000000000000000000 --- a/tests2/hivemind/smoketest/votes/test_group.sh +++ /dev/null @@ -1,118 +0,0 @@ -#!/bin/bash - -function echo(){ builtin echo $(basename $0 .sh): "$@"; } -pushd () { command pushd "$@" > /dev/null; } -popd () { command popd "$@" > /dev/null; } - -function print_help_and_quit { - echo Usage: jobs test_hived_path ref_hived_path test_work_path ref_work_path block_limit [--dont-copy-config] - echo Example: 16 ~/steemit/1/hived ~/steemit/2/hived ~/steemit/1/wdir ~/steemit/2/wdir 5000000 - exit -1 -} - -if [ $# -lt 6 -o $# -gt 7 ] -then - print_help_and_quit -fi - -COPY_CONFIG=$7 - -if [ "$COPY_CONFIG" != "--dont-copy-config" -a "$COPY_CONFIG" != "" ] -then - echo "Unknown option: " $7 - print_help_and_quit -fi - -SCRIPT_DIR=../scripts -PY_SCRIPT_DIR=../../api_tests -REPLAY_SCRIPT=run_replay.sh -NODE_SCRIPT=open_node.sh -NODE_ADDRESS=0.0.0.0 -TEST_PORT=8090 -REF_PORT=8091 -TEST_NODE=$NODE_ADDRESS:$TEST_PORT -REF_NODE=$NODE_ADDRESS:$REF_PORT -TEST_NODE_OPT=--webserver-http-endpoint=$TEST_NODE -REF_NODE_OPT=--webserver-http-endpoint=$REF_NODE -EXIT_CODE=0 -JOBS=$1 -TEST_HIVED_PATH=$2 -REF_HIVED_PATH=$3 -TEST_WORK_PATH=$4 -REF_WORK_PATH=$5 -BLOCK_LIMIT=$6 -WDIR=$PWD/logs -TEST_HIVED_PID=-1 -REF_HIVED_PID=-1 -export HIVED_NODE_PID=-1 - -function run_replay { - echo Running $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - $SCRIPT_DIR/$REPLAY_SCRIPT $TEST_HIVED_PATH $REF_HIVED_PATH $TEST_WORK_PATH $REF_WORK_PATH $BLOCK_LIMIT $COPY_CONFIG - [ $? -ne 0 ] && echo test group FAILED && exit -1 -} - -function open_node { - echo Running $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 - . $SCRIPT_DIR/$NODE_SCRIPT $1 $2 $3 $4 $5 -} - -function run_test { - echo Running test $1 - WDIR=$PWD/$1/logs - rm -rf $WDIR - mkdir -p $1 - pushd $PY_SCRIPT_DIR - - echo Running python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE $WDIR - python3 $1 $JOBS http://$TEST_NODE http://$REF_NODE 50 $WDIR - [ $? -ne 0 ] && echo test $1 FAILED && EXIT_CODE=-1 - - popd -} - -run_replay - -open_node "tested" $TEST_HIVED_PATH $TEST_NODE_OPT $TEST_WORK_PATH $TEST_PORT -TEST_HIVED_PID=$HIVED_NODE_PID - -open_node "reference" $REF_HIVED_PATH $REF_NODE_OPT $REF_WORK_PATH $REF_PORT -REF_HIVED_PID=$HIVED_NODE_PID - -function cleanup { - ARG=$1 - if [ $TEST_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $TEST_HIVED_PID & - wait -n $TEST_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $TEST_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - if [ $REF_HIVED_PID -ne -1 ] - then - sleep 0.5 && kill -s SIGINT $REF_HIVED_PID & - wait -n $REF_HIVED_PID - [ $? -ne 0 ] && echo ERROR: $REF_HIVED_PATH exit failed && EXIT_CODE=-1 - fi - - wait - - if [ $ARG -eq 0 ] - then - exit $EXIT_CODE - else - exit $ARG - fi -} - -trap cleanup SIGINT SIGPIPE - -echo TEST_HIVED_PID: $TEST_HIVED_PID REF_HIVED_PID: $REF_HIVED_PID -if [ $TEST_HIVED_PID -ne -1 ] && [ $REF_HIVED_PID -ne -1 ]; then - run_test "test_list_votes.py" - # obsolete: run_test "test_list_votes2.py" -else - EXIT_CODE=-1 -fi - -cleanup $EXIT_CODE diff --git a/tests2/unit/BoostTestTargets.cmake b/tests2/unit/BoostTestTargets.cmake deleted file mode 100644 index d0edf7ed25f5fdb46f4cdd660103a74bed382675..0000000000000000000000000000000000000000 --- a/tests2/unit/BoostTestTargets.cmake +++ /dev/null @@ -1,258 +0,0 @@ -# - Add tests using boost::test -# -# Add this line to your test files in place of including a basic boost test header: -# #include <BoostTestTargetConfig.h> -# -# If you cannot do that and must use the included form for a given test, -# include the line -# // OVERRIDE_BOOST_TEST_INCLUDED_WARNING -# in the same file with the boost test include. -# -# include(BoostTestTargets) -# add_boost_test(<testdriver_name> SOURCES <source1> [<more sources...>] -# [FAIL_REGULAR_EXPRESSION <additional fail regex>] -# [LAUNCHER <generic launcher script>] -# [LIBRARIES <library> [<library>...]] -# [RESOURCES <resource> [<resource>...]] -# [TESTS <testcasename> [<testcasename>...]]) -# -# If for some reason you need access to the executable target created, -# it can be found in ${${testdriver_name}_TARGET_NAME} as specified when -# you called add_boost_test -# -# Requires CMake 2.6 or newer (uses the 'function' command) -# -# Requires: -# GetForceIncludeDefinitions -# CopyResourcesToBuildTree -# -# Original Author: -# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net> -# http://academic.cleardefinition.com -# Iowa State University HCI Graduate Program/VRAC -# -# Copyright Iowa State University 2009-2010. -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) - -if(__add_boost_test) - return() -endif() -set(__add_boost_test YES) - -set(BOOST_TEST_TARGET_PREFIX "boosttest") - -if(NOT Boost_FOUND) - find_package(Boost 1.34.0 QUIET) -endif() -if("${Boost_VERSION}0" LESS "1034000") - set(_shared_msg - "NOTE: boost::test-based targets and tests cannot " - "be added: boost >= 1.34.0 required but not found. " - "(found: '${Boost_VERSION}'; want >=103400) ") - if(BUILD_TESTING) - message(FATAL_ERROR - ${_shared_msg} - "You may disable BUILD_TESTING to continue without the " - "tests.") - else() - message(STATUS - ${_shared_msg} - "BUILD_TESTING disabled, so continuing anyway.") - endif() -endif() - -include(GetForceIncludeDefinitions.cmake) -include(CopyResourcesToBuildTree.cmake) - -if(Boost_FOUND AND NOT "${Boost_VERSION}0" LESS "1034000") - set(_boosttesttargets_libs) - set(_boostConfig "BoostTestTargetsIncluded.h") - if(NOT Boost_UNIT_TEST_FRAMEWORK_LIBRARY) - find_package(Boost 1.34.0 QUIET COMPONENTS unit_test_framework) - endif() - if(Boost_UNIT_TEST_FRAMEWORK_LIBRARY) - set(_boosttesttargets_libs "${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}") - if(Boost_USE_STATIC_LIBS) - set(_boostConfig "BoostTestTargetsStatic.h") - else() - if(NOT APPLE) - set(_boostConfig "BoostTestTargetsDynamic.h") - endif() - endif() - endif() - get_filename_component(_moddir ${CMAKE_CURRENT_LIST_FILE} PATH) - configure_file("${_moddir}/${_boostConfig}" - "${CMAKE_CURRENT_BINARY_DIR}/BoostTestTargetConfig.h" - COPYONLY) - include_directories("${CMAKE_CURRENT_BINARY_DIR}") -endif() - -function(add_boost_test _name) - if(NOT BUILD_TESTING) - return() - endif() - - # parse arguments - set(_nowhere) - set(_curdest _nowhere) - set(_val_args - SOURCES - FAIL_REGULAR_EXPRESSION - LAUNCHER - LIBRARIES - RESOURCES - TESTS) - set(_bool_args - USE_COMPILED_LIBRARY) - foreach(_arg ${_val_args} ${_bool_args}) - set(${_arg}) - endforeach() - foreach(_element ${ARGN}) - list(FIND _val_args "${_element}" _val_arg_find) - list(FIND _bool_args "${_element}" _bool_arg_find) - if("${_val_arg_find}" GREATER "-1") - set(_curdest "${_element}") - elseif("${_bool_arg_find}" GREATER "-1") - set("${_element}" ON) - set(_curdest _nowhere) - else() - list(APPEND ${_curdest} "${_element}") - endif() - endforeach() - - if(_nowhere) - message(FATAL_ERROR "Syntax error in use of add_boost_test!") - endif() - - if(NOT SOURCES) - message(FATAL_ERROR - "Syntax error in use of add_boost_test: at least one source file required!") - endif() - - if(Boost_FOUND AND NOT "${Boost_VERSION}0" LESS "1034000") - - include_directories(${Boost_INCLUDE_DIRS}) - - set(includeType) - foreach(src ${SOURCES}) - file(READ ${src} thefile) - if("${thefile}" MATCHES ".*BoostTestTargetConfig.h.*") - set(includeType CONFIGURED) - set(includeFileLoc ${src}) - break() - elseif("${thefile}" MATCHES ".*boost/test/included/unit_test.hpp.*") - set(includeType INCLUDED) - set(includeFileLoc ${src}) - set(_boosttesttargets_libs) # clear this out - linking would be a bad idea - if(NOT - "${thefile}" - MATCHES - ".*OVERRIDE_BOOST_TEST_INCLUDED_WARNING.*") - message("Please replace the include line in ${src} with this alternate include line instead:") - message(" \#include <BoostTestTargetConfig.h>") - message("Once you've saved your changes, re-run CMake. (See BoostTestTargets.cmake for more info)") - endif() - break() - endif() - endforeach() - - if(NOT _boostTestTargetsNagged${_name} STREQUAL "${includeType}") - if("${includeType}" STREQUAL "CONFIGURED") - message(STATUS - "Test '${_name}' uses the CMake-configurable form of the boost test framework - congrats! (Including File: ${includeFileLoc})") - elseif("${includeType}" STREQUAL "INCLUDED") - message("In test '${_name}': ${includeFileLoc} uses the 'included' form of the boost unit test framework.") - else() - message("In test '${_name}': Didn't detect the CMake-configurable boost test include.") - message("Please replace your existing boost test include in that test with the following:") - message(" \#include <BoostTestTargetConfig.h>") - message("Once you've saved your changes, re-run CMake. (See BoostTestTargets.cmake for more info)") - endif() - endif() - set(_boostTestTargetsNagged${_name} - "${includeType}" - CACHE - INTERNAL - "" - FORCE) - - - if(RESOURCES) - list(APPEND SOURCES ${RESOURCES}) - endif() - - # Generate a unique target name, using the relative binary dir - # and provided name. (transform all / into _ and remove all other - # non-alphabet characters) - file(RELATIVE_PATH - targetpath - "${CMAKE_BINARY_DIR}" - "${CMAKE_CURRENT_BINARY_DIR}") - string(REGEX REPLACE "[^A-Za-z/_]" "" targetpath "${targetpath}") - string(REPLACE "/" "_" targetpath "${targetpath}") - - set(_target_name ${_name}) - set(${_name}_TARGET_NAME "${_target_name}" PARENT_SCOPE) - - # Build the test. - add_executable(${_target_name} ${SOURCES}) - - list(APPEND LIBRARIES ${_boosttesttargets_libs}) - - if(LIBRARIES) - target_link_libraries(${_target_name} ${LIBRARIES}) - endif() - - if(RESOURCES) - set_property(TARGET ${_target_name} PROPERTY RESOURCE ${RESOURCES}) - copy_resources_to_build_tree(${_target_name}) - endif() - - if(NOT Boost_TEST_FLAGS) -# set(Boost_TEST_FLAGS --catch_system_error=yes --output_format=XML) - set(Boost_TEST_FLAGS --catch_system_error=yes) - endif() - - # TODO: Figure out why only recent boost handles individual test running properly - - if(LAUNCHER) - set(_test_command ${LAUNCHER} "\$<TARGET_FILE:${_target_name}>") - else() - set(_test_command ${_target_name}) - endif() - - if(TESTS AND ( "${Boost_VERSION}" VERSION_GREATER "103799" )) - foreach(_test ${TESTS}) - add_test( - unit/${_name}-${_test} - ${_test_command} --run_test=${_test} ${Boost_TEST_FLAGS} - ) - if(FAIL_REGULAR_EXPRESSION) - set_tests_properties(unit/${_name}-${_test} - PROPERTIES - FAIL_REGULAR_EXPRESSION - "${FAIL_REGULAR_EXPRESSION}") - endif() - endforeach() - else() - add_test( - unit/${_name}-boost_test - ${_test_command} ${Boost_TEST_FLAGS} - ) - if(FAIL_REGULAR_EXPRESSION) - set_tests_properties(unit/${_name}-boost_test - PROPERTIES - FAIL_REGULAR_EXPRESSION - "${FAIL_REGULAR_EXPRESSION}") - endif() - endif() - - # CppCheck the test if we can. - if(COMMAND add_cppcheck) - add_cppcheck(${_target_name} STYLE UNUSED_FUNCTIONS) - endif() - - endif() -endfunction() diff --git a/tests2/unit/BoostTestTargetsDynamic.h b/tests2/unit/BoostTestTargetsDynamic.h deleted file mode 100644 index 4bff5677d546a86754c601b154530d89dff1593f..0000000000000000000000000000000000000000 --- a/tests2/unit/BoostTestTargetsDynamic.h +++ /dev/null @@ -1,8 +0,0 @@ -// Small header computed by CMake to set up boost test. -// include AFTER #define BOOST_TEST_MODULE whatever -// but before any other boost test includes. - -// Using the Boost UTF dynamic library - -#define BOOST_TEST_DYN_LINK -#include <boost/test/unit_test.hpp> diff --git a/tests2/unit/BoostTestTargetsIncluded.h b/tests2/unit/BoostTestTargetsIncluded.h deleted file mode 100644 index 253133ce2fa1e543a27c19e354b8bd59d1bcea53..0000000000000000000000000000000000000000 --- a/tests2/unit/BoostTestTargetsIncluded.h +++ /dev/null @@ -1,7 +0,0 @@ -// Small header computed by CMake to set up boost test. -// include AFTER #define BOOST_TEST_MODULE whatever -// but before any other boost test includes. - -// Using the Boost UTF included framework - -#include <boost/test/included/unit_test.hpp> diff --git a/tests2/unit/BoostTestTargetsStatic.h b/tests2/unit/BoostTestTargetsStatic.h deleted file mode 100644 index dd3cddae10410200bcec9310140a5f6f70b44bf0..0000000000000000000000000000000000000000 --- a/tests2/unit/BoostTestTargetsStatic.h +++ /dev/null @@ -1,7 +0,0 @@ -// Small header computed by CMake to set up boost test. -// include AFTER #define BOOST_TEST_MODULE whatever -// but before any other boost test includes. - -// Using the Boost UTF static library - -#include <boost/test/unit_test.hpp> diff --git a/tests2/unit/CMakeLists.txt b/tests2/unit/CMakeLists.txt deleted file mode 100644 index b2282f8fcd9790e57ec5fbdb281c88a78230223a..0000000000000000000000000000000000000000 --- a/tests2/unit/CMakeLists.txt +++ /dev/null @@ -1,283 +0,0 @@ -add_subdirectory(db_fixture) -add_subdirectory(bmic_objects) - -find_package( Gperftools QUIET ) -if( GPERFTOOLS_FOUND ) - message( STATUS "Found gperftools; compiling tests with TCMalloc") - list( APPEND PLATFORM_SPECIFIC_LIBS tcmalloc ) -endif() - -INCLUDE(CTest) - -ENABLE_TESTING() - -file(GLOB UNIT_TESTS "tests/*.cpp") - -include(BoostTestTargets.cmake) - -function(parse_unit_tests RESULT) - set(SOURCES) - foreach(_element ${ARGN}) - list(APPEND SOURCES "${_element}") - endforeach() - - set(tests) - - foreach(src ${SOURCES}) - file(READ ${src} thefile) - #string(REGEX MATCH "" test_suite "${thefile}" ) - string(REGEX MATCH "BOOST_FIXTURE_TEST_SUITE\\([A-Za-z0-9_, ]*\\)" test_suite "${thefile}" ) - - if( NOT (test_suite STREQUAL "") ) - string(SUBSTRING "${test_suite}" 25 -1 test_suite) - string(FIND "${test_suite}" "," comma_loc ) - string(SUBSTRING "${test_suite}" 0 ${comma_loc} test_suite) - string(STRIP "${test_suite}" test_suite) - - string( REGEX MATCHALL "BOOST_AUTO_TEST_CASE\\([A-Za-z0-9_, ]*\\)" cases "${thefile}" ) - - foreach( test_case ${cases} ) - string(SUBSTRING "${test_case}" 22 -1 test_case) - string(FIND "${test_case}" ")" paren_loc ) - string(SUBSTRING "${test_case}" 0 ${paren_loc} test_case) - string(STRIP "${test_case}" test_case) - - list(APPEND tests "${test_suite}/${test_case}") - endforeach() - endif() - endforeach() - - set(${RESULT} ${tests} PARENT_SCOPE) -endfunction() - -parse_unit_tests(TEST_CASES ${UNIT_TESTS}) - -#message(STATUS "${TEST_CASES}") - -add_boost_test( chain_test - SOURCES ${UNIT_TESTS} - TESTS - automated_action_tests/push_pending_required_actions - automated_action_tests/push_pending_optional_actions - automated_action_tests/full_block - automated_action_tests/pending_required_execution - automated_action_tests/unexpected_required_action - automated_action_tests/missing_required_action - automated_action_tests/optional_action_expiration - automated_action_tests/unexpected_optional_action - automated_action_tests/reject_optional_action - basic_tests/parse_size_test - basic_tests/valid_name_test - basic_tests/merkle_root - operation_tests/account_create_validate - operation_tests/account_create_authorities - operation_tests/account_create_apply - operation_tests/account_update_validate - operation_tests/account_update_authorities - operation_tests/account_update_apply - operation_tests/comment_validate - operation_tests/comment_authorities - operation_tests/comment_apply - operation_tests/comment_delete_apply - operation_tests/vote_validate - operation_tests/vote_authorities - operation_tests/vote_apply - operation_tests/transfer_validate - operation_tests/transfer_authorities - operation_tests/signature_stripping - operation_tests/transfer_apply - operation_tests/transfer_to_vesting_validate - operation_tests/transfer_to_vesting_authorities - operation_tests/transfer_to_vesting_apply - operation_tests/withdraw_vesting_validate - operation_tests/withdraw_vesting_authorities - operation_tests/withdraw_vesting_apply - operation_tests/witness_update_validate - operation_tests/witness_update_authorities - operation_tests/witness_update_apply - operation_tests/account_witness_vote_validate - operation_tests/account_witness_vote_authorities - operation_tests/account_witness_vote_apply - operation_tests/account_witness_proxy_validate - operation_tests/account_witness_proxy_authorities - operation_tests/account_witness_proxy_apply - operation_tests/custom_authorities - operation_tests/custom_json_authorities - operation_tests/custom_binary_authorities - operation_tests/feed_publish_validate - operation_tests/feed_publish_authorities - operation_tests/feed_publish_apply - operation_tests/convert_validate - operation_tests/convert_authorities - operation_tests/convert_apply - operation_tests/fixture_convert_checks_balance - operation_tests/limit_order_create_validate - operation_tests/limit_order_create_authorities - operation_tests/limit_order_create_apply - operation_tests/limit_order_create2_authorities - operation_tests/limit_order_create2_apply - operation_tests/limit_order_cancel_validate - operation_tests/limit_order_cancel_authorities - operation_tests/limit_order_cancel_apply - operation_tests/pow_validate - operation_tests/pow_authorities - operation_tests/pow_apply - operation_tests/account_recovery - operation_tests/change_recovery_account - operation_tests/escrow_transfer_validate - operation_tests/escrow_transfer_authorities - operation_tests/escrow_transfer_apply - operation_tests/escrow_approve_validate - operation_tests/escrow_approve_authorities - operation_tests/escrow_approve_apply - operation_tests/escrow_dispute_validate - operation_tests/escrow_dispute_authorities - operation_tests/escrow_dispute_apply - operation_tests/escrow_release_validate - operation_tests/escrow_release_authorities - operation_tests/escrow_release_apply - operation_tests/transfer_to_savings_validate - operation_tests/transfer_to_savings_authorities - operation_tests/transfer_to_savings_apply - operation_tests/transfer_from_savings_validate - operation_tests/transfer_from_savings_authorities - operation_tests/transfer_from_savings_apply - operation_tests/cancel_transfer_from_savings_validate - operation_tests/cancel_transfer_from_savings_authorities - operation_tests/cancel_transfer_from_savings_apply - operation_tests/decline_voting_rights_authorities - operation_tests/decline_voting_rights_apply - operation_tests/claim_reward_balance_validate - operation_tests/claim_reward_balance_authorities - operation_tests/account_create_with_delegation_authorities - operation_tests/account_create_with_delegation_apply - operation_tests/claim_reward_balance_apply - operation_tests/delegate_vesting_shares_validate - operation_tests/delegate_vesting_shares_authorities - operation_tests/delegate_vesting_shares_apply - operation_tests/issue_971_vesting_removal - operation_tests/comment_beneficiaries_validate - operation_tests/comment_beneficiaries_apply - operation_tests/witness_set_properties_validate - operation_tests/witness_set_properties_authorities - operation_tests/witness_set_properties_apply - operation_tests/claim_account_validate - operation_tests/claim_account_authorities - operation_tests/claim_account_apply - operation_tests/create_claimed_account_validate - operation_tests/create_claimed_account_authorities - operation_tests/create_claimed_account_apply - operation_tests/account_auth_tests - operation_tests/account_update2_validate - operation_tests/account_update2_authorities - operation_tests/account_update2_apply - operation_time_tests/comment_payout_equalize - operation_time_tests/comment_payout_dust - operation_time_tests/recent_claims_decay - operation_time_tests/vesting_withdrawals - operation_time_tests/vesting_withdraw_route - operation_time_tests/feed_publish_mean - operation_time_tests/convert_delay - operation_time_tests/hive_inflation - operation_time_tests/hbd_interest - operation_time_tests/liquidity_rewards - operation_time_tests/post_rate_limit - operation_time_tests/comment_freeze - operation_time_tests/hbd_stability - operation_time_tests/hbd_price_feed_limit - operation_time_tests/clear_null_account - operation_time_tests/generate_account_subsidies - operation_time_tests/account_subsidy_witness_limits - proposal_tests/generating_payments - proposal_tests/generating_payments_01 - proposal_tests/generating_payments_02 - proposal_tests/generating_payments_03 - proposal_tests/proposals_maintenance - proposal_tests/proposal_object_apply - proposal_tests/proposal_vote_object_apply - proposal_tests/proposal_vote_object_01_apply - proposal_tests/create_proposal_000 - proposal_tests/create_proposal_001 - proposal_tests/create_proposal_002 - proposal_tests/create_proposal_003 - proposal_tests/create_proposal_004 - proposal_tests/create_proposal_005 - proposal_tests/create_proposal_006 - proposal_tests/create_proposal_007 - proposal_tests/create_proposal_008 - proposal_tests/update_proposal_votes_000 - proposal_tests/update_proposal_votes_001 - proposal_tests/update_proposal_votes_002 - proposal_tests/update_proposal_votes_003 - proposal_tests/update_proposal_votes_004 - proposal_tests/update_proposal_votes_005 - proposal_tests/update_proposal_votes_006 - proposal_tests/remove_proposal_000 - proposal_tests/remove_proposal_001 - proposal_tests/remove_proposal_002 - proposal_tests/remove_proposal_003 - proposal_tests/remove_proposal_004 - proposal_tests/remove_proposal_005 - proposal_tests/remove_proposal_006 - proposal_tests/remove_proposal_007 - proposal_tests/remove_proposal_008 - proposal_tests/remove_proposal_009 - proposal_tests/remove_proposal_010 - proposal_tests/remove_proposal_011 - proposal_tests/remove_proposal_012 - proposal_tests/proposals_maintenance_01 - proposal_tests/proposals_maintenance_02 - proposal_tests/proposals_removing_with_threshold - proposal_tests/proposals_removing_with_threshold_01 - proposal_tests/proposals_removing_with_threshold_02 - serialization_tests/serialization_raw_test - serialization_tests/serialization_json_test - serialization_tests/legacy_asset_test - serialization_tests/asset_test - serialization_tests/asset_raw_test - serialization_tests/json_tests - serialization_tests/extended_private_key_type_test - serialization_tests/extended_public_key_type_test - serialization_tests/version_test - serialization_tests/hardfork_version_test - serialization_tests/min_block_size - serialization_tests/legacy_signed_transaction - serialization_tests/static_variant_json_test - serialization_tests/legacy_operation_test - serialization_tests/asset_symbol_type_test - serialization_tests/unpack_clear_test - serialization_tests/unpack_recursion_test - undo_tests/undo_basic - undo_tests/undo_object_disappear - undo_tests/undo_key_collision - undo_tests/undo_different_indexes - undo_tests/undo_generate_blocks -) - -target_link_libraries( chain_test db_fixture chainbase hive_chain hive_protocol account_history_plugin market_history_plugin rc_plugin witness_plugin debug_node_plugin fc ${PLATFORM_SPECIFIC_LIBS} ) - -file(GLOB PLUGIN_TESTS "plugin_tests/*.cpp") - -parse_unit_tests(TEST_CASES ${PLUGIN_TESTS}) - -#message(STATUS "${TEST_CASES}") - -add_boost_test( plugin_test - SOURCES ${PLUGIN_TESTS} - TESTS - json_rpc/basic_validation - json_rpc/syntax_validation - json_rpc/misc_validation - json_rpc/positive_validation - json_rpc/semantics_validation - market_history/mh_test - transaction_status/transaction_status_test -) - -target_link_libraries( plugin_test db_fixture hive_chain hive_protocol account_history_plugin market_history_plugin rc_plugin witness_plugin debug_node_plugin transaction_status_plugin transaction_status_api_plugin fc ${PLATFORM_SPECIFIC_LIBS} ) - -if(MSVC) - set_source_files_properties( tests/serialization_tests.cpp PROPERTIES COMPILE_FLAGS "/bigobj" ) -endif(MSVC) - -#add_subdirectory( generate_empty_blocks ) diff --git a/tests2/unit/CopyResourcesToBuildTree.cmake b/tests2/unit/CopyResourcesToBuildTree.cmake deleted file mode 100644 index 3512cc48445b0a2f3ab1c9422edd1fbd3ffff3d3..0000000000000000000000000000000000000000 --- a/tests2/unit/CopyResourcesToBuildTree.cmake +++ /dev/null @@ -1,83 +0,0 @@ -# - Copy the resources your app needs to the build tree. -# -# copy_resources_to_build_tree(<target_name>) -# -# Requires CMake 2.6 or newer (uses the 'function' command) -# -# Original Author: -# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net> -# http://academic.cleardefinition.com -# Iowa State University HCI Graduate Program/VRAC -# -# Copyright Iowa State University 2009-2010. -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) - -if(__copy_resources_to_build_tree) - return() -endif() -set(__copy_resources_to_build_tree YES) - -function(copy_resources_to_build_tree _target) - get_target_property(_resources ${_target} RESOURCE) - if(NOT _resources) - # Bail if no resources - message(STATUS - "Told to copy resources for target ${_target}, but " - "no resources are set!") - return() - endif() - - get_target_property(_path ${_target} LOCATION) - get_filename_component(_path "${_path}" PATH) - - if(NOT MSVC AND NOT "${CMAKE_GENERATOR}" MATCHES "Makefiles") - foreach(_config ${CMAKE_CONFIGURATION_TYPES}) - get_target_property(_path${_config} ${_target} LOCATION_${_config}) - get_filename_component(_path${_config} "${_path${_config}}" PATH) - add_custom_command(TARGET ${_target} - POST_BUILD - COMMAND - ${CMAKE_COMMAND} - ARGS -E make_directory "${_path${_config}}/" - COMMENT "Creating directory ${_path${_config}}/") - endforeach() - endif() - - foreach(_res ${_resources}) - if(NOT IS_ABSOLUTE "${_res}") - get_filename_component(_res "${_res}" ABSOLUTE) - endif() - get_filename_component(_name "${_res}" NAME) - - if(MSVC) - # Working dir is solution file dir, not exe file dir. - add_custom_command(TARGET ${_target} - POST_BUILD - COMMAND - ${CMAKE_COMMAND} - ARGS -E copy "${_res}" "${CMAKE_BINARY_DIR}/" - COMMENT "Copying ${_name} to ${CMAKE_BINARY_DIR}/ for MSVC") - else() - if("${CMAKE_GENERATOR}" MATCHES "Makefiles") - add_custom_command(TARGET ${_target} - POST_BUILD - COMMAND - ${CMAKE_COMMAND} - ARGS -E copy "${_res}" "${_path}/" - COMMENT "Copying ${_name} to ${_path}/") - else() - foreach(_config ${CMAKE_CONFIGURATION_TYPES}) - add_custom_command(TARGET ${_target} - POST_BUILD - COMMAND - ${CMAKE_COMMAND} - ARGS -E copy "${_res}" "${_path${_config}}" - COMMENT "Copying ${_name} to ${_path${_config}}") - endforeach() - - endif() - endif() - endforeach() -endfunction() diff --git a/tests2/unit/GetForceIncludeDefinitions.cmake b/tests2/unit/GetForceIncludeDefinitions.cmake deleted file mode 100644 index efcca047b7ee2fb83de76ead25e489cd0eebc0ec..0000000000000000000000000000000000000000 --- a/tests2/unit/GetForceIncludeDefinitions.cmake +++ /dev/null @@ -1,44 +0,0 @@ -# - Get the platform-appropriate flags to add to force inclusion of a file -# -# The most common use of this is to use a generated config.h-type file -# placed out of the source tree in all files. -# -# get_force_include_definitions(var forcedincludefiles...) - -# where var is the name of your desired output variable, and everything -# else is a source file to forcibly include. -# a list item to be filtered. -# -# Original Author: -# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net> -# http://academic.cleardefinition.com -# Iowa State University HCI Graduate Program/VRAC -# -# Copyright Iowa State University 2009-2010. -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) - -if(__get_force_include_definitions) - return() -endif() -set(__get_force_include_definitions YES) - -function(get_force_include_definitions var) - set(_flagprefix) - if(CMAKE_COMPILER_IS_GNUCXX) - set(_flag "-include") - elseif(MSVC) - set(_flag "/FI") - else() - message(SEND_ERROR "You don't seem to be using MSVC or GCC, but") - message(SEND_ERROR "the project called get_force_include_definitions.") - message(SEND_ERROR "Contact this project with the name of your") - message(FATAL_ERROR "compiler and preferably the flag to force includes") - endif() - - set(_out) - foreach(_item ${ARGN}) - list(APPEND _out "${_flag} \"${_item}\"") - endforeach() - set(${var} "${_out}" PARENT_SCOPE) -endfunction() diff --git a/tests2/unit/bmic_objects/CMakeLists.txt b/tests2/unit/bmic_objects/CMakeLists.txt deleted file mode 100644 index 4fd49ffed56bef792cf212880b035c2235f8bf30..0000000000000000000000000000000000000000 --- a/tests2/unit/bmic_objects/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -find_package( Gperftools QUIET ) -if( GPERFTOOLS_FOUND ) - message( STATUS "Found gperftools; compiling tests with TCMalloc") - list( APPEND PLATFORM_SPECIFIC_LIBS tcmalloc ) -endif() - -add_library(bmic_manager_tests INTERFACE ) - -target_include_directories( bmic_manager_tests INTERFACE ./ ) diff --git a/tests2/unit/bmic_objects/bmic_manager_tests.hpp b/tests2/unit/bmic_objects/bmic_manager_tests.hpp deleted file mode 100644 index 18a6f66c3a3d58f0ca6113b7b5b3c3c6ac07b218..0000000000000000000000000000000000000000 --- a/tests2/unit/bmic_objects/bmic_manager_tests.hpp +++ /dev/null @@ -1,136 +0,0 @@ -#pragma once - -#include <boost/multi_index/composite_key.hpp> -#include <chainbase/util/object_id.hpp> - -#include <boost/multi_index_container.hpp> -#include <boost/multi_index/hashed_index.hpp> -#include <boost/multi_index/identity.hpp> -#include <boost/multi_index/member.hpp> -#include <boost/multi_index/ordered_index.hpp> -#include <boost/multi_index/random_access_index.hpp> -#include <boost/multi_index/sequenced_index.hpp> - -#include <algorithm> -#include <iostream> -#include <iterator> -#include <random> -#include <string> - -using namespace boost::multi_index; - -namespace bmic -{ - struct test_object - { - typedef chainbase::oid<test_object> id_type; - - template <class Constructor, class Allocator> - test_object( Constructor&& c, Allocator a ) - : id( 0 ), val( 0 ), name( a ) - { - c(*this); - } - - template <class Constructor, class Allocator> - test_object( Constructor&& c, int64_t _id, Allocator a ) - : id( _id ), val( 0 ), name( a ) - { - c(*this); - } - - id_type id; - uint32_t val; - std::string name; - }; - - struct OrderedIndex; - struct CompositeOrderedIndex; - - using test_object_index = boost::multi_index_container<test_object, - indexed_by< - ordered_unique< - tag<OrderedIndex>, member<test_object, test_object::id_type, &test_object::id>>, - ordered_unique< tag< CompositeOrderedIndex >, - composite_key< test_object, - member< test_object, std::string, &test_object::name >, - member< test_object, uint32_t, &test_object::val > - > - > - >, - std::allocator<test_object> - >; - - struct test_object2 - { - typedef chainbase::oid<test_object2> id_type; - - template <class Constructor, class Allocator> - test_object2( Constructor&& c, Allocator a ) - : id( 0 ), val( 0 ) - { - c(*this); - } - - id_type id; - uint32_t val; - }; - - struct OrderedIndex2; - struct CompositeOrderedIndex2; - - using test_object_index2 = boost::multi_index_container<test_object2, - indexed_by< - ordered_unique< - tag<OrderedIndex2>, member<test_object2, test_object2::id_type, &test_object2::id>>, - ordered_unique< tag< CompositeOrderedIndex2 >, - composite_key< test_object2, - member< test_object2, uint32_t, &test_object2::val >, - member<test_object2, test_object2::id_type, &test_object2::id> - > - > - >, - std::allocator<test_object2> - >; - - struct test_object3 - { - typedef chainbase::oid<test_object3> id_type; - - template <class Constructor, class Allocator> - test_object3( Constructor&& c, Allocator a ) - : id( 0 ), val( 0 ), val2( 0 ), val3( 0 ) - { - c(*this); - } - - id_type id; - uint32_t val; - uint32_t val2; - uint32_t val3; - }; - - struct OrderedIndex3; - struct CompositeOrderedIndex3a; - struct CompositeOrderedIndex3b; - - using test_object_index3 = boost::multi_index_container<test_object3, - indexed_by< - ordered_unique< - tag<OrderedIndex3>, member<test_object3, test_object3::id_type, &test_object3::id>>, - ordered_unique< tag< CompositeOrderedIndex3a>, - composite_key< test_object3, - member< test_object3, uint32_t, &test_object3::val >, - member< test_object3, uint32_t, &test_object3::val2 > - > - >, - ordered_unique< tag< CompositeOrderedIndex3b>, - composite_key< test_object3, - member< test_object3, uint32_t, &test_object3::val >, - member< test_object3, uint32_t, &test_object3::val3 > - > - > - >, - std::allocator<test_object3> - >; -} diff --git a/tests2/unit/db_fixture/CMakeLists.txt b/tests2/unit/db_fixture/CMakeLists.txt deleted file mode 100644 index 1e5055f120a7f51e1e5193b88fc1293677559c96..0000000000000000000000000000000000000000 --- a/tests2/unit/db_fixture/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -file(GLOB HEADERS "database_fixture.hpp") -set(SOURCES database_fixture.cpp) - -find_package( Gperftools QUIET ) -if( GPERFTOOLS_FOUND ) - message( STATUS "Found gperftools; compiling tests with TCMalloc") - list( APPEND PLATFORM_SPECIFIC_LIBS tcmalloc ) -endif() - -add_library(db_fixture - ${SOURCES} - ${HEADERS}) - -target_link_libraries(db_fixture - hive_chain - hive_protocol - account_history_plugin - market_history_plugin - block_api_plugin - database_api_plugin - rc_plugin - webserver_plugin - witness_plugin - debug_node_plugin - condenser_api_plugin - fc - ${PLATFORM_SPECIFIC_LIBS}) diff --git a/tests2/unit/db_fixture/database_fixture.cpp b/tests2/unit/db_fixture/database_fixture.cpp deleted file mode 100644 index ffb19c63974ac8da2d95852b84e8cfd41dfdbb91..0000000000000000000000000000000000000000 --- a/tests2/unit/db_fixture/database_fixture.cpp +++ /dev/null @@ -1,1508 +0,0 @@ -#include <boost/test/unit_test.hpp> -#include <boost/program_options.hpp> - -#include <hive/utilities/tempdir.hpp> -#include <hive/utilities/database_configuration.hpp> - -#include <hive/chain/history_object.hpp> -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/sps_objects.hpp> -#include <hive/chain/util/delayed_voting.hpp> - -#include <hive/plugins/account_history/account_history_plugin.hpp> -#include <hive/plugins/chain/chain_plugin.hpp> -#include <hive/plugins/rc/rc_plugin.hpp> -#include <hive/plugins/webserver/webserver_plugin.hpp> -#include <hive/plugins/witness/witness_plugin.hpp> - -#include <hive/plugins/condenser_api/condenser_api_plugin.hpp> - -#include <hive/chain/smt_objects/nai_pool_object.hpp> - -#include <fc/crypto/digest.hpp> -#include <fc/smart_ref_impl.hpp> - -#include <iostream> -#include <iomanip> -#include <sstream> - -#include "database_fixture.hpp" - -//using namespace hive::chain::test; - -uint32_t HIVE_TESTING_GENESIS_TIMESTAMP = 1431700000; - -using namespace hive::plugins::webserver; -using namespace hive::plugins::database_api; -using namespace hive::plugins::block_api; -using hive::plugins::condenser_api::condenser_api_plugin; - -namespace hive { namespace chain { - -using std::cout; -using std::cerr; - -clean_database_fixture::clean_database_fixture( uint16_t shared_file_size_in_mb ) -{ - try { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - appbase::app().register_plugin< hive::plugins::account_history::account_history_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - appbase::app().register_plugin< hive::plugins::rc::rc_plugin >(); - appbase::app().register_plugin< hive::plugins::witness::witness_plugin >(); - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::account_history::account_history_plugin, - hive::plugins::debug_node::debug_node_plugin, - hive::plugins::rc::rc_plugin, - hive::plugins::witness::witness_plugin - >( argc, argv ); - - hive::plugins::rc::rc_plugin_skip_flags rc_skip; - rc_skip.skip_reject_not_enough_rc = 1; - rc_skip.skip_deduct_rc = 0; - rc_skip.skip_negative_rc_balance = 1; - rc_skip.skip_reject_unknown_delta_vests = 0; - appbase::app().get_plugin< hive::plugins::rc::rc_plugin >().set_rc_plugin_skip_flags( rc_skip ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - init_account_pub_key = init_account_priv_key.get_public_key(); - - open_database( shared_file_size_in_mb ); - - generate_block(); - db->set_hardfork( HIVE_BLOCKCHAIN_VERSION.minor_v() ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - } catch ( const fc::exception& e ) - { - edump( (e.to_detail_string()) ); - throw; - } - - return; -} - -clean_database_fixture::~clean_database_fixture() -{ try { - // If we're unwinding due to an exception, don't do any more checks. - // This way, boost test's last checkpoint tells us approximately where the error was. - if( !std::uncaught_exception() ) - { - BOOST_CHECK( db->get_node_properties().skip_flags == database::skip_nothing ); - } - - if( data_dir ) - db->wipe( data_dir->path(), data_dir->path(), true ); - return; -} FC_CAPTURE_AND_LOG( () ) - exit(1); -} - -void clean_database_fixture::validate_database() -{ - database_fixture::validate_database(); - appbase::app().get_plugin< hive::plugins::rc::rc_plugin >().validate_database(); -} - -void clean_database_fixture::resize_shared_mem( uint64_t size ) -{ - db->wipe( data_dir->path(), data_dir->path(), true ); - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - init_account_pub_key = init_account_priv_key.get_public_key(); - - { - hive::chain::open_args args; - args.data_dir = data_dir->path(); - args.shared_mem_dir = args.data_dir; - args.initial_supply = INITIAL_TEST_SUPPLY; - args.hbd_initial_supply = HBD_INITIAL_TEST_SUPPLY; - args.shared_file_size = size; - args.database_cfg = hive::utilities::default_database_configuration(); - db->open( args ); - } - - boost::program_options::variables_map options; - - - generate_block(); - db->set_hardfork( HIVE_BLOCKCHAIN_VERSION.minor_v() ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); -} - -live_database_fixture::live_database_fixture() -{ - try - { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - - ilog( "Loading saved chain" ); - _chain_dir = fc::current_path() / "test_blockchain"; - FC_ASSERT( fc::exists( _chain_dir ), "Requires blockchain to test on in ./test_blockchain" ); - - appbase::app().register_plugin< hive::plugins::account_history::account_history_plugin >(); - appbase::app().initialize< - hive::plugins::account_history::account_history_plugin - >( argc, argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - { - hive::chain::open_args args; - args.data_dir = _chain_dir; - args.shared_mem_dir = args.data_dir; - args.database_cfg = hive::utilities::default_database_configuration(); - db->open( args ); - } - - validate_database(); - generate_block(); - - ilog( "Done loading saved chain" ); - } - FC_LOG_AND_RETHROW() -} - -live_database_fixture::~live_database_fixture() -{ - try - { - // If we're unwinding due to an exception, don't do any more checks. - // This way, boost test's last checkpoint tells us approximately where the error was. - if( !std::uncaught_exception() ) - { - BOOST_CHECK( db->get_node_properties().skip_flags == database::skip_nothing ); - } - - db->pop_block(); - db->close(); - return; - } - FC_CAPTURE_AND_LOG( () ) - exit(1); -} - -fc::ecc::private_key database_fixture::generate_private_key(string seed) -{ - static const fc::ecc::private_key committee = fc::ecc::private_key::regenerate( fc::sha256::hash( string( "init_key" ) ) ); - if( seed == "init_key" ) - return committee; - return fc::ecc::private_key::regenerate( fc::sha256::hash( seed ) ); -} - -#ifdef HIVE_ENABLE_SMT -asset_symbol_type database_fixture::get_new_smt_symbol( uint8_t token_decimal_places, chain::database* db ) -{ - // The list of available nais is not dependent on SMT desired precision (token_decimal_places). - static std::vector< asset_symbol_type >::size_type next_nai = 0; - auto available_nais = db->get< nai_pool_object >().pool(); - FC_ASSERT( available_nais.size() > 0, "No available nai returned by get_nai_pool." ); - const asset_symbol_type& new_nai = available_nais[ next_nai++ % available_nais.size() ]; - // Note that token's precision is needed now, when creating actual symbol. - return asset_symbol_type::from_nai( new_nai.to_nai(), token_decimal_places ); -} -#endif - -void database_fixture::open_database( uint16_t shared_file_size_in_mb ) -{ - if( !data_dir ) - { - data_dir = fc::temp_directory( hive::utilities::temp_directory_path() ); - db->_log_hardforks = false; - - idump( (data_dir->path()) ); - - hive::chain::open_args args; - args.data_dir = data_dir->path(); - args.shared_mem_dir = args.data_dir; - args.initial_supply = INITIAL_TEST_SUPPLY; - args.hbd_initial_supply = HBD_INITIAL_TEST_SUPPLY; - args.shared_file_size = 1024 * 1024 * shared_file_size_in_mb; // 8MB(default) or more: file for testing - args.database_cfg = hive::utilities::default_database_configuration(); - args.sps_remove_threshold = 20; - db->open(args); - } - else - { - idump( (data_dir->path()) ); - } -} - -void database_fixture::generate_block(uint32_t skip, const fc::ecc::private_key& key, int miss_blocks) -{ - skip |= default_skip; - db_plugin->debug_generate_blocks( hive::utilities::key_to_wif( key ), 1, skip, miss_blocks ); -} - -void database_fixture::generate_blocks( uint32_t block_count ) -{ - auto produced = db_plugin->debug_generate_blocks( debug_key, block_count, default_skip, 0 ); - BOOST_REQUIRE( produced == block_count ); -} - -void database_fixture::generate_blocks(fc::time_point_sec timestamp, bool miss_intermediate_blocks) -{ - db_plugin->debug_generate_blocks_until( debug_key, timestamp, miss_intermediate_blocks, default_skip ); - BOOST_REQUIRE( ( db->head_block_time() - timestamp ).to_seconds() < HIVE_BLOCK_INTERVAL ); -} - -void database_fixture::generate_days_blocks( uint32_t days, bool skip_interm_blocks ) -{ - fc::time_point_sec timestamp = db->head_block_time(); - timestamp += fc::days(days); - generate_blocks( timestamp, skip_interm_blocks ); -} - -fc::string database_fixture::get_current_time_iso_string() const -{ - fc::time_point_sec current_time = db->head_block_time(); - return current_time.to_iso_string(); -} - -const account_object& database_fixture::account_create( - const string& name, - const string& creator, - const private_key_type& creator_key, - const share_type& fee, - const public_key_type& key, - const public_key_type& post_key, - const string& json_metadata - ) -{ - try - { - auto actual_fee = std::min( fee, db->get_witness_schedule_object().median_props.account_creation_fee.amount ); - auto fee_remainder = fee - actual_fee; - - account_create_operation op; - op.new_account_name = name; - op.creator = creator; - op.fee = asset( actual_fee, HIVE_SYMBOL ); - op.owner = authority( 1, key, 1 ); - op.active = authority( 1, key, 1 ); - op.posting = authority( 1, post_key, 1 ); - op.memo_key = key; - op.json_metadata = json_metadata; - - trx.operations.push_back( op ); - - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( trx, creator_key ); - trx.validate(); - db->push_transaction( trx, 0 ); - trx.clear(); - - if( fee_remainder > 0 ) - { - vest( HIVE_INIT_MINER_NAME, name, asset( fee_remainder, HIVE_SYMBOL ) ); - } - - const account_object& acct = db->get_account( name ); - - return acct; - } - FC_CAPTURE_AND_RETHROW( (name)(creator) ) -} - -const account_object& database_fixture::account_create( - const string& name, - const public_key_type& key, - const public_key_type& post_key -) -{ - try - { - return account_create( - name, - HIVE_INIT_MINER_NAME, - init_account_priv_key, - std::max( db->get_witness_schedule_object().median_props.account_creation_fee.amount * HIVE_CREATE_ACCOUNT_WITH_HIVE_MODIFIER, share_type( 100 ) ), - key, - post_key, - "" ); - } - FC_CAPTURE_AND_RETHROW( (name) ); -} - -const account_object& database_fixture::account_create( - const string& name, - const public_key_type& key -) -{ - return account_create( name, key, key ); -} - -const witness_object& database_fixture::witness_create( - const string& owner, - const private_key_type& owner_key, - const string& url, - const public_key_type& signing_key, - const share_type& fee ) -{ - try - { - witness_update_operation op; - op.owner = owner; - op.url = url; - op.block_signing_key = signing_key; - op.fee = asset( fee, HIVE_SYMBOL ); - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( trx, owner_key ); - trx.validate(); - db->push_transaction( trx, 0 ); - trx.clear(); - - return db->get_witness( owner ); - } - FC_CAPTURE_AND_RETHROW( (owner)(url) ) -} - -void database_fixture::fund( - const string& account_name, - const share_type& amount - ) -{ - try - { - transfer( HIVE_INIT_MINER_NAME, account_name, asset( amount, HIVE_SYMBOL ) ); - - } FC_CAPTURE_AND_RETHROW( (account_name)(amount) ) -} - -void database_fixture::fund( - const string& account_name, - const asset& amount - ) -{ - try - { - db_plugin->debug_update( [=]( database& db) - { - if( amount.symbol.space() == asset_symbol_type::smt_nai_space ) - { - db.adjust_balance(account_name, amount); - db.adjust_supply(amount); - // Note that SMT have no equivalent of HBD, hence no virtual supply, hence no need to update it. - return; - } - - db.modify( db.get_account( account_name ), [&]( account_object& a ) - { - if( amount.symbol == HIVE_SYMBOL ) - a.balance += amount; - else if( amount.symbol == HBD_SYMBOL ) - { - a.hbd_balance += amount; - a.hbd_seconds_last_update = db.head_block_time(); - } - }); - - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - if( amount.symbol == HIVE_SYMBOL ) - gpo.current_supply += amount; - else if( amount.symbol == HBD_SYMBOL ) - gpo.current_hbd_supply += amount; - }); - - if( amount.symbol == HBD_SYMBOL ) - { - const auto& median_feed = db.get_feed_history(); - if( median_feed.current_median_history.is_null() ) - db.modify( median_feed, [&]( feed_history_object& f ) - { - f.current_median_history = price( asset( 1, HBD_SYMBOL ), asset( 1, HIVE_SYMBOL ) ); - }); - } - - db.update_virtual_supply(); - }, default_skip ); - } - FC_CAPTURE_AND_RETHROW( (account_name)(amount) ) -} - -void database_fixture::convert( - const string& account_name, - const asset& amount ) -{ - try - { - if ( amount.symbol == HIVE_SYMBOL ) - { - db->adjust_balance( account_name, -amount ); - db->adjust_balance( account_name, db->to_hbd( amount ) ); - db->adjust_supply( -amount ); - db->adjust_supply( db->to_hbd( amount ) ); - } - else if ( amount.symbol == HBD_SYMBOL ) - { - db->adjust_balance( account_name, -amount ); - db->adjust_balance( account_name, db->to_hive( amount ) ); - db->adjust_supply( -amount ); - db->adjust_supply( db->to_hive( amount ) ); - } - } FC_CAPTURE_AND_RETHROW( (account_name)(amount) ) -} - -void database_fixture::transfer( - const string& from, - const string& to, - const asset& amount ) -{ - try - { - transfer_operation op; - op.from = from; - op.to = to; - op.amount = amount; - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.validate(); - - if( from == HIVE_INIT_MINER_NAME ) - { - sign( trx, init_account_priv_key ); - } - - db->push_transaction( trx, ~0 ); - trx.clear(); - } FC_CAPTURE_AND_RETHROW( (from)(to)(amount) ) -} - -void database_fixture::vest( const string& from, const string& to, const asset& amount ) -{ - try - { - FC_ASSERT( amount.symbol == HIVE_SYMBOL, "Can only vest TESTS" ); - - transfer_to_vesting_operation op; - op.from = from; - op.to = to; - op.amount = amount; - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.validate(); - - // This sign() call fixes some tests, like withdraw_vesting_apply, that use this method - // with debug_plugin such that trx may be re-applied with less generous skip flags. - if( from == HIVE_INIT_MINER_NAME ) - { - sign( trx, init_account_priv_key ); - } - - db->push_transaction( trx, ~0 ); - trx.clear(); - } FC_CAPTURE_AND_RETHROW( (from)(to)(amount) ) -} - -void database_fixture::vest( const string& from, const share_type& amount ) -{ - try - { - transfer_to_vesting_operation op; - op.from = from; - op.to = ""; - op.amount = asset( amount, HIVE_SYMBOL ); - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.validate(); - - if( from == HIVE_INIT_MINER_NAME ) - { - sign( trx, init_account_priv_key ); - } - - db->push_transaction( trx, ~0 ); - trx.clear(); - } FC_CAPTURE_AND_RETHROW( (from)(amount) ) -} - -void database_fixture::proxy( const string& account, const string& proxy ) -{ - try - { - account_witness_proxy_operation op; - op.account = account; - op.proxy = proxy; - trx.operations.push_back( op ); - trx.set_expiration(db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION); - db->push_transaction( trx, ~0 ); - trx.clear(); - } FC_CAPTURE_AND_RETHROW( (account)(proxy) ) -} - -void database_fixture::set_price_feed( const price& new_price ) -{ - for( size_t i = 1; i < 8; i++ ) - { - witness_set_properties_operation op; - op.owner = HIVE_INIT_MINER_NAME + fc::to_string( i ); - op.props[ "hbd_exchange_rate" ] = fc::raw::pack_to_vector( new_price ); - op.props[ "key" ] = fc::raw::pack_to_vector( init_account_pub_key ); - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - db->push_transaction( trx, ~0 ); - trx.clear(); - } - - generate_blocks( HIVE_BLOCKS_PER_HOUR ); - - BOOST_REQUIRE( -#ifdef IS_TEST_NET - !db->skip_price_feed_limit_check || -#endif - db->get(feed_history_id_type()).current_median_history == new_price - ); -} - -void database_fixture::set_witness_props( const flat_map< string, vector< char > >& props ) -{ - trx.clear(); - for( size_t i=0; i<HIVE_MAX_WITNESSES; i++ ) - { - witness_set_properties_operation op; - op.owner = HIVE_INIT_MINER_NAME + (i == 0 ? "" : fc::to_string( i )); - op.props = props; - if( props.find( "key" ) == props.end() ) - op.props["key"] = fc::raw::pack_to_vector( init_account_pub_key ); - - trx.operations.push_back( op ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - db->push_transaction( trx, ~0 ); - trx.clear(); - } - - const witness_schedule_object* wso = &(db->get_witness_schedule_object()); - uint32_t old_next_shuffle = wso->next_shuffle_block_num; - - for( size_t i=0; i<2*HIVE_MAX_WITNESSES+1; i++ ) - { - generate_block(); - wso = &(db->get_witness_schedule_object()); - if( wso->next_shuffle_block_num != old_next_shuffle ) - return; - } - FC_ASSERT( false, "Couldn't apply properties in ${n} blocks", ("n", 2*HIVE_MAX_WITNESSES+1) ); -} - -account_id_type database_fixture::get_account_id( const string& account_name )const -{ - return db->get_account( account_name ).get_id(); -} - -asset database_fixture::get_balance( const string& account_name )const -{ - return db->get_account( account_name ).get_balance(); -} - -asset database_fixture::get_hbd_balance( const string& account_name )const -{ - return db->get_account( account_name ).get_hbd_balance(); -} - -asset database_fixture::get_savings( const string& account_name )const -{ - return db->get_account( account_name ).get_savings(); -} - -asset database_fixture::get_hbd_savings( const string& account_name )const -{ - return db->get_account( account_name ).get_hbd_savings(); -} - -asset database_fixture::get_rewards( const string& account_name )const -{ - return db->get_account( account_name ).get_rewards(); -} - -asset database_fixture::get_hbd_rewards( const string& account_name )const -{ - return db->get_account( account_name ).get_hbd_rewards(); -} - -asset database_fixture::get_vesting( const string& account_name )const -{ - return db->get_account( account_name ).get_vesting(); -} - -asset database_fixture::get_vest_rewards( const string& account_name )const -{ - return db->get_account( account_name ).get_vest_rewards(); -} - -asset database_fixture::get_vest_rewards_as_hive( const string& account_name )const -{ - return db->get_account( account_name ).get_vest_rewards_as_hive(); -} - -void database_fixture::sign(signed_transaction& trx, const fc::ecc::private_key& key) -{ - trx.sign( key, db->get_chain_id(), default_sig_canon ); -} - -vector< operation > database_fixture::get_last_operations( uint32_t num_ops ) -{ - vector< operation > ops; - const auto& acc_hist_idx = db->get_index< account_history_index >().indices().get< by_id >(); - auto itr = acc_hist_idx.end(); - - while( itr != acc_hist_idx.begin() && ops.size() < num_ops ) - { - itr--; - const buffer_type& _serialized_op = db->get(itr->op).serialized_op; - std::vector<char> serialized_op; - serialized_op.reserve( _serialized_op.size() ); - std::copy( _serialized_op.begin(), _serialized_op.end(), std::back_inserter( serialized_op ) ); - ops.push_back( fc::raw::unpack_from_vector< hive::chain::operation >( serialized_op ) ); - } - - return ops; -} - -void database_fixture::validate_database() -{ - try - { - db->validate_invariants(); -#ifdef HIVE_ENABLE_SMT - db->validate_smt_invariants(); -#endif - } - FC_LOG_AND_RETHROW(); -} - -#ifdef HIVE_ENABLE_SMT - -template< typename T > -asset_symbol_type t_smt_database_fixture< T >::create_smt_with_nai( const string& account_name, const fc::ecc::private_key& key, - uint32_t nai, uint8_t token_decimal_places ) -{ - smt_create_operation op; - signed_transaction tx; - try - { - fund( account_name, 10 * 1000 * 1000 ); - this->generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - convert( account_name, ASSET( "5000.000 TESTS" ) ); - - op.symbol = asset_symbol_type::from_nai( nai, token_decimal_places ); - op.precision = op.symbol.decimals(); - op.smt_creation_fee = this->db->get_dynamic_global_properties().smt_creation_fee; - op.control_account = account_name; - - tx.operations.push_back( op ); - tx.set_expiration( this->db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.sign( key, this->db->get_chain_id(), fc::ecc::bip_0062 ); - - this->db->push_transaction( tx, 0 ); - - this->generate_block(); - } - FC_LOG_AND_RETHROW(); - - return op.symbol; -} - -template< typename T > -asset_symbol_type t_smt_database_fixture< T >::create_smt( const string& account_name, const fc::ecc::private_key& key, - uint8_t token_decimal_places ) -{ - asset_symbol_type symbol; - try - { - auto nai_symbol = this->get_new_smt_symbol( token_decimal_places, this->db ); - symbol = create_smt_with_nai( account_name, key, nai_symbol.to_nai(), token_decimal_places ); - } - FC_LOG_AND_RETHROW(); - - return symbol; -} - -void sub_set_create_op( smt_create_operation* op, account_name_type control_acount, chain::database& db ) -{ - op->precision = op->symbol.decimals(); - op->smt_creation_fee = db.get_dynamic_global_properties().smt_creation_fee; - op->control_account = control_acount; -} - -void set_create_op( smt_create_operation* op, account_name_type control_account, uint8_t token_decimal_places, chain::database& db ) -{ - op->symbol = database_fixture::get_new_smt_symbol( token_decimal_places, &db ); - sub_set_create_op( op, control_account, db ); -} - -void set_create_op( smt_create_operation* op, account_name_type control_account, uint32_t token_nai, uint8_t token_decimal_places, chain::database& db ) -{ - op->symbol.from_nai(token_nai, token_decimal_places); - sub_set_create_op( op, control_account, db ); -} - -template< typename T > -std::array<asset_symbol_type, 3> t_smt_database_fixture< T >::create_smt_3(const char* control_account_name, const fc::ecc::private_key& key) -{ - smt_create_operation op0; - smt_create_operation op1; - smt_create_operation op2; - - try - { - fund( control_account_name, 10 * 1000 * 1000 ); - this->generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - convert( control_account_name, ASSET( "5000.000 TESTS" ) ); - - set_create_op( &op0, control_account_name, 0, *this->db ); - set_create_op( &op1, control_account_name, 1, *this->db ); - set_create_op( &op2, control_account_name, 1, *this->db ); - - signed_transaction tx; - tx.operations.push_back( op0 ); - tx.operations.push_back( op1 ); - tx.operations.push_back( op2 ); - tx.set_expiration( this->db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.sign( key, this->db->get_chain_id(), fc::ecc::bip_0062 ); - this->db->push_transaction( tx, 0 ); - - this->generate_block(); - - std::array<asset_symbol_type, 3> retVal; - retVal[0] = op0.symbol; - retVal[1] = op1.symbol; - retVal[2] = op2.symbol; - std::sort(retVal.begin(), retVal.end(), - [](const asset_symbol_type & a, const asset_symbol_type & b) -> bool - { - return a.to_nai() < b.to_nai(); - }); - return retVal; - } - FC_LOG_AND_RETHROW(); -} - -void push_invalid_operation(const operation& invalid_op, const fc::ecc::private_key& key, database* db) -{ - signed_transaction tx; - tx.operations.push_back( invalid_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.sign( key, db->get_chain_id(), fc::ecc::bip_0062 ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::assert_exception ); -} - -template< typename T > -void t_smt_database_fixture< T >::create_invalid_smt( const char* control_account_name, const fc::ecc::private_key& key ) -{ - // Fail due to precision too big. - smt_create_operation op_precision; - HIVE_REQUIRE_THROW( set_create_op( &op_precision, control_account_name, HIVE_ASSET_MAX_DECIMALS + 1, *this->db ), fc::assert_exception ); -} - -template< typename T > -void t_smt_database_fixture< T >::create_conflicting_smt( const asset_symbol_type existing_smt, const char* control_account_name, - const fc::ecc::private_key& key ) -{ - // Fail due to the same nai & precision. - smt_create_operation op_same; - set_create_op( &op_same, control_account_name, existing_smt.to_nai(), existing_smt.decimals(), *this->db ); - push_invalid_operation( op_same, key, this->db ); - // Fail due to the same nai (though different precision). - smt_create_operation op_same_nai; - set_create_op( &op_same_nai, control_account_name, existing_smt.to_nai(), existing_smt.decimals() == 0 ? 1 : 0, *this->db ); - push_invalid_operation (op_same_nai, key, this->db ); -} - -template< typename T > -smt_generation_unit t_smt_database_fixture< T >::get_generation_unit( const units& hive_unit, const units& token_unit ) -{ - smt_generation_unit ret; - - ret.hive_unit = hive_unit; - ret.token_unit = token_unit; - - return ret; -} - -template< typename T > -smt_capped_generation_policy t_smt_database_fixture< T >::get_capped_generation_policy -( - const smt_generation_unit& pre_soft_cap_unit, - const smt_generation_unit& post_soft_cap_unit, - uint16_t soft_cap_percent, - uint32_t min_unit_ratio, - uint32_t max_unit_ratio -) -{ - smt_capped_generation_policy ret; - - ret.pre_soft_cap_unit = pre_soft_cap_unit; - ret.post_soft_cap_unit = post_soft_cap_unit; - - ret.soft_cap_percent = soft_cap_percent; - - ret.min_unit_ratio = min_unit_ratio; - ret.max_unit_ratio = max_unit_ratio; - - return ret; -} - -template asset_symbol_type t_smt_database_fixture< clean_database_fixture >::create_smt( const string& account_name, const fc::ecc::private_key& key, uint8_t token_decimal_places ); - -template asset_symbol_type t_smt_database_fixture< database_fixture >::create_smt( const string& account_name, const fc::ecc::private_key& key, uint8_t token_decimal_places ); - -template void t_smt_database_fixture< clean_database_fixture >::create_invalid_smt( const char* control_account_name, const fc::ecc::private_key& key ); -template void t_smt_database_fixture< clean_database_fixture >::create_conflicting_smt( const asset_symbol_type existing_smt, const char* control_account_name, const fc::ecc::private_key& key ); -template std::array<asset_symbol_type, 3> t_smt_database_fixture< clean_database_fixture >::create_smt_3( const char* control_account_name, const fc::ecc::private_key& key ); - -template smt_generation_unit t_smt_database_fixture< clean_database_fixture >::get_generation_unit( const units& hive_unit, const units& token_unit ); -template smt_capped_generation_policy t_smt_database_fixture< clean_database_fixture >::get_capped_generation_policy -( - const smt_generation_unit& pre_soft_cap_unit, - const smt_generation_unit& post_soft_cap_unit, - uint16_t soft_cap_percent, - uint32_t min_unit_ratio, - uint32_t max_unit_ratio -); - -#endif - -void sps_proposal_database_fixture::plugin_prepare() -{ - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - init_account_pub_key = init_account_priv_key.get_public_key(); - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::debug_node::debug_node_plugin - >( argc, argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - open_database(); - - generate_block(); - db->set_hardfork( HIVE_NUM_HARDFORKS ); - generate_block(); - - - validate_database(); -} - -int64_t sps_proposal_database_fixture::create_proposal( std::string creator, std::string receiver, - time_point_sec start_date, time_point_sec end_date, - asset daily_pay, const fc::ecc::private_key& key ) -{ - signed_transaction tx; - create_proposal_operation op; - - op.creator = creator; - op.receiver = receiver; - - op.start_date = start_date; - op.end_date = end_date; - - op.daily_pay = daily_pay; - - static uint32_t cnt = 0; - op.subject = std::to_string( cnt ); - - const std::string permlink = "permlink" + std::to_string( cnt ); - post_comment(creator, permlink, "title", "body", "test", key); - - op.permlink = permlink; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, key ); - db->push_transaction( tx, 0 ); - tx.signatures.clear(); - tx.operations.clear(); - - const auto& proposal_idx = db-> template get_index< proposal_index >().indices(). template get< by_proposal_id >(); - auto itr = proposal_idx.end(); - BOOST_REQUIRE( proposal_idx.begin() != itr ); - --itr; - BOOST_REQUIRE( creator == itr->creator ); - - //An unique subject is generated by cnt - ++cnt; - - return itr->proposal_id; -} - -void sps_proposal_database_fixture::update_proposal(uint64_t proposal_id, std::string creator, - asset daily_pay, std::string subject, std::string permlink, - const fc::ecc::private_key& key ) -{ - signed_transaction tx; - update_proposal_operation op; - - op.proposal_id = proposal_id; - op.creator = creator; - op.daily_pay = daily_pay; - op.subject = subject; - op.permlink = permlink; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, key ); - db->push_transaction( tx, 0 ); - tx.signatures.clear(); - tx.operations.clear(); -} - -void sps_proposal_database_fixture::vote_proposal( std::string voter, const std::vector< int64_t >& id_proposals, bool approve, const fc::ecc::private_key& key ) -{ - update_proposal_votes_operation op; - - op.voter = voter; - op.proposal_ids.insert(id_proposals.cbegin(), id_proposals.cend()); - op.approve = approve; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, key ); - db->push_transaction( tx, 0 ); -} - -bool sps_proposal_database_fixture::exist_proposal( int64_t id ) -{ - const auto& proposal_idx = db->get_index< proposal_index >().indices(). template get< by_proposal_id >(); - return proposal_idx.find( id ) != proposal_idx.end(); -} - -const proposal_object* sps_proposal_database_fixture::find_proposal( int64_t id ) -{ - const auto& proposal_idx = db->get_index< proposal_index >().indices(). template get< by_proposal_id >(); - auto found = proposal_idx.find( id ); - - if( found != proposal_idx.end() ) - return &(*found); - else - return nullptr; -} - -void sps_proposal_database_fixture::remove_proposal(account_name_type _deleter, flat_set<int64_t> _proposal_id, const fc::ecc::private_key& _key) -{ - remove_proposal_operation rp; - rp.proposal_owner = _deleter; - rp.proposal_ids = _proposal_id; - - signed_transaction trx; - trx.operations.push_back( rp ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( trx, _key ); - db->push_transaction( trx, 0 ); - trx.signatures.clear(); - trx.operations.clear(); -} - -bool sps_proposal_database_fixture::find_vote_for_proposal(const std::string& _user, int64_t _proposal_id) -{ - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices(). template get< by_voter_proposal >(); - auto found_vote = proposal_vote_idx.find( boost::make_tuple(_user, _proposal_id ) ); - return found_vote != proposal_vote_idx.end(); -} - -uint64_t sps_proposal_database_fixture::get_nr_blocks_until_maintenance_block() -{ - auto block_time = db->head_block_time(); - - auto next_maintenance_time = db->get_dynamic_global_properties().next_maintenance_time; - auto ret = ( next_maintenance_time - block_time ).to_seconds() / HIVE_BLOCK_INTERVAL; - - FC_ASSERT( next_maintenance_time >= block_time ); - - return ret; -} - -void sps_proposal_database_fixture::post_comment( std::string _authro, std::string _permlink, std::string _title, std::string _body, std::string _parent_permlink, const fc::ecc::private_key& _key) -{ - generate_blocks( db->head_block_time() + HIVE_MIN_ROOT_COMMENT_INTERVAL + fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - comment_operation comment; - - comment.author = _authro; - comment.permlink = _permlink; - comment.title = _title; - comment.body = _body; - comment.parent_permlink = _parent_permlink; - - signed_transaction trx; - trx.operations.push_back( comment ); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( trx, _key ); - db->push_transaction( trx, 0 ); - trx.signatures.clear(); - trx.operations.clear(); -} - -void hf23_database_fixture::push_transaction( const operation& op, const fc::ecc::private_key& key ) -{ - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, key ); - db->push_transaction( tx, 0 ); -} - -void hf23_database_fixture::vest( const string& from, const string& to, const asset& amount, const fc::ecc::private_key& key ) -{ - FC_ASSERT( amount.symbol == HIVE_SYMBOL, "Can only vest TESTS" ); - - transfer_to_vesting_operation op; - op.from = from; - op.to = to; - op.amount = amount; - - push_transaction( op, key ); -} - -void hf23_database_fixture::delegate_vest( const string& delegator, const string& delegatee, const asset& amount, const fc::ecc::private_key& key ) -{ - delegate_vesting_shares_operation op; - op.vesting_shares = amount; - op.delegator = delegator; - op.delegatee = delegatee; - - push_transaction( op, key ); -} - -void delayed_vote_database_fixture::push_transaction( const operation& op, const fc::ecc::private_key& key ) -{ - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, key ); - db->push_transaction( tx, 0 ); -} - -void delayed_vote_database_fixture::witness_vote( const std::string& account, const std::string& witness, const bool approve, const fc::ecc::private_key& key ) -{ - account_witness_vote_operation op; - - op.account = account; - op.witness = witness; - op.approve = approve; - - push_transaction( op, key ); -} - -void delayed_vote_database_fixture::vest( const string& from, const string& to, const asset& amount, const fc::ecc::private_key& key ) -{ - FC_ASSERT( amount.symbol == HIVE_SYMBOL, "Can only vest TESTS" ); - - transfer_to_vesting_operation op; - op.from = from; - op.to = to; - op.amount = amount; - - push_transaction( op, key ); -} - -void delayed_vote_database_fixture::decline_voting_rights( const string& account, const bool decline, const fc::ecc::private_key& key ) -{ - decline_voting_rights_operation op; - op.account = account; - op.decline = decline; - - push_transaction( op, key ); -} - -time_point_sec delayed_vote_database_fixture::move_forward_with_update( const fc::microseconds& time, delayed_voting::opt_votes_update_data_items& items ) -{ - std::vector<std::pair<account_name_type,votes_update_data> > tmp; - tmp.reserve( items->size() ); - - for(const votes_update_data& var : *items) - tmp.emplace_back(var.account->name, var); - - items->clear(); - - generate_blocks( db->head_block_time() + time ); - - for(const auto& var : tmp) - { - auto x = var.second; - x.account = &db->get_account(var.first); - items->insert(x); - } - - return db->head_block_time(); -}; - -void delayed_vote_database_fixture::withdraw_vesting( const string& account, const asset& amount, const fc::ecc::private_key& key ) -{ - FC_ASSERT( amount.symbol == VESTS_SYMBOL, "Can only withdraw VESTS"); - - withdraw_vesting_operation op; - op.account = account; - op.vesting_shares = amount; - - push_transaction( op, key ); -} - -void delayed_vote_database_fixture::proxy( const string& account, const string& proxy, const fc::ecc::private_key& key ) -{ - account_witness_proxy_operation op; - op.account = account; - op.proxy = proxy; - trx.operations.push_back( op ); - - push_transaction( op, key ); -} - -share_type delayed_vote_database_fixture::get_votes( const string& witness_name ) -{ - const auto& idx = db->get_index< witness_index >().indices().get< by_name >(); - auto found = idx.find( witness_name ); - - if( found == idx.end() ) - return 0; - else - return found->votes.value; -} - -int32_t delayed_vote_database_fixture::get_user_voted_witness_count( const account_name_type& name ) -{ - int32_t res = 0; - - const auto& vidx = db->get_index< witness_vote_index >().indices().get<by_account_witness>(); - auto itr = vidx.lower_bound( boost::make_tuple( name, account_name_type() ) ); - while( itr != vidx.end() && itr->account == name ) - { - ++itr; - ++res; - } - return res; -} - -asset delayed_vote_database_fixture::to_vest( const asset& liquid, const bool to_reward_balance ) -{ - const auto& cprops = db->get_dynamic_global_properties(); - price vesting_share_price = to_reward_balance ? cprops.get_reward_vesting_share_price() : cprops.get_vesting_share_price(); - - return liquid * ( vesting_share_price ); -} - -template< typename COLLECTION > -fc::optional< size_t > delayed_vote_database_fixture::get_position_in_delayed_voting_array( const COLLECTION& collection, size_t day, size_t minutes ) -{ - if( collection.empty() ) - return fc::optional< size_t >(); - - auto time = collection[ 0 ].time + fc::days( day ) + fc::minutes( minutes ); - - size_t idx = 0; - for( auto& item : collection ) - { - auto end_of_day = item.time + fc::days( 1 ); - - if( end_of_day > time ) - return idx; - - ++idx; - } - - return fc::optional< size_t >(); -} - -template< typename COLLECTION > -bool delayed_vote_database_fixture::check_collection( const COLLECTION& collection, ushare_type idx, const fc::time_point_sec& time, const ushare_type val ) -{ - if( idx.value >= collection.size() ) - return false; - else - { - bool check_time = collection[ idx.value ].time == time; - bool check_val = collection[ idx.value ].val == val; - return check_time && check_val; - } -} - -template< typename COLLECTION > -bool delayed_vote_database_fixture::check_collection( const COLLECTION& collection, const bool withdraw_executor, const share_type val, const account_object& obj ) -{ - auto found = collection->find( { withdraw_executor, val, &obj } ); - if( found == collection->end() ) - return false; - - if( !found->account ) - return false; - return ( found->withdraw_executor == withdraw_executor ) && ( found->val == val ) && ( found->account->get_id() == obj.get_id() ); -} - -using dvd_vector = std::vector< delayed_votes_data >; -using bip_dvd_vector = chainbase::t_vector< delayed_votes_data >; - -template fc::optional< size_t > delayed_vote_database_fixture::get_position_in_delayed_voting_array< bip_dvd_vector >( const bip_dvd_vector& collection, size_t day, size_t minutes ); -template bool delayed_vote_database_fixture::check_collection< dvd_vector >( const dvd_vector& collection, ushare_type idx, const fc::time_point_sec& time, const ushare_type val ); -#ifndef ENABLE_MIRA -template bool delayed_vote_database_fixture::check_collection< bip_dvd_vector >( const bip_dvd_vector& collection, ushare_type idx, const fc::time_point_sec& time, const ushare_type val ); -#endif -template bool delayed_vote_database_fixture::check_collection< delayed_voting::opt_votes_update_data_items >( const delayed_voting::opt_votes_update_data_items& collection, const bool withdraw_executor, const share_type val, const account_object& obj ); - -json_rpc_database_fixture::json_rpc_database_fixture() -{ - try { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - appbase::app().register_plugin< hive::plugins::account_history::account_history_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - appbase::app().register_plugin< hive::plugins::witness::witness_plugin >(); - rpc_plugin = &appbase::app().register_plugin< hive::plugins::json_rpc::json_rpc_plugin >(); - appbase::app().register_plugin< hive::plugins::block_api::block_api_plugin >(); - appbase::app().register_plugin< hive::plugins::database_api::database_api_plugin >(); - appbase::app().register_plugin< hive::plugins::condenser_api::condenser_api_plugin >(); - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::account_history::account_history_plugin, - hive::plugins::debug_node::debug_node_plugin, - hive::plugins::json_rpc::json_rpc_plugin, - hive::plugins::block_api::block_api_plugin, - hive::plugins::database_api::database_api_plugin, - hive::plugins::condenser_api::condenser_api_plugin - >( argc, argv ); - - appbase::app().get_plugin< hive::plugins::condenser_api::condenser_api_plugin >().plugin_startup(); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - init_account_pub_key = init_account_priv_key.get_public_key(); - - open_database(); - - generate_block(); - db->set_hardfork( HIVE_BLOCKCHAIN_VERSION.minor_v() ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - } catch ( const fc::exception& e ) - { - edump( (e.to_detail_string()) ); - throw; - } - - return; -} - -json_rpc_database_fixture::~json_rpc_database_fixture() -{ - // If we're unwinding due to an exception, don't do any more checks. - // This way, boost test's last checkpoint tells us approximately where the error was. - if( !std::uncaught_exception() ) - { - BOOST_CHECK( db->get_node_properties().skip_flags == database::skip_nothing ); - } - - if( data_dir ) - db->wipe( data_dir->path(), data_dir->path(), true ); - return; -} - -fc::variant json_rpc_database_fixture::get_answer( std::string& request ) -{ - return fc::json::from_string( rpc_plugin->call( request ) ); -} - -void check_id_equal( const fc::variant& id_a, const fc::variant& id_b ) -{ - BOOST_REQUIRE( id_a.get_type() == id_b.get_type() ); - - switch( id_a.get_type() ) - { - case fc::variant::int64_type: - BOOST_REQUIRE( id_a.as_int64() == id_b.as_int64() ); - break; - case fc::variant::uint64_type: - BOOST_REQUIRE( id_a.as_uint64() == id_b.as_uint64() ); - break; - case fc::variant::string_type: - BOOST_REQUIRE( id_a.as_string() == id_b.as_string() ); - break; - case fc::variant::null_type: - break; - default: - BOOST_REQUIRE( false ); - } -} - -void json_rpc_database_fixture::review_answer( fc::variant& answer, int64_t code, bool is_warning, bool is_fail, fc::optional< fc::variant > id ) -{ - fc::variant_object error; - int64_t answer_code; - - if( is_fail ) - { - if( id.valid() && code != JSON_RPC_INVALID_REQUEST ) - { - BOOST_REQUIRE( answer.get_object().contains( "id" ) ); - check_id_equal( answer[ "id" ], *id ); - } - - BOOST_REQUIRE( answer.get_object().contains( "error" ) ); - BOOST_REQUIRE( answer["error"].is_object() ); - error = answer["error"].get_object(); - BOOST_REQUIRE( error.contains( "code" ) ); - BOOST_REQUIRE( error["code"].is_int64() ); - answer_code = error["code"].as_int64(); - BOOST_REQUIRE( answer_code == code ); - if( is_warning ) - BOOST_TEST_MESSAGE( error["message"].as_string() ); - } - else - { - BOOST_REQUIRE( answer.get_object().contains( "result" ) ); - BOOST_REQUIRE( answer.get_object().contains( "id" ) ); - if( id.valid() ) - check_id_equal( answer[ "id" ], *id ); - } -} - -void json_rpc_database_fixture::make_array_request( std::string& request, int64_t code, bool is_warning, bool is_fail ) -{ - fc::variant answer = get_answer( request ); - BOOST_REQUIRE( answer.is_array() ); - - fc::variants request_array = fc::json::from_string( request ).get_array(); - fc::variants array = answer.get_array(); - - BOOST_REQUIRE( array.size() == request_array.size() ); - for( size_t i = 0; i < array.size(); ++i ) - { - fc::optional< fc::variant > id; - - try - { - id = request_array[i][ "id" ]; - } - catch( ... ) {} - - review_answer( array[i], code, is_warning, is_fail, id ); - } -} - -fc::variant json_rpc_database_fixture::make_request( std::string& request, int64_t code, bool is_warning, bool is_fail ) -{ - fc::variant answer = get_answer( request ); - BOOST_REQUIRE( answer.is_object() ); - fc::optional< fc::variant > id; - - try - { - id = fc::json::from_string( request ).get_object()[ "id" ]; - } - catch( ... ) {} - - review_answer( answer, code, is_warning, is_fail, id ); - - return answer; -} - -void json_rpc_database_fixture::make_positive_request( std::string& request ) -{ - make_request( request, 0/*code*/, false/*is_warning*/, false/*is_fail*/); -} - -namespace test { - -bool _push_block( database& db, const signed_block& b, uint32_t skip_flags /* = 0 */ ) -{ - return db.push_block( b, skip_flags); -} - -void _push_transaction( database& db, const signed_transaction& tx, uint32_t skip_flags /* = 0 */ ) -{ try { - db.push_transaction( tx, skip_flags ); -} FC_CAPTURE_AND_RETHROW((tx)) } - -} // hive::chain::test - -} } // hive::chain diff --git a/tests2/unit/db_fixture/database_fixture.hpp b/tests2/unit/db_fixture/database_fixture.hpp deleted file mode 100644 index 7fc781eff11a5e126469299367c19f2f0f8249c8..0000000000000000000000000000000000000000 --- a/tests2/unit/db_fixture/database_fixture.hpp +++ /dev/null @@ -1,507 +0,0 @@ -#pragma once - -#include <appbase/application.hpp> -#include <hive/chain/database.hpp> -#include <hive/chain/util/delayed_voting.hpp> -#include <fc/io/json.hpp> -#include <fc/smart_ref_impl.hpp> - -#include <hive/plugins/debug_node/debug_node_plugin.hpp> - -#include <hive/utilities/key_conversion.hpp> - -#include <hive/plugins/block_api/block_api_plugin.hpp> -#include <hive/plugins/condenser_api/condenser_api_legacy_asset.hpp> -#include <hive/plugins/database_api/database_api_plugin.hpp> - -#include <fc/network/http/connection.hpp> -#include <fc/network/ip.hpp> - -#include <array> -#include <iostream> - -#define INITIAL_TEST_SUPPLY (10000000000ll) -#define HBD_INITIAL_TEST_SUPPLY (300000000ll) - -extern uint32_t HIVE_TESTING_GENESIS_TIMESTAMP; - -#define PUSH_TX \ - hive::chain::test::_push_transaction - -#define PUSH_BLOCK \ - hive::chain::test::_push_block - -// See below -#define REQUIRE_OP_VALIDATION_SUCCESS( op, field, value ) \ -{ \ - const auto temp = op.field; \ - op.field = value; \ - op.validate(); \ - op.field = temp; \ -} -#define REQUIRE_OP_EVALUATION_SUCCESS( op, field, value ) \ -{ \ - const auto temp = op.field; \ - op.field = value; \ - trx.operations.back() = op; \ - op.field = temp; \ - db.push_transaction( trx, ~0 ); \ -} - -/*#define HIVE_REQUIRE_THROW( expr, exc_type ) \ -{ \ - std::string req_throw_info = fc::json::to_string( \ - fc::mutable_variant_object() \ - ("source_file", __FILE__) \ - ("source_lineno", __LINE__) \ - ("expr", #expr) \ - ("exc_type", #exc_type) \ - ); \ - if( fc::enable_record_assert_trip ) \ - std::cout << "HIVE_REQUIRE_THROW begin " \ - << req_throw_info << std::endl; \ - BOOST_REQUIRE_THROW( expr, exc_type ); \ - if( fc::enable_record_assert_trip ) \ - std::cout << "HIVE_REQUIRE_THROW end " \ - << req_throw_info << std::endl; \ -}*/ - -#define HIVE_REQUIRE_THROW( expr, exc_type ) \ - BOOST_REQUIRE_THROW( expr, exc_type ); - -#define HIVE_CHECK_THROW( expr, exc_type ) \ -{ \ - std::string req_throw_info = fc::json::to_string( \ - fc::mutable_variant_object() \ - ("source_file", __FILE__) \ - ("source_lineno", __LINE__) \ - ("expr", #expr) \ - ("exc_type", #exc_type) \ - ); \ - if( fc::enable_record_assert_trip ) \ - std::cout << "HIVE_CHECK_THROW begin " \ - << req_throw_info << std::endl; \ - BOOST_CHECK_THROW( expr, exc_type ); \ - if( fc::enable_record_assert_trip ) \ - std::cout << "HIVE_CHECK_THROW end " \ - << req_throw_info << std::endl; \ -} - -#define REQUIRE_OP_VALIDATION_FAILURE_2( op, field, value, exc_type ) \ -{ \ - const auto temp = op.field; \ - op.field = value; \ - HIVE_REQUIRE_THROW( op.validate(), exc_type ); \ - op.field = temp; \ -} -#define REQUIRE_OP_VALIDATION_FAILURE( op, field, value ) \ - REQUIRE_OP_VALIDATION_FAILURE_2( op, field, value, fc::exception ) - -#define REQUIRE_THROW_WITH_VALUE_2(op, field, value, exc_type) \ -{ \ - auto bak = op.field; \ - op.field = value; \ - trx.operations.back() = op; \ - op.field = bak; \ - HIVE_REQUIRE_THROW(db.push_transaction(trx, ~0), exc_type); \ -} - -#define REQUIRE_THROW_WITH_VALUE( op, field, value ) \ - REQUIRE_THROW_WITH_VALUE_2( op, field, value, fc::exception ) - -///This simply resets v back to its default-constructed value. Requires v to have a working assingment operator and -/// default constructor. -#define RESET(v) v = decltype(v)() -///This allows me to build consecutive test cases. It's pretty ugly, but it works well enough for unit tests. -/// i.e. This allows a test on update_account to begin with the database at the end state of create_account. -#define INVOKE(test) ((struct test*)this)->test_method(); trx.clear() - -#define PREP_ACTOR(name) \ - fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name)); \ - fc::ecc::private_key name ## _post_key = generate_private_key(std::string( BOOST_PP_STRINGIZE(name) ) + "_post" ); \ - public_key_type name ## _public_key = name ## _private_key.get_public_key(); - -#define ACTOR(name) \ - PREP_ACTOR(name) \ - const auto& name = account_create(BOOST_PP_STRINGIZE(name), name ## _public_key, name ## _post_key.get_public_key()); \ - account_id_type name ## _id = name.get_id(); (void)name ## _id; - -#define GET_ACTOR(name) \ - fc::ecc::private_key name ## _private_key = generate_private_key(BOOST_PP_STRINGIZE(name)); \ - const account_object& name = get_account(BOOST_PP_STRINGIZE(name)); \ - account_id_type name ## _id = name.get_id(); \ - (void)name ##_id - -#define ACTORS_IMPL(r, data, elem) ACTOR(elem) -#define ACTORS(names) BOOST_PP_SEQ_FOR_EACH(ACTORS_IMPL, ~, names) \ - validate_database(); - -#define SMT_SYMBOL( name, decimal_places, db ) \ - asset_symbol_type name ## _symbol = get_new_smt_symbol( decimal_places, db ); - -#define ASSET( s ) \ - hive::plugins::condenser_api::legacy_asset::from_string( s ).to_asset() - -#define FUND( account_name, amount ) \ - fund( account_name, amount ); \ - generate_block(); - -// To be incorporated into fund() method if deemed appropriate. -// 'SMT' would be dropped from the name then. -#define FUND_SMT_REWARDS( account_name, amount ) \ - db->adjust_reward_balance( account_name, amount ); \ - db->adjust_supply( amount ); \ - generate_block(); - -#define OP2TX(OP,TX,KEY) \ -TX.operations.push_back( OP ); \ -TX.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); \ -TX.sign( KEY, db->get_chain_id(), fc::ecc::bip_0062 ); - -#define PUSH_OP(OP,KEY) \ -{ \ - signed_transaction tx; \ - OP2TX(OP,tx,KEY) \ - db->push_transaction( tx, 0 ); \ -} - -#define PUSH_OP_TWICE(OP,KEY) \ -{ \ - signed_transaction tx; \ - OP2TX(OP,tx,KEY) \ - db->push_transaction( tx, 0 ); \ - db->push_transaction( tx, database::skip_transaction_dupe_check ); \ -} - -#define FAIL_WITH_OP(OP,KEY,EXCEPTION) \ -{ \ - signed_transaction tx; \ - OP2TX(OP,tx,KEY) \ - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), EXCEPTION ); \ -} - -namespace hive { namespace chain { - -using namespace hive::protocol; - -struct database_fixture { - // the reason we use an app is to exercise the indexes of built-in - // plugins - chain::database* db = nullptr; - signed_transaction trx; - public_key_type committee_key; - account_id_type committee_account; - fc::ecc::private_key private_key = fc::ecc::private_key::generate(); - fc::ecc::private_key init_account_priv_key = fc::ecc::private_key::regenerate( fc::sha256::hash( string( "init_key" ) ) ); - string debug_key = hive::utilities::key_to_wif( init_account_priv_key ); - public_key_type init_account_pub_key = init_account_priv_key.get_public_key(); - uint32_t default_skip = 0 | database::skip_undo_history_check | database::skip_authority_check; - fc::ecc::canonical_signature_type default_sig_canon = fc::ecc::fc_canonical; - - plugins::debug_node::debug_node_plugin* db_plugin; - - optional<fc::temp_directory> data_dir; - bool skip_key_index_test = false; - - database_fixture() {} - virtual ~database_fixture() { appbase::reset(); } - - static fc::ecc::private_key generate_private_key( string seed = "init_key" ); -#ifdef HIVE_ENABLE_SMT - static asset_symbol_type get_new_smt_symbol( uint8_t token_decimal_places, chain::database* db ); -#endif - - static const uint16_t shared_file_size_in_mb_64 = 64; - static const uint16_t shared_file_size_in_mb_512 = 512; - - void open_database( uint16_t shared_file_size_in_mb = shared_file_size_in_mb_64 ); - void generate_block(uint32_t skip = 0, - const fc::ecc::private_key& key = generate_private_key("init_key"), - int miss_blocks = 0); - - /** - * @brief Generates block_count blocks - * @param block_count number of blocks to generate - */ - void generate_blocks(uint32_t block_count); - - /** - * @brief Generates blocks until the head block time matches or exceeds timestamp - * @param timestamp target time to generate blocks until - */ - void generate_blocks(fc::time_point_sec timestamp, bool miss_intermediate_blocks = true); - - void generate_days_blocks( uint32_t days, bool skip_interm_blocks = true ); - fc::string get_current_time_iso_string() const; - - const account_object& account_create( - const string& name, - const string& creator, - const private_key_type& creator_key, - const share_type& fee, - const public_key_type& key, - const public_key_type& post_key, - const string& json_metadata - ); - - const account_object& account_create( - const string& name, - const public_key_type& key, - const public_key_type& post_key - ); - - const account_object& account_create( - const string& name, - const public_key_type& key - ); - - const witness_object& witness_create( - const string& owner, - const private_key_type& owner_key, - const string& url, - const public_key_type& signing_key, - const share_type& fee - ); - - void fund( const string& account_name, const share_type& amount = 500000 ); - void fund( const string& account_name, const asset& amount ); - void transfer( const string& from, const string& to, const asset& amount ); - void convert( const string& account_name, const asset& amount ); - void vest( const string& from, const string& to, const asset& amount ); - void vest( const string& from, const share_type& amount ); - void proxy( const string& account, const string& proxy ); - void set_price_feed( const price& new_price ); - void set_witness_props( const flat_map< string, vector< char > >& new_props ); - account_id_type get_account_id( const string& account_name )const; - asset get_balance( const string& account_name )const; - asset get_hbd_balance( const string& account_name )const; - asset get_savings( const string& account_name )const; - asset get_hbd_savings( const string& account_name )const; - asset get_rewards( const string& account_name )const; - asset get_hbd_rewards( const string& account_name )const; - asset get_vesting( const string& account_name )const; - asset get_vest_rewards( const string& account_name )const; - asset get_vest_rewards_as_hive( const string& account_name )const; - void sign( signed_transaction& trx, const fc::ecc::private_key& key ); - - vector< operation > get_last_operations( uint32_t ops ); - - void validate_database(); -}; - -struct clean_database_fixture : public database_fixture -{ - clean_database_fixture( uint16_t shared_file_size_in_mb = shared_file_size_in_mb_512 ); - virtual ~clean_database_fixture(); - - void resize_shared_mem( uint64_t size ); - void validate_database(); -}; - -struct live_database_fixture : public database_fixture -{ - live_database_fixture(); - virtual ~live_database_fixture(); - - fc::path _chain_dir; -}; - -#ifdef HIVE_ENABLE_SMT -template< typename T > -struct t_smt_database_fixture : public T -{ - using units = flat_map< account_name_type, uint16_t >; - - using database_fixture::set_price_feed; - using database_fixture::fund; - using database_fixture::convert; - - t_smt_database_fixture(){} - virtual ~t_smt_database_fixture(){} - - asset_symbol_type create_smt( const string& account_name, const fc::ecc::private_key& key, - uint8_t token_decimal_places ); - asset_symbol_type create_smt_with_nai( const string& account_name, const fc::ecc::private_key& key, - uint32_t nai, uint8_t token_decimal_places ); - - /// Creates 3 different SMTs for provided control account, one with 0 precision, the other two with the same non-zero precision. - std::array<asset_symbol_type, 3> create_smt_3(const char* control_account_name, const fc::ecc::private_key& key); - /// Tries to create SMTs with too big precision or invalid name. - void create_invalid_smt( const char* control_account_name, const fc::ecc::private_key& key ); - /// Tries to create SMTs matching existing one. First attempt with matching precision, second one with different (but valid) precision. - void create_conflicting_smt( const asset_symbol_type existing_smt, const char* control_account_name, const fc::ecc::private_key& key ); - - //smt_setup_operation - smt_generation_unit get_generation_unit ( const units& hive_unit = units(), const units& token_unit = units() ); - smt_capped_generation_policy get_capped_generation_policy - ( - const smt_generation_unit& pre_soft_cap_unit = smt_generation_unit(), - const smt_generation_unit& post_soft_cap_unit = smt_generation_unit(), - uint16_t soft_cap_percent = 0, - uint32_t min_unit_ratio = 0, - uint32_t max_unit_ratio = 0 - ); -}; - -using smt_database_fixture = t_smt_database_fixture< clean_database_fixture >; -using smt_database_fixture_for_plugin = t_smt_database_fixture< database_fixture >; - -#endif - -struct sps_proposal_database_fixture : public virtual clean_database_fixture -{ - sps_proposal_database_fixture( uint16_t shared_file_size_in_mb = shared_file_size_in_mb_64 ) - : clean_database_fixture( shared_file_size_in_mb ){} - virtual ~sps_proposal_database_fixture(){} - - void plugin_prepare(); - - int64_t create_proposal( std::string creator, std::string receiver, - time_point_sec start_date, time_point_sec end_date, - asset daily_pay, const fc::ecc::private_key& key ); - - void update_proposal( uint64_t proposal_id, std::string creator, - asset daily_pay, std::string subject, std::string permlink, - const fc::ecc::private_key& key ); - - void vote_proposal( std::string voter, const std::vector< int64_t >& id_proposals, bool approve, const fc::ecc::private_key& key ); - - bool exist_proposal( int64_t id ); - const proposal_object* find_proposal( int64_t id ); - - void remove_proposal(account_name_type _deleter, flat_set<int64_t> _proposal_id, const fc::ecc::private_key& _key); - - bool find_vote_for_proposal(const std::string& _user, int64_t _proposal_id); - - uint64_t get_nr_blocks_until_maintenance_block(); - - void post_comment( std::string _authro, std::string _permlink, std::string _title, std::string _body, std::string _parent_permlink, const fc::ecc::private_key& _key); - - struct create_proposal_data - { - std::string creator ; - std::string receiver ; - fc::time_point_sec start_date ; - fc::time_point_sec end_date ; - hive::protocol::asset daily_pay ; - std::string subject ; - std::string url ; - - create_proposal_data(fc::time_point_sec _start) - { - creator = "alice"; - receiver = "bob"; - start_date = _start + fc::days( 1 ); - end_date = start_date + fc::days( 2 ); - daily_pay = asset( 100, HBD_SYMBOL ); - subject = "hello"; - url = "http:://something.html"; - } - }; - -}; - -struct sps_proposal_database_fixture_performance : public sps_proposal_database_fixture -{ - sps_proposal_database_fixture_performance( uint16_t shared_file_size_in_mb = 512 ) - : sps_proposal_database_fixture( shared_file_size_in_mb ) - { - db->get_benchmark_dumper().set_enabled( true ); - db->set_sps_remove_threshold( -1 ); - } -}; - - -struct hf23_database_fixture : public clean_database_fixture -{ - private: - - void push_transaction( const operation& op, const fc::ecc::private_key& key ); - - public: - - hf23_database_fixture( uint16_t shared_file_size_in_mb = shared_file_size_in_mb_64 ) - : clean_database_fixture( shared_file_size_in_mb ){} - virtual ~hf23_database_fixture(){} - - void vest( const string& from, const string& to, const asset& amount, const fc::ecc::private_key& key ); - void delegate_vest( const string& delegator, const string& delegatee, const asset& amount, const fc::ecc::private_key& key ); -}; - -struct hf24_database_fixture : public clean_database_fixture -{ - hf24_database_fixture( uint16_t shared_file_size_in_mb = shared_file_size_in_mb_64 ) - : clean_database_fixture( shared_file_size_in_mb ) - {} - virtual ~hf24_database_fixture() {} -}; - -struct delayed_vote_database_fixture : public virtual clean_database_fixture -{ - private: - - void push_transaction( const operation& op, const fc::ecc::private_key& key ); - - public: - - delayed_vote_database_fixture( uint16_t shared_file_size_in_mb = 8 ) - : clean_database_fixture( shared_file_size_in_mb ){} - virtual ~delayed_vote_database_fixture(){} - - void witness_vote( const std::string& account, const std::string& witness, const bool approve, const fc::ecc::private_key& key ); - void vest( const string& from, const string& to, const asset& amount, const fc::ecc::private_key& key ); - void withdraw_vesting( const string& account, const asset& amount, const fc::ecc::private_key& key ); - void proxy( const string& account, const string& proxy, const fc::ecc::private_key& key ); - void decline_voting_rights( const string& account, const bool decline, const fc::ecc::private_key& key ); - - share_type get_votes( const string& witness_name ); - int32_t get_user_voted_witness_count( const account_name_type& name ); - - asset to_vest( const asset& liquid, const bool to_reward_balance = false ); - time_point_sec move_forward_with_update( const fc::microseconds& time, delayed_voting::opt_votes_update_data_items& items ); - - template< typename COLLECTION > - fc::optional< size_t > get_position_in_delayed_voting_array( const COLLECTION& collection, size_t day, size_t minutes ); - - template< typename COLLECTION > - bool check_collection( const COLLECTION& collection, ushare_type idx, const fc::time_point_sec& time, const ushare_type val ); - - template< typename COLLECTION > - bool check_collection( const COLLECTION& collection, const bool withdraw_executor, const share_type val, const account_object& obj ); -}; - -struct delayed_vote_proposal_database_fixture - : public delayed_vote_database_fixture, - public sps_proposal_database_fixture -{ - delayed_vote_proposal_database_fixture( uint16_t shared_file_size_in_mb = 8 ) - : delayed_vote_database_fixture( shared_file_size_in_mb ), - sps_proposal_database_fixture( shared_file_size_in_mb ) {} - virtual ~delayed_vote_proposal_database_fixture(){} -}; - -struct json_rpc_database_fixture : public database_fixture -{ - private: - hive::plugins::json_rpc::json_rpc_plugin* rpc_plugin; - - fc::variant get_answer( std::string& request ); - void review_answer( fc::variant& answer, int64_t code, bool is_warning, bool is_fail, fc::optional< fc::variant > id ); - - public: - - json_rpc_database_fixture(); - virtual ~json_rpc_database_fixture(); - - void make_array_request( std::string& request, int64_t code = 0, bool is_warning = false, bool is_fail = true ); - fc::variant make_request( std::string& request, int64_t code = 0, bool is_warning = false, bool is_fail = true ); - void make_positive_request( std::string& request ); -}; - -namespace test -{ - bool _push_block( database& db, const signed_block& b, uint32_t skip_flags = 0 ); - void _push_transaction( database& db, const signed_transaction& tx, uint32_t skip_flags = 0 ); -} - -} } diff --git a/tests2/unit/generate_empty_blocks/CMakeLists.txt b/tests2/unit/generate_empty_blocks/CMakeLists.txt deleted file mode 100644 index 6c13d501ddbe27b7aae57e14a36e0054b4d51fda..0000000000000000000000000000000000000000 --- a/tests2/unit/generate_empty_blocks/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -add_executable( generate_empty_blocks main.cpp ) -if( UNIX AND NOT APPLE ) - set(rt_library rt ) -endif() - -target_link_libraries( generate_empty_blocks - PRIVATE vaporware_app vaporware_chain fc ${CMAKE_DL_LIBS} ${PLATFORM_SPECIFIC_LIBS} ) - -install( TARGETS - generate_empty_blocks - - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib -) diff --git a/tests2/unit/plugin_tests/basic_plugin_tests.cpp b/tests2/unit/plugin_tests/basic_plugin_tests.cpp deleted file mode 100644 index 6fc84d0dc2b7d9401b104e32c6e90f83c1603ebf..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/basic_plugin_tests.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#if defined IS_TEST_NET && !defined ENABLE_MIRA && !defined ENABLE_STD_ALLOCATOR -#include <boost/test/unit_test.hpp> - -#include <hive/plugins/account_by_key/account_by_key_objects.hpp> -#include <hive/plugins/account_history_rocksdb/account_history_rocksdb_objects.hpp> -//#include <hive/plugins/block_log_info/block_log_info_objects.hpp> -#include <hive/plugins/market_history/market_history_plugin.hpp> -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/reputation/reputation_objects.hpp> -#include <hive/plugins/transaction_status/transaction_status_objects.hpp> -#include <hive/plugins/witness/witness_plugin_objects.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; -using namespace hive::plugins; - -BOOST_FIXTURE_TEST_SUITE( basic_plugin_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( plugin_object_size ) -{ - try - { - BOOST_CHECK_EQUAL( sizeof( account_by_key::key_lookup_object ), 56 ); - //3.4M, lasting, expected 3*account_object on average - - BOOST_CHECK_EQUAL( sizeof( account_history_rocksdb::volatile_operation_object ), 112 ); - //temporary, at most as many as operations in reversible blocks - - //BOOST_CHECK_EQUAL( sizeof( block_log_info::block_log_hash_state_object ), 0 ); - //BOOST_CHECK_EQUAL( sizeof( block_log_info::block_log_pending_message_object ), 0 ); - - BOOST_CHECK_EQUAL( sizeof( market_history::bucket_object ), 104 ); - //temporary, regulated amount, ~13k - BOOST_CHECK_EQUAL( sizeof( market_history::order_history_object ), 88 ); - //permanent, growing with executed limit_order_object, 2.5M atm - - BOOST_CHECK_EQUAL( sizeof( rc::rc_resource_param_object ), 368 ); - //singleton - BOOST_CHECK_EQUAL( sizeof( rc::rc_pool_object ), 48 ); - //singleton - BOOST_CHECK_EQUAL( sizeof( rc::rc_account_object ), 64 ); - //permanent, as many as account_object, 1.3M atm - BOOST_CHECK_EQUAL( sizeof( rc::rc_delegation_pool_object ), 40 ); - //unused - BOOST_CHECK_EQUAL( sizeof( rc::rc_indel_edge_object ), 48 ); - //unused - BOOST_CHECK_EQUAL( sizeof( rc::rc_outdel_drc_edge_object ), 64 ); - //unused - - BOOST_CHECK_EQUAL( sizeof( reputation::reputation_object ), 32 ); - //lasting, as many as account_object, 1.3M atm - - BOOST_CHECK_EQUAL( sizeof( transaction_status::transaction_status_object ), 28 ); - //temporary, depends on tracking flag, cuts out data from too old blocks - - BOOST_CHECK_EQUAL( sizeof( witness::witness_custom_op_object ), 32 ); - //temporary, at most as many as account_object affected by custom ops in single block - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/plugin_tests/json_rpc.cpp b/tests2/unit/plugin_tests/json_rpc.cpp deleted file mode 100644 index 2d00344a6357865ca5559671dfb544f6ef7ff6af..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/json_rpc.cpp +++ /dev/null @@ -1,316 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/account_object.hpp> -#include <hive/chain/comment_object.hpp> -#include <hive/protocol/hive_operations.hpp> -#include <hive/plugins/json_rpc/json_rpc_plugin.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( json_rpc, json_rpc_database_fixture ) - -BOOST_AUTO_TEST_CASE( basic_validation ) -{ - try - { - std::string request; - - /* - According to: - http://www.jsonrpc.org/specification - - -32700 Parse error Invalid JSON was received by the server. - -32600 Invalid Request The JSON sent is not a valid Request object. - -32601 Method not found The method does not exist / is not available. - -32602 Invalid params Invalid method parameter(s). - -32603 Internal error Internal JSON-RPC error. - -32000 to -32099 Server error Reserved for implementation-defined server-errors. - */ - - //==============jsonrpc============== - request = "{}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "[]"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[1,2,3]"; - make_array_request( request, JSON_RPC_PARSE_ERROR ); - - request = "{\"JSONRPC\": \"2.0\", \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"1.0\", \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc_\": \"2.0\", \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2\", \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": 2.0, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": true, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": null, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": {}, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": [], \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": { \"jsonrpc\":\"2.0\" }, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "\"jsonrpc\" \"2.0\""; - make_request( request, JSON_RPC_PARSE_ERROR ); - //==============jsonrpc============== - - //==============method============== - request = "{\"jsonrpc\": \"2.0\", \"METHOD\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method_\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"xyz\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": 123, \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": false, \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": null, \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": {}, \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": [], \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - //==============method============== - - //==============params============== - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\" }"; - make_request( request, JSON_RPC_NO_PARAMS, true/*warning*/ ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": call, \"params\":1, \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": call, \"params\":\"abc\", \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": call, \"params\":true, \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": call, \"params\":\"true, \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": call, \"params\":\"true\", \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - //==============params============== - - //==============id============== - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": [], \"id\": null}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": [], \"id\": 5.4}"; - make_request( request, JSON_RPC_INVALID_REQUEST ); - //==============id============== - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( syntax_validation ) -{ - try - { - std::string request; - - request = ""; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "\""; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{abcde}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{ \"abcde\" }"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\":, \"method\": \"call\", \"params\": [], \"id\": 1}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[{]"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[{ \"jsonrpc\": \"2.0\" },{ \"jsonrpc\" }]"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\" \"method\" \"call\"}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", method: call}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[{\"jsonrpc\": \"2.0\", \"method\": \"call\"}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": ]}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\" []}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\" [5,]}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\":{\"arg1\"}}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\":{\"arg1\":}}"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[ {\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\":{}, ]"; - make_request( request, JSON_RPC_SERVER_ERROR ); - - request = "[ {\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\":{} }, {\"jsonrpc\": \"2.0\", \"method\" ]"; - make_request( request, JSON_RPC_SERVER_ERROR ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( misc_validation ) -{ - try - { - std::string request; - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"a.b.c\", \"params\": [\"a\",\"b\", {} ], \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"a..c\", \"params\": [\"a\",\"b\", {} ], \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"fake_api.fake_method\", \"params\": [\"a\",\"b\", {} ], \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": [\"fake_api\",\"fake_method\", {} ], \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": {}, \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": { \"fake_api\":\"database_api\", \"fake_method\":\"get_dynamic_global_properties\", \"fake_args\":{} }, \"id\": 1}"; - make_request( request, JSON_RPC_PARSE_PARAMS_ERROR ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( positive_validation ) -{ - try - { - std::string request; - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\"], \"id\":1}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\", {}], \"id\":3}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.get_dynamic_global_properties\",\"id\":4}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.get_dynamic_global_properties\", \"params\":{}, \"id\":5}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"condenser_api\", \"get_dynamic_global_properties\", []], \"id\":8}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"condenser_api.get_dynamic_global_properties\", \"params\":[], \"id\":12}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"find_accounts\", {\"accounts\":[\"init_miner\"]}], \"id\":13}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.find_accounts\", \"params\":{\"accounts\":[\"init_miner\"]}, \"id\":14}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"find_accounts\", {}], \"id\":15}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"find_accounts\"], \"id\":15}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.find_accounts\", \"params\":{\"accounts\":[\"init_miner\"]}, \"id\":17}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.find_accounts\", \"params\":{}, \"id\":16}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"database_api.find_accounts\", \"id\":18}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"condenser_api\", \"get_accounts\", [[\"init_miner\"]]], \"id\":6}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"condenser_api.get_accounts\", \"params\":[[\"init_miner\"]], \"id\":7}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"condenser_api\", \"get_accounts\", [[]]], \"id\":8}"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"condenser_api.get_accounts\", \"params\":[[]], \"id\":9}"; - make_positive_request( request ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": [\"block_api\",\"get_block\", {\"block_num\":23} ], \"id\": 10}"; - make_positive_request( request ); - - request = "{\"jsonrpc\": \"2.0\", \"method\": \"block_api.get_block\", \"params\": {\"block_num\":0}, \"id\": 11}"; - make_positive_request( request ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( semantics_validation ) -{ - try - { - std::string request; - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\"], \"id\":20 }"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\"], \"id\":\"20\" }"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\"], \"id\":-20 }"; - make_positive_request( request ); - - request = "{\"jsonrpc\":\"2.0\", \"method\":\"call\", \"params\":[\"database_api\", \"get_dynamic_global_properties\"], \"id\":\"-20\" }"; - make_positive_request( request ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/plugin_tests/main.cpp b/tests2/unit/plugin_tests/main.cpp deleted file mode 100644 index 0182f826828e5f4e6d38e0ed9af6279d4706bb37..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/main.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2015 Cryptonomex, Inc., and contributors. - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#define BOOST_TEST_MODULE plugin_test -#include <BoostTestTargetConfig.h> - -#include <cstdlib> -#include <iostream> -#include <boost/test/included/unit_test.hpp> - -/* -extern uint32_t HIVE_TESTING_GENESIS_TIMESTAMP; - -boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) { - std::srand(time(NULL)); - std::cout << "Random number generator seeded to " << time(NULL) << std::endl; - const char* genesis_timestamp_str = getenv("HIVE_TESTING_GENESIS_TIMESTAMP"); - if( genesis_timestamp_str != nullptr ) - { - HIVE_TESTING_GENESIS_TIMESTAMP = std::stoul( genesis_timestamp_str ); - } - std::cout << "HIVE_TESTING_GENESIS_TIMESTAMP is " << HIVE_TESTING_GENESIS_TIMESTAMP << std::endl; - return nullptr; -} -*/ diff --git a/tests2/unit/plugin_tests/market_history.cpp b/tests2/unit/plugin_tests/market_history.cpp deleted file mode 100644 index b9f15afb85f350e134c2bb7f8ae35f805d7122d7..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/market_history.cpp +++ /dev/null @@ -1,351 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/account_object.hpp> -#include <hive/chain/comment_object.hpp> -#include <hive/protocol/hive_operations.hpp> - -#include <hive/plugins/market_history/market_history_plugin.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( market_history, database_fixture ) - -BOOST_AUTO_TEST_CASE( mh_test ) -{ - using namespace hive::plugins::market_history; - - try - { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - appbase::app().register_plugin< market_history_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - init_account_pub_key = init_account_priv_key.get_public_key(); - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::market_history::market_history_plugin, - hive::plugins::debug_node::debug_node_plugin - >( argc, argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - open_database(); - - generate_block(); - db->set_hardfork( HIVE_NUM_HARDFORKS ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - - ACTORS( (alice)(bob)(sam) ); - generate_block(); - - fund( "alice", ASSET( "1000.000 TESTS" ) ); - fund( "alice", ASSET( "1000.000 TBD" ) ); - fund( "bob", ASSET( "1000.000 TESTS" ) ); - fund( "sam", ASSET( "1000.000 TESTS" ) ); - - const auto& bucket_idx = db->get_index< bucket_index >().indices().get< by_bucket >(); - const auto& order_hist_idx = db->get_index< order_history_index >().indices().get< by_id >(); - - BOOST_REQUIRE( bucket_idx.begin() == bucket_idx.end() ); - BOOST_REQUIRE( order_hist_idx.begin() == order_hist_idx.end() ); - validate_database(); - - signed_transaction tx; - - auto fill_order_a_time = db->head_block_time(); - auto time_a = fc::time_point_sec( ( fill_order_a_time.sec_since_epoch() / 15 ) * 15 ); - - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = ASSET( "1.000 TBD" ); - op.min_to_receive = ASSET( "2.000 TESTS" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "bob"; - op.amount_to_sell = ASSET( "1.500 TESTS" ); - op.min_to_receive = ASSET( "0.750 TBD" ); - tx.operations.push_back( op ); - sign(tx, bob_private_key); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + ( 60 * 90 ) ); - - auto fill_order_b_time = db->head_block_time(); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "sam"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = ASSET( "0.500 TBD" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + 60 ); - - auto fill_order_c_time = db->head_block_time(); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "alice"; - op.amount_to_sell = ASSET( "0.500 TBD" ); - op.min_to_receive = ASSET( "0.900 TESTS" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "bob"; - op.amount_to_sell = ASSET( "0.450 TESTS" ); - op.min_to_receive = ASSET( "0.250 TBD" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - auto bucket = bucket_idx.begin(); - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - - bucket++; - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.250 TBD" ).amount ); - - bucket++; - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) + 60 ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.500 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.250 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) + 60 ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.500 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 300 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 300 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.450 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 3600 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 3600 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 60 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.450 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "0.750 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 86400 ); - BOOST_REQUIRE( bucket->open == HIVE_GENESIS_TIME ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "2.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == ASSET( "0.750 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.close == ASSET( "0.250 TBD" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == ASSET( "1.500 TBD" ).amount ); - bucket++; - - BOOST_REQUIRE( bucket == bucket_idx.end() ); - - auto order = order_hist_idx.begin(); - - BOOST_REQUIRE( order->time == fill_order_a_time ); - BOOST_REQUIRE( order->op.current_owner == "bob" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "1.500 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == ASSET( "0.750 TBD" ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_b_time ); - BOOST_REQUIRE( order->op.current_owner == "sam" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "0.500 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == ASSET( "0.250 TBD" ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_c_time ); - BOOST_REQUIRE( order->op.current_owner == "alice" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "0.250 TBD" ) ); - BOOST_REQUIRE( order->op.open_owner == "sam" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == ASSET( "0.500 TESTS" ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_c_time ); - BOOST_REQUIRE( order->op.current_owner == "bob" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "0.450 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == ASSET( "0.250 TBD" ) ); - order++; - - BOOST_REQUIRE( order == order_hist_idx.end() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/plugin_tests/plugin_ops.cpp b/tests2/unit/plugin_tests/plugin_ops.cpp deleted file mode 100644 index 7e11795dc88705c411a092f48eeab787a4321d6b..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/plugin_ops.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#ifdef IS_TEST_NET -#include <hive/chain/account_object.hpp> -#include <hive/chain/generic_custom_operation_interpreter.hpp> - -#include <boost/test/unit_test.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::chain::test; -/* -namespace hive { namespace plugin_tests { - -using namespace hive::app; -using namespace hive::chain; - -struct test_a_operation : base_operation -{ - string account; - - void validate() { FC_ASSERT( account.size() ); } -}; - -struct test_b_operation : base_operation -{ - string account; - - void validate() { FC_ASSERT( account.size() ); } -}; - -typedef fc::static_variant< - test_a_operation, - test_b_operation > test_op; - -class test_plugin : public plugin -{ - public: - test_plugin( application* app ); - - std::string plugin_name()const override { return "TEST"; } - - std::shared_ptr< generic_custom_operation_interpreter< test_op > > _evaluator_registry; -}; - -HIVE_DEFINE_PLUGIN_EVALUATOR( test_plugin, test_a_operation, test_a ); -HIVE_DEFINE_PLUGIN_EVALUATOR( test_plugin, test_b_operation, test_b ); - -void test_a_evaluator::do_apply( const test_a_operation& o ) -{ - const auto& account = db().get_account( o.account ); - - db().modify( account, [&]( account_object& a ) - { - a.json_metadata = "a"; - }); -} - -void test_b_evaluator::do_apply( const test_b_operation& o ) -{ - const auto& account = db().get_account( o.account ); - - db().modify( account, [&]( account_object& a ) - { - a.json_metadata = "b"; - }); -} - -test_plugin::test_plugin( application* app ) : plugin( app ) -{ - _evaluator_registry = std::make_shared< generic_custom_operation_interpreter< test_op > >( database() ); - - _evaluator_registry->register_evaluator< test_a_evaluator >( *this ); - _evaluator_registry->register_evaluator< test_b_evaluator >( *this ); - - database().set_custom_operation_interpreter( plugin_name(), _evaluator_registry ); -} - -} } // hive::plugin_tests - -HIVE_DEFINE_PLUGIN( test, hive::plugin_tests::test_plugin ) - -FC_REFLECT( hive::plugin_tests::test_a_operation, (account) ) -FC_REFLECT( hive::plugin_tests::test_b_operation, (account) ) - -HIVE_DECLARE_OPERATION_TYPE( hive::plugin_tests::test_op ); -FC_REFLECT_TYPENAME( hive::plugin_tests::test_op ); -HIVE_DEFINE_OPERATION_TYPE( hive::plugin_tests::test_op ); -*/ - - -#endif \ No newline at end of file diff --git a/tests2/unit/plugin_tests/smt_market_history.cpp b/tests2/unit/plugin_tests/smt_market_history.cpp deleted file mode 100644 index e1561813fad08c04c1a63e2f6392c9742faf0779..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/smt_market_history.cpp +++ /dev/null @@ -1,354 +0,0 @@ -#if defined IS_TEST_NET && defined HIVE_ENABLE_SMT -#include <boost/test/unit_test.hpp> - -#include <hive/chain/account_object.hpp> -#include <hive/chain/comment_object.hpp> -#include <hive/protocol/hive_operations.hpp> - -#include <hive/plugins/market_history/market_history_plugin.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( smt_market_history, smt_database_fixture_for_plugin ) - -BOOST_AUTO_TEST_CASE( smt_mh_test ) -{ - using namespace hive::plugins::market_history; - - try - { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - appbase::app().register_plugin< market_history_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - init_account_pub_key = init_account_priv_key.get_public_key(); - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::market_history::market_history_plugin, - hive::plugins::debug_node::debug_node_plugin - >( argc, argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - open_database(); - - generate_block(); - db->set_hardfork( HIVE_NUM_HARDFORKS ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - - ACTORS( (alice)(bob)(sam)(smtcreator) ); - - signed_transaction tx; - asset_symbol_type any_smt_symbol = create_smt( "smtcreator", smtcreator_private_key, 3); - - fund( "alice", ASSET( "1000.000 TESTS" ) ); - fund( "bob", ASSET( "1000.000 TESTS" ) ); - fund( "sam", ASSET( "1000.000 TESTS" ) ); - fund( "alice", asset( 1000000, any_smt_symbol ) ); - - tx.operations.clear(); - tx.signatures.clear(); - - const auto& bucket_idx = db->get_index< bucket_index >().indices().get< by_bucket >(); - const auto& order_hist_idx = db->get_index< order_history_index >().indices().get< by_id >(); - - BOOST_REQUIRE( bucket_idx.begin() == bucket_idx.end() ); - BOOST_REQUIRE( order_hist_idx.begin() == order_hist_idx.end() ); - validate_database(); - - auto fill_order_a_time = db->head_block_time(); - auto time_a = fc::time_point_sec( ( fill_order_a_time.sec_since_epoch() / 15 ) * 15 ); - - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = asset( 1000, any_smt_symbol ); - op.min_to_receive = ASSET( "2.000 TESTS" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "bob"; - op.amount_to_sell = ASSET( "1.500 TESTS" ); - op.min_to_receive = asset( 750, any_smt_symbol ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + ( 60 * 90 ) ); - - auto fill_order_b_time = db->head_block_time(); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "sam"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = asset( 500, any_smt_symbol ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + 60 ); - - auto fill_order_c_time = db->head_block_time(); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "alice"; - op.amount_to_sell = asset( 500, any_smt_symbol ); - op.min_to_receive = ASSET( "0.900 TESTS" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "bob"; - op.amount_to_sell = ASSET( "0.450 TESTS" ); - op.min_to_receive = asset( 250, any_smt_symbol ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - auto bucket = bucket_idx.begin(); - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 250, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 15 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) + 60 ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 500, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 250, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 60 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) + 60 ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "0.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 500, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 300 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 300 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 90 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.450 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 3600 ); - BOOST_REQUIRE( bucket->open == time_a ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "1.500 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "1.500 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 3600 ); - BOOST_REQUIRE( bucket->open == time_a + ( 60 * 60 ) ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "0.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "1.450 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 750, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket->seconds == 86400 ); - BOOST_REQUIRE( bucket->open == HIVE_GENESIS_TIME ); - BOOST_REQUIRE( bucket->hive.high == ASSET( "0.450 TESTS " ).amount ); - BOOST_REQUIRE( bucket->non_hive.high == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.low == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.low == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.open == ASSET( "1.500 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.open == asset( 750, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.close == ASSET( "0.450 TESTS").amount ); - BOOST_REQUIRE( bucket->non_hive.close == asset( 250, any_smt_symbol ).amount ); - BOOST_REQUIRE( bucket->hive.volume == ASSET( "2.950 TESTS" ).amount ); - BOOST_REQUIRE( bucket->non_hive.volume == asset( 1500, any_smt_symbol ).amount ); - bucket++; - - BOOST_REQUIRE( bucket == bucket_idx.end() ); - - auto order = order_hist_idx.begin(); - - BOOST_REQUIRE( order->time == fill_order_a_time ); - BOOST_REQUIRE( order->op.current_owner == "bob" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "1.500 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == asset( 750, any_smt_symbol ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_b_time ); - BOOST_REQUIRE( order->op.current_owner == "sam" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "0.500 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == asset( 250, any_smt_symbol ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_c_time ); - BOOST_REQUIRE( order->op.current_owner == "alice" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == asset( 250, any_smt_symbol ) ); - BOOST_REQUIRE( order->op.open_owner == "sam" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == ASSET( "0.500 TESTS" ) ); - order++; - - BOOST_REQUIRE( order->time == fill_order_c_time ); - BOOST_REQUIRE( order->op.current_owner == "bob" ); - BOOST_REQUIRE( order->op.current_orderid == 0 ); - BOOST_REQUIRE( order->op.current_pays == ASSET( "0.450 TESTS" ) ); - BOOST_REQUIRE( order->op.open_owner == "alice" ); - BOOST_REQUIRE( order->op.open_orderid == 0 ); - BOOST_REQUIRE( order->op.open_pays == asset( 250, any_smt_symbol ) ); - order++; - - BOOST_REQUIRE( order == order_hist_idx.end() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/plugin_tests/transaction_status.cpp b/tests2/unit/plugin_tests/transaction_status.cpp deleted file mode 100644 index e1556fd094e37cad4e1875c0ad2df797745c4bfc..0000000000000000000000000000000000000000 --- a/tests2/unit/plugin_tests/transaction_status.cpp +++ /dev/null @@ -1,475 +0,0 @@ -#if defined IS_TEST_NET -#include <boost/test/unit_test.hpp> -#include <hive/chain/account_object.hpp> -#include <hive/protocol/hive_operations.hpp> -#include <hive/protocol/config.hpp> -#include <hive/plugins/transaction_status/transaction_status_plugin.hpp> -#include <hive/plugins/transaction_status/transaction_status_objects.hpp> -#include <hive/plugins/transaction_status_api/transaction_status_api_plugin.hpp> -#include <hive/plugins/transaction_status_api/transaction_status_api.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; - -#define TRANSCATION_STATUS_TRACK_AFTER_BLOCK 1300 -#define TRANSCATION_STATUS_TRACK_AFTER_BLOCK_STR BOOST_PP_STRINGIZE( TRANSCATION_STATUS_TRACK_AFTER_BLOCK ) -#define TRANSACTION_STATUS_TEST_BLOCK_DEPTH 30 -#define TRANSACTION_STATUS_TEST_BLOCK_DEPTH_STR BOOST_PP_STRINGIZE( TRANSACTION_STATUS_TEST_BLOCK_DEPTH ) - -BOOST_FIXTURE_TEST_SUITE( transaction_status, database_fixture ); - -BOOST_AUTO_TEST_CASE( transaction_status_test ) -{ - using namespace hive::plugins::transaction_status; - - try - { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - - for ( int i = 1; i < argc; i++ ) - { - const std::string arg = argv[ i ]; - if ( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if ( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - - appbase::app().register_plugin< transaction_status_plugin >(); - appbase::app().register_plugin< hive::plugins::transaction_status_api::transaction_status_api_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - init_account_pub_key = init_account_priv_key.get_public_key(); - - // We create an argc/argv so that the transaction_status plugin can be initialized with a reasonable block depth - int test_argc = 5; - const char* test_argv[] = { boost::unit_test::framework::master_test_suite().argv[0], - "--transaction-status-block-depth", - TRANSACTION_STATUS_TEST_BLOCK_DEPTH_STR, - "--transaction-status-track-after-block", - TRANSCATION_STATUS_TRACK_AFTER_BLOCK_STR }; - - db_plugin->logging = false; - appbase::app().initialize< - hive::plugins::transaction_status_api::transaction_status_api_plugin, - hive::plugins::debug_node::debug_node_plugin >( test_argc, (char**)test_argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - auto tx_status_api = &appbase::app().get_plugin< hive::plugins::transaction_status_api::transaction_status_api_plugin >(); - BOOST_REQUIRE( tx_status_api ); - - auto tx_status = &appbase::app().get_plugin< hive::plugins::transaction_status::transaction_status_plugin >(); - BOOST_REQUIRE( tx_status ); - - open_database(); - - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_trx_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_block_num >().empty() ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - generate_block(); - db->set_hardfork( HIVE_NUM_HARDFORKS ); - generate_block(); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - - ACTORS( (alice)(bob) ); - generate_block(); - - fund( "alice", ASSET( "1000.000 TESTS" ) ); - fund( "alice", ASSET( "1000.000 TBD" ) ); - fund( "bob", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - validate_database(); - - BOOST_TEST_MESSAGE(" -- transaction status tracking test" ); - - signed_transaction tx0; - transfer_operation op0; - auto tx0_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op0.from = "alice"; - op0.to = "bob"; - op0.amount = ASSET( "5.000 TESTS" ); - - // Create transaction 0 - tx0.operations.push_back( op0 ); - tx0.set_expiration( tx0_expiration ); - sign( tx0, alice_private_key ); - db->push_transaction( tx0, 0 ); - - // Tracking should not be enabled until we have reached TRANSCATION_STATUS_TRACK_AFTER_BLOCK - ( HIVE_MAX_TIME_UNTIL_EXPIRATION / HIVE_BLOCK_INTERVAL ) blocks - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_trx_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_block_num >().empty() ); - - // Transaction 0 should not be tracked - auto tso = db->find< transaction_status_object, by_trx_id >( tx0.id() ); - BOOST_REQUIRE( tso == nullptr ); - - auto api_return = tx_status_api->api->find_transaction( { .transaction_id = tx0.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx0.id(), tx0_expiration } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - generate_blocks( TRANSCATION_STATUS_TRACK_AFTER_BLOCK - db->head_block_num() ); - - signed_transaction tx1; - transfer_operation op1; - auto tx1_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op1.from = "alice"; - op1.to = "bob"; - op1.amount = ASSET( "5.000 TESTS" ); - - // Create transaction 1 - tx1.operations.push_back( op1 ); - tx1.set_expiration( tx1_expiration ); - sign( tx1, alice_private_key ); - db->push_transaction( tx1, 0 ); - - // Transaction 1 exists in the mem pool - tso = db->find< transaction_status_object, by_trx_id >( tx1.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num == 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id() } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id(), tx1_expiration } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - generate_block(); - - /* - * Test for two transactions in the same block - */ - - // Create transaction 2 - signed_transaction tx2; - transfer_operation op2; - auto tx2_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op2.from = "alice"; - op2.to = "bob"; - op2.amount = ASSET( "5.000 TESTS" ); - - tx2.operations.push_back( op2 ); - tx2.set_expiration( tx2_expiration ); - sign( tx2, alice_private_key ); - db->push_transaction( tx2, 0 ); - - // Create transaction 3 - signed_transaction tx3; - transfer_operation op3; - auto tx3_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op3.from = "bob"; - op3.to = "alice"; - op3.amount = ASSET( "5.000 TESTS" ); - - tx3.operations.push_back( op3 ); - tx3.set_expiration( tx3_expiration ); - sign( tx3, bob_private_key ); - db->push_transaction( tx3, 0 ); - - // Transaction 1 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx1.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num == db->head_block_num() ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id() } ); - BOOST_REQUIRE( api_return.status == within_reversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( api_return.block_num == db->head_block_num() ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id(), tx1_expiration } ); - BOOST_REQUIRE( api_return.status == within_reversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( api_return.block_num == db->head_block_num() ); - - // Transaction 2 exists in a mem pool - tso = db->find< transaction_status_object, by_trx_id >( tx2.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num == 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id() } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id(), tx2_expiration } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // Transaction 3 exists in a mem pool - tso = db->find< transaction_status_object, by_trx_id >( tx3.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num == 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id() } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id(), tx3_expiration } ); - BOOST_REQUIRE( api_return.status == within_mempool ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - generate_blocks( TRANSACTION_STATUS_TEST_BLOCK_DEPTH ); - - // Transaction 1 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx1.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id() } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id(), tx1_expiration } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - // Transaction 2 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx2.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id() } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id(), tx2_expiration } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - // Transaction 3 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx3.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id() } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id(), tx3_expiration } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - generate_blocks( HIVE_MAX_TIME_UNTIL_EXPIRATION / HIVE_BLOCK_INTERVAL ); - - // Transaction 1 is no longer tracked - tso = db->find< transaction_status_object, by_trx_id >( tx1.id() ); - BOOST_REQUIRE( tso == nullptr ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id(), tx1_expiration } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // Transaction 2 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx2.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id() } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id(), tx2_expiration } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - // Transaction 3 exists in a block - tso = db->find< transaction_status_object, by_trx_id >( tx3.id() ); - BOOST_REQUIRE( tso != nullptr ); - BOOST_REQUIRE( tso->block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id() } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id(), tx3_expiration } ); - BOOST_REQUIRE( api_return.status == within_irreversible_block ); - BOOST_REQUIRE( api_return.block_num.valid() ); - BOOST_REQUIRE( *api_return.block_num > 0 ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - generate_block(); - - // Transaction 2 is no longer tracked - tso = db->find< transaction_status_object, by_trx_id >( tx2.id() ); - BOOST_REQUIRE( tso == nullptr ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id(), tx2_expiration } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // Transaction 3 is no longer tracked - tso = db->find< transaction_status_object, by_trx_id >( tx3.id() ); - BOOST_REQUIRE( tso == nullptr ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx3.id(), tx3_expiration } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // At this point our index should be empty - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_trx_id >().empty() ); - BOOST_REQUIRE( db->get_index< transaction_status_index >().indices().get< by_block_num >().empty() ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - generate_block(); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx1.id(), tx1_expiration } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id() } ); - BOOST_REQUIRE( api_return.status == unknown ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - api_return = tx_status_api->api->find_transaction( { .transaction_id = tx2.id(), tx2_expiration } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - /** - * Testing transactions that do not exist, but expirations are provided - */ - BOOST_TEST_MESSAGE( " -- transaction status expiration test" ); - - // The time of our last irreversible block - auto lib_time = db->fetch_block_by_number( db->get_dynamic_global_properties().last_irreversible_block_num )->timestamp; - api_return = tx_status_api->api->find_transaction( { .transaction_id = transaction_id_type(), .expiration = lib_time } ); - BOOST_REQUIRE( api_return.status == expired_irreversible ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // One second after our last irreversible block - auto after_lib_time = lib_time + fc::seconds(1); - api_return = tx_status_api->api->find_transaction( { .transaction_id = transaction_id_type(), after_lib_time } ); - BOOST_REQUIRE( api_return.status == expired_reversible ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - // One second before our block depth - auto old_time = db->fetch_block_by_number( db->head_block_num() - TRANSACTION_STATUS_TEST_BLOCK_DEPTH + 1 )->timestamp - fc::seconds(1); - api_return = tx_status_api->api->find_transaction( { .transaction_id = transaction_id_type(), old_time } ); - BOOST_REQUIRE( api_return.status == too_old ); - BOOST_REQUIRE( api_return.block_num.valid() == false ); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - /** - * Testing transaction status plugin state - */ - BOOST_TEST_MESSAGE( " -- transaction status state test" ); - - // Create transaction 4 - signed_transaction tx4; - transfer_operation op4; - auto tx4_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op4.from = "alice"; - op4.to = "bob"; - op4.amount = ASSET( "5.000 TESTS" ); - - tx4.operations.push_back( op4 ); - tx4.set_expiration( tx4_expiration ); - sign( tx4, alice_private_key ); - db->push_transaction( tx4, 0 ); - - generate_block(); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - const auto& tx_status_obj = db->get< transaction_status_object, by_trx_id >( tx4.id() ); - db->remove( tx_status_obj ); - - // Upper bound of transaction status state should cause state to be invalid - BOOST_REQUIRE( tx_status->state_is_valid() == false ); - - tx_status->rebuild_state(); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - - // Create transaction 5 - signed_transaction tx5; - transfer_operation op5; - auto tx5_expiration = db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION; - - op5.from = "alice"; - op5.to = "bob"; - op5.amount = ASSET( "5.000 TESTS" ); - - tx5.operations.push_back( op5 ); - tx5.set_expiration( tx5_expiration ); - sign( tx5, alice_private_key ); - db->push_transaction( tx5, 0 ); - - generate_blocks( TRANSACTION_STATUS_TEST_BLOCK_DEPTH + ( HIVE_MAX_TIME_UNTIL_EXPIRATION / HIVE_BLOCK_INTERVAL ) - 1 ); - - const auto& tx_status_obj2 = db->get< transaction_status_object, by_trx_id >( tx5.id() ); - db->remove( tx_status_obj2 ); - - // Lower bound of transaction status state should cause state to be invalid - BOOST_REQUIRE( tx_status->state_is_valid() == false ); - - tx_status->rebuild_state(); - - BOOST_REQUIRE( tx_status->state_is_valid() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif - diff --git a/tests2/unit/tests/automated_action_tests.cpp b/tests2/unit/tests/automated_action_tests.cpp deleted file mode 100644 index d505e980adb27ee9ab3d047f831d485b64cfaa04..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/automated_action_tests.cpp +++ /dev/null @@ -1,340 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> - -#include <hive/chain/pending_required_action_object.hpp> -#include <hive/chain/pending_optional_action_object.hpp> - -#include <hive/plugins/witness/block_producer.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -BOOST_FIXTURE_TEST_SUITE( automated_action_tests, clean_database_fixture ) - - -BOOST_AUTO_TEST_CASE( push_pending_required_actions ) -{ - BOOST_TEST_MESSAGE( "Testing: push_pending_required_actions" ); - - BOOST_TEST_MESSAGE( "--- Failure pushing invalid required action" ); - example_required_action req_action; - req_action.account = ""; - BOOST_REQUIRE_THROW( req_action.validate(), fc::assert_exception ); - - BOOST_REQUIRE_THROW( db->push_required_action( req_action ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success pushing future action" ); - req_action.account = HIVE_INIT_MINER_NAME; - req_action.validate(); - db->push_required_action( req_action, db->head_block_time() + HIVE_BLOCK_INTERVAL ); - auto pending_req_action = db->get_index< pending_required_action_index, by_execution >().begin()->action.get< example_required_action >(); - auto pending_execution = db->get_index< pending_required_action_index, by_execution> ().begin()->execution_time; - BOOST_REQUIRE( pending_req_action == req_action ); - BOOST_REQUIRE( pending_execution == db->head_block_time() + HIVE_BLOCK_INTERVAL ); - - BOOST_TEST_MESSAGE( "--- Failure pushing past action" ); - BOOST_REQUIRE_THROW( db->push_required_action( req_action, db->head_block_time() - HIVE_BLOCK_INTERVAL ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success pushing action now" ); - req_action.account = HIVE_TEMP_ACCOUNT; - db->push_required_action( req_action ); - pending_req_action = db->get_index< pending_required_action_index, by_execution >().begin()->action.get< example_required_action >(); - pending_execution = db->get_index< pending_required_action_index, by_execution> ().begin()->execution_time; - BOOST_REQUIRE( pending_req_action == req_action ); - BOOST_REQUIRE( pending_execution == db->head_block_time() ); -} - - -BOOST_AUTO_TEST_CASE( push_pending_optional_actions ) -{ - BOOST_TEST_MESSAGE( "Testing: push_pending_optional_actions" ); - - BOOST_TEST_MESSAGE( "--- Failure pushing invalid required action" ); - example_optional_action opt_action; - opt_action.account = ""; - BOOST_REQUIRE_THROW( opt_action.validate(), fc::assert_exception ); - - BOOST_REQUIRE_THROW( db->push_optional_action( opt_action ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success pushing future action" ); - opt_action.account = HIVE_INIT_MINER_NAME; - opt_action.validate(); - db->push_optional_action( opt_action, db->head_block_time() + HIVE_BLOCK_INTERVAL ); - auto pending_opt_action = db->get_index< pending_optional_action_index, by_execution >().begin()->action.get< example_optional_action >(); - auto pending_execution = db->get_index< pending_optional_action_index, by_execution> ().begin()->execution_time; - BOOST_REQUIRE( pending_opt_action.account == opt_action.account ); - BOOST_REQUIRE( pending_execution == db->head_block_time() + HIVE_BLOCK_INTERVAL ); - - BOOST_TEST_MESSAGE( "--- Failure pushing past action" ); - BOOST_REQUIRE_THROW( db->push_optional_action( opt_action, db->head_block_time() - HIVE_BLOCK_INTERVAL ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success pushing action now" ); - opt_action.account = HIVE_TEMP_ACCOUNT; - db->push_optional_action( opt_action ); - pending_opt_action = db->get_index< pending_optional_action_index, by_execution >().begin()->action.get< example_optional_action >(); - pending_execution = db->get_index< pending_optional_action_index, by_execution> ().begin()->execution_time; - BOOST_REQUIRE( pending_opt_action.account == opt_action.account ); - BOOST_REQUIRE( pending_execution == db->head_block_time() ); -} - - -BOOST_AUTO_TEST_CASE( full_block ) -{ try { - resize_shared_mem( 1024 * 1024 * 32 ); // Due to number of objects in the test, it requires a large file. (32 MB) - - // Verify correct delay semantics when a 25% of the block is full of required actions - BOOST_TEST_MESSAGE( "Testing full block action delay" ); - - generate_block(); - - example_required_action req_action; - example_optional_action opt_action; - uint32_t num_actions = 0; - - db_plugin->debug_update( [&num_actions, &req_action, &opt_action](database& db) - { - uint64_t block_size = 0; - uint64_t action_partition_size = ( db.get_dynamic_global_properties().maximum_block_size * db.get_dynamic_global_properties().required_actions_partition_percent ) / HIVE_100_PERCENT; - - while( block_size < action_partition_size ) - { - req_action.account = HIVE_INIT_MINER_NAME + fc::to_string( num_actions ); - db.push_required_action( req_action ); - block_size += fc::raw::pack_size( required_automated_action( req_action ) ); - num_actions++; - } - - opt_action.account = HIVE_TEMP_ACCOUNT; - db.push_optional_action( opt_action ); - }); - - generate_block(); - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - // In a full block scenario, there would be no optional actions included nor the last required action - // Clear optional actions and the last required action and resign. - block.extensions.erase( *block.extensions.end() ); - block.extensions.begin()->get< required_automated_actions >().pop_back(); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - db->push_block( block ); - - { - const auto& pending_req_index = db->get_index< pending_required_action_index, by_execution >(); - const auto& pending_opt_index = db->get_index< pending_optional_action_index, by_execution >(); - - auto pending_req_action = pending_req_index.begin(); - auto pending_opt_action = pending_opt_index.begin(); - - BOOST_REQUIRE( pending_req_action != pending_req_index.end() ); - BOOST_REQUIRE( pending_req_action->action.get< example_required_action >() == req_action ); - BOOST_REQUIRE( pending_req_action->execution_time == db->head_block_time() - HIVE_BLOCK_INTERVAL ); - BOOST_REQUIRE( pending_opt_action != pending_opt_index.end() ); - BOOST_REQUIRE( pending_opt_action->action.get< example_optional_action >().account == opt_action.account ); - BOOST_REQUIRE( pending_opt_action->execution_time == db->head_block_time() - HIVE_BLOCK_INTERVAL ); - } - - BOOST_TEST_MESSAGE( "--- Testing inclusion of delayed action" ); - generate_block(); - - { - const auto& pending_req_index = db->get_index< pending_required_action_index, by_execution >(); - - auto pending_req_action = pending_req_index.begin(); - - BOOST_REQUIRE( pending_req_action == pending_req_index.end() ); - - auto block = db->fetch_block_by_number( db->head_block_num() ); - auto extensions_itr = block->extensions.begin(); - BOOST_REQUIRE( req_action == extensions_itr->get< required_automated_actions >().begin()->get< example_required_action >() ); - ++extensions_itr; - BOOST_REQUIRE( opt_action.account == extensions_itr->get< optional_automated_actions >().begin()->get< example_optional_action >().account ); - } - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( pending_required_execution ) -{ try { - // Check correct inclusion semantics when the next pending action has a later execution time - BOOST_TEST_MESSAGE( "Testing correct inclusion for scheduling actions in the future." ); - - example_required_action req_action; - - db_plugin->debug_update( [&req_action](database& db) - { - req_action.account = HIVE_INIT_MINER_NAME; - db.push_required_action( req_action ); - - req_action.account = HIVE_NULL_ACCOUNT; - db.push_required_action( req_action, db.head_block_time() + (2 * HIVE_BLOCK_INTERVAL ) ); - }); - - auto pending_itr = db->get_index< pending_required_action_index, by_execution >().begin(); - BOOST_REQUIRE( !( pending_itr->action.get< example_required_action >() == req_action ) ); - - generate_block(); - - pending_itr = db->get_index< pending_required_action_index, by_execution >().begin(); - BOOST_REQUIRE( pending_itr->action.get< example_required_action >() == req_action ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( unexpected_required_action ) -{ try { - // Check failure when block includes an unexpected required action - BOOST_TEST_MESSAGE( "Testing rejection of a block with an expected required action" ); - - // This test will log the later error and the next block contains many transactions. - // Generate one block to make the error smaller. - generate_block(); - - generate_block(); - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - example_required_action req_action; - req_action.account = HIVE_TEMP_ACCOUNT; - required_automated_actions req_actions; - req_actions.push_back( req_action ); - block.extensions.insert( req_actions ); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - BOOST_REQUIRE_THROW( db->push_block( block ), fc::assert_exception ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( missing_required_action ) -{ try { - // Check failure when block does not include an expected required action - BOOST_TEST_MESSAGE( "Testing rejection of a block with a missing required action" ); - - // This test will log the later error and the next block contains many transactions. - // Generate one block to make the error smaller. - generate_block(); - - example_required_action req_action; - - db_plugin->debug_update( [&req_action](database& db) - { - req_action.account = HIVE_INIT_MINER_NAME; - db.push_required_action( req_action ); - }); - - generate_block(); - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - block.extensions.clear(); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - BOOST_REQUIRE_THROW( db->push_block( block ), fc::assert_exception ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( optional_action_expiration ) -{ try { - BOOST_TEST_MESSAGE( "Testing local expiration of an optional action" ); - - for( uint32_t i = 0; i < HIVE_MAX_WITNESSES; i++ ) - { - generate_block(); - } - - auto next_lib_time = db->fetch_block_by_number( db->get_dynamic_global_properties().last_irreversible_block_num + 1 )->timestamp; - - db_plugin->debug_update( [=]( database& db ) - { - db.create< pending_optional_action_object >( [&]( pending_optional_action_object& o ) - { - example_optional_action opt_action; - opt_action.account = HIVE_NULL_ACCOUNT; - o.action = opt_action; - o.execution_time = next_lib_time; - }); - }); - - generate_block(); - - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - block.extensions.erase( *block.extensions.rbegin() ); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - db->push_block( block ); - - const auto& opt_action_idx = db->get_index< pending_optional_action_index, by_execution >(); - auto opt_itr = opt_action_idx.begin(); - - BOOST_REQUIRE( opt_itr == opt_action_idx.end() ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( unexpected_optional_action ) -{ try { - // Check success including an optional action not present in pending state - BOOST_TEST_MESSAGE( "Testing an unexpected valid optional action" ); - - generate_block(); - - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - example_optional_action opt_action; - opt_action.account = HIVE_NULL_ACCOUNT; - optional_automated_actions opt_actions = { opt_action }; - block.extensions.insert( opt_actions ); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - db->push_block( block ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_CASE( reject_optional_action ) -{ try { - // Check rejection of an invalid optional action - BOOST_TEST_MESSAGE( "Testing an unexpected invalid optional action" ); - - // This test will log the later error and the next block contains many transactions. - // Generate one block to make the error smaller. - generate_block(); - - generate_block(); - - signed_block block = *(db->fetch_block_by_number( db->head_block_num() )); - - db->pop_block(); - - example_optional_action opt_action; - opt_action.account = "_foobar"; - optional_automated_actions opt_actions = { opt_action }; - block.extensions.insert( opt_actions ); - block.sign( HIVE_INIT_PRIVATE_KEY ); - - BOOST_REQUIRE_THROW( db->push_block( block ), fc::assert_exception ); - -} FC_LOG_AND_RETHROW() } - - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/basic_tests.cpp b/tests2/unit/tests/basic_tests.cpp deleted file mode 100644 index 8a933aaed4fd94531cd387604a52ce69398e8566..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/basic_tests.cpp +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Copyright (c) 2015 Cryptonomex, Inc., and contributors. - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/chain/database.hpp> -#include <hive/protocol/protocol.hpp> - -#include <hive/protocol/hive_operations.hpp> -#include <hive/chain/account_object.hpp> -#include <hive/chain/block_summary_object.hpp> -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/sps_objects.hpp> -#include <hive/chain/transaction_object.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <fc/crypto/digest.hpp> -#include <fc/crypto/hex.hpp> -#include "../db_fixture/database_fixture.hpp" - -#include <algorithm> -#include <random> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( basic_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( parse_size_test ) -{ - BOOST_CHECK_THROW( fc::parse_size( "" ), fc::parse_error_exception ); - BOOST_CHECK_THROW( fc::parse_size( "k" ), fc::parse_error_exception ); - - BOOST_CHECK_EQUAL( fc::parse_size( "0" ), 0 ); - BOOST_CHECK_EQUAL( fc::parse_size( "1" ), 1 ); - BOOST_CHECK_EQUAL( fc::parse_size( "2" ), 2 ); - BOOST_CHECK_EQUAL( fc::parse_size( "3" ), 3 ); - BOOST_CHECK_EQUAL( fc::parse_size( "4" ), 4 ); - - BOOST_CHECK_EQUAL( fc::parse_size( "9" ), 9 ); - BOOST_CHECK_EQUAL( fc::parse_size( "10" ), 10 ); - BOOST_CHECK_EQUAL( fc::parse_size( "11" ), 11 ); - BOOST_CHECK_EQUAL( fc::parse_size( "12" ), 12 ); - - BOOST_CHECK_EQUAL( fc::parse_size( "314159265"), 314159265 ); - BOOST_CHECK_EQUAL( fc::parse_size( "1k" ), 1024 ); - BOOST_CHECK_THROW( fc::parse_size( "1a" ), fc::parse_error_exception ); - BOOST_CHECK_EQUAL( fc::parse_size( "1kb" ), 1000 ); - BOOST_CHECK_EQUAL( fc::parse_size( "1MiB" ), 1048576 ); - BOOST_CHECK_EQUAL( fc::parse_size( "32G" ), 34359738368 ); -} - -/** - * Verify that names are RFC-1035 compliant https://tools.ietf.org/html/rfc1035 - * https://github.com/cryptonomex/graphene/issues/15 - */ -BOOST_AUTO_TEST_CASE( valid_name_test ) -{ - BOOST_CHECK( !is_valid_account_name( "a" ) ); - BOOST_CHECK( !is_valid_account_name( "A" ) ); - BOOST_CHECK( !is_valid_account_name( "0" ) ); - BOOST_CHECK( !is_valid_account_name( "." ) ); - BOOST_CHECK( !is_valid_account_name( "-" ) ); - - BOOST_CHECK( !is_valid_account_name( "aa" ) ); - BOOST_CHECK( !is_valid_account_name( "aA" ) ); - BOOST_CHECK( !is_valid_account_name( "a0" ) ); - BOOST_CHECK( !is_valid_account_name( "a." ) ); - BOOST_CHECK( !is_valid_account_name( "a-" ) ); - - BOOST_CHECK( is_valid_account_name( "aaa" ) ); - BOOST_CHECK( !is_valid_account_name( "aAa" ) ); - BOOST_CHECK( is_valid_account_name( "a0a" ) ); - BOOST_CHECK( !is_valid_account_name( "a.a" ) ); - BOOST_CHECK( is_valid_account_name( "a-a" ) ); - - BOOST_CHECK( is_valid_account_name( "aa0" ) ); - BOOST_CHECK( !is_valid_account_name( "aA0" ) ); - BOOST_CHECK( is_valid_account_name( "a00" ) ); - BOOST_CHECK( !is_valid_account_name( "a.0" ) ); - BOOST_CHECK( is_valid_account_name( "a-0" ) ); - - BOOST_CHECK( is_valid_account_name( "aaa-bbb-ccc" ) ); - BOOST_CHECK( is_valid_account_name( "aaa-bbb.ccc" ) ); - - BOOST_CHECK( !is_valid_account_name( "aaa,bbb-ccc" ) ); - BOOST_CHECK( !is_valid_account_name( "aaa_bbb-ccc" ) ); - BOOST_CHECK( !is_valid_account_name( "aaa-BBB-ccc" ) ); - - BOOST_CHECK( !is_valid_account_name( "1aaa-bbb" ) ); - BOOST_CHECK( !is_valid_account_name( "-aaa-bbb-ccc" ) ); - BOOST_CHECK( !is_valid_account_name( ".aaa-bbb-ccc" ) ); - BOOST_CHECK( !is_valid_account_name( "/aaa-bbb-ccc" ) ); - - BOOST_CHECK( !is_valid_account_name( "aaa-bbb-ccc-" ) ); - BOOST_CHECK( !is_valid_account_name( "aaa-bbb-ccc." ) ); - BOOST_CHECK( !is_valid_account_name( "aaa-bbb-ccc.." ) ); - BOOST_CHECK( !is_valid_account_name( "aaa-bbb-ccc/" ) ); - - BOOST_CHECK( !is_valid_account_name( "aaa..bbb-ccc" ) ); - BOOST_CHECK( is_valid_account_name( "aaa.bbb-ccc" ) ); - BOOST_CHECK( is_valid_account_name( "aaa.bbb.ccc" ) ); - - BOOST_CHECK( is_valid_account_name( "aaa--bbb--ccc" ) ); - BOOST_CHECK( !is_valid_account_name( "xn--san-p8a.de" ) ); - BOOST_CHECK( is_valid_account_name( "xn--san-p8a.dex" ) ); - BOOST_CHECK( !is_valid_account_name( "xn-san-p8a.de" ) ); - BOOST_CHECK( is_valid_account_name( "xn-san-p8a.dex" ) ); - - BOOST_CHECK( is_valid_account_name( "this-label-has" ) ); - BOOST_CHECK( !is_valid_account_name( "this-label-has-more-than-63-char.act.ers-64-to-be-really-precise" ) ); - BOOST_CHECK( !is_valid_account_name( "none.of.these.labels.has.more.than-63.chars--but.still.not.valid" ) ); -} - -BOOST_AUTO_TEST_CASE( merkle_root ) -{ - signed_block block; - vector<signed_transaction> tx; - vector<digest_type> t; - const uint32_t num_tx = 10; - - for( uint32_t i=0; i<num_tx; i++ ) - { - tx.emplace_back(); - tx.back().ref_block_prefix = i; - t.push_back( tx.back().merkle_digest() ); - } - - auto c = []( const digest_type& digest ) -> checksum_type - { return checksum_type::hash( digest ); }; - - auto d = []( const digest_type& left, const digest_type& right ) -> digest_type - { return digest_type::hash( std::make_pair( left, right ) ); }; - - BOOST_CHECK( block.calculate_merkle_root() == checksum_type() ); - - block.transactions.push_back( tx[0] ); - BOOST_CHECK( block.calculate_merkle_root() == - c(t[0]) - ); - - digest_type dA, dB, dC, dD, dE, dI, dJ, dK, dM, dN, dO; - - /**************** - * * - * A=d(0,1) * - * / \ * - * 0 1 * - * * - ****************/ - - dA = d(t[0], t[1]); - - block.transactions.push_back( tx[1] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dA) ); - - /************************* - * * - * I=d(A,B) * - * / \ * - * A=d(0,1) B=2 * - * / \ / * - * 0 1 2 * - * * - *************************/ - - dB = t[2]; - dI = d(dA, dB); - - block.transactions.push_back( tx[2] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dI) ); - - /*************************** - * * - * I=d(A,B) * - * / \ * - * A=d(0,1) B=d(2,3) * - * / \ / \ * - * 0 1 2 3 * - * * - *************************** - */ - - dB = d(t[2], t[3]); - dI = d(dA, dB); - - block.transactions.push_back( tx[3] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dI) ); - - /*************************************** - * * - * __M=d(I,J)__ * - * / \ * - * I=d(A,B) J=C * - * / \ / * - * A=d(0,1) B=d(2,3) C=4 * - * / \ / \ / * - * 0 1 2 3 4 * - * * - ***************************************/ - - dC = t[4]; - dJ = dC; - dM = d(dI, dJ); - - block.transactions.push_back( tx[4] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dM) ); - - /************************************** - * * - * __M=d(I,J)__ * - * / \ * - * I=d(A,B) J=C * - * / \ / * - * A=d(0,1) B=d(2,3) C=d(4,5) * - * / \ / \ / \ * - * 0 1 2 3 4 5 * - * * - **************************************/ - - dC = d(t[4], t[5]); - dJ = dC; - dM = d(dI, dJ); - - block.transactions.push_back( tx[5] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dM) ); - - /*********************************************** - * * - * __M=d(I,J)__ * - * / \ * - * I=d(A,B) J=d(C,D) * - * / \ / \ * - * A=d(0,1) B=d(2,3) C=d(4,5) D=6 * - * / \ / \ / \ / * - * 0 1 2 3 4 5 6 * - * * - ***********************************************/ - - dD = t[6]; - dJ = d(dC, dD); - dM = d(dI, dJ); - - block.transactions.push_back( tx[6] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dM) ); - - /************************************************* - * * - * __M=d(I,J)__ * - * / \ * - * I=d(A,B) J=d(C,D) * - * / \ / \ * - * A=d(0,1) B=d(2,3) C=d(4,5) D=d(6,7) * - * / \ / \ / \ / \ * - * 0 1 2 3 4 5 6 7 * - * * - *************************************************/ - - dD = d(t[6], t[7]); - dJ = d(dC, dD); - dM = d(dI, dJ); - - block.transactions.push_back( tx[7] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dM) ); - - /************************************************************************ - * * - * _____________O=d(M,N)______________ * - * / \ * - * __M=d(I,J)__ N=K * - * / \ / * - * I=d(A,B) J=d(C,D) K=E * - * / \ / \ / * - * A=d(0,1) B=d(2,3) C=d(4,5) D=d(6,7) E=8 * - * / \ / \ / \ / \ / * - * 0 1 2 3 4 5 6 7 8 * - * * - ************************************************************************/ - - dE = t[8]; - dK = dE; - dN = dK; - dO = d(dM, dN); - - block.transactions.push_back( tx[8] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dO) ); - - /************************************************************************ - * * - * _____________O=d(M,N)______________ * - * / \ * - * __M=d(I,J)__ N=K * - * / \ / * - * I=d(A,B) J=d(C,D) K=E * - * / \ / \ / * - * A=d(0,1) B=d(2,3) C=d(4,5) D=d(6,7) E=d(8,9) * - * / \ / \ / \ / \ / \ * - * 0 1 2 3 4 5 6 7 8 9 * - * * - ************************************************************************/ - - dE = d(t[8], t[9]); - dK = dE; - dN = dK; - dO = d(dM, dN); - - block.transactions.push_back( tx[9] ); - BOOST_CHECK( block.calculate_merkle_root() == c(dO) ); -} - -BOOST_AUTO_TEST_CASE( adjust_balance_test ) -{ - ACTORS( (alice) ); - - generate_block(); - - BOOST_TEST_MESSAGE( "Testing adjust_balance" ); - - BOOST_TEST_MESSAGE( " --- Testing adding HIVE_SYMBOL" ); - db->adjust_balance( "alice", asset( 50000, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( "alice", HIVE_SYMBOL ) == asset( 50000, HIVE_SYMBOL ) ); - - BOOST_TEST_MESSAGE( " --- Testing deducting HIVE_SYMBOL" ); - HIVE_REQUIRE_THROW( db->adjust_balance( "alice", asset( -50001, HIVE_SYMBOL ) ), fc::assert_exception ); - db->adjust_balance( "alice", asset( -30000, HIVE_SYMBOL ) ); - db->adjust_balance( "alice", asset( -20000, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( "alice", HIVE_SYMBOL ) == asset( 0, HIVE_SYMBOL ) ); - - BOOST_TEST_MESSAGE( " --- Testing adding HBD_SYMBOL" ); - db->adjust_balance( "alice", asset( 100000, HBD_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( "alice", HBD_SYMBOL ) == asset( 100000, HBD_SYMBOL ) ); - - BOOST_TEST_MESSAGE( " --- Testing deducting HBD_SYMBOL" ); - HIVE_REQUIRE_THROW( db->adjust_balance( "alice", asset( -100001, HBD_SYMBOL ) ), fc::assert_exception ); - db->adjust_balance( "alice", asset( -50000, HBD_SYMBOL ) ); - db->adjust_balance( "alice", asset( -25000, HBD_SYMBOL ) ); - db->adjust_balance( "alice", asset( -25000, HBD_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( "alice", HBD_SYMBOL ) == asset( 0, HBD_SYMBOL ) ); -} - -uint8_t find_msb( const uint128_t& u ) -{ - uint64_t x; - uint8_t places; - x = (u.lo ? u.lo : 1); - places = (u.hi ? 64 : 0); - x = (u.hi ? u.hi : x); - return uint8_t( boost::multiprecision::detail::find_msb(x) + places ); -} - -uint64_t approx_sqrt( const uint128_t& x ) -{ - if( (x.lo == 0) && (x.hi == 0) ) - return 0; - - uint8_t msb_x = find_msb(x); - uint8_t msb_z = msb_x >> 1; - - uint128_t msb_x_bit = uint128_t(1) << msb_x; - uint64_t msb_z_bit = uint64_t (1) << msb_z; - - uint128_t mantissa_mask = msb_x_bit - 1; - uint128_t mantissa_x = x & mantissa_mask; - uint64_t mantissa_z_hi = (msb_x & 1) ? msb_z_bit : 0; - uint64_t mantissa_z_lo = (mantissa_x >> (msb_x - msb_z)).lo; - uint64_t mantissa_z = (mantissa_z_hi | mantissa_z_lo) >> 1; - uint64_t result = msb_z_bit | mantissa_z; - - return result; -} - -BOOST_AUTO_TEST_CASE( curation_weight_test ) -{ - fc::uint128_t rshares = 856158; - fc::uint128_t s = uint128_t( 0, 2000000000000ull ); - fc::uint128_t sqrt = approx_sqrt( rshares + 2 * s ); - uint64_t result = ( rshares / sqrt ).to_uint64(); - - BOOST_REQUIRE( sqrt.to_uint64() == 2002250 ); - BOOST_REQUIRE( result == 0 ); - - rshares = 0; - sqrt = approx_sqrt( rshares + 2 * s ); - result = ( rshares / sqrt ).to_uint64(); - - BOOST_REQUIRE( sqrt.to_uint64() == 2002250 ); - BOOST_REQUIRE( result == 0 ); - - result = ( uint128_t( 0 ) - uint128_t( 0 ) ).to_uint64(); - - BOOST_REQUIRE( result == 0 ); - rshares = uint128_t( 0, 3351842535167ull ); - - for( int64_t i = 856158; i >= 0; --i ) - { - uint64_t old_weight = util::evaluate_reward_curve( rshares - i, protocol::convergent_square_root, s ).to_uint64(); - uint64_t new_weight = util::evaluate_reward_curve( rshares, protocol::convergent_square_root, s ).to_uint64(); - - BOOST_REQUIRE( old_weight <= new_weight ); - - uint128_t w( new_weight - old_weight ); - - w *= 300; - w /= 300; - BOOST_REQUIRE( w.to_uint64() == new_weight - old_weight ); - } - - //idump( (delta)(old_weight)(new_weight) ); - -} - -#if !defined ENABLE_MIRA && !defined ENABLE_STD_ALLOCATOR -BOOST_AUTO_TEST_CASE( chain_object_size ) -{ - //typical elements of various objects - BOOST_CHECK_EQUAL( sizeof( account_object::id_type ), 4 ); //hidden first element of all objects (here just an example, all are the same size) - BOOST_CHECK_EQUAL( sizeof( account_id_type ), 4 ); //all id_refs are of the same size - BOOST_CHECK_EQUAL( sizeof( time_point_sec ), 4 ); - BOOST_CHECK_EQUAL( sizeof( share_type ), 8 ); - BOOST_CHECK_EQUAL( sizeof( HIVE_asset ), 8 ); //all tiny assets are of the same size - BOOST_CHECK_EQUAL( sizeof( asset ), 16 ); - BOOST_CHECK_EQUAL( sizeof( account_name_type ), 16 ); - BOOST_CHECK_EQUAL( sizeof( shared_string ), 32 ); //it has dynamic component as well - BOOST_CHECK_EQUAL( sizeof( price ), 32 ); - BOOST_CHECK_EQUAL( sizeof( t_vector< char > ), 32 ); //it has dynamic component as well, all vectors have the same static size - - /* - The purpose of this test is to make you think about the impact on RAM when you make changes in chain objects. - Also somewhat helps in catching new problems with alignment (f.e. when you added a flag member and object - grew by 8 bytes it might be inevitable but it should prompt you to double check member placement). - Finally, especially when you are adding new objects, you should think if there is a mechanism (resource cost or - hard limit) that prevents use of the object creating operation in RAM attack. - */ - - //top RAM gluttons - BOOST_CHECK_EQUAL( sizeof( comment_object ), 36 ); //85M+ growing fast - BOOST_CHECK_EQUAL( sizeof( comment_content_object ), 104 ); //as many as comment_object, dynamic size matters the most, in HiveMind - - //permanent objects (no operation to remove) - BOOST_CHECK_EQUAL( sizeof( account_object ), 488 ); //1.3M+ - BOOST_CHECK_EQUAL( sizeof( account_metadata_object ), 72 ); //as many as account_object, but only FatNode (also to be moved to HiveMind) - BOOST_CHECK_EQUAL( sizeof( account_authority_object ), 248 ); //as many as account_object - BOOST_CHECK_EQUAL( sizeof( liquidity_reward_balance_object ), 48 ); //obsolete - only created/modified up to HF12 (683 objects) - BOOST_CHECK_EQUAL( sizeof( witness_object ), 352 ); //small but potentially as many as account_object - - //lasting objects (operation to create and remove, but with potential to grow) - BOOST_CHECK_EQUAL( sizeof( vesting_delegation_object ), 64 ); //1M+ (potential of account_object squared !!!) - BOOST_CHECK_EQUAL( sizeof( withdraw_vesting_route_object ), 48 ); //45k (potential of 10*account_object) - BOOST_CHECK_EQUAL( sizeof( witness_vote_object ), 40 ); //450k (potential of 30*account_object) - - //buffered objects (operation to create, op/vop to remove after certain time) - BOOST_CHECK_EQUAL( sizeof( transaction_object ), 64 ); //at most <1h> of transactions - BOOST_CHECK_EQUAL( sizeof( vesting_delegation_expiration_object ), 48 ); //at most <5d> of undelegates - BOOST_CHECK_EQUAL( sizeof( owner_authority_history_object ), 104 ); //at most <30d> of ownership updates - BOOST_CHECK_EQUAL( sizeof( account_recovery_request_object ), 104 ); //at most <1d> of account recoveries - BOOST_CHECK_EQUAL( sizeof( change_recovery_account_request_object ), 48 ); //at most <30d> of recovery account changes - BOOST_CHECK_EQUAL( sizeof( comment_cashout_object ), 200 //at most <7d> of unpaid comments (all comments prior to HF19) -#ifdef HIVE_ENABLE_SMT - + 32 -#endif - ); - BOOST_CHECK_EQUAL( sizeof( comment_vote_object ), 48 ); //at most <7d> of votes on unpaid comments - BOOST_CHECK_EQUAL( sizeof( convert_request_object ), 56 ); //at most <3.5d> of conversion requests - BOOST_CHECK_EQUAL( sizeof( escrow_object ), 120 ); //small but potentially lasting forever, limited to 255*account_object - BOOST_CHECK_EQUAL( sizeof( savings_withdraw_object ), 104 ); //at most <3d> of saving withdrawals - BOOST_CHECK_EQUAL( sizeof( limit_order_object ), 80 ); //at most <28d> of limit orders - BOOST_CHECK_EQUAL( sizeof( decline_voting_rights_request_object ), 32 ); //at most <30d> of decline requests - BOOST_CHECK_EQUAL( sizeof( proposal_object ), 144 ); //potentially infinite, but costs a lot to make (especially after HF24) - BOOST_CHECK_EQUAL( sizeof( proposal_vote_object ), 32 ); //potentially infinite, but limited by account_object and time of proposal_object life - - //singletons (size only affects performance, especially with MIRA) - BOOST_CHECK_EQUAL( sizeof( reward_fund_object ), 96 ); - BOOST_CHECK_EQUAL( sizeof( dynamic_global_property_object ), 344 -#ifdef HIVE_ENABLE_SMT - + 16 -#endif - ); - BOOST_CHECK_EQUAL( sizeof( block_summary_object ), 24 ); //always 64k objects - BOOST_CHECK_EQUAL( sizeof( hardfork_property_object ), 88 ); - BOOST_CHECK_EQUAL( sizeof( feed_history_object ), 136 ); //dynamic size worth 7*24 of sizeof(price) - BOOST_CHECK_EQUAL( sizeof( witness_schedule_object ), 536 ); - - //TODO: categorize and evaluate size potential of SMT related objects: - //account_regular_balance_object - //account_rewards_balance_object - //nai_pool_object - //smt_token_object - //smt_ico_object - //smt_token_emissions_object - //smt_contribution_object - - //only used in tests, but open for use in theory: - //pending_optional_action_object - //pending_required_action_object - - //not used in regular chain - //operation_object //obsolete? AH plugin - //account_history_object //obsolete? AH plugin -} -#endif - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests2/unit/tests/block_tests.cpp b/tests2/unit/tests/block_tests.cpp deleted file mode 100644 index aac4b35dada22025fffb3267d8d6a339cadb2dde..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/block_tests.cpp +++ /dev/null @@ -1,893 +0,0 @@ -/* - * Copyright (c) 2015 Cryptonomex, Inc., and contributors. - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/history_object.hpp> - -#include <hive/plugins/account_history/account_history_plugin.hpp> -#include <hive/plugins/witness/block_producer.hpp> - -#include <hive/utilities/tempdir.hpp> -#include <hive/utilities/database_configuration.hpp> - -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using namespace hive::plugins; - -#define TEST_SHARED_MEM_SIZE (1024 * 1024 * 8) - -BOOST_AUTO_TEST_SUITE(block_tests) - -void open_test_database( database& db, const fc::path& dir ) -{ - hive::chain::open_args args; - args.data_dir = dir; - args.shared_mem_dir = dir; - args.initial_supply = INITIAL_TEST_SUPPLY; - args.hbd_initial_supply = HBD_INITIAL_TEST_SUPPLY; - args.shared_file_size = TEST_SHARED_MEM_SIZE; - args.database_cfg = hive::utilities::default_database_configuration(); - db.open( args ); -} - -BOOST_AUTO_TEST_CASE( generate_empty_blocks ) -{ - try { - fc::time_point_sec now( HIVE_TESTING_GENESIS_TIMESTAMP ); - fc::temp_directory data_dir( hive::utilities::temp_directory_path() ); - signed_block b; - - // TODO: Don't generate this here - auto init_account_priv_key = fc::ecc::private_key::regenerate( fc::sha256::hash( string( "init_key" ) ) ); - signed_block cutoff_block; - { - database db; - witness::block_producer bp( db ); - db._log_hardforks = false; - open_test_database( db, data_dir.path() ); - b = bp.generate_block(db.get_slot_time(1), db.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - - // TODO: Change this test when we correct #406 - // n.b. we generate HIVE_MIN_UNDO_HISTORY+1 extra blocks which will be discarded on save - for( uint32_t i = 1; ; ++i ) - { - BOOST_CHECK( db.head_block_id() == b.id() ); - //witness_id_type prev_witness = b.witness; - string cur_witness = db.get_scheduled_witness(1); - //BOOST_CHECK( cur_witness != prev_witness ); - b = bp.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key, database::skip_nothing); - BOOST_CHECK( b.witness == cur_witness ); - uint32_t cutoff_height = db.get_dynamic_global_properties().last_irreversible_block_num; - if( cutoff_height >= 200 ) - { - auto block = db.fetch_block_by_number( cutoff_height ); - BOOST_REQUIRE( block.valid() ); - cutoff_block = *block; - break; - } - } - db.close(); - } - { - database db; - witness::block_producer bp( db ); - db._log_hardforks = false; - open_test_database( db, data_dir.path() ); - -#ifndef ENABLE_MIRA - BOOST_CHECK_EQUAL( db.head_block_num(), cutoff_block.block_num() ); -#endif - - b = cutoff_block; - for( uint32_t i = 0; i < 200; ++i ) - { -#ifndef ENABLE_MIRA - BOOST_CHECK( db.head_block_id() == b.id() ); -#else - BOOST_CHECK( i==0 || ( db.head_block_id() == b.id() ) ); -#endif - //witness_id_type prev_witness = b.witness; - string cur_witness = db.get_scheduled_witness(1); - //BOOST_CHECK( cur_witness != prev_witness ); - b = bp.generate_block(db.get_slot_time(1), cur_witness, init_account_priv_key, database::skip_nothing); - } -#ifndef ENABLE_MIRA - BOOST_CHECK_EQUAL( db.head_block_num(), cutoff_block.block_num()+200 ); -#endif - } - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( undo_block ) -{ - try { - fc::temp_directory data_dir( hive::utilities::temp_directory_path() ); - { - database db; - witness::block_producer bp( db ); - db._log_hardforks = false; - open_test_database( db, data_dir.path() ); - fc::time_point_sec now( HIVE_TESTING_GENESIS_TIMESTAMP ); - std::vector< time_point_sec > time_stack; - - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - for( uint32_t i = 0; i < 5; ++i ) - { - now = db.get_slot_time(1); - time_stack.push_back( now ); - auto b = bp.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing ); - } - BOOST_CHECK( db.head_block_num() == 5 ); - BOOST_CHECK( db.head_block_time() == now ); - db.pop_block(); - time_stack.pop_back(); - now = time_stack.back(); - BOOST_CHECK( db.head_block_num() == 4 ); - BOOST_CHECK( db.head_block_time() == now ); - db.pop_block(); - time_stack.pop_back(); - now = time_stack.back(); - BOOST_CHECK( db.head_block_num() == 3 ); - BOOST_CHECK( db.head_block_time() == now ); - db.pop_block(); - time_stack.pop_back(); - now = time_stack.back(); - BOOST_CHECK( db.head_block_num() == 2 ); - BOOST_CHECK( db.head_block_time() == now ); - for( uint32_t i = 0; i < 5; ++i ) - { - now = db.get_slot_time(1); - time_stack.push_back( now ); - auto b = bp.generate_block( now, db.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing ); - } - BOOST_CHECK( db.head_block_num() == 7 ); - } - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( fork_blocks ) -{ - try { - fc::temp_directory data_dir1( hive::utilities::temp_directory_path() ); - fc::temp_directory data_dir2( hive::utilities::temp_directory_path() ); - - //TODO This test needs 6-7 ish witnesses prior to fork - - database db1; - witness::block_producer bp1( db1 ); - db1._log_hardforks = false; - open_test_database( db1, data_dir1.path() ); - database db2; - witness::block_producer bp2( db2 ); - db2._log_hardforks = false; - open_test_database( db2, data_dir2.path() ); - - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - for( uint32_t i = 0; i < 10; ++i ) - { - auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - try { - PUSH_BLOCK( db2, b ); - } FC_CAPTURE_AND_RETHROW( ("db2") ); - } - for( uint32_t i = 10; i < 13; ++i ) - { - auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - } - string db1_tip = db1.head_block_id().str(); - uint32_t next_slot = 3; - for( uint32_t i = 13; i < 16; ++i ) - { - auto b = bp2.generate_block(db2.get_slot_time(next_slot), db2.get_scheduled_witness(next_slot), init_account_priv_key, database::skip_nothing); - next_slot = 1; - // notify both databases of the new block. - // only db2 should switch to the new fork, db1 should not - PUSH_BLOCK( db1, b ); - BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip); - BOOST_CHECK_EQUAL(db2.head_block_id().str(), b.id().str()); - } - - //The two databases are on distinct forks now, but at the same height. Make a block on db2, make it invalid, then - //pass it to db1 and assert that db1 doesn't switch to the new fork. - signed_block good_block; - BOOST_CHECK_EQUAL(db1.head_block_num(), 13); - BOOST_CHECK_EQUAL(db2.head_block_num(), 13); - { - auto b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - good_block = b; - b.transactions.emplace_back(signed_transaction()); - b.transactions.back().operations.emplace_back(transfer_operation()); - b.sign( init_account_priv_key ); - BOOST_CHECK_EQUAL(b.block_num(), 14); - HIVE_CHECK_THROW(PUSH_BLOCK( db1, b ), fc::exception); - } - BOOST_CHECK_EQUAL(db1.head_block_num(), 13); - BOOST_CHECK_EQUAL(db1.head_block_id().str(), db1_tip); - - // assert that db1 switches to new fork with good block - BOOST_CHECK_EQUAL(db2.head_block_num(), 14); - PUSH_BLOCK( db1, good_block ); - BOOST_CHECK_EQUAL(db1.head_block_id().str(), db2.head_block_id().str()); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( switch_forks_undo_create ) -{ - try { - fc::temp_directory dir1( hive::utilities::temp_directory_path() ), - dir2( hive::utilities::temp_directory_path() ); - database db1, - db2; - witness::block_producer bp1( db1 ), - bp2( db2 ); - db1._log_hardforks = false; - open_test_database( db1, dir1.path() ); - db2._log_hardforks = false; - open_test_database( db2, dir2.path() ); - - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - public_key_type init_account_pub_key = init_account_priv_key.get_public_key(); - db1.get_index< account_index >(); - - //* - signed_transaction trx; - account_create_operation cop; - cop.new_account_name = "alice"; - cop.creator = HIVE_INIT_MINER_NAME; - cop.owner = authority(1, init_account_pub_key, 1); - cop.active = cop.owner; - trx.operations.push_back(cop); - trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - PUSH_TX( db1, trx ); - //*/ - // generate blocks - // db1 : A - // db2 : B C D - - auto b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - - auto alice_id = db1.get_account( "alice" ).get_id(); - BOOST_CHECK( db1.get(alice_id).name == "alice" ); - - b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - db1.push_block(b); - b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - db1.push_block(b); - HIVE_REQUIRE_THROW(db2.get(alice_id), std::exception); - db1.get(alice_id); /// it should be included in the pending state - db1.clear_pending(); // clear it so that we can verify it was properly removed from pending state. - HIVE_REQUIRE_THROW(db1.get(alice_id), std::exception); - - PUSH_TX( db2, trx ); - - b = bp2.generate_block(db2.get_slot_time(1), db2.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - db1.push_block(b); - - BOOST_CHECK( db1.get(alice_id).name == "alice"); - BOOST_CHECK( db2.get(alice_id).name == "alice"); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( duplicate_transactions ) -{ - try { - fc::temp_directory dir1( hive::utilities::temp_directory_path() ), - dir2( hive::utilities::temp_directory_path() ); - database db1, - db2; - witness::block_producer bp1( db1 ); - db1._log_hardforks = false; - open_test_database( db1, dir1.path() ); - db2._log_hardforks = false; - open_test_database( db2, dir2.path() ); - BOOST_CHECK( db1.get_chain_id() == db2.get_chain_id() ); - - auto skip_sigs = database::skip_transaction_signatures | database::skip_authority_check; - - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - public_key_type init_account_pub_key = init_account_priv_key.get_public_key(); - - signed_transaction trx; - account_create_operation cop; - cop.new_account_name = "alice"; - cop.creator = HIVE_INIT_MINER_NAME; - cop.owner = authority(1, init_account_pub_key, 1); - cop.active = cop.owner; - trx.operations.push_back(cop); - trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - PUSH_TX( db1, trx, skip_sigs ); - - trx = decltype(trx)(); - transfer_operation t; - t.from = HIVE_INIT_MINER_NAME; - t.to = "alice"; - t.amount = asset(500,HIVE_SYMBOL); - trx.operations.push_back(t); - trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - PUSH_TX( db1, trx, skip_sigs ); - - HIVE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception); - - auto b = bp1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key, skip_sigs ); - PUSH_BLOCK( db2, b, skip_sigs ); - - HIVE_CHECK_THROW(PUSH_TX( db1, trx, skip_sigs ), fc::exception); - HIVE_CHECK_THROW(PUSH_TX( db2, trx, skip_sigs ), fc::exception); - BOOST_CHECK_EQUAL(db1.get_balance( "alice", HIVE_SYMBOL ).amount.value, 500); - BOOST_CHECK_EQUAL(db2.get_balance( "alice", HIVE_SYMBOL ).amount.value, 500); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( tapos ) -{ - try { - fc::temp_directory dir1( hive::utilities::temp_directory_path() ); - database db1; - witness::block_producer bp1( db1 ); - db1._log_hardforks = false; - open_test_database( db1, dir1.path() ); - - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - public_key_type init_account_pub_key = init_account_priv_key.get_public_key(); - - auto b = bp1.generate_block( db1.get_slot_time(1), db1.get_scheduled_witness( 1 ), init_account_priv_key, database::skip_nothing); - - BOOST_TEST_MESSAGE( "Creating a transaction with reference block" ); - idump((db1.head_block_id())); - signed_transaction trx; - //This transaction must be in the next block after its reference, or it is invalid. - trx.set_reference_block( db1.head_block_id() ); - - account_create_operation cop; - cop.new_account_name = "alice"; - cop.creator = HIVE_INIT_MINER_NAME; - cop.owner = authority(1, init_account_pub_key, 1); - cop.active = cop.owner; - trx.operations.push_back(cop); - trx.set_expiration( db1.head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - - BOOST_TEST_MESSAGE( "Pushing Pending Transaction" ); - idump((trx)); - db1.push_transaction(trx); - BOOST_TEST_MESSAGE( "Generating a block" ); - b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - trx.clear(); - - transfer_operation t; - t.from = HIVE_INIT_MINER_NAME; - t.to = "alice"; - t.amount = asset(50,HIVE_SYMBOL); - trx.operations.push_back(t); - trx.set_expiration( db1.head_block_time() + fc::seconds(2) ); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - idump((trx)(db1.head_block_time())); - b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - idump((b)); - b = bp1.generate_block(db1.get_slot_time(1), db1.get_scheduled_witness(1), init_account_priv_key, database::skip_nothing); - trx.signatures.clear(); - trx.sign( init_account_priv_key, db1.get_chain_id(), fc::ecc::fc_canonical ); - BOOST_REQUIRE_THROW( db1.push_transaction(trx, 0/*database::skip_transaction_signatures | database::skip_authority_check*/), fc::exception ); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_FIXTURE_TEST_CASE( optional_tapos, clean_database_fixture ) -{ - try - { - idump((db->get_account("initminer"))); - ACTORS( (alice)(bob) ); - - generate_block(); - - BOOST_TEST_MESSAGE( "Create transaction" ); - - transfer( HIVE_INIT_MINER_NAME, "alice", asset( 1000000, HIVE_SYMBOL ) ); - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = asset(1000,HIVE_SYMBOL); - signed_transaction tx; - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=0" ); - - tx.ref_block_num = 0; - tx.ref_block_prefix = 0; - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - PUSH_TX( *db, tx ); - - BOOST_TEST_MESSAGE( "proper ref_block_num, ref_block_prefix" ); - - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - PUSH_TX( *db, tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "ref_block_num=0, ref_block_prefix=12345678" ); - - tx.ref_block_num = 0; - tx.ref_block_prefix = 0x12345678; - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_TEST_MESSAGE( "ref_block_num=1, ref_block_prefix=12345678" ); - - tx.ref_block_num = 1; - tx.ref_block_prefix = 0x12345678; - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_TEST_MESSAGE( "ref_block_num=9999, ref_block_prefix=12345678" ); - - tx.ref_block_num = 9999; - tx.ref_block_prefix = 0x12345678; - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( PUSH_TX( *db, tx, database::skip_transaction_dupe_check ), fc::exception ); - } - catch (fc::exception& e) - { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_FIXTURE_TEST_CASE( double_sign_check, clean_database_fixture ) -{ try { - generate_block(); - ACTOR(bob); - share_type amount = 1000; - - transfer_operation t; - t.from = HIVE_INIT_MINER_NAME; - t.to = "bob"; - t.amount = asset(amount,HIVE_SYMBOL); - trx.operations.push_back(t); - trx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - trx.validate(); - - db->push_transaction(trx, ~0); - - trx.operations.clear(); - t.from = "bob"; - t.to = HIVE_INIT_MINER_NAME; - t.amount = asset(amount,HIVE_SYMBOL); - trx.operations.push_back(t); - trx.validate(); - - BOOST_TEST_MESSAGE( "Verify that not-signing causes an exception" ); - HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), fc::exception ); - - BOOST_TEST_MESSAGE( "Verify that double-signing causes an exception" ); - sign( trx, bob_private_key ); - sign( trx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "Verify that signing with an extra, unused key fails" ); - trx.signatures.pop_back(); - sign( trx, generate_private_key( "bogus" ) ); - HIVE_REQUIRE_THROW( db->push_transaction(trx, 0), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "Verify that signing once with the proper key passes" ); - trx.signatures.pop_back(); - db->push_transaction(trx, 0); - sign( trx, bob_private_key ); - -} FC_LOG_AND_RETHROW() } - -BOOST_FIXTURE_TEST_CASE( pop_block_twice, clean_database_fixture ) -{ - try - { - uint32_t skip_flags = ( - database::skip_witness_signature - | database::skip_transaction_signatures - | database::skip_authority_check - ); - - // Sam is the creator of accounts - auto init_account_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init_key")) ); - private_key_type sam_key = generate_private_key( "sam" ); - account_create( "sam", sam_key.get_public_key() ); - - //Get a sane head block time - generate_block( skip_flags ); - - transaction tx; - signed_transaction ptx; - - db->get_account( HIVE_INIT_MINER_NAME ); - // transfer from committee account to Sam account - transfer( HIVE_INIT_MINER_NAME, "sam", asset( 100000, HIVE_SYMBOL ) ); - - generate_block(skip_flags); - - account_create( "alice", generate_private_key( "alice" ).get_public_key() ); - generate_block(skip_flags); - account_create( "bob", generate_private_key( "bob" ).get_public_key() ); - generate_block(skip_flags); - - db->pop_block(); - db->pop_block(); - } catch(const fc::exception& e) { - edump( (e.to_detail_string()) ); - throw; - } -} - -BOOST_FIXTURE_TEST_CASE( rsf_missed_blocks, clean_database_fixture ) -{ - try - { - generate_block(); - - auto rsf = [&]() -> string - { - fc::uint128 rsf = db->get_dynamic_global_properties().recent_slots_filled; - string result = ""; - result.reserve(128); - for( int i=0; i<128; i++ ) - { - result += ((rsf.lo & 1) == 0) ? '0' : '1'; - rsf >>= 1; - } - return result; - }; - - auto pct = []( uint32_t x ) -> uint32_t - { - return uint64_t( HIVE_100_PERCENT ) * x / 128; - }; - - BOOST_TEST_MESSAGE("checking initial participation rate" ); - BOOST_CHECK_EQUAL( rsf(), - "1111111111111111111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), HIVE_100_PERCENT ); - - BOOST_TEST_MESSAGE("Generating a block skipping 1" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 1 ); - BOOST_CHECK_EQUAL( rsf(), - "0111111111111111111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(127) ); - - BOOST_TEST_MESSAGE("Generating a block skipping 1" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 1 ); - BOOST_CHECK_EQUAL( rsf(), - "0101111111111111111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(126) ); - - BOOST_TEST_MESSAGE("Generating a block skipping 2" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 2 ); - BOOST_CHECK_EQUAL( rsf(), - "0010101111111111111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(124) ); - - BOOST_TEST_MESSAGE("Generating a block for skipping 3" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 3 ); - BOOST_CHECK_EQUAL( rsf(), - "0001001010111111111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(121) ); - - BOOST_TEST_MESSAGE("Generating a block skipping 5" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 5 ); - BOOST_CHECK_EQUAL( rsf(), - "0000010001001010111111111111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(116) ); - - BOOST_TEST_MESSAGE("Generating a block skipping 8" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 8 ); - BOOST_CHECK_EQUAL( rsf(), - "0000000010000010001001010111111111111111111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(108) ); - - BOOST_TEST_MESSAGE("Generating a block skipping 13" ); - generate_block( ~database::skip_fork_db, init_account_priv_key, 13 ); - BOOST_CHECK_EQUAL( rsf(), - "0000000000000100000000100000100010010101111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) ); - - BOOST_TEST_MESSAGE("Generating a block skipping none" ); - generate_block(); - BOOST_CHECK_EQUAL( rsf(), - "1000000000000010000000010000010001001010111111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) ); - - BOOST_TEST_MESSAGE("Generating a block" ); - generate_block(); - BOOST_CHECK_EQUAL( rsf(), - "1100000000000001000000001000001000100101011111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) ); - - generate_block(); - BOOST_CHECK_EQUAL( rsf(), - "1110000000000000100000000100000100010010101111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) ); - - generate_block(); - BOOST_CHECK_EQUAL( rsf(), - "1111000000000000010000000010000010001001010111111111111111111111" - "1111111111111111111111111111111111111111111111111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(95) ); - - generate_block( ~database::skip_fork_db, init_account_priv_key, 64 ); - BOOST_CHECK_EQUAL( rsf(), - "0000000000000000000000000000000000000000000000000000000000000000" - "1111100000000000001000000001000001000100101011111111111111111111" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(31) ); - - generate_block( ~database::skip_fork_db, init_account_priv_key, 32 ); - BOOST_CHECK_EQUAL( rsf(), - "0000000000000000000000000000000010000000000000000000000000000000" - "0000000000000000000000000000000001111100000000000001000000001000" - ); - BOOST_CHECK_EQUAL( db->witness_participation_rate(), pct(8) ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_FIXTURE_TEST_CASE( skip_block, clean_database_fixture ) -{ - try - { - BOOST_TEST_MESSAGE( "Skipping blocks through db" ); - BOOST_REQUIRE( db->head_block_num() == 2 ); - - witness::block_producer bp( *db ); - int init_block_num = db->head_block_num(); - int miss_blocks = fc::minutes( 1 ).to_seconds() / HIVE_BLOCK_INTERVAL; - auto witness = db->get_scheduled_witness( miss_blocks ); - auto block_time = db->get_slot_time( miss_blocks ); - bp.generate_block( block_time , witness, init_account_priv_key, 0 ); - - BOOST_CHECK_EQUAL( db->head_block_num(), init_block_num + 1 ); - BOOST_CHECK( db->head_block_time() == block_time ); - - BOOST_TEST_MESSAGE( "Generating a block through fixture" ); - generate_block(); - - BOOST_CHECK_EQUAL( db->head_block_num(), init_block_num + 2 ); - BOOST_CHECK( db->head_block_time() == block_time + HIVE_BLOCK_INTERVAL ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_FIXTURE_TEST_CASE( hardfork_test, database_fixture ) -{ - try - { - try { - int argc = boost::unit_test::framework::master_test_suite().argc; - char** argv = boost::unit_test::framework::master_test_suite().argv; - for( int i=1; i<argc; i++ ) - { - const std::string arg = argv[i]; - if( arg == "--record-assert-trip" ) - fc::enable_record_assert_trip = true; - if( arg == "--show-test-names" ) - std::cout << "running test " << boost::unit_test::framework::current_test_case().p_name << std::endl; - } - appbase::app().register_plugin< hive::plugins::account_history::account_history_plugin >(); - db_plugin = &appbase::app().register_plugin< hive::plugins::debug_node::debug_node_plugin >(); - init_account_pub_key = init_account_priv_key.get_public_key(); - - appbase::app().initialize< - hive::plugins::account_history::account_history_plugin, - hive::plugins::debug_node::debug_node_plugin - >( argc, argv ); - - db = &appbase::app().get_plugin< hive::plugins::chain::chain_plugin >().db(); - BOOST_REQUIRE( db ); - - - open_database(); - - generate_blocks( 2 ); - - vest( "initminer", 10000 ); - - // Fill up the rest of the required miners - for( int i = HIVE_NUM_INIT_MINERS; i < HIVE_MAX_WITNESSES; i++ ) - { - account_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_pub_key ); - fund( HIVE_INIT_MINER_NAME + fc::to_string( i ), HIVE_MIN_PRODUCER_REWARD.amount.value ); - witness_create( HIVE_INIT_MINER_NAME + fc::to_string( i ), init_account_priv_key, "foo.bar", init_account_pub_key, HIVE_MIN_PRODUCER_REWARD.amount ); - } - - validate_database(); - } catch ( const fc::exception& e ) - { - edump( (e.to_detail_string()) ); - throw; - } - - BOOST_TEST_MESSAGE( "Check hardfork not applied at genesis" ); - BOOST_REQUIRE( db->has_hardfork( 0 ) ); - BOOST_REQUIRE( !db->has_hardfork( HIVE_HARDFORK_0_1 ) ); - - BOOST_TEST_MESSAGE( "Generate blocks up to the hardfork time and check hardfork still not applied" ); - generate_blocks( fc::time_point_sec( HIVE_HARDFORK_0_1_TIME - HIVE_BLOCK_INTERVAL ), true ); - - BOOST_REQUIRE( db->has_hardfork( 0 ) ); - BOOST_REQUIRE( !db->has_hardfork( HIVE_HARDFORK_0_1 ) ); - - BOOST_TEST_MESSAGE( "Generate a block and check hardfork is applied" ); - generate_block(); - - string op_msg = "Testnet: Hardfork applied"; - auto itr = db->get_index< account_history_index >().indices().get< by_id >().end(); - itr--; - - BOOST_REQUIRE( db->has_hardfork( 0 ) ); - BOOST_REQUIRE( db->has_hardfork( HIVE_HARDFORK_0_1 ) ); - operation hardfork_vop = hardfork_operation( HIVE_HARDFORK_0_1 ); - - BOOST_REQUIRE( get_last_operations( 1 )[0] == hardfork_vop ); - BOOST_REQUIRE( db->get(itr->op).timestamp == db->head_block_time() ); - - BOOST_TEST_MESSAGE( "Testing hardfork is only applied once" ); - generate_block(); - - itr = db->get_index< account_history_index >().indices().get< by_id >().end(); - itr--; - - BOOST_REQUIRE( db->has_hardfork( 0 ) ); - BOOST_REQUIRE( db->has_hardfork( HIVE_HARDFORK_0_1 ) ); - BOOST_REQUIRE( get_last_operations( 1 )[0] == hardfork_vop ); - BOOST_REQUIRE( db->get(itr->op).timestamp == db->head_block_time() - HIVE_BLOCK_INTERVAL ); - - } - catch( fc::exception& e ) - { - db->wipe( data_dir->path(), data_dir->path(), true ); - throw e; - } - catch( std::exception& e ) - { - db->wipe( data_dir->path(), data_dir->path(), true ); - throw e; - } - - db->wipe( data_dir->path(), data_dir->path(), true ); -} - -BOOST_FIXTURE_TEST_CASE( generate_block_size, clean_database_fixture ) -{ - try - { - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.maximum_block_size = HIVE_MIN_BLOCK_SIZE_LIMIT; - }); - }); - generate_block(); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - transfer_operation op; - op.from = HIVE_INIT_MINER_NAME; - op.to = HIVE_TEMP_ACCOUNT; - op.amount = asset( 1000, HIVE_SYMBOL ); - - // tx minus op is 79 bytes - // op is 33 bytes (32 for op + 1 byte static variant tag) - // total is 65254 - // Original generation logic only allowed 115 bytes for the header - // We are targetting a size (minus header) of 65421 which creates a block of "size" 65535 - // This block will actually be larger because the header estimates is too small - - for( size_t i = 0; i < 1975; i++ ) - { - tx.operations.push_back( op ); - } - - sign( tx, init_account_priv_key ); - db->push_transaction( tx, 0 ); - - // Second transaction, tx minus op is 78 (one less byte for operation vector size) - // We need a 88 byte op. We need a 22 character memo (1 byte for length) 55 = 32 (old op) + 55 + 1 - op.memo = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, init_account_priv_key ); - db->push_transaction( tx, 0 ); - - generate_block(); - - // The last transfer should have been delayed due to size - auto head_block = db->fetch_block_by_number( db->head_block_num() ); - BOOST_REQUIRE( head_block->transactions.size() == 1 ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/bmic_tests.cpp b/tests2/unit/tests/bmic_tests.cpp deleted file mode 100644 index 89e9f751db3b60790476e71a78cf6050105efcf1..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/bmic_tests.cpp +++ /dev/null @@ -1,468 +0,0 @@ -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include "../bmic_objects/bmic_manager_tests.hpp" - -template < typename Container, typename Object, typename Call > -void basic_test( const std::vector< uint64_t >& v, Call&& call ) -{ - Container c; - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item, &call ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - call( obj ); - obj.val = 100 - item; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Removing all objects" ); - c.clear(); - BOOST_REQUIRE( c.size() == 0 ); - - BOOST_TEST_MESSAGE( "Creating 1 object" ); - auto constructor2 = [ &call ]( Object &obj ) - { - obj.id = typename Object::id_type( 0 ); - call( obj ); - obj.val = 888; - }; - c.emplace( std::move( Object( constructor2, std::allocator< Object >() ) ) ); - - BOOST_TEST_MESSAGE( "Modyfing 1 object" ); - BOOST_REQUIRE( c.modify( c.begin(), []( Object& obj ){ obj.val = obj.val + 1; } ) == true ); - BOOST_REQUIRE( c.size() == 1 ); - - BOOST_TEST_MESSAGE( "Removing 1 object" ); - c.erase( c.begin() ); - BOOST_REQUIRE( c.size() == 0 ); - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item, &call ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - call( obj ); - obj.val = 100 - item; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Removing all objects one by one" ); - auto it = c.begin(); - while( it != c.end() ) - { - auto tmp = it; - ++it; - c.erase( tmp ); - } - BOOST_REQUIRE( c.size() == 0 ); -} - -template < typename Container, typename Object, typename Call > -void insert_remove_test( const std::vector< uint64_t >& v, Call&& call ) -{ - Container c; - - int64_t cnt = 0; - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item, &call ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - call( obj ); - obj.val = item; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - ++cnt; - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Removing objects one by one. Every object is removed by erase method" ); - for( int64_t i = 0; i < cnt; ++i ) - { - auto found = c.find( typename Object::id_type( i ) ); - BOOST_REQUIRE( found != c.end() ); - c.erase( found ); - BOOST_REQUIRE( v.size() - i - 1 == c.size() ); - } - BOOST_REQUIRE( c.size() == 0 ); - - BOOST_TEST_MESSAGE( "Creating 2 objects" ); - cnt = 0; - for( const auto& item: v ) - { - auto constructor = [ &item, &cnt, &call ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - call( obj ); - obj.val = cnt; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - if( ++cnt == 2 ) - break; - } - BOOST_REQUIRE( c.size() == 2 ); - - BOOST_TEST_MESSAGE( "Removing first object" ); - const Object& object = *( c.begin() ); - auto found = c.iterator_to( object ); - BOOST_REQUIRE( found != c.end() ); - c.erase( found ); - BOOST_REQUIRE( c.size() == 1 ); - - BOOST_TEST_MESSAGE( "Adding object with id_key = 0" ); - auto constructor1 = [ &v, &call ]( Object &obj ) - { - obj.id = typename Object::id_type( v[0] ); - call( obj ); - obj.val = 100; - }; - c.emplace( std::move( Object( constructor1, std::allocator< Object >() ) ) ); - BOOST_REQUIRE( c.size() == 2 ); - - BOOST_TEST_MESSAGE( "Remove second object" ); - found = c.end(); - --found; - auto first = std::prev( found, 1 ); - c.erase( found ); - BOOST_REQUIRE( c.size() == 1 ); - c.erase( first ); - BOOST_REQUIRE( c.size() == 0 ); -} - -template < typename Container, typename Object, typename Call1, typename Call2, typename Call3, typename Call4 > -void insert_remove_collision_test( const std::vector< uint64_t >& v, Call1&& call1, Call2&& call2, Call3&& call3, Call4&& call4 ) -{ - Container c; - - BOOST_TEST_MESSAGE( "Adding 2 objects with collision - the same id" ); - c.emplace( std::move( Object( call1, std::allocator< Object >() ) ) ); - auto failed_emplace = c.emplace( Object( call2, std::allocator< Object >() ) ); - BOOST_REQUIRE( failed_emplace.second == false ); - BOOST_REQUIRE( c.size() == 1 ); - - BOOST_TEST_MESSAGE( "Removing object and adding 2 objects with collision - the same name+val" ); - c.erase( c.begin() ); - c.emplace( std::move( Object( call3, std::allocator< Object >() ) ) ); - failed_emplace = c.emplace( Object( call4, std::allocator< Object >() ) ); - BOOST_REQUIRE( failed_emplace.second == false ); - BOOST_REQUIRE( c.size() == 1 ); -} - -template < typename Container, typename Object, typename Call1, typename Call2, typename Call3, typename Call4, typename Call5 > -void modify_test( const std::vector< uint64_t >& v, Call1&& call1, Call2&& call2, Call3&& call3, Call4&& call4, Call5&& call5 ) -{ - Container c; - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item, &call1 ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - call1( obj ); - obj.val = item + 100; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Modifying key in all objects" ); - auto it = c.begin(); - auto end = c.end(); - for( ; it != end; ++it ) - c.modify( it, call2 ); - BOOST_REQUIRE( v.size() == c.size() ); - int32_t cnt = 0; - for( const auto& item : c ) - { - BOOST_REQUIRE( size_t( item.id ) == v[ cnt++ ] ); - call3( item ); - call4( item ); - } - - BOOST_TEST_MESSAGE( "Modifying 'val' key in order to create collisions for all objects" ); - uint32_t first_val = c.begin()->val; - it = std::next( c.begin(), 1 ); - for( ; it != end; ++it ) - { - bool result = c.modify( it, [&]( Object& obj ){ obj.val = first_val; } ); - call5( result ); - if( !result ) - it = c.begin(); - } -} - -template < typename Container, typename Object, typename SimpleIndex, typename ComplexIndex > -void misc_test( const std::vector< uint64_t >& v ) -{ - Container c; - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - obj.name = "any_name"; - obj.val = item + 200; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Reading all elements" ); - uint32_t cnt = 0; - for( const auto& item : c ) - { - BOOST_REQUIRE( size_t( item.id ) == v[ cnt++ ] ); - BOOST_REQUIRE( item.name == "any_name" ); - BOOST_REQUIRE( item.val == size_t( item.id ) + 200 ); - } - - BOOST_TEST_MESSAGE( "Removing 2 objects: first and last" ); - c.erase( c.iterator_to( *( c.begin() ) ) ); - c.erase( c.iterator_to( *( std::prev( c.end(), 1 ) ) ) ); - BOOST_REQUIRE( v.size() - 2 == c.size() ); - - //Modyfing key `name` in one object. - auto it1 = c.iterator_to( *c.begin() ); - c.modify( it1, []( Object& obj ){ obj.name = "completely_different_name"; } ); - it1 = c.iterator_to( *c.begin() ); - BOOST_REQUIRE( it1->name == "completely_different_name" ); - uint32_t val1 = it1->val; - - //Creating collision in two objects: [1] and [2] - auto it2 = c.iterator_to( *std::next( c.begin(), 2 ) ); - BOOST_REQUIRE( c.modify( it2, [ val1 ]( Object& obj ){ obj.name = "completely_different_name"; obj.val = val1;} ) == false ); - - //Removing object [1]. - it1 = c.iterator_to( *std::next( c.begin(), 1 ) ); - c.erase( it1 ); - BOOST_REQUIRE( v.size() - 4 == c.size() ); - - //Removing all remaining objects - auto it_erase = c.begin(); - while( it_erase != c.end() ) - { - auto tmp = it_erase; - ++it_erase; - c.erase( tmp ); - } - BOOST_REQUIRE( c.size() == 0 ); - - cnt = 0; - BOOST_TEST_MESSAGE( "Creating `v.size()` objects. There are 'v.size() - 1' collisions." ); - for( const auto& item: v ) - { - auto constructor = [ &item ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - obj.name = "all_objects_have_the_same_name"; - obj.val = 667; - }; - if( cnt == 0 ) - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - else - BOOST_REQUIRE_THROW( c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ), boost::exception ); - } - BOOST_REQUIRE( c.size() == 1 ); - auto it_only_one = c.iterator_to( *c.begin() ); - BOOST_REQUIRE( size_t( it_only_one->id ) == v[0] ); - BOOST_REQUIRE( it_only_one->name == "all_objects_have_the_same_name" ); - BOOST_REQUIRE( it_only_one->val == 667 ); - - BOOST_TEST_MESSAGE( "Erasing one objects." ); - c.erase( it_only_one ); - BOOST_REQUIRE( c.size() == 0 ); - - cnt = 0; - BOOST_TEST_MESSAGE( "Creating `v.size()` objects." ); - for( const auto& item: v ) - { - auto constructor = [ &item, &cnt ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - obj.name = "object nr:" + std::to_string( cnt++ ); - obj.val = 5000; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( c.size() == v.size() ); - - BOOST_TEST_MESSAGE( "Finding some objects according to given index." ); - const auto& ordered_idx = c.template get< SimpleIndex >(); - const auto& composite_ordered_idx = c.template get< ComplexIndex >(); - - auto found = ordered_idx.find( typename Object::id_type( v.size() - 1 ) ); - BOOST_REQUIRE( found != ordered_idx.end() ); - BOOST_REQUIRE( size_t( found->id ) == v.size() - 1 ); - - found = ordered_idx.find( typename Object::id_type( 987654 ) ); - BOOST_REQUIRE( found == ordered_idx.end() ); - - found = ordered_idx.find( typename Object::id_type( v[0] ) ); - BOOST_REQUIRE( found != ordered_idx.end() ); - - auto cfound = composite_ordered_idx.find( boost::make_tuple( "stupid_name", 5000 ) ); - BOOST_REQUIRE( cfound == composite_ordered_idx.end() ); - - cfound = composite_ordered_idx.find( boost::make_tuple( "object nr:" + std::to_string( 0 ), 5000 ) ); - auto copy_cfound = cfound; - auto cfound2 = composite_ordered_idx.find( boost::make_tuple( "object nr:" + std::to_string( 9 ), 5000 ) ); - BOOST_REQUIRE( cfound == composite_ordered_idx.begin() ); - BOOST_REQUIRE( cfound2 == std::prev( composite_ordered_idx.end(), 1 ) ); - cnt = 0; - while( cfound++ != composite_ordered_idx.end() ) - ++cnt; - BOOST_REQUIRE( cnt == v.size() ); - - BOOST_TEST_MESSAGE( "Removing all data using iterators from 'ComplexIndex' index"); - while( copy_cfound != composite_ordered_idx.end() ) - { - auto tmp = copy_cfound; - ++copy_cfound; - c.erase( c.iterator_to( *tmp ) ); - } - BOOST_REQUIRE( c.size() == 0 ); -} - -template < typename Container, typename Object, typename SimpleIndex, typename ComplexIndex, typename AnotherComplexIndex > -void misc_test3( const std::vector< uint64_t >& v ) -{ - Container c; - - BOOST_TEST_MESSAGE( "Creating `v.size()` objects" ); - for( const auto& item: v ) - { - auto constructor = [ &item ]( Object &obj ) - { - obj.id = typename Object::id_type( item ); - obj.val = item + 1; - obj.val2 = item + 2; - obj.val3 = item + 3; - }; - c.emplace( std::move( Object( constructor, std::allocator< Object >() ) ) ); - } - BOOST_REQUIRE( v.size() == c.size() ); - - BOOST_TEST_MESSAGE( "Finding some objects according to given index." ); - const auto& ordered_idx = c.template get< SimpleIndex >(); - const auto& composite_ordered_idx = c.template get< ComplexIndex >(); - const auto& another_composite_ordered_idx = c.template get< AnotherComplexIndex >(); - - auto found = ordered_idx.lower_bound( typename Object::id_type( 5739854 ) ); - BOOST_REQUIRE( found == ordered_idx.end() ); - - found = ordered_idx.upper_bound( typename Object::id_type( 5739854 ) ); - BOOST_REQUIRE( found == ordered_idx.end() ); - - found = ordered_idx.lower_bound( ordered_idx.begin()->id ); - BOOST_REQUIRE( found == ordered_idx.begin() ); - - auto found2 = ordered_idx.upper_bound( ordered_idx.begin()->id ); - BOOST_REQUIRE( found == std::prev( found2, 1 ) ); - - auto cfound = composite_ordered_idx.find( boost::make_tuple( 667, 5000 ) ); - BOOST_REQUIRE( cfound == composite_ordered_idx.end() ); - - cfound = composite_ordered_idx.find( boost::make_tuple( 0 + 1, 0 + 2 ) ); - BOOST_REQUIRE( cfound != composite_ordered_idx.end() ); - - auto another_cfound = another_composite_ordered_idx.find( boost::make_tuple( 0 + 1, 0 + 3 ) ); - BOOST_REQUIRE( another_cfound != another_composite_ordered_idx.end() ); - - BOOST_TEST_MESSAGE( "Removing 1 object using iterator from 'AnotherComplexIndex' index"); - c.erase( c.iterator_to( *another_cfound ) ); - BOOST_REQUIRE( c.size() == v.size() - 1 ); - - another_cfound = another_composite_ordered_idx.find( boost::make_tuple( 0 + 1, 0 + 3 ) ); - BOOST_REQUIRE( another_cfound == another_composite_ordered_idx.end() ); -} - -BOOST_AUTO_TEST_SUITE(bmic_tests) - -BOOST_AUTO_TEST_CASE(basic_tests) -{ - auto c1 = []( bmic::test_object& obj ) { obj.name = "_name"; }; - auto c1b = []( bmic::test_object2& obj ) {}; - auto c1c = []( bmic::test_object3& obj ) { obj.val2 = 5; obj.val3 = 5; }; - - basic_test< bmic::test_object_index, bmic::test_object >( { 0, 1, 2, 3, 4, 5 }, c1 ); - basic_test< bmic::test_object_index2, bmic::test_object2 >( { 0, 1, 2 }, c1b ); - basic_test< bmic::test_object_index3, bmic::test_object3 >( { 0, 1, 2, 3, 4 }, c1c ); -} - -BOOST_AUTO_TEST_CASE(insert_remove_tests) -{ - auto c1 = []( bmic::test_object& obj ) { obj.name = "_name"; }; - auto c1b = []( bmic::test_object2& obj ) {}; - auto c1c = []( bmic::test_object3& obj ) { obj.val2 = 7; obj.val3 = obj.val2 + 1; }; - - insert_remove_test< bmic::test_object_index, bmic::test_object >( { 0, 1, 2, 3, 4, 5, 6, 7 }, c1 ); - insert_remove_test< bmic::test_object_index2, bmic::test_object2 >( { 0, 1, 2, 3, 4, 5, 6, 7 }, c1b ); - insert_remove_test< bmic::test_object_index3, bmic::test_object3 >( { 0, 1, 2, 3 }, c1c ); -} - -BOOST_AUTO_TEST_CASE(insert_remove_collision_tests) -{ - auto c1 = []( bmic::test_object& obj ) { obj.id = bmic::test_object::id_type( 0 ); obj.name = "_name7"; obj.val = 7; }; - auto c2 = []( bmic::test_object& obj ) { obj.id = bmic::test_object::id_type( 0 ); obj.name = "_name8"; obj.val = 8; }; - auto c3 = []( bmic::test_object& obj ) { obj.id = bmic::test_object::id_type( 0 ); obj.name = "the_same_name"; obj.val = 7; }; - auto c4 = []( bmic::test_object& obj ) { obj.id = bmic::test_object::id_type( 1 ); obj.name = "the_same_name"; obj.val = 7; }; - - auto c1b = []( bmic::test_object2& obj ) { obj.id = bmic::test_object2::id_type( 0 ); obj.val = 7; }; - auto c2b = []( bmic::test_object2& obj ) { obj.id = bmic::test_object2::id_type( 0 ); obj.val = 8; }; - auto c3b = []( bmic::test_object2& obj ) { obj.id = bmic::test_object2::id_type( 6 ); obj.val = 7; }; - auto c4b = []( bmic::test_object2& obj ) { obj.id = bmic::test_object2::id_type( 6 ); obj.val = 7; }; - - auto c1c = []( bmic::test_object3& obj ) { obj.id = bmic::test_object3::id_type( 0 ); obj.val = 20; obj.val2 = 20; }; - auto c2c = []( bmic::test_object3& obj ) { obj.id = bmic::test_object3::id_type( 1 ); obj.val = 20; obj.val2 = 20; }; - auto c3c = []( bmic::test_object3& obj ) { obj.id = bmic::test_object3::id_type( 2 ); obj.val = 30; obj.val3 = 30; }; - auto c4c = []( bmic::test_object3& obj ) { obj.id = bmic::test_object3::id_type( 3 ); obj.val = 30; obj.val3 = 30; }; - - insert_remove_collision_test< bmic::test_object_index, bmic::test_object >( {}, c1, c2, c3, c4 ); - insert_remove_collision_test< bmic::test_object_index2, bmic::test_object2 >( {}, c1b, c2b, c3b, c4b ); - insert_remove_collision_test< bmic::test_object_index3, bmic::test_object3 >( {}, c1c, c2c, c3c, c4c ); -} - -BOOST_AUTO_TEST_CASE(modify_tests) -{ - auto c1 = []( bmic::test_object& obj ) { obj.name = "_name"; }; - auto c2 = []( bmic::test_object& obj ){ obj.name = "new_name"; }; - auto c3 = []( const bmic::test_object& obj ){ BOOST_REQUIRE( obj.name == "new_name" ); }; - auto c4 = []( const bmic::test_object& obj ){ BOOST_REQUIRE( obj.val == size_t( obj.id ) + 100 ); }; - auto c5 = []( bool result ){ BOOST_REQUIRE( result == false ); }; - - auto c1b = []( bmic::test_object2& obj ) { obj.val = 889; }; - auto c2b = []( bmic::test_object2& obj ){ obj.val = 2889; }; - auto c3b = []( const bmic::test_object2& obj ){ BOOST_REQUIRE( obj.val == 2889 ); }; - auto c4b = []( const bmic::test_object2& obj ){ /*empty*/ }; - auto c5b = []( bool result ){ BOOST_REQUIRE( result == true ); }; - - modify_test< bmic::test_object_index, bmic::test_object >( { 0, 1, 2, 3 }, c1, c2, c3, c4, c5 ); - modify_test< bmic::test_object_index2, bmic::test_object2 >( { 0, 1, 2, 3, 4, 5 }, c1b, c2b, c3b, c4b, c5b ); -} - -BOOST_AUTO_TEST_CASE(misc_tests) -{ - misc_test< bmic::test_object_index, bmic::test_object, bmic::OrderedIndex, bmic::CompositeOrderedIndex >( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ); -} - -BOOST_AUTO_TEST_CASE(misc_tests3) -{ - misc_test3< bmic::test_object_index3, bmic::test_object3, bmic::OrderedIndex3, bmic::CompositeOrderedIndex3a, bmic::CompositeOrderedIndex3b >( { 0, 1, 2 } ); -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests2/unit/tests/delayed_voting_tests.cpp b/tests2/unit/tests/delayed_voting_tests.cpp deleted file mode 100644 index 76a610d231051ff3d045ea07d9c9c6693c68221a..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/delayed_voting_tests.cpp +++ /dev/null @@ -1,2824 +0,0 @@ -//#if defined(IS_TEST_NET) - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/sps_objects.hpp> - -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <hive/chain/util/delayed_voting_processor.hpp> -#include <hive/chain/util/delayed_voting.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> -#include <deque> -#include <array> - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-but-set-variable" - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -constexpr int DAYS_FOR_DELAYED_VOTING{ (HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS / HIVE_DELAYED_VOTING_INTERVAL_SECONDS) }; - -#define VOTING_POWER( account ) db->get_account( account ).witness_vote_weight().value -#define PROXIED_VSF( account ) db->get_account( account ).proxied_vsf_votes_total().value -#define DELAYED_VOTES( account ) static_cast<int64_t>( db->get_account( account ).sum_delayed_votes.value ) -#define CAN_VOTE( account ) db->get_account( account ).can_vote - -namespace -{ - -std::string asset_to_string( const asset& a ) -{ - return hive::plugins::condenser_api::legacy_asset::from_asset( a ).to_string(); -} - -} // namespace - -// Tests with combined delayed voting and proposals -BOOST_FIXTURE_TEST_SUITE( delayed_voting_proposal_tests, delayed_vote_proposal_database_fixture ) - -BOOST_AUTO_TEST_CASE( delayed_proposal_test_01 ) -{ - try - { - BOOST_TEST_MESSAGE( R"(Scenario: - - * create one proposal - * carol vests - * carol sets `update_proposal_votes_operation` - * each hour check if votes are constant - * after 30 days proposal receives votes - )"); - - // const - const auto TESTS_1000 = ASSET( "1000.000 TESTS" ); - const auto TBD_100 = ASSET( "100.000 TBD" ); - - //setup - ACTORS( (alice)(bob)(carol) ) - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", TESTS_1000 ); - FUND( "bob", TESTS_1000 ); - FUND( "carol", TESTS_1000 ); - - FUND( "alice", TBD_100 ); - FUND( "bob", TBD_100 ); - FUND( "carol", TBD_100 ); - generate_block(); - - // create one proposal - create_proposal_data cpd(db->head_block_time()); - cpd.end_date = cpd.start_date + fc::days( 2* DAYS_FOR_DELAYED_VOTING ); - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - - // carol vest - vest("carol", "carol", ASSET("10.000 TESTS"), carol_private_key); - - // carol votes - vote_proposal("carol", { proposal_1 }, true, carol_private_key); - - // check - for(int i = 0; i < (24*DAYS_FOR_DELAYED_VOTING) - 1; i++) - { - generate_blocks( db->head_block_time() + fc::hours(1).to_seconds()); - auto * ptr = find_proposal(proposal_1); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( ptr->total_votes == 0ul ); - } - - generate_days_blocks( 1, true ); - auto * ptr = find_proposal(proposal_1); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( static_cast<long>( ptr->total_votes ) == get_vesting( "carol" ).amount.value ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_proposal_test_02 ) -{ - try - { - BOOST_TEST_MESSAGE( R"(Scenario: - - * create two proposals - * carol vests - * carol sets `update_proposal_votes_operation` for first proposal - * each hour check if votes are constant - * carol vests again and `update_proposal_votes_operation` for second proposal - * after 30 days first proposal receives votes - * after 15 days second one, too - )"); - - // const - const auto TESTS_1000 = ASSET( "1000.000 TESTS" ); - const auto TBD_100 = ASSET( "100.000 TBD" ); - - //setup - ACTORS( (alice)(bob)(carol) ) - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", TESTS_1000 ); - FUND( "bob", TESTS_1000 ); - FUND( "carol", TESTS_1000 ); - - FUND( "alice", TBD_100 ); - FUND( "bob", TBD_100 ); - FUND( "carol", TBD_100 ); - generate_block(); - - // create one proposal - create_proposal_data cpd1(db->head_block_time()); - cpd1.end_date = cpd1.start_date + fc::days( 2* DAYS_FOR_DELAYED_VOTING ); - int64_t proposal_1 = create_proposal( cpd1.creator, cpd1.receiver, cpd1.start_date, cpd1.end_date, cpd1.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - - // create one proposal - create_proposal_data cpd2(db->head_block_time()); - cpd2.end_date = cpd2.start_date + fc::days( 2* DAYS_FOR_DELAYED_VOTING ); - int64_t proposal_2 = create_proposal( cpd2.creator, cpd2.receiver, cpd2.start_date, cpd2.end_date, cpd2.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_2 >= 0); - - // carol vest - vest("carol", "carol", ASSET("10.000 TESTS"), carol_private_key); - - // carol votes - vote_proposal("carol", { proposal_1 }, true, carol_private_key); - const auto carol_power_1 = get_vesting( "carol" ).amount.value; - - auto * ptr = find_proposal(proposal_1); //<- just init - - // check - for(int i = 0; i < (24*DAYS_FOR_DELAYED_VOTING) - 1; i++) - { - generate_blocks( db->head_block_time() + fc::hours(1).to_seconds()); - ptr = find_proposal(proposal_1); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( ptr->total_votes == 0ul ); - - if( i == (12 * DAYS_FOR_DELAYED_VOTING)) - { - vest("carol", "carol", ASSET("10.000 TESTS"), carol_private_key); - vote_proposal("carol", { proposal_1, proposal_2 }, true, carol_private_key); - } - - if(i > (12 * DAYS_FOR_DELAYED_VOTING)) - { - ptr = find_proposal(proposal_2); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( ptr->total_votes == 0ul ); - } - } - - generate_days_blocks( 1, true ); - ptr = find_proposal(proposal_1); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( static_cast<long>(ptr->total_votes) == carol_power_1 ); - - ptr = find_proposal(proposal_2); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( static_cast<long>(ptr->total_votes) == carol_power_1 ); - - for(int i = 0; i < ( 12 * ( DAYS_FOR_DELAYED_VOTING / 2 ) ) - 1; i++) - { - generate_blocks( db->head_block_time() + fc::hours(1).to_seconds()); - ptr = find_proposal(proposal_2); - BOOST_REQUIRE( ptr != nullptr ); - BOOST_REQUIRE( static_cast<long>(ptr->total_votes) == carol_power_1 ); - } - - for(int _ = 0; _ < 8; _++ ) - { - generate_days_blocks( 1, true ); - ptr = find_proposal(proposal_2); - } - BOOST_REQUIRE( get_vesting( "carol" ).amount.value == static_cast<long>(ptr->total_votes) ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() - - -BOOST_FIXTURE_TEST_SUITE( delayed_voting_tests, delayed_vote_database_fixture ) - -BOOST_AUTO_TEST_CASE( delayed_voting_proxy_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: Setting proxy - more complex tests" ); - - auto start_time = db->head_block_time(); - - ACTORS( (alice)(bob)(celine)(witness1)(witness2) ) - generate_block(); - - asset _1 = ASSET( "1.000 TESTS" ); - asset _2 = ASSET( "2.000 TESTS" ); - asset _3 = ASSET( "3.000 TESTS" ); - asset _4 = ASSET( "4.000 TESTS" ); - asset _5 = ASSET( "5.000 TESTS" ); - - auto amount = []( const asset& _asset ) - { - return _asset.amount.value; - }; - - auto vamount = [ &amount, this ]( const asset& _asset ) - { - return amount( to_vest( _asset ) ); - }; - - using proxy_data = std::map< std::string, delayed_votes_data >; - proxy_data proxy_0; - proxy_data proxy_1; - proxy_data proxy_2; - proxy_data proxy_15; - proxy_data proxy_30; - proxy_data proxy_31; - - - auto fill = [ this ]( proxy_data& proxy, const std::string& account_name, size_t day, size_t minutes ) - { - auto dq = db->get_account( account_name ).delayed_votes; - - fc::optional< size_t > idx = get_position_in_delayed_voting_array( dq, day, minutes ); - if( !idx.valid() ) - return; - - auto found = proxy.find( account_name ); - - if( found != proxy.end() ) - proxy.erase( found ); - - proxy[ account_name ] = dq[ *idx ]; - }; - - auto cmp = [ this ]( proxy_data& proxy, const std::string& account_name, size_t val, uint32_t day, size_t minutes ) - { - auto dq = db->get_account( account_name ).delayed_votes; - - fc::optional< size_t > idx = get_position_in_delayed_voting_array( dq, day, minutes ); - if( !idx.valid() ) - return true; - - auto found = proxy.find( account_name ); - if( found == proxy.end() ) - { - //current day doesn't exist yet, but previous day must exist - BOOST_REQUIRE( dq.size() > 0 ); - return true; - } - else - { - auto _val = val + found->second.val; - return check_collection( dq, *idx, found->second.time, _val ); - } - }; - - share_type votes_witness1 = get_votes( "witness1" ); - share_type votes_witness2 = get_votes( "witness2" ); - - size_t day = 0; - - { - BOOST_TEST_MESSAGE( "Getting init data..." ); - fill( proxy_0, "alice", day, 0/*minutes*/ ); - fill( proxy_0, "bob", day, 0/*minutes*/ ); - fill( proxy_0, "celine", day, 0/*minutes*/ ); - fill( proxy_0, "witness1", day, 0/*minutes*/ ); - fill( proxy_0, "witness2", day, 0/*minutes*/ ); - } - { - BOOST_TEST_MESSAGE( "Preparing accounts..." ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "celine", ASSET( "10000.000 TESTS" ) ); - FUND( "witness1", ASSET( "10000.000 TESTS" ) ); - FUND( "witness2", ASSET( "10000.000 TESTS" ) ); - - witness_create( "witness1", witness1_private_key, "url.witness1", witness1_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - witness_create( "witness2", witness2_private_key, "url.witness2", witness2_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - auto _v1 = vamount( _1 ); - vest( "alice", "alice", _1, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_0, "alice", _v1, day, 0/*minutes*/ ) ); - fill( proxy_0, "alice", day, 0/*minutes*/ ); - generate_block(); - - auto _v2 = vamount( _2 ); - vest( "alice", "bob", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_0, "bob", _v2, day, 0/*minutes*/ ) ); - fill( proxy_0, "bob", day, 0/*minutes*/ ); - generate_block(); - - auto _v3 = vamount( _3 ); - vest( "alice", "celine", _3, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_0, "celine", _v3, day, 0/*minutes*/ ) ); - fill( proxy_0, "celine", day, 0/*minutes*/ ); - generate_block(); - - auto _v4 = vamount( _4 ); - vest( "alice", "witness1", _4, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_0, "witness1", _v4, day, 0/*minutes*/ ) ); - fill( proxy_0, "witness1", day, 0/*minutes*/ ); - generate_block(); - - auto _v5 = vamount( _5 ); - vest( "alice", "witness2", _5, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_0, "witness2", _v5, day, 0/*minutes*/ ) ); - fill( proxy_0, "witness2", day, 0/*minutes*/ ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - } - { - /* - *****intial actions***** - `celine` votes `witness1` - `celine` votes `witness2` - - `alice` sets proxy `celine` - - `bob` votes `witness2` - */ - witness_vote( "celine", "witness1", true/*approve*/, celine_private_key ); - witness_vote( "celine", "witness2", true/*approve*/, celine_private_key ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - - proxy( "alice", "celine", alice_private_key ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - - witness_vote( "bob", "witness2", true/*approve*/, bob_private_key ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - - /* - info: `->` ==`proxy` - - Finally there are set following connections: - - alice -> celine : witness1 - - alice -> celine : witness2 - bob : witness2 - */ - } - - size_t minutes = 0; - - { - /* - *****`+ 1 day`***** - `alice` makes vests - `bob` makes vests - `alice` makes vests - `bob` makes vests - `celine` makes vests - */ - start_time += HIVE_DELAYED_VOTING_INTERVAL_SECONDS; - generate_blocks( start_time, true ); - day = 1; - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*1*/ ), true ); - auto _v1 = vamount( _1 ); - vest( "alice", "alice", _1, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_1, "alice", _v1, day, minutes ) ); - fill( proxy_1, "alice", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*2*/ ), true ); - auto _v2 = vamount( _2 ); - vest( "alice", "bob", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_1, "bob", _v2, day, minutes ) ); - fill( proxy_1, "bob", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*3*/ ), true ); - _v1 = vamount( _1 ); - vest( "alice", "alice", _1, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_1, "alice", _v1, day, minutes ) ); - fill( proxy_1, "alice", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*4*/ ), true ); - _v2 = vamount( _2 ); - vest( "alice", "bob", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_1, "bob", _v2, day, minutes ) ); - fill( proxy_1, "bob", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*5*/ ), true ); - _v1 = vamount( _1 ); - vest( "alice", "celine", _1, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_1, "celine", _v1, day, minutes ) ); - fill( proxy_1, "celine", day, minutes ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - } - { - /* - *****`+ 2 days`***** - `alice` makes vests - `celine` makes vests - */ - start_time += HIVE_DELAYED_VOTING_INTERVAL_SECONDS; - generate_blocks( start_time, true ); - day = 2; - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*6*/ ), true ); - auto _v5 = vamount( _5 ); - vest( "alice", "alice", _5, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_2, "alice", _v5, day, minutes ) ); - fill( proxy_2, "alice", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*7*/ ), true ); - auto _v2 = vamount( _2 ); - vest( "alice", "celine", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_2, "celine", _v2, day, minutes ) ); - fill( proxy_2, "celine", day, minutes ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - } - { - /* - *****`+ 15 days`***** - `alice` makes vests - `bob` makes vests - `celine` makes vests - */ - start_time += 13 * HIVE_DELAYED_VOTING_INTERVAL_SECONDS; - generate_blocks( start_time, true ); - day = 15; - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*8*/ ), true ); - auto _v2 = vamount( _2 ); - vest( "alice", "alice", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_15, "alice", _v2, day, minutes ) ); - fill( proxy_15, "alice", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*9*/ ), true ); - auto _v3 = vamount( _3 ); - vest( "alice", "bob", _3, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_15, "bob", _v3, day, minutes ) ); - fill( proxy_15, "bob", day, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*10*/ ), true ); - auto _v4 = vamount( _4 ); - vest( "alice", "celine", _4, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_15, "celine", _v4, day, minutes ) ); - fill( proxy_15, "celine", day, minutes ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - } - { - /* - *****`30 days - 1 block`***** - */ - start_time += 15 * HIVE_DELAYED_VOTING_INTERVAL_SECONDS - HIVE_BLOCK_INTERVAL; - generate_blocks( start_time, true ); - - BOOST_REQUIRE( get_votes( "witness1" ) == votes_witness1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_witness2 ); - } - - using proxy_data_map = std::map< uint32_t, proxy_data >; - - using name_items = std::vector< std::string >; - using witness_map = std::map< std::string, name_items >; - - /* - info: `->` ==`proxy` - - Finally there are set following connections: - - alice -> celine : witness1 - - alice -> celine : witness2 - bob : witness2 - */ - proxy_data_map pd_map{ - { 0, proxy_0 }, - { 1, proxy_1 }, - { 2, proxy_2 }, - { 15, proxy_15 } - }; - witness_map m_map { - { "witness1", { "alice", "celine" } }, - { "witness2", { "alice", "celine", "bob" } } - }; - - auto calculate_votes = [ &pd_map, &m_map ]( uint32_t nr_day_after_30days_interval, const std::string& witness ) -> ushare_type - { - auto found_proxy = pd_map.find( nr_day_after_30days_interval ); - if( found_proxy == pd_map.end() ) - return 0; - - auto found_voters = m_map.find( witness ); - if( found_voters == m_map.end() ) - return 0; - - proxy_data& proxy = found_proxy->second; - name_items& voters = found_voters->second; - - ushare_type res = 0; - for( auto& item : voters ) - { - auto found_voter = proxy.find( item ); - if( found_voter != proxy.end() ) - res += found_voter->second.val; - } - - return res; - }; - - auto witness1_result_00 = calculate_votes( 0/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_00 = calculate_votes( 0/*nr_day_after_30days_interval*/, "witness2" ); - - { - /* - *****`30 days`***** - `alice` makes vests - `bob` makes vests - `celine` makes vests - */ - start_time += HIVE_BLOCK_INTERVAL; - generate_blocks( start_time, true ); - day = 30; - size_t diff = 1;//because `1` element in delayed_votes has been removed already - - BOOST_REQUIRE( witness1_result_00 >= 0 ); - BOOST_REQUIRE( witness2_result_00 >= 0 ); - - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + witness1_result_00.value ) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + witness2_result_00.value ) ); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*11*/ ), true ); - auto _v5 = vamount( _5 ); - vest( "alice", "alice", _5, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_30, "alice", _v5, day, minutes ) ); - fill( proxy_30, "alice", day - diff, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*12*/ ), true ); - auto _v1 = vamount( _1 ); - vest( "alice", "bob", _1, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_30, "bob", _v1, day, minutes ) ); - fill( proxy_30, "bob", day - diff, minutes ); - generate_block(); - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*13*/ ), true ); - auto _v2 = vamount( _2 ); - vest( "alice", "celine", _2, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_30, "celine", _v2, day, minutes ) ); - fill( proxy_30, "celine", day - diff, minutes ); - generate_block(); - } - - auto witness1_result_01 = calculate_votes( 1/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_01 = calculate_votes( 1/*nr_day_after_30days_interval*/, "witness2" ); - - //Displaying diagnostic data. - for( auto& item : pd_map ) - { - std::string str_day = "day: " +std::to_string( item.first/*day number*/ ); - proxy_data& voters = item.second;//std::map< std::string, delayed_votes_data >; - std::string str_voters; - std::string c = std::string( " : " ); - for( auto& voter : voters ) - str_voters += std::string( "(" ) + voter.first + c + std::to_string( voter.second.val.value ) + c + voter.second.time.to_iso_string() + std::string( ")" ); - std::string str = str_day + str_voters; - idump( (str) ); - } - - { - /* - *****`+ 31 days`***** - `celine` makes vests - */ - start_time += fc::seconds( HIVE_DELAYED_VOTING_INTERVAL_SECONDS ) ; - generate_blocks( start_time, true ); - day = 31; - size_t diff = 2;//because `2` elements in delayed_votes have been removed already - - ++minutes; - generate_blocks( start_time + fc::minutes( minutes/*14*/ ), true ); - auto _v5 = vamount( _5 ); - vest( "alice", "celine", _5, alice_private_key ); - BOOST_REQUIRE( cmp( proxy_31, "celine", _v5, day, minutes ) ); - fill( proxy_31, "celine", day - diff, minutes ); - generate_block(); - } - { - /* - *****`lasted 31 days`***** - */ - start_time += fc::hours( 23 ) + fc::minutes( 59 ); - generate_blocks( start_time, true ); - - BOOST_REQUIRE( witness1_result_01 > 0 ); - BOOST_REQUIRE( witness2_result_01 > 0 ); - - idump( ( VOTING_POWER( "alice" ) ) ); - idump( ( VOTING_POWER( "bob" ) ) ); - idump( ( VOTING_POWER( "celine" ) ) ); - idump( (votes_witness1) ); - idump( (witness1_result_00) ); - idump( (witness1_result_01) ); - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + ( witness1_result_00 + witness1_result_01 ).value ) ); - - idump( (votes_witness2) ); - idump( (witness2_result_00) ); - idump( (witness2_result_01) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + ( witness2_result_00 + witness2_result_01 ).value ) ); - - start_time += fc::minutes( 1 ); - generate_blocks( start_time, true ); - } - - auto witness1_result_02 = calculate_votes( 2/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_02 = calculate_votes( 2/*nr_day_after_30days_interval*/, "witness2" ); - - { - /* - *****`lasted 32 days`***** - */ - start_time += fc::hours( 23 ) + fc::minutes( 59 ); - generate_blocks( start_time, true ); - - BOOST_REQUIRE( witness1_result_02 > 0 ); - BOOST_REQUIRE( witness1_result_02 > 0 ); - - idump( ( VOTING_POWER( "alice" ) ) ); - idump( ( VOTING_POWER( "bob" ) ) ); - idump( ( VOTING_POWER( "celine" ) ) ); - idump( (votes_witness1) ); - idump( (witness1_result_00) ); - idump( (witness1_result_01) ); - idump( (witness1_result_02) ); - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + ( witness1_result_00 + witness1_result_01 + witness1_result_02 ).value ) ); - - idump( (votes_witness2) ); - idump( (witness2_result_00) ); - idump( (witness2_result_01) ); - idump( (witness2_result_02) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + ( witness2_result_00 + witness2_result_01 + witness2_result_02 ).value ) ); - - start_time += fc::minutes( 1 ); - generate_blocks( start_time, true ); - } - { - /* - *****`lasted 40 days`***** - */ - start_time += 8 * HIVE_DELAYED_VOTING_INTERVAL_SECONDS; - generate_blocks( start_time, true ); - - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + ( witness1_result_00 + witness1_result_01 + witness1_result_02 ).value ) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + ( witness2_result_00 + witness2_result_01 + witness2_result_02 ).value ) ); - - proxy( "alice", "", alice_private_key ); - generate_block(); - - auto _copy_m_map = m_map; - - m_map.clear(); - m_map = { - { "witness1", { "celine" } }, - { "witness2", { "celine", "bob" } } - }; - - auto witness1_result_no_proxy_00 = calculate_votes( 0/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_no_proxy_00 = calculate_votes( 0/*nr_day_after_30days_interval*/, "witness2" ); - - auto witness1_result_no_proxy_01 = calculate_votes( 1/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_no_proxy_01 = calculate_votes( 1/*nr_day_after_30days_interval*/, "witness2" ); - - auto witness1_result_no_proxy_02 = calculate_votes( 2/*nr_day_after_30days_interval*/, "witness1" ); - auto witness2_result_no_proxy_02 = calculate_votes( 2/*nr_day_after_30days_interval*/, "witness2" ); - - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + ( witness1_result_no_proxy_00 + witness1_result_no_proxy_01 + witness1_result_no_proxy_02 ).value ) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + ( witness2_result_no_proxy_00 + witness2_result_no_proxy_01 + witness2_result_no_proxy_02 ).value ) ); - - proxy( "alice", "celine", alice_private_key ); - generate_block(); - - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + ( witness1_result_00 + witness1_result_01 + witness1_result_02 ).value ) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + ( witness2_result_00 + witness2_result_01 + witness2_result_02 ).value ) ); - - m_map = _copy_m_map; - } - - pd_map[ 30 ] = proxy_30; - pd_map[ 31 ] = proxy_31; - - { - /* - *****`lasted 80 days`***** - */ - start_time += 40 * HIVE_DELAYED_VOTING_INTERVAL_SECONDS; - generate_blocks( start_time, true ); - - idump( ( VOTING_POWER( "alice" ) ) ); - idump( ( VOTING_POWER( "bob" ) ) ); - idump( ( VOTING_POWER( "celine" ) ) ); - - auto calculate_total = [ &calculate_votes ]( const std::string& witness_name ) - { - auto v_0 = calculate_votes( 0/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_0) ); - - auto v_1 = calculate_votes( 1/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_1) ); - - auto v_2 = calculate_votes( 2/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_2) ); - - auto v_15 = calculate_votes( 15/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_15) ); - - auto v_30 = calculate_votes( 30/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_30) ); - - auto v_31 = calculate_votes( 31/*nr_day_after_30days_interval*/, witness_name ); - idump( (v_31) ); - - return v_0 + v_1 + v_2 + v_15 + v_30 + v_31; - }; - - BOOST_REQUIRE( get_votes( "witness1" ) == ( votes_witness1 + calculate_total( "witness1" ).value ) ); - BOOST_REQUIRE( get_votes( "witness2" ) == ( votes_witness2 + calculate_total( "witness2" ).value ) ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_proxy_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: Setting proxy" ); - - ACTORS( (alice)(bob)(celine)(witness) ) - generate_block(); - - { - BOOST_TEST_MESSAGE( "Preparing accounts..." ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "celine", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - } - { - BOOST_TEST_MESSAGE( "Preparing witnesses..." ); - - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - } - - asset _1 = ASSET( "1.000 TESTS" ); - asset _2 = ASSET( "2.000 TESTS" ); - asset _3 = ASSET( "3.000 TESTS" ); - asset _4 = ASSET( "4.000 TESTS" ); - - auto start_time = db->head_block_time(); - - share_type votes_01 = get_votes( "witness" ); - - { - BOOST_TEST_MESSAGE( "Transform TESTS->VESTS for every account..." ); - - vest( "alice", "alice", _1, alice_private_key ); - vest( "alice", "bob", _2, alice_private_key ); - vest( "alice", "celine", _3, alice_private_key ); - vest( "alice", "witness", _4, alice_private_key ); - } - { - BOOST_TEST_MESSAGE( "Creating proxies..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_celine = get_vesting( "celine" ); - auto v_witness = get_vesting( "witness" ); - - proxy( "alice", "celine", alice_private_key ); - proxy( "bob", "celine", bob_private_key ); - - BOOST_REQUIRE( get_vesting( "alice" ) == v_alice ); - BOOST_REQUIRE( get_vesting( "bob" ) == v_bob ); - BOOST_REQUIRE( get_vesting( "celine" ) == v_celine ); - BOOST_REQUIRE( get_vesting( "witness" ) == v_witness ); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 ); - } - { - BOOST_TEST_MESSAGE( "Voting..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_celine = get_vesting( "celine" ); - auto v_witness = get_vesting( "witness" ); - - witness_vote( "celine", "witness", true/*approve*/, celine_private_key ); - - BOOST_REQUIRE( get_vesting( "alice" ) == v_alice ); - BOOST_REQUIRE( get_vesting( "bob" ) == v_bob ); - BOOST_REQUIRE( get_vesting( "celine" ) == v_celine ); - BOOST_REQUIRE( get_vesting( "witness" ) == v_witness ); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 ); - } - { - BOOST_TEST_MESSAGE( "Move time forward..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_celine = get_vesting( "celine" ); - auto v_witness = get_vesting( "witness" ); - - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - - BOOST_REQUIRE( get_vesting( "alice" ) == v_alice ); - BOOST_REQUIRE( get_vesting( "bob" ) == v_bob ); - BOOST_REQUIRE( get_vesting( "celine" ) == v_celine ); - BOOST_REQUIRE( get_vesting( "witness" ) == v_witness ); - - auto sum = v_alice + v_bob + v_celine; - share_type votes_02 = get_votes( "witness" ); - BOOST_REQUIRE( votes_02 == votes_01 + sum.amount.value ); - } - { - BOOST_TEST_MESSAGE( "Remove account `alice` with proxy..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_celine = get_vesting( "celine" ); - auto v_witness = get_vesting( "witness" ); - - proxy( "alice", "", alice_private_key ); - generate_block(); - - BOOST_REQUIRE( get_vesting( "alice" ) == v_alice ); - BOOST_REQUIRE( get_vesting( "bob" ) == v_bob ); - BOOST_REQUIRE( get_vesting( "celine" ) == v_celine ); - BOOST_REQUIRE( get_vesting( "witness" ) == v_witness ); - - auto sum = v_bob + v_celine; - share_type votes_02 = get_votes( "witness" ); - BOOST_REQUIRE( votes_02 == votes_01 + sum.amount.value ); - } - { - BOOST_TEST_MESSAGE( "Remove account `bob` with proxy..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_celine = get_vesting( "celine" ); - auto v_witness = get_vesting( "witness" ); - - proxy( "bob", "", bob_private_key ); - generate_block(); - - BOOST_REQUIRE( get_vesting( "alice" ) == v_alice ); - BOOST_REQUIRE( get_vesting( "bob" ) == v_bob ); - BOOST_REQUIRE( get_vesting( "celine" ) == v_celine ); - BOOST_REQUIRE( get_vesting( "witness" ) == v_witness ); - - share_type votes_02 = get_votes( "witness" ); - BOOST_REQUIRE( votes_02 == votes_01 + v_celine.amount.value ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_many_vesting_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: Transferring vests many times from one person to another" ); - - ACTORS( (alice)(bob)(witness) ) - generate_block(); - - { - BOOST_TEST_MESSAGE( "Preparing accounts..." ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - } - { - BOOST_TEST_MESSAGE( "Preparing witnesses..." ); - - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - } - - asset _one = ASSET( "1.000 TESTS" ); - - auto start_time = db->head_block_time(); - - share_type votes_01 = get_votes( "witness" ); - - { - BOOST_TEST_MESSAGE( "Transform a few times TESTS->VESTS..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_witness = get_vesting( "witness" ); - - asset v_alice_00 = asset( 0, VESTS_SYMBOL ); - asset v_bob_00 = asset( 0, VESTS_SYMBOL ); - - for( int i = 0; i < 3; ++i ) - { - vest( "bob", "bob", _one, bob_private_key ); - v_bob_00 += to_vest( _one ); - - vest( "alice", "bob", _one, alice_private_key ); - v_alice_00 += to_vest( _one ); - - vest( "bob", "alice", _one, bob_private_key ); - v_bob_00 += to_vest( _one ); - - generate_block(); - } - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == ( v_alice + v_alice_00 ).amount.value ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == ( v_bob + v_bob_00 ).amount.value ); - BOOST_REQUIRE( get_vesting( "witness" ).amount.value == v_witness.amount.value ); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 ); - } - { - BOOST_TEST_MESSAGE( "Witness voting..." ); - - auto v_alice = get_vesting( "alice" ); - auto v_bob = get_vesting( "bob" ); - auto v_witness = get_vesting( "witness" ); - - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - witness_vote( "bob", "witness", true/*approve*/, bob_private_key ); - generate_block(); - witness_vote( "bob", "witness", false/*approve*/, bob_private_key ); - generate_block(); - witness_vote( "bob", "witness", true/*approve*/, bob_private_key ); - generate_block(); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == v_alice.amount.value ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == v_bob.amount.value ); - BOOST_REQUIRE( get_vesting( "witness" ).amount.value == v_witness.amount.value ); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 ); - - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - - auto sum = v_alice + v_bob; - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 + sum.amount.value ); - - witness_vote( "bob", "witness", false/*approve*/, bob_private_key ); - generate_block(); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 + v_alice.amount.value ); - - witness_vote( "alice", "witness", false/*approve*/, alice_private_key ); - generate_block(); - BOOST_REQUIRE( get_votes( "witness" ) == votes_01 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delaying voting" ); - - ACTORS( (alice)(bob)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //auto start_time = db->head_block_time(); - - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - //Prepare witnesses - - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - auto start_time = db->head_block_time(); - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - - share_type basic_votes = get_votes( "witness" ); - - //Make some vests - vest( "bob", "alice", ASSET( "1000.000 TESTS" ), bob_private_key ); - generate_block(); - - share_type votes_01 = get_votes( "witness" ); - BOOST_REQUIRE( votes_01 == basic_votes ); - - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - generate_block(); - - auto votes_power = get_vesting( "alice" ); - share_type votes_02 = get_votes( "witness" ); - BOOST_REQUIRE( votes_02 == basic_votes + votes_power.amount.value ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_04 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delaying voting v4" ); - - ACTORS( (bob)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //auto start_time = db->head_block_time(); - - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - auto start_time = db->head_block_time(); - const share_type basic_votes = get_votes( "witness" ); - - //Make some vests - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - generate_block(); - - witness_vote( "bob", "witness", true/*approve*/, bob_private_key ); - generate_block(); - - BOOST_REQUIRE( basic_votes == get_votes( "witness" ) ); - for(int i = 1; i < (HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS / HIVE_DELAYED_VOTING_INTERVAL_SECONDS) - 1; i++) - { - generate_blocks( start_time + (i * HIVE_DELAYED_VOTING_INTERVAL_SECONDS) , true ); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes ); - } - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - generate_block(); - - auto votes_power = get_vesting( "bob" ); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes + votes_power.amount.value ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_05 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delaying voting v5" ); - - ACTORS( (bob)(witness1)(witness2) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //auto start_time = db->head_block_time(); - - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "witness1", ASSET( "10000.000 TESTS" ) ); - FUND( "witness2", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness1", witness1_private_key, "url.witness1", witness1_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - witness_create( "witness2", witness2_private_key, "url.witness2", witness2_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - auto start_time = db->head_block_time(); - share_type basic_votes_1 = get_votes( "witness1" ); - share_type basic_votes_2 = get_votes( "witness2" ); - - //Make some vests - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - generate_block(); - - witness_vote( "bob", "witness1", true/*approve*/, bob_private_key ); - generate_block(); - - share_type votes_01_1 = get_votes( "witness1" ); - share_type votes_01_2 = get_votes( "witness2" ); - BOOST_REQUIRE( basic_votes_1 == votes_01_1 ); - BOOST_REQUIRE( basic_votes_2 == votes_01_2 ); - - for(int i = 1; i < DAYS_FOR_DELAYED_VOTING - 1; i++) - { - generate_blocks( start_time + (i * HIVE_DELAYED_VOTING_INTERVAL_SECONDS) , true ); - if( i == static_cast<int>( DAYS_FOR_DELAYED_VOTING/2 )) witness_vote( "bob", "witness2", true/*approve*/, bob_private_key ); - BOOST_REQUIRE( get_votes( "witness1" ) == votes_01_1 ); - BOOST_REQUIRE( get_votes( "witness2" ) == votes_01_2 ); - } - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - generate_block(); - - auto votes_power = get_vesting( "bob" ); - BOOST_REQUIRE( get_votes( "witness1" ) == basic_votes_1 + votes_power.amount.value ); - BOOST_REQUIRE( get_votes( "witness2" ) == basic_votes_2 + votes_power.amount.value ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_06 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delaying voting v6" ); - - ACTORS( (bob)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //auto start_time = db->head_block_time(); - - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - const auto start_time = db->head_block_time(); - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - const share_type basic_votes = get_votes( "witness" ); - - //Make some vests - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - generate_block(); - - HIVE_REQUIRE_THROW( witness_vote( "bob", "witness", false/*approve*/, bob_private_key ), fc::assert_exception) ; - generate_block(); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes ); - - witness_vote( "bob", "witness", true/*approve*/, bob_private_key ); - generate_block(); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes ); - - witness_vote( "bob", "witness", false/*approve*/, bob_private_key ); - generate_block(); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes ); - - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_06 ) -{ - try - { - BOOST_TEST_MESSAGE( "Complex scenario for `delayed_voting` class" ); - - ACTORS( (user0)(user1)(user2)(user3)(user4)(user5)(user6)(user7)(user8)(user9) ) - - std::array< std::string, 10 > accs{ - "user0", - "user1", - "user2", - "user3", - "user4", - "user5", - "user6", - "user7", - "user8", - "user9" - }; - - delayed_voting dv = delayed_voting( *db ); - - delayed_voting::opt_votes_update_data_items withdraw_items = delayed_voting::votes_update_data_items(); - auto start_time = db->head_block_time(); - - for( uint32_t i = 0; i < 10; ++i ) - { - int64_t cnt = 0; - for( auto& item : accs ) - { - const uint64_t pre_size{ withdraw_items->size() }; - for(int j = 0; j < 10; j++) - { - dv.add_delayed_value( db->get_account( item ), start_time + fc::days(1), 10'000 ); - start_time = move_forward_with_update( fc::days( 1 ), withdraw_items ); - - const bool withdraw_executor = cnt == accs.size() - 1; - dv.add_votes( withdraw_items, withdraw_executor, 10'000, db->get_account( item ) ); - - if( withdraw_executor ) - dv.add_votes( withdraw_items, withdraw_executor, -10'000, db->get_account( item ) ); - - BOOST_REQUIRE( i == 0 || pre_size == withdraw_items->size()); - } - ++cnt; - } - dv.update_votes( withdraw_items, start_time ); - BOOST_REQUIRE_EQUAL( withdraw_items->size(), accs.size() ); - start_time = move_forward_with_update( fc::days( 40 ), withdraw_items ); - } - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) >= 0 ); - - start_time = move_forward_with_update( fc::days( 13 * 7 ), withdraw_items ); - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) == 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_05 ) -{ - try - { - BOOST_TEST_MESSAGE( "Complex scenario for `delayed_voting` class" ); - - ACTORS( (user0)(user1)(user2)(user3)(user4)(user5)(user6)(user7)(user8)(user9) ) - - std::array< std::string, 10 > accs{ - "user0", - "user1", - "user2", - "user3", - "user4", - "user5", - "user6", - "user7", - "user8", - "user9" - }; - - delayed_voting dv = delayed_voting( *db ); - - auto start_time = db->head_block_time(); - delayed_voting::opt_votes_update_data_items withdraw_items = delayed_voting::votes_update_data_items(); - - - { - for( uint32_t i = 0; i < 29; ++i ) - { - int64_t cnt = 0; - for( auto& item : accs ) - { - dv.add_delayed_value( db->get_account( item ), start_time + fc::days(1), 10'000 ); - - const bool withdraw_executor = cnt == accs.size() - 1; - dv.add_votes( withdraw_items, withdraw_executor, 10'000, db->get_account( item ) ); - - if( withdraw_executor ) - dv.add_votes( withdraw_items, withdraw_executor, -10'000, db->get_account( item ) ); - ++cnt; - } - start_time = move_forward_with_update( fc::days( 1 ), withdraw_items ); - } - dv.update_votes( withdraw_items, start_time ); - - BOOST_REQUIRE_EQUAL( withdraw_items->size(), accs.size() ); - } - { - for( uint32_t i = 0; i < 29; ++i ) - { - start_time = move_forward_with_update( fc::days( 1 ), withdraw_items ); - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) >= 0 ); - } - - start_time = move_forward_with_update( fc::days( 1 ), withdraw_items ); - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) == 0 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_03 ) -{ - try - { - // support function - const auto get_delayed_vote_count = [&]( const account_name_type& name = "bob", const std::vector<uint64_t>& data_to_compare ) - { - const auto& idx = db->get_index< account_index, by_delayed_voting >(); - for(const auto& usr : idx) - if(usr.name == name) - return std::equal( - usr.delayed_votes.begin(), - usr.delayed_votes.end(), - data_to_compare.begin(), - data_to_compare.end(), - [](const delayed_votes_data& x, const uint64_t y){ return x.val == y; }); - return false; - }; - - // user setup - BOOST_TEST_MESSAGE( "Testing: `delayed_voting::run` method" ); - const auto start_time = db->head_block_time(); - ACTORS( (alice)(celine)(bob)(witness) ) - generate_block(); - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - FUND( "bob", ASSET( "100000.000 TESTS" ) ); - FUND( "celine", ASSET( "100000.000 TESTS" ) ); - FUND( "alice", ASSET( "100000.000 TESTS" ) ); - FUND( "witness", ASSET( "100000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - vest( "bob", "bob", ASSET( "100.000 TESTS" ), bob_private_key ); - vest( "alice", "alice", ASSET( "100.000 TESTS" ), alice_private_key ); - vest( "celine", "celine", ASSET( "100.000 TESTS" ), celine_private_key ); - generate_block(); - - // validation data - const auto basic_votes{ get_votes( "witness" ) }; - std::vector<uint64_t> alice_values; alice_values.reserve(30); - - // initial voting - witness_vote("bob", "witness", true, bob_private_key); - generate_block(); - witness_vote("alice", "witness", true, alice_private_key); - generate_block(); - - // validation data pt 2 - alice_values.push_back(get_vesting( "alice" ).amount.value); - uint64_t last{ alice_values.back() }; - - // entry check - BOOST_REQUIRE( get_delayed_vote_count("bob", { { static_cast<uint64_t>(get_vesting( "bob" ).amount.value) } }) ); - BOOST_REQUIRE( get_delayed_vote_count("alice", { { static_cast<uint64_t>(get_vesting( "alice" ).amount.value)} }) ); - - // check everyday for month - bool s = false; - for(int i = 1; i < DAYS_FOR_DELAYED_VOTING - 1; i++) - { - // 1 day - generate_blocks( start_time + (i * HIVE_DELAYED_VOTING_INTERVAL_SECONDS) , true ); - - // base checks for witness, bob and celine - BOOST_REQUIRE( get_votes("witness") == basic_votes ); - BOOST_REQUIRE( get_delayed_vote_count("bob", { { static_cast<uint64_t>(get_vesting( "bob" ).amount.value)} }) ); - BOOST_REQUIRE( get_delayed_vote_count("celine", { { static_cast<uint64_t>(get_vesting( "celine" ).amount.value)} }) ); - - // celine arythmia - s=!s; - witness_vote("celine", "witness", s, celine_private_key); - - // alice tap - vest( "alice", "alice", ASSET( "100.000 TESTS" ), alice_private_key ); - - // alice check - const uint64_t val = static_cast<uint64_t>(get_vesting( "alice" ).amount.value); - alice_values.push_back(val - last); - last = val; - BOOST_REQUIRE( get_delayed_vote_count("alice", alice_values) ); - } - - // check is bob ok - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS, true ); - BOOST_REQUIRE( get_delayed_vote_count("bob", {}) ); - - // check is alice ok (after another month) - generate_blocks( start_time + (2 * HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS) , true ); - BOOST_REQUIRE( get_delayed_vote_count("alice", {}) ); - - // check is witness ok - const auto alice_power = get_vesting( "alice" ).amount.value; - const auto bob_power = get_vesting( "bob" ).amount.value; - const auto celine_power = (s ? get_vesting( "celine" ).amount.value : 0l); - - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power + bob_power + celine_power); - validate_database(); - - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_04 ) -{ - try - { - BOOST_TEST_MESSAGE( "Complex scenario for `delayed_voting` class" ); - - ACTORS( (user0)(user1)(user2)(user3)(user4)(user5)(user6)(user7)(user8)(user9) ) - - std::array< std::string, 10 > accs{ - "user0", - "user1", - "user2", - "user3", - "user4", - "user5", - "user6", - "user7", - "user8", - "user9" - }; - - delayed_voting dv = delayed_voting( *db ); - - auto start_time = db->head_block_time(); - - auto move_forward = [ &start_time, this ]( const fc::microseconds& time ) - { - generate_blocks( db->head_block_time() + time ); - start_time = db->head_block_time(); - }; - - { - for( uint32_t i = 0; i < 36; ++i ) - { - for( auto& item : accs ) - dv.add_delayed_value( db->get_account( item ), start_time + fc::hours( i ), ( i + 1 ) * 1'000'000/*milion*/ ); - } - - move_forward( fc::days( 4 ) ); - } - { - int64_t cnt = 0; - delayed_voting::opt_votes_update_data_items withdraw_items = delayed_voting::votes_update_data_items(); - - for( auto& item : accs ) - { - bool withdraw_executor = cnt == accs.size() - 1; - - dv.add_votes( withdraw_items, withdraw_executor, ( cnt + 1 ) * 10, db->get_account( item ) ); - - if( withdraw_executor ) - dv.add_votes( withdraw_items, withdraw_executor, -8888, db->get_account( item ) ); - - ++cnt; - } - BOOST_REQUIRE( withdraw_items->size() == accs.size() ); - dv.update_votes( withdraw_items, start_time ); - } - { - for( uint32_t i = 0; i < 34; ++i ) - { - move_forward( fc::days( 1 ) ); - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) >= 0 ); - } - - move_forward( fc::days( 1 ) ); - - for( auto& item : accs ) - BOOST_REQUIRE( DELAYED_VOTES( item ) == 0 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_02 ) -{ - auto vcmp = []( const std::vector< delayed_votes_data >& a, const account_object::t_delayed_votes& b ) - { - return std::equal( a.begin(), a.end(), b.begin() ); - }; - - BOOST_TEST_MESSAGE( "Testing: `delayed_voting::update_votes` method" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - - generate_block(); - - /* - The collection `items` stores `votes_update_data` structure. Below is the definition. - struct votes_update_data - { - bool withdraw_executor; - mutable int64_t val;; - const account_object* account; - }; - */ - delayed_voting::opt_votes_update_data_items items = delayed_voting::votes_update_data_items(); - - delayed_voting dv = delayed_voting( *db ); - - fc::time_point_sec time = db->head_block_time() + fc::hours( 5 ); - - auto& __alice = db->get_account( "alice" ); - auto alice_dv = __alice.delayed_votes; - auto alice_sum = __alice.sum_delayed_votes; - - auto& __bob = db->get_account( "bob" ); - auto bob_dv = __bob.delayed_votes; - auto bob_sum = __bob.sum_delayed_votes; - - { - delayed_voting::opt_votes_update_data_items _items; - dv.update_votes( _items, time ); - auto& _alice = db->get_account( "alice" ); - BOOST_REQUIRE( vcmp( { { alice_dv[0].time, alice_dv[0].val } }, _alice.delayed_votes ) ); - BOOST_REQUIRE( alice_sum == _alice.sum_delayed_votes ); - } - { - dv.update_votes( items, time ); - auto& _alice = db->get_account( "alice" ); - BOOST_REQUIRE( vcmp( { { alice_dv[0].time, alice_dv[0].val } }, _alice.delayed_votes ) ); - BOOST_REQUIRE( alice_sum == _alice.sum_delayed_votes ); - } - { - dv.add_votes( items, false/*withdraw_executor*/, 0/*val*/, db->get_account( "alice" ) ); - dv.update_votes( items, time ); - auto& _alice = db->get_account( "alice" ); - BOOST_REQUIRE( vcmp( { { alice_dv[0].time, alice_dv[0].val } }, _alice.delayed_votes ) ); - BOOST_REQUIRE( alice_sum == _alice.sum_delayed_votes ); - } - { - dv.add_votes( items, false/*withdraw_executor*/, -5/*val*/, db->get_account( "alice" ) ); - //delayed_voting_messages::incorrect_votes_update - HIVE_REQUIRE_THROW( dv.update_votes( items, time ), fc::exception ); - items->clear(); - - dv.add_votes( items, true/*withdraw_executor*/, 1/*val*/, db->get_account( "alice" ) ); - //delayed_voting_messages::incorrect_votes_update - HIVE_REQUIRE_THROW( dv.update_votes( items, time ), fc::exception ); - items->clear(); - } - { - auto& alice = db->get_account( "alice" ); - auto& bob = db->get_account( "bob" ); - - dv.add_delayed_value( alice, time, 70 ); - dv.add_delayed_value( bob, time, 88 ); - - dv.add_votes( items, false/*withdraw_executor*/, 7/*val*/, db->get_account( "alice" ) ); - dv.add_votes( items, true/*withdraw_executor*/, -8/*val*/, db->get_account( "bob" ) ); - dv.update_votes( items, time ); - - auto& alice2 = db->get_account( "alice" ); - BOOST_REQUIRE( vcmp( { { alice_dv[0].time, alice_dv[0].val + 70 + 7 } }, alice2.delayed_votes ) ); - BOOST_REQUIRE( alice_sum + 70 + 7 == alice2.sum_delayed_votes ); - - auto& bob2 = db->get_account( "bob" ); - BOOST_REQUIRE( vcmp( { { bob_dv[0].time, bob_dv[0].val + 88 - 8 } }, bob2.delayed_votes ) ); - BOOST_REQUIRE( bob_sum + 88 - 8 == bob2.sum_delayed_votes ); - } - -} - -BOOST_AUTO_TEST_CASE( delayed_voting_basic_01 ) -{ - /* - The collection `items` stores `votes_update_data` structure. Below is the definition. - struct votes_update_data - { - bool withdraw_executor; - mutable int64_t val;; - const account_object* account; - }; - */ - delayed_voting::opt_votes_update_data_items items = delayed_voting::votes_update_data_items(); - - auto cmp = [ &items, this ]( bool withdraw_executor, int64_t val, const account_object& obj ) - { - return check_collection( items, withdraw_executor, val, obj ); - }; - - BOOST_TEST_MESSAGE( "Testing: `delayed_voting::add_votes` method" ); - - ACTORS( (alice)(bob)(celine) ) - - std::array< const account_object*, 3 > accs{ &db->get_account( "alice" ), - &db->get_account( "bob" ), - &db->get_account( "celine" ) - }; - - delayed_voting dv = delayed_voting( *db ); - - { - delayed_voting::opt_votes_update_data_items _items; - dv.add_votes( _items, true/*withdraw_executor*/, 1/*val*/, *accs[0] ); - BOOST_REQUIRE( !_items.valid() ); - } - { - dv.add_votes( items, true/*withdraw_executor*/, 0/*val*/, *accs[0] ); - BOOST_REQUIRE( items->size() == 0 ); - } - { - dv.add_votes( items, true/*withdraw_executor*/, 1/*val*/, *accs[0] ); - BOOST_REQUIRE( items->size() == 1 ); - BOOST_REQUIRE( cmp( true, 1, *accs[0] ) ); - } - { - //delayed_voting_messages::incorrect_withdraw_data - HIVE_REQUIRE_THROW( dv.add_votes( items, false/*withdraw_executor*/, 88/*val*/, *accs[0] ), fc::exception ); - } - { - dv.add_votes( items, true/*withdraw_executor*/, 2/*val*/, *accs[1] ); - BOOST_REQUIRE( items->size() == 2 ); - BOOST_REQUIRE( cmp( true, 1, *accs[0] ) ); - BOOST_REQUIRE( cmp( true, 2, *accs[1] ) ); - } - { - dv.add_votes( items, true/*withdraw_executor*/, 3/*val*/, *accs[1] ); - BOOST_REQUIRE( items->size() == 2 ); - BOOST_REQUIRE( cmp( true, 1, *accs[0] ) ); - BOOST_REQUIRE( cmp( true, 5, *accs[1] ) ); - } - { - dv.add_votes( items, true/*withdraw_executor*/, 4/*val*/, *accs[2] ); - BOOST_REQUIRE( items->size() == 3 ); - BOOST_REQUIRE( cmp( true, 1, *accs[0] ) ); - BOOST_REQUIRE( cmp( true, 5, *accs[1] ) ); - BOOST_REQUIRE( cmp( true, 4, *accs[2] ) ); - } - { - //delayed_voting_messages::incorrect_withdraw_data - HIVE_REQUIRE_THROW( dv.add_votes( items, false/*withdraw_executor*/, 4/*val*/, *accs[1] ), fc::exception ); - } -} - -BOOST_AUTO_TEST_CASE( delayed_voting_processor_03 ) -{ - std::vector< delayed_votes_data > dq; - - ushare_type sum = 0; - - fc::time_point_sec time = fc::variant( "2020-02-02T03:04:05" ).as< fc::time_point_sec >(); - - { - //nothing to do - delayed_voting_processor::erase( dq, sum, 0ul ); - delayed_voting_processor::add( dq, sum, time/*time*/, 0/*val*/ ); - delayed_voting_processor::erase_front( dq, sum ); - } - - { - BOOST_REQUIRE( dq.size() == 0 ); - //delayed_voting_messages::incorrect_erased_votes - HIVE_REQUIRE_THROW( delayed_voting_processor::erase( dq, sum, 1 ), fc::exception ); - } - - { - delayed_voting_processor::add( dq, sum, time/*time*/, 666ul/*val*/ ); - delayed_voting_processor::erase( dq, sum, 666ul ); - BOOST_REQUIRE( dq.size() == 0 ); - } - - { - delayed_voting_processor::add( dq, sum, time + fc::days( 1 )/*time*/, 22ul/*val*/ ); - delayed_voting_processor::add( dq, sum, time + fc::days( 2 )/*time*/, 33ul/*val*/ ); - delayed_voting_processor::erase( dq, sum, 55 ); - BOOST_REQUIRE( dq.size() == 0 ); - } -} - -BOOST_AUTO_TEST_CASE( delayed_voting_processor_02 ) -{ - std::vector< delayed_votes_data > dq; - - auto cmp = [ &dq, this ]( ushare_type idx, const fc::time_point_sec& time, ushare_type val ) - { - return check_collection( dq, idx, time, val ); - }; - - ushare_type sum = 0; - - fc::time_point_sec time = fc::variant( "2020-01-02T03:04:05" ).as< fc::time_point_sec >(); - - const ushare_type _max = 10; - ushare_type calculated_sum = 0; - - //dq={1,2,3,4,5,6,7,8,9,10} - for( ushare_type i = 0; i < _max; ++i ) - { - calculated_sum += i + 1; - delayed_voting_processor::add( dq, sum, time + fc::days( ( i + 1 ).value )/*time*/, i + 1/*val*/ ); - } - BOOST_REQUIRE( dq.size() == _max ); - BOOST_REQUIRE( sum == calculated_sum ); - - for( ushare_type i = 0; i < _max; ++i ) - BOOST_REQUIRE( cmp( i/*idx*/, time + fc::days( ( i + 1 ).value )/*time*/, i + 1/*val*/ ) ); - - //Decrease gradually last element by `1` in `dq`. - for( ushare_type cnt = 0; cnt < _max - 1; ++cnt ) - { - idump( (cnt) ); - - delayed_voting_processor::erase( dq, sum, 1 ); - BOOST_REQUIRE( dq.size() == _max ); - BOOST_REQUIRE( sum == calculated_sum - ( cnt + 1 ) ); - - for( ushare_type i = 0; i < _max; ++i ) - { - if( i == _max - 1 ) - BOOST_REQUIRE( cmp( i/*idx*/, time + fc::days( ( i + 1 ).value )/*time*/, i - cnt/*val*/ ) ); - else - BOOST_REQUIRE( cmp( i/*idx*/, time + fc::days( ( i + 1 ).value )/*time*/, i + 1/*val*/ ) ); - } - } - - //dq={1,2,3,4,5,6,7,8,9,1} - //Last element has only `1`, so after below operation last element should be removed - delayed_voting_processor::erase( dq, sum, 1ul ); - BOOST_REQUIRE( dq.size() == _max - 1 ); - BOOST_REQUIRE( sum == calculated_sum - 10 ); - - //dq={1,2,3,4,5,6,7,8,9} - //Two last elements will disappear. - delayed_voting_processor::erase( dq, sum, 17ul ); - BOOST_REQUIRE( dq.size() == _max - 3 ); - BOOST_REQUIRE( sum == calculated_sum - 27 ); - - //dq={1,2,3,4,5,6,7} - delayed_voting_processor::erase( dq, sum, 7ul ); - BOOST_REQUIRE( dq.size() == _max - 4 ); - BOOST_REQUIRE( sum == calculated_sum - 34 ); - - //dq={1,2,3,4,5,6} - delayed_voting_processor::erase( dq, sum, 18ul ); - BOOST_REQUIRE( dq.size() == _max - 8 ); - BOOST_REQUIRE( sum == calculated_sum - 52 ); - - //delayed_voting_messages::incorrect_erased_votes - //dq={1,2} - HIVE_REQUIRE_THROW( delayed_voting_processor::erase( dq, sum, 10ul ), fc::exception ); - - //dq={1,2} - delayed_voting_processor::erase( dq, sum, 3ul ); - BOOST_REQUIRE( dq.size() == 0 ); - BOOST_REQUIRE( sum == 0 ); -} - -BOOST_AUTO_TEST_CASE( delayed_voting_processor_01 ) -{ - std::vector< delayed_votes_data > dq; - - auto cmp = [ &dq, this ]( size_t idx, const fc::time_point_sec& time, uint64_t val ) - { - return check_collection( dq, idx, time, val ); - }; - - ushare_type sum = 0; - - fc::time_point_sec time = fc::variant( "2000-01-01T00:00:00" ).as< fc::time_point_sec >(); - - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 )/*time*/, 1ul/*val*/ ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 1 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 )/*time*/, 1ul/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 1 )/*time*/, 2ul/*val*/ ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 3 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 )/*time*/, 3/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 24 ) - fc::seconds( 1 )/*time*/, 3ul/*val*/ ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 6 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 )/*time*/, 6/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 24 )/*time*/, 4ul/*val*/ ); - BOOST_REQUIRE( dq.size() == 2 ); - BOOST_REQUIRE( sum == 10 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 )/*time*/, 6/*val*/ ) ); - BOOST_REQUIRE( cmp( 1/*idx*/, time + fc::minutes( 1 ) + fc::hours( 24 )/*time*/, 4/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 5ul/*val*/ ); - BOOST_REQUIRE( dq.size() == 3 ); - BOOST_REQUIRE( sum == 15 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 )/*time*/, 6/*val*/ ) ); - BOOST_REQUIRE( cmp( 1/*idx*/, time + fc::minutes( 1 ) + fc::hours( 24 )/*time*/, 4/*val*/ ) ); - BOOST_REQUIRE( cmp( 2/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, /*val*/5 ) ); - } - { - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 2 ); - BOOST_REQUIRE( sum == 9 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 24 )/*time*/, 4/*val*/ ) ); - BOOST_REQUIRE( cmp( 1/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 5/*val*/ ) ); - } - { - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 5 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 5/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 2 ) + fc::hours( 2*24 )/*time*/, 6/*val*/ ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 11 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 11/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 3*24 )/*time*/, 7/*val*/ ); - BOOST_REQUIRE( dq.size() == 2 ); - BOOST_REQUIRE( sum == 18 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 11/*val*/ ) ); - BOOST_REQUIRE( cmp( 1/*idx*/, time + fc::minutes( 1 ) + fc::hours( 3*24 )/*time*/, 7/*val*/ ) ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::minutes( 1 ) + fc::hours( 3*24 ) + fc::seconds( 3 )/*time*/, 8/*val*/ ); - BOOST_REQUIRE( dq.size() == 2 ); - BOOST_REQUIRE( sum == 26 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 2*24 )/*time*/, 11/*val*/ ) ); - BOOST_REQUIRE( cmp( 1/*idx*/, time + fc::minutes( 1 ) + fc::hours( 3*24 )/*time*/, 15/*val*/ ) ); - } - { - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 15 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::minutes( 1 ) + fc::hours( 3*24 )/*time*/, 15/*val*/ ) ); - } - { - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - BOOST_REQUIRE( sum == 0 ); - - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - BOOST_REQUIRE( sum == 0 ); - - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - BOOST_REQUIRE( sum == 0 ); - } - { - //delayed_voting_messages::incorrect_sum_equal - sum = 1; - HIVE_REQUIRE_THROW( delayed_voting_processor::erase_front( dq, sum ), fc::exception ); - - sum = 0; - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - } - { - delayed_voting_processor::add( dq, sum, time, 2/*val*/ ); - --sum; - //delayed_voting_messages::incorrect_sum_greater_equal - HIVE_REQUIRE_THROW( delayed_voting_processor::erase_front( dq, sum ), fc::exception ); - - ++sum; - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - BOOST_REQUIRE( sum == 0 ); - } - { - delayed_voting_processor::add( dq, sum, time + fc::seconds( 30 )/*time*/, 1000/*val*/ ); - BOOST_REQUIRE( dq.size() == 1 ); - BOOST_REQUIRE( sum == 1000 ); - BOOST_REQUIRE( cmp( 0/*idx*/, time + fc::seconds( 30 )/*time*/, 1000/*val*/ ) ); - - //delayed_voting_messages::incorrect_head_time - HIVE_REQUIRE_THROW( delayed_voting_processor::add( dq, sum, time + fc::seconds( 29 )/*time*/, 1000/*val*/ ), fc::exception ); - - delayed_voting_processor::erase_front( dq, sum ); - BOOST_REQUIRE( dq.size() == 0 ); - } -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline voting rights: casual use" ); - - ACTORS( (bob)(alice)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - // auto start_time = db->head_block_time(); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - //Make some vests - const share_type basic_votes = get_votes( "witness" ); - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - vest( "alice", "alice", ASSET( "1000.000 TESTS" ), alice_private_key ); - generate_block(); - - // alice - do - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - - // alice - check - generate_days_blocks( 30, true ); - const auto alice_power = get_vesting( "alice" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power ); - - // blocked bob - do - decline_voting_rights("bob", true, bob_private_key); - generate_blocks( db->head_block_time() + HIVE_OWNER_AUTH_RECOVERY_PERIOD, true ); - BOOST_REQUIRE( CAN_VOTE("bob") == false ); - HIVE_REQUIRE_THROW( witness_vote( "bob", "witness", true, bob_private_key ), fc::assert_exception ); - generate_block(); - - // blocked bob - check - generate_days_blocks( 30, true ); - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline voting rights: casual use with spontaneus vote" ); - - ACTORS( (bob)(alice)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - //Make some vests - const share_type basic_votes = get_votes( "witness" ); - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - vest( "alice", "alice", ASSET( "1000.000 TESTS" ), alice_private_key ); - generate_days_blocks( 30, true ); - - // alice - do - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - - // alice - check - const auto alice_power = get_vesting( "alice" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power ); - - // bob block - decline_voting_rights("bob", true, bob_private_key); - generate_blocks( db->head_block_time() + (HIVE_OWNER_AUTH_RECOVERY_PERIOD.to_seconds() / 2), true ); - - // bob check - BOOST_REQUIRE( CAN_VOTE("bob") ); - - // bob account is voting - witness_vote( "bob", "witness", true, bob_private_key ); - generate_blocks( db->head_block_time() + (HIVE_OWNER_AUTH_RECOVERY_PERIOD.to_seconds() / 3), true ); - - // bob check - BOOST_REQUIRE( CAN_VOTE("bob") ); - BOOST_REQUIRE( get_user_voted_witness_count( "bob" ) == 1 ); - const auto bob_power = get_vesting( "bob" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power + bob_power ); - - // bobs block request is active - generate_blocks( db->head_block_time() + (HIVE_OWNER_AUTH_RECOVERY_PERIOD.to_seconds() / 3), true ); - - // blocked bob - check - HIVE_REQUIRE_THROW( witness_vote( "bob", "witness", true, bob_private_key ), fc::assert_exception ); - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power ); - BOOST_REQUIRE( CAN_VOTE("bob") == false ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_03 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline voting rights: casual use with cancel" ); - - const std::function<bool(const account_name_type)> is_cancelled = [&](const account_name_type name) - { - const auto& request_idx = db->get_index< decline_voting_rights_request_index >().indices().get< by_account >(); - return request_idx.find( name ) == request_idx.end(); - }; - - ACTORS( (bob)(alice)(witness)(witness2) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - // auto start_time = db->head_block_time(); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - FUND( "witness2", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - witness_create( "witness2", witness2_private_key, "url.witness2", witness2_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - //Make some vests - const share_type basic_votes = get_votes( "witness" ); - const share_type basic_votes2 = get_votes( "witness2" ); - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - vest( "alice", "alice", ASSET( "1000.000 TESTS" ), alice_private_key ); - generate_days_blocks( 30, true ); - - // alice - do - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - - // alice - check - const auto alice_power = get_vesting( "alice" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power ); - - // bob block - decline_voting_rights("bob", true, bob_private_key); - generate_blocks( db->head_block_time() + (HIVE_OWNER_AUTH_RECOVERY_PERIOD.to_seconds() / 2), true ); - - // bob check - BOOST_REQUIRE( CAN_VOTE("bob") ); - - // bob account tries to vote - witness_vote( "bob", "witness", true, bob_private_key ); - BOOST_REQUIRE( get_user_voted_witness_count( "bob" ) == 1 ); - const auto bob_power = get_vesting( "bob" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power + bob_power ); - - // bob cancel block request - decline_voting_rights("bob", false, bob_private_key); - generate_block(); - - // check - BOOST_REQUIRE( CAN_VOTE("bob") ); - BOOST_REQUIRE( is_cancelled( "bob" ) ); - - // bob account is voting again - witness_vote( "bob", "witness2", true, bob_private_key ); - generate_block(); - - // check - BOOST_REQUIRE( get_votes("witness") == basic_votes + alice_power + bob_power ); - BOOST_REQUIRE( get_votes("witness2") == basic_votes2 + bob_power ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_04 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline voting rights: casual use with cancel" ); - - const std::function<bool(const account_name_type)> is_cancelled = [&](const account_name_type name) - { - const auto& request_idx = db->get_index< decline_voting_rights_request_index >().indices().get< by_account >(); - return request_idx.find( name ) == request_idx.end(); - }; - - ACTORS( (bob)(alice)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - // auto start_time = db->head_block_time(); - FUND( "bob", ASSET( "10000.000 TESTS" ) ); - FUND( "alice", ASSET( "10000.000 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - - //Prepare witnesses - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - //Make some vests - const share_type basic_votes = get_votes( "witness" ); - vest( "bob", "bob", ASSET( "1000.000 TESTS" ), bob_private_key ); - witness_vote( "bob", "witness", true, bob_private_key ); - generate_block(); - BOOST_REQUIRE( get_votes("witness") == basic_votes ); - generate_blocks( db->head_block_time() + ( HIVE_DELAYED_VOTING_INTERVAL_SECONDS * 29 ) , true ); // 120s - - // bob check - BOOST_REQUIRE( CAN_VOTE("bob") ); - BOOST_REQUIRE( get_user_voted_witness_count( "bob" ) == 1 ); - const auto bob_power = get_vesting( "bob" ).amount.value; - BOOST_REQUIRE( get_votes("witness") == basic_votes ); - - // bob block - decline_voting_rights("bob", true, bob_private_key); - generate_blocks( db->head_block_time() + (HIVE_OWNER_AUTH_RECOVERY_PERIOD.to_seconds() / 2), true ); - - // bob check - BOOST_REQUIRE( CAN_VOTE("bob") ); - BOOST_REQUIRE( get_user_voted_witness_count( "bob" ) == 1 ); - BOOST_REQUIRE( get_votes("witness") == basic_votes ); - - - decline_voting_rights("bob", false, bob_private_key); - - generate_blocks( db->head_block_time() + HIVE_DELAYED_VOTING_INTERVAL_SECONDS , true ); - - BOOST_REQUIRE( get_votes("witness") == basic_votes + bob_power ); - BOOST_REQUIRE( CAN_VOTE("bob") ); // block has been cancelled - BOOST_REQUIRE( get_user_voted_witness_count( "bob" ) == 1 ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( small_common_test_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: simulation of trying to overcome system" ); - - ACTORS( (alice)(witness) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //auto start_time = db->head_block_time(); - - FUND( "alice", ASSET( "1000000.001 TESTS" ) ); - FUND( "witness", ASSET( "10000.000 TESTS" ) ); - //Prepare witnesses - - witness_create( "witness", witness_private_key, "url.witness", witness_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - - auto start_time = db->head_block_time(); - witness_vote( "alice", "witness", true/*approve*/, alice_private_key ); - generate_block(); - - share_type basic_votes = get_votes( "witness" ); - - //First start timer with low, not suspicious amount of vests - vest( "alice", "alice", ASSET( "0.001 TESTS" ), alice_private_key ); - generate_block(); - - share_type votes_01 = get_votes( "witness" ); - BOOST_REQUIRE( votes_01 == basic_votes ); - - generate_blocks( start_time + fc::days(DAYS_FOR_DELAYED_VOTING - 1) , true ); - generate_block(); - - // just before lock down alice vests huge amount of TESTs - const auto alice_vp = get_vesting( "alice" ).amount.value; - vest( "alice", "alice", ASSET( "1000000.000 TESTS" ), alice_private_key ); - const auto alice_vp_2 = get_vesting( "alice" ).amount.value; - generate_block(); - - generate_blocks( start_time + HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS , true ); - generate_block(); - - // lock is working and alice doesn't have huge amount of votes in sneaky way - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes + alice_vp ); - generate_blocks( start_time + (2 * HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ) , true ); - BOOST_REQUIRE( get_votes( "witness" ) == basic_votes + alice_vp_2 ); - - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -#define ACCOUNT_REPORT( account ) \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << account << " has " << asset_to_string( get_vesting( account )) ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << account << " has " << asset_to_string( get_balance( account )) ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << account << " has " << VOTING_POWER( account ) << " voting power" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << account << " has " << PROXIED_VSF( account ) << " proxied vsf" ) - -#define WITNESS_VOTES( witness ) db->get_witness( witness ).votes.value - -#define DAY_REPORT( day ) \ - BOOST_TEST_MESSAGE( "[scenario_01]: current day: " << day ); \ - ACCOUNT_REPORT( "alice" ); \ - ACCOUNT_REPORT( "alice0bp" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "alice0bp" << " has " << WITNESS_VOTES( "alice0bp" ) << " votes" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "alice0bp" << " has " << DELAYED_VOTES( "alice0bp" ) << " delayed votes" ); \ - ACCOUNT_REPORT( "bob" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "expected_bob_vests = " << asset_to_string( expected_bob_vests ) ); \ - ACCOUNT_REPORT( "bob0bp" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "bob0bp" << " has " << WITNESS_VOTES( "bob0bp" ) << " votes" ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "bob0bp" << " has " << DELAYED_VOTES( "bob0bp" ) << " delayed votes" ); \ - ACCOUNT_REPORT( "carol" ) - -#define CHECK_ACCOUNT_VESTS( account ) \ - BOOST_REQUIRE( get_vesting( #account ) == expected_ ## account ## _vests ) - -#define CHECK_ACCOUNT_HIVE( account ) \ - BOOST_REQUIRE( get_balance( #account ) == expected_ ## account ## _hive ) - -#define CHECK_ACCOUNT_VP( account ) \ - BOOST_REQUIRE( VOTING_POWER( #account ) == expected_ ## account ## _vp ) - -#define CHECK_WITNESS_VOTES( witness ) \ - BOOST_REQUIRE( WITNESS_VOTES( #witness ) == expected_ ## witness ## _votes ) - -#define DAY_CHECK \ - BOOST_REQUIRE( get_balance( "alice" ).amount.value != 0 ); \ - BOOST_REQUIRE( get_balance( "alice" ) == get_balance( "carol" ) ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "expected_alice_vests = " << asset_to_string( expected_alice_vests ) ); \ - CHECK_ACCOUNT_VESTS( alice ); \ - BOOST_REQUIRE( DELAYED_VOTES( "alice0bp" ) == expected_alice0bp_delayed_votes ); \ - BOOST_REQUIRE( VOTING_POWER( "alice" ) == WITNESS_VOTES( "alice0bp" ) ); \ - BOOST_TEST_MESSAGE( "[scenario_01]: " << "expected_bob_vests = " << asset_to_string( expected_bob_vests ) ); \ - CHECK_ACCOUNT_VESTS( bob ); \ - BOOST_REQUIRE( DELAYED_VOTES( "bob0bp" ) == expected_bob0bp_delayed_votes ); \ - BOOST_REQUIRE( VOTING_POWER( "bob" ) == WITNESS_VOTES( "bob0bp" ) ) - -#define GOTO_DAY( day ) \ - generate_days_blocks( day - today ); \ - today = day - -BOOST_AUTO_TEST_CASE( scenario_01 ) -{ - try { - - asset initial_alice_vests; - asset initial_alice0bp_vests; - int64_t initial_alice0bp_vp; - int64_t initial_alice0bp_votes; - int64_t initial_alice0bp_delayed_votes; - asset initial_bob_vests; - asset initial_bob0bp_vests; - int64_t initial_bob0bp_vp; - int64_t initial_bob0bp_votes; - int64_t initial_bob0bp_delayed_votes; - asset initial_carol_hive; - - asset expected_alice_vests = initial_alice_vests; - asset expected_alice0bp_vests; - int64_t expected_alice0bp_vp; - int64_t expected_alice0bp_votes; - int64_t expected_alice0bp_delayed_votes; - asset expected_bob_vests; - asset expected_bob0bp_vests; - int64_t expected_bob0bp_vp; - int64_t expected_bob0bp_votes; - int64_t expected_bob0bp_delayed_votes; - asset expected_carol_hive; - -/* https://gitlab.syncad.com/hive-group/hive/issues/5#note_24084 - - actors: alice, alice.bp (witness of alice choice), bob, bob.bp (witness of bob choice), carol -*/ - ACTORS( (alice)(alice0bp)(bob)(bob0bp)(carol) ); - generate_block(); - - BOOST_TEST_MESSAGE( "[scenario_01]: after account creation" ); - BOOST_TEST_MESSAGE( "[scenario_01]: alice has " << asset_to_string( get_vesting( "alice" )) ); - BOOST_TEST_MESSAGE( "[scenario_01]: alice has " << asset_to_string( get_balance( "alice" )) ); - - witness_create( "alice0bp", alice0bp_private_key, "url.alice.bp", alice0bp_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - witness_create( "bob0bp", bob0bp_private_key, "url.bob.bp", bob0bp_private_key.get_public_key(), HIVE_MIN_PRODUCER_REWARD.amount ); - generate_block(); - -/* - For simplicity we are going to assume 1 vest == 1 HIVE at all times but in reality all conversions - are done using rate from the time when action is performed. - - Before test starts alice has 1300 HIVE in liquid form. She sets up vest route in the following way: - - to alice in vest form 25% - - to bob in vest form 25% - - to carol in liquid form 25% - - leaving remaining 25% for herself in liquid form. -*/ - signed_transaction tx; - fund( "alice", ASSET( "1300.000 TESTS" ) ); - - { - BOOST_TEST_MESSAGE( "[scenario_01]: Setting up alice destination" ); - set_withdraw_vesting_route_operation op; - op.from_account = "alice"; - op.to_account = "alice"; - op.percent = HIVE_1_PERCENT * 25; - op.auto_vest = true; - tx.operations.push_back( op ); - } - - { - BOOST_TEST_MESSAGE( "[scenario_01]: Setting up bob destination" ); - set_withdraw_vesting_route_operation op; - op.from_account = "alice"; - op.to_account = "bob"; - op.percent = HIVE_1_PERCENT * 25; - op.auto_vest = true; - tx.operations.push_back( op ); - } - - { - BOOST_TEST_MESSAGE( "[scenario_01]: Setting up carol destination" ); - set_withdraw_vesting_route_operation op; - op.from_account = "alice"; - op.to_account = "carol"; - op.percent = HIVE_1_PERCENT * 25; - op.auto_vest = false; - tx.operations.push_back( op ); - } - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - // set alice.bp as witness of alice choice - witness_vote( "alice", "alice0bp", true/*approve*/, alice_private_key ); - // set bob.bp as witness of bob choice - witness_vote( "bob", "bob0bp", true/*approve*/, bob_private_key ); - - generate_block(); - -/* - Day 0: alice powers up 1000 HIVE; she has 1000 vests, including delayed maturing on day 30 and 300 HIVE -*/ - uint32_t today = 0; - asset origin_alice_vests = get_vesting( "alice" ); - BOOST_TEST_MESSAGE( "[scenario_01]: day_zero = " << today ); - BOOST_TEST_MESSAGE( "[scenario_01]: head_block_num = " << db->head_block_num() ); - - BOOST_TEST_MESSAGE( "[scenario_01]: alice powers up 1000" ); - vest( "alice", "alice", ASSET( "1000.000 TESTS" ), alice_private_key ); - validate_database(); - - DAY_REPORT( today ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "300.000 TESTS" ) ); - -/* - Day 5: alice powers up 300 HIVE; she has 1300 vests, including delayed 1000 maturing on day 30 and 300 maturing on day 35, 0 HIVE -*/ - BOOST_TEST_MESSAGE( "[scenario_01]: before set_current_day( 5 ): " << get_current_time_iso_string() ); - GOTO_DAY( 5 ); - BOOST_TEST_MESSAGE( "[scenario_01]: after set_current_day( 5 ): " << get_current_time_iso_string() ); - - BOOST_TEST_MESSAGE( "[scenario_01]: alice powers up 300" ); - vest( "alice", "alice", ASSET( "300.000 TESTS" ), alice_private_key ); - validate_database(); - - DAY_REPORT( today ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - -/* - Day 10: alice powers down 1300 vests; this schedules virtual PD actions on days 17, 24, 31, 38, 45, 52, 59, 66, 73, 80, 87, 94 and 101 -*/ - GOTO_DAY( 10 ); - - int64_t new_vests = (get_vesting( "alice" ) - origin_alice_vests).amount.value; - int64_t new_vests_portion = new_vests / HIVE_VESTING_WITHDRAW_INTERVALS; - - int64_t quarter = new_vests / 4; - int64_t portion = quarter / HIVE_VESTING_WITHDRAW_INTERVALS; - - BOOST_TEST_MESSAGE( "[scenario_01]: alice powers down all new vests" ); - withdraw_vesting( "alice", asset( new_vests, VESTS_SYMBOL ), alice_private_key ); - validate_database(); - - DAY_REPORT( today ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - -/* - Day 17: PD of 100 vests from alice gives 25 HIVE to carol, 25 HIVE to alice, powers up 25 vests to bob (maturing on day 47) - and ignores 25 vests of power down (power down canceled in 25% by vest route to alice); - since there is nonzero balance as delayed, 75 vests are subtracted from second record leaving 1000 (30day) + 225 (35day) - alice 25S+1225v=0+1000(30d)+225(35d); bob 25v=0+25(47d); carol 25S -*/ - initial_alice_vests = get_vesting( "alice" ); - initial_alice0bp_vests = get_vesting( "alice0bp" ); - initial_alice0bp_vp = VOTING_POWER( "alice0bp" ); - initial_alice0bp_votes = WITNESS_VOTES( "alice0bp" ); - initial_alice0bp_delayed_votes = DELAYED_VOTES( "alice0bp" ); - initial_bob_vests = get_vesting( "bob" ); - initial_bob0bp_vests = get_vesting( "bob0bp" ); - initial_bob0bp_vp = VOTING_POWER( "bob0bp"); - initial_bob0bp_votes = WITNESS_VOTES( "bob0bp" ); - initial_bob0bp_delayed_votes = DELAYED_VOTES( "bob0bp" ); - initial_carol_hive = get_balance( "carol" ); - - expected_alice_vests = initial_alice0bp_vests; - expected_alice0bp_vests = initial_alice0bp_vests; - expected_alice0bp_vp = initial_alice0bp_vp; - expected_alice0bp_votes = initial_alice0bp_votes; - expected_alice0bp_delayed_votes = initial_alice0bp_delayed_votes; - expected_bob_vests = initial_bob_vests; - expected_bob0bp_vests = initial_bob0bp_vests; - expected_bob0bp_vp = initial_bob0bp_vp; - expected_bob0bp_votes = initial_bob0bp_votes; - expected_bob0bp_delayed_votes = initial_bob0bp_delayed_votes; - expected_carol_hive = initial_carol_hive; - - GOTO_DAY( 17 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( new_vests_portion + 1, VESTS_SYMBOL ); - expected_alice_vests += asset( portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( portion, VESTS_SYMBOL ); - expected_alice0bp_delayed_votes = get_vesting( "alice0bp" ).amount.value; - DAY_CHECK; - -/* - Day 24: PD of 100 vests from alice split like above - alice 50S+1150v=0+1000(30d)+150(35d); bob 50v=0+25(47d)+25(54d); carol 50S -*/ - GOTO_DAY( 24 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 2 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 2 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 2 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 30: 1000 vests matures on alice, alice.bp receives 1000 vests of new voting power (1000v) - alice 50S+1150v=1000+150(35d); bob 50v=0+25(47d)+25(54d); carol 50S -*/ - GOTO_DAY( 30 ); - DAY_REPORT( today ); - - expected_alice0bp_delayed_votes = 0; - expected_bob0bp_delayed_votes = 0; - DAY_CHECK; - -/* - Day 31: PD of 100 vests from alice - alice 75S+1075v=1000+75(35d); bob 75v=0+25(47d)+25(54d)+25(61d); carol 75S -*/ - GOTO_DAY( 31 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 3 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 3 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 3 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 35: remaining 75 vests mature on alice, alice.bp receives 75 vests of new voting power (1075v) - alice 75S+1075v=1075; bob 75v=0+25(47d)+25(54d)+25(61d); carol 75S -*/ - GOTO_DAY( 35 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 38: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (1000v) - alice 100S+1000v=1000; bob 100v=0+25(47d)+25(54d)+25(61d)+25(68d); carol 100S -*/ - GOTO_DAY( 38 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 4 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 4 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 4 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 45: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (925v) - alice 125S+925v=925; bob 125v=0+25(47d)+25(54d)+25(61d)+25(68d)+25(75d); carol 125S -*/ - GOTO_DAY( 45 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 5 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 5 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 5 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 47: first 25 vests mature on bob, bob.bp receives 25 vests of new voting power (25v) - alice 125S+925v=925; bob 125v=25+25(54d)+25(61d)+25(68d)+25(75d); carol 125S -*/ - GOTO_DAY( 47 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 52: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (850v) - alice 150S+850v=850; bob 150v=25+25(54d)+25(61d)+25(68d)+25(75d)+25(82d); carol 150S -*/ - GOTO_DAY( 52 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 6 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 6 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 6 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 54: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (50v) - alice 150S+850v=850; bob 150v=50+25(61d)+25(68d)+25(75d)+25(82d); carol 150S -*/ - GOTO_DAY( 54 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 59: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (775v) - alice 175S+775v=775; bob 175v=50+25(61d)+25(68d)+25(75d)+25(82d)+25(89d); carol 175S -*/ - GOTO_DAY( 59 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 7 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 7 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 7 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 61: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (75v) - alice 175S+775v=775; bob 175v=75+25(68d)+25(75d)+25(82d)+25(89d); carol 175S -*/ - GOTO_DAY( 61 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 66: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (700v) - alice 200S+700v=700; bob 200v=75+25(68d)+25(75d)+25(82d)+25(89d)+25(96d); carol 200S -*/ - GOTO_DAY( 66 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 8 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 8 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 8 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 68: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (100v) - alice 200S+700v=700; bob 200v=100+25(75d)+25(82d)+25(89d)+25(96d); carol 200S -*/ - GOTO_DAY( 68 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 73: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (625v) - alice 225S+625v=625; bob 225v=100+25(75d)+25(82d)+25(89d)+25(96d)+25(103d); carol 225S -*/ - GOTO_DAY( 73 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 9 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 9 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 9 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 75: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (125v) - alice 225S+625v=625; bob 225v=125+25(82d)+25(89d)+25(96d)+25(103d); carol 225S -*/ - GOTO_DAY( 75 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 80: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (550v) - alice 250S+550v=550; bob 250v=125+25(82d)+25(89d)+25(96d)+25(103d)+25(110d); carol 250S -*/ - GOTO_DAY( 80 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 10 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 10 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 10 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 82: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (150v) - alice 250S+550v=550; bob 250v=150+25(89d)+25(96d)+25(103d)+25(110d); carol 250S -*/ - GOTO_DAY( 82 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 87: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (475v) - alice 275S+475v=475; bob 275v=150+25(89d)+25(96d)+25(103d)+25(110d)+25(117d); carol 275S -*/ - GOTO_DAY( 87 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 11 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 11 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 11 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 89: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (175v) - alice 275S+475v=475; bob 275v=175+25(96d)+25(103d)+25(110d)+25(117d); carol 275S -*/ - GOTO_DAY( 89 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 94: PD of 100 vests from alice, alice.bp loses 75 vests of voting power (400v) - alice 300S+400v=400; bob 300v=175+25(96d)+25(103d)+25(110d)+25(117d)+25(124d); carol 300S -*/ - GOTO_DAY( 94 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( 12 * (new_vests_portion + 1), VESTS_SYMBOL ); - expected_alice_vests += asset( 12 * portion, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( 12 * portion, VESTS_SYMBOL ); - DAY_CHECK; - -/* - Day 96: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (200v) - alice 300S+400v=400; bob 300v=200+25(103d)+25(110d)+25(117d)+25(124d); carol 300S -*/ - GOTO_DAY( 96 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 101: last scheduled PD of 100 vests from alice, alice.bp loses 75 vests of voting power (325v) - alice 325S+325v=325; bob 325v=200+25(103d)+25(110d)+25(117d)+25(124d)+25(131d); carol 325S -*/ - GOTO_DAY( 101 ); - DAY_REPORT( today ); - - expected_alice_vests = initial_alice_vests - asset( new_vests, VESTS_SYMBOL ); - expected_alice_vests += asset( quarter - 3, VESTS_SYMBOL ); - expected_bob_vests = initial_bob_vests + asset( quarter - 3, VESTS_SYMBOL ); - BOOST_REQUIRE( get_vesting( "alice" ) == get_vesting( "bob" ) ); - DAY_CHECK; - -/* - Day 103: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (225v) - alice 325S+325v=325; bob 325v=225+25(110d)+25(117d)+25(124d)+25(131d); carol 325S -*/ - GOTO_DAY( 103 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 110: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (250v) - alice 325S+325v=325; bob 325v=250+25(117d)+25(124d)+25(131d); carol 325S -*/ - GOTO_DAY( 110 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 117: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (275v) - alice 325S+325v=325; bob 325v=275+25(124d)+25(131d); carol 325S -*/ - GOTO_DAY( 117 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 124: 25 vests mature on bob, bob.bp receives 25 vests of new voting power (300v) - alice 325S+325v=325; bob 325v=300+25(131d); carol 325S -*/ - GOTO_DAY( 124 ); - DAY_REPORT( today ); - DAY_CHECK; - -/* - Day 131: last 25 vests mature on bob, bob.bp receives 25 vests of new voting power (325v) - alice 325S+325v=325; bob 325v=325; carol 325S -*/ - GOTO_DAY( 131 ); - DAY_REPORT( today ); - DAY_CHECK; - - } - FC_LOG_AND_RETHROW() -} - -#undef VOTING_POWER -#undef PROXIED_VSF -#undef ACCOUNT_REPORT -#undef WITNESS_VOTES -#undef DELAYED_VOTES -#undef DAY_REPORT -#undef CHECK_ACCOUNT_VESTS -#undef CHECK_ACCOUNT_HIVE -#undef CHECK_ACCOUNT_VP -#undef CHECK_WITNESS_VOTES -#undef DAY_CHECK -#undef GOTO_DAY - -BOOST_AUTO_TEST_SUITE_END() - -#pragma GCC diagnostic pop - -//#endif // #if defined(IS_TEST_NET) diff --git a/tests2/unit/tests/hf23_tests.cpp b/tests2/unit/tests/hf23_tests.cpp deleted file mode 100644 index 284c236bf4cad90a6edf959c57a28a35a1c78797..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/hf23_tests.cpp +++ /dev/null @@ -1,1340 +0,0 @@ -#ifdef IS_TEST_NET - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> -#include <hive/protocol/sps_operations.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> -#include <hive/chain/util/hf23_helper.hpp> - -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -#define DELEGATED_VESTS( account ) db->get_account( account ).get_delegated_vesting().amount.value -#define RECEIVED_VESTS( account ) db->get_account( account ).get_received_vesting().amount.value - -namespace -{ - -std::string asset_to_string( const asset& a ) -{ - return hive::plugins::condenser_api::legacy_asset::from_asset( a ).to_string(); -} - -} // namespace - - -BOOST_FIXTURE_TEST_SUITE( hf23_tests, hf23_database_fixture ) - -BOOST_AUTO_TEST_CASE( restore_accounts_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Saving during HF23 and restoring balances during HF24" ); - - ACTORS( (alice0)(alice1)(alice2)(alice3)(alice4)(dude) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - std::set< std::string > accounts{ "alice0", "alice1", "alice2", "alice3", "alice4" }; - - struct tmp_data - { - std::string name; - - asset balance; - asset hbd_balance; - }; - auto cmp = []( const tmp_data& a, const tmp_data& b ) - { - return std::strcmp( a.name.c_str(), b.name.c_str() ) < 0; - }; - std::set< tmp_data, decltype( cmp ) > old_balances( cmp ); - hf23_helper::hf23_items _balances; - - uint32_t cnt = 1; - for( auto& account : accounts ) - { - FUND( account, asset( cnt * 1000, HIVE_SYMBOL ) ); - FUND( account, asset( cnt * 1000 + 1, HBD_SYMBOL ) ); - ++cnt; - - old_balances.emplace( tmp_data{ account, get_balance( account ), get_hbd_balance( account ) } ); - } - { - FUND( "dude", asset( 68, HIVE_SYMBOL ) ); - FUND( "dude", asset( 78, HBD_SYMBOL ) ); - generate_block(); - } - { - db->clear_accounts( _balances, accounts ); - - for( auto& account : accounts ) - { - auto& _acc = db->get_account( account ); - - idump(( _acc.get_balance() )); - idump(( _acc.get_hbd_balance() )); - BOOST_REQUIRE( _acc.get_balance() == asset( 0, HIVE_SYMBOL ) ); - BOOST_REQUIRE( _acc.get_hbd_balance() == asset( 0, HBD_SYMBOL ) ); - } - BOOST_REQUIRE( get_balance( "dude" ) == asset( 68, HIVE_SYMBOL ) ); - BOOST_REQUIRE( get_hbd_balance( "dude" ) == asset( 78, HBD_SYMBOL ) ); - } - { - auto accounts_ex = accounts; - accounts_ex.insert( "dude" ); - accounts_ex.insert( "devil" ); - - db->restore_accounts( _balances, accounts_ex ); - - auto itr_old_balances = old_balances.begin(); - for( auto& account : accounts ) - { - auto& _acc = db->get_account( account ); - - BOOST_REQUIRE( account == itr_old_balances->name ); - BOOST_REQUIRE( _acc.get_balance() == itr_old_balances->balance ); - BOOST_REQUIRE( _acc.get_hbd_balance() == itr_old_balances->hbd_balance ); - - ++itr_old_balances; - } - BOOST_REQUIRE( get_balance( "dude" ) == asset( 68, HIVE_SYMBOL ) ); - BOOST_REQUIRE( get_hbd_balance( "dude" ) == asset( 78, HBD_SYMBOL ) ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( restore_accounts_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Saving during HF23 and restoring balances during HF24" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "1000.000 TESTS" ) ); - FUND( "alice", ASSET( "20.000 TBD" ) ); - FUND( "bob", ASSET( "900.000 TESTS" ) ); - FUND( "bob", ASSET( "10.000 TBD" ) ); - FUND( "carol", ASSET( "3600.000 TESTS" ) ); - FUND( "carol", ASSET( "3500.000 TBD" ) ); - - hf23_helper::hf23_items _hf23_items; - - const std::set< std::string > accounts{ "alice", "bob" }; - - { - auto& _alice = db->get_account( "alice" ); - auto& _bob = db->get_account( "bob" ); - - auto alice_balance = _alice.get_balance(); - auto alice_hbd_balance = _alice.get_hbd_balance(); - auto bob_balance = _bob.get_balance(); - auto bob_hbd_balance = _bob.get_hbd_balance(); - - { - hf23_helper::gather_balance( _hf23_items, _alice.name, _alice.get_balance(), _alice.get_hbd_balance() ); - db->adjust_balance( db->get_treasury_name(), _alice.get_balance() ); - db->adjust_balance( db->get_treasury_name(), _alice.get_hbd_balance() ); - db->adjust_balance( "alice", -_alice.get_balance() ); - db->adjust_balance( "alice", -_alice.get_hbd_balance() ); - } - { - hf23_helper::gather_balance( _hf23_items, _bob.name, _bob.get_balance(), _bob.get_hbd_balance() ); - db->adjust_balance( db->get_treasury_name(), _bob.get_balance() ); - db->adjust_balance( db->get_treasury_name(), _bob.get_hbd_balance() ); - db->adjust_balance( "bob", -_bob.get_balance() ); - db->adjust_balance( "bob", -_bob.get_hbd_balance() ); - } - - asset _2000 = ASSET( "2000.000 TESTS" ); - asset _10 = ASSET( "10.000 TBD" ); - asset _800 = ASSET( "800.000 TESTS" ); - asset _70 = ASSET( "70.000 TBD" ); - asset _5000 = ASSET( "5000.000 TESTS" ); - asset _4000 = ASSET( "4000.000 TBD" ); - - { - //Create another balances for `alice` - db->adjust_balance( "carol", -_2000 ); - db->adjust_balance( "carol", -_10 ); - db->adjust_balance( "alice", _2000 ); - db->adjust_balance( "alice", _10 ); - - generate_block(); - - BOOST_REQUIRE( get_balance( "alice" ) == _2000 ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == _10 ); - } - { - //Create another balances for `bob` - db->adjust_balance( "carol", -_800 ); - db->adjust_balance( "carol", -_70 ); - db->adjust_balance( "bob", _800 ); - db->adjust_balance( "bob", _70 ); - - generate_block(); - - BOOST_REQUIRE( get_balance( "bob" ) == _800 ); - BOOST_REQUIRE( get_hbd_balance( "bob" ) == _70 ); - } - - std::set< std::string > restored_accounts = { "bob", "alice", "carol" }; - - auto treasury_balance_start = db->get_treasury().get_balance(); - auto treasury_hbd_balance_start = db->get_treasury().get_hbd_balance(); - - { - auto last_supply = db->get_dynamic_global_properties().get_current_hbd_supply(); - - FUND( db->get_treasury_name(), _5000 ); - FUND( db->get_treasury_name(), _4000 ); - - generate_block(); - - auto interest = db->get_dynamic_global_properties().get_current_hbd_supply() - last_supply - _4000; - - BOOST_REQUIRE( db->get_treasury().get_balance() == _5000 + treasury_balance_start ); - BOOST_REQUIRE( db->get_treasury().get_hbd_balance() == _4000 + treasury_hbd_balance_start + interest ); - - treasury_balance_start += _5000; - treasury_hbd_balance_start += _4000 + interest; - } - - database_fixture::validate_database(); - - db->restore_accounts( _hf23_items, restored_accounts ); - - auto& _alice2 = db->get_account( "alice" ); - auto& _bob2 = db->get_account( "bob" ); - const auto& _treasury2 = db->get_treasury(); - - BOOST_REQUIRE( _alice2.get_balance() == _2000 + alice_balance ); - BOOST_REQUIRE( _alice2.get_hbd_balance() == _10 + alice_hbd_balance ); - BOOST_REQUIRE( _bob2.get_balance() == _800 + bob_balance ); - BOOST_REQUIRE( _bob2.get_hbd_balance() == _70 + bob_hbd_balance ); - - BOOST_REQUIRE( _treasury2.get_balance() == treasury_balance_start - ( alice_balance + bob_balance ) ); - BOOST_REQUIRE( _treasury2.get_hbd_balance() == treasury_hbd_balance_start - ( alice_hbd_balance + bob_hbd_balance ) ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -hf23_helper::hf23_item get_balances( const account_object& obj ) -{ - hf23_helper::hf23_item res; - - res.name = obj.name; - - res.balance = obj.get_balance(); - res.hbd_balance = obj.get_hbd_balance(); - - return res; -} - -bool cmp_hf23_item( const hf23_helper::hf23_item& a, const hf23_helper::hf23_item& b ) -{ - return a.name == b.name && a.balance == b.balance && a.hbd_balance == b.hbd_balance; -} - -BOOST_AUTO_TEST_CASE( save_test_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Saving one account balances" ); - - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "1000.000 TESTS" ) ); - FUND( "alice", ASSET( "20.000 TBD" ) ); - - hf23_helper::hf23_items _hf23_items; - - const std::set< std::string > accounts{ "alice", "bob" }; - - { - hf23_helper::gather_balance( _hf23_items, "alice", get_balance( "alice" ), get_hbd_balance( "alice" ) ); - } - { - BOOST_REQUIRE_EQUAL( _hf23_items.size(), 1u ); - - auto alice_balances = get_balances( db->get_account( "alice" ) ); - - hf23_helper::hf23_items cmp_balances = { alice_balances }; - - BOOST_REQUIRE_EQUAL( _hf23_items.size(), cmp_balances.size() ); - BOOST_REQUIRE( cmp_hf23_item( *_hf23_items.begin(), *cmp_balances.begin() ) ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( save_test_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Saving accounts balances" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - FUND( "alice", ASSET( "1000.000 TESTS" ) ); - FUND( "bob", ASSET( "2000.000 TESTS" ) ); - - FUND( "alice", ASSET( "20.000 TBD" ) ); - - const std::set< std::string > accounts{ "alice", "bob" }; - hf23_helper::hf23_items _hf23_items; - - { - vest( "alice", "alice", ASSET( "10.000 TESTS" ), alice_private_key ); - vest( "bob", "bob", ASSET( "10.000 TESTS" ), bob_private_key ); - - hf23_helper::gather_balance( _hf23_items, "alice", get_balance( "alice" ), get_hbd_balance( "alice" ) ); - hf23_helper::gather_balance( _hf23_items, "bob", get_balance( "bob" ), get_hbd_balance( "bob" ) ); - } - { - auto alice_balances = get_balances( db->get_account( "alice" ) ); - auto bob_balances = get_balances( db->get_account( "bob" ) ); - - hf23_helper::hf23_items cmp_balances = { alice_balances, bob_balances }; - - BOOST_REQUIRE_EQUAL( _hf23_items.size(), cmp_balances.size() ); - - auto iter = _hf23_items.begin(); - auto cmp_iter = cmp_balances.begin(); - - for( uint32_t i = 0; i < cmp_balances.size(); ++i ) - { - BOOST_REQUIRE( cmp_hf23_item( *iter, *cmp_iter ) ); - ++iter; - ++cmp_iter; - } - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_06 ) -{ - try - { - BOOST_TEST_MESSAGE( "VEST delegations - object of type `vesting_delegation_expiration_object` is generated" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto _10 = ASSET( "10.000 TESTS" ); - auto _20 = ASSET( "20.000 TESTS" ); - auto _1v = ASSET( "1.000000 VESTS" ); - auto _2v = ASSET( "2.000000 VESTS" ); - auto _3v = ASSET( "3.000000 VESTS" ); - auto _1000 = ASSET( "1000.000 TESTS" ); - - FUND( "alice", _1000 ); - FUND( "bob", _1000 ); - - { - vest( "alice", "alice", _10, alice_private_key ); - vest( "bob", "bob", _20, bob_private_key ); - } - { - delegate_vest( "alice", "bob", _3v, alice_private_key ); - generate_block(); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) == idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - { - delegate_vest( "alice", "bob", _3v, alice_private_key ); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) == idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - { - delegate_vest( "alice", "bob", _2v, alice_private_key ); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) != idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - { - delegate_vest( "alice", "bob", _1v, alice_private_key ); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) != idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - { - const auto& _bob = db->get_account( "bob" ); - db->clear_account( _bob ); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) != idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - { - const auto& _alice = db->get_account( "alice" ); - db->clear_account( _alice ); - - const auto& idx = db->get_index< vesting_delegation_expiration_index, by_account_expiration >(); - BOOST_REQUIRE( idx.lower_bound( "alice" ) == idx.end() ); - BOOST_REQUIRE( idx.lower_bound( "bob" ) == idx.end() ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_05 ) -{ - try - { - BOOST_TEST_MESSAGE( "VEST delegations - more complex scenarios" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto _10 = ASSET( "10.000 TESTS" ); - auto _20 = ASSET( "20.000 TESTS" ); - auto _1v = ASSET( "1.000000 VESTS" ); - auto _2v = ASSET( "2.000000 VESTS" ); - auto _3v = ASSET( "3.000000 VESTS" ); - auto _1000 = ASSET( "1000.000 TESTS" ); - - FUND( "alice", _1000 ); - FUND( "bob", _1000 ); - FUND( "carol", _1000 ); - - { - vest( "alice", "alice", _10, alice_private_key ); - vest( "bob", "bob", _20, bob_private_key ); - vest( "carol", "carol", _10, carol_private_key ); - } - { - delegate_vest( "alice", "bob", _1v, alice_private_key ); - delegate_vest( "alice", "bob", _2v, alice_private_key ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == _2v.amount.value ); - - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == _2v.amount.value ); - } - { - delegate_vest( "alice", "carol", _1v, alice_private_key ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == _3v.amount.value ); - - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == _2v.amount.value ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == _1v.amount.value ); - } - { - delegate_vest( "carol", "bob", _1v, carol_private_key ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == _3v.amount.value ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == _1v.amount.value ); - - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == _3v.amount.value ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == _1v.amount.value ); - } - { - const auto& _carol = db->get_account( "carol" ); - db->clear_account( _carol ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == _3v.amount.value ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == _2v.amount.value ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == _1v.amount.value ); - } - { - const auto& _alice = db->get_account( "alice" ); - db->clear_account( _alice ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == 0l ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_04 ) -{ - try - { - BOOST_TEST_MESSAGE( "VEST delegations" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto _10 = ASSET( "10.000 TESTS" ); - auto _20 = ASSET( "20.000 TESTS" ); - auto _1v = ASSET( "1.000000 VESTS" ); - auto _2v = ASSET( "2.000000 VESTS" ); - auto _1000 = ASSET( "1000.000 TESTS" ); - - FUND( "alice", _1000 ); - FUND( "bob", _1000 ); - FUND( "carol", _1000 ); - - { - vest( "alice", "alice", _10, alice_private_key ); - vest( "alice", "alice", _20, alice_private_key ); - - delegate_vest( "alice", "bob", _1v, alice_private_key ); - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) != 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) != 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == 0l ); - - auto previous = DELEGATED_VESTS( "alice" ); - - delegate_vest( "alice", "carol", _2v, alice_private_key ); - - auto next = DELEGATED_VESTS( "alice" ); - BOOST_REQUIRE( next > previous ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) != 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) != 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) != 0l ); - } - { - const auto& _alice = db->get_account( "alice" ); - db->clear_account( _alice ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == 0l ); - - const auto& _bob = db->get_account( "bob" ); - db->clear_account( _bob ); - - BOOST_REQUIRE( DELEGATED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( DELEGATED_VESTS( "carol" ) == 0l ); - - BOOST_REQUIRE( RECEIVED_VESTS( "alice" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "bob" ) == 0l ); - BOOST_REQUIRE( RECEIVED_VESTS( "carol" ) == 0l ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_03 ) -{ - try - { - BOOST_TEST_MESSAGE( "Vesting every account to anothers accounts" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto _1 = ASSET( "1.000 TESTS" ); - auto _2 = ASSET( "2.000 TESTS" ); - auto _3 = ASSET( "3.000 TESTS" ); - auto _1000 = ASSET( "1000.000 TESTS" ); - - FUND( "alice", _1000 ); - FUND( "bob", _1000 ); - FUND( "carol", _1000 ); - - BOOST_REQUIRE( get_vesting( "alice" ) == get_vesting( "bob" ) ); - BOOST_REQUIRE( get_vesting( "bob" ) == get_vesting( "carol" ) ); - - { - vest( "alice", "bob", _1, alice_private_key ); - vest( "bob", "carol", _2, bob_private_key ); - vest( "carol", "alice", _3, carol_private_key ); - BOOST_REQUIRE_GT( get_vesting( "alice" ).amount.value, get_vesting( "carol" ).amount.value ); - BOOST_REQUIRE_GT( get_vesting( "carol" ).amount.value, get_vesting( "bob" ).amount.value ); - } - { - auto vest_bob = get_vesting( "bob" ).amount.value; - auto vest_carol = get_vesting( "carol" ).amount.value; - - const auto& _alice = db->get_account( "alice" ); - db->clear_account( _alice ); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == vest_bob ); - BOOST_REQUIRE( get_vesting( "carol" ).amount.value == vest_carol ); - - const auto& _bob = db->get_account( "bob" ); - db->clear_account( _bob ); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "carol" ).amount.value == vest_carol ); - - const auto& _carol = db->get_account( "carol" ); - db->clear_account( _carol ); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "carol" ).amount.value == 0l ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Vesting" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto _1 = ASSET( "1.000 TESTS" ); - auto _1000 = ASSET( "1000.000 TESTS" ); - - FUND( "alice", _1000 ); - FUND( "bob", _1000 ); - - BOOST_REQUIRE( get_vesting( "alice" ) == get_vesting( "bob" ) ); - - { - vest( "alice", "alice", _1, alice_private_key ); - BOOST_REQUIRE_GT( get_vesting( "alice" ).amount.value, get_vesting( "bob" ).amount.value ); - } - { - auto vest_bob = get_vesting( "bob" ).amount.value; - - const auto& _alice = db->get_account( "alice" ); - db->clear_account( _alice ); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == vest_bob ); - - const auto& _bob = db->get_account( "bob" ); - db->clear_account( _bob ); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == 0l ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == 0l ); - } - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( basic_test_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Calling clear_account" ); - - ACTORS( (alice) ) - generate_block(); - - const auto& _alice = db->get_account( "alice" ); - - db->clear_account( _alice ); - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -#define CLEAR( who ) \ - if( !db->pending_transaction_session().valid() ) \ - db->pending_transaction_session() = db->start_undo_session(); \ - db->clear_account( db->get_account( who ) ); \ - database_fixture::validate_database() -//since generating block runs undo and reapplies transactions since last block (and clear_account is not a transaction) -//it is better to do it explicitly to avoid confusion when reading and debugging test -#define UNDO_CLEAR db->pending_transaction_session().reset() - -BOOST_AUTO_TEST_CASE( escrow_cleanup_test ) -{ - -#define REQUIRE_BALANCE( alice, bob, carol, treasury, getter, asset ) \ - BOOST_REQUIRE( getter( "alice" ) == ASSET( alice " " asset ) ); \ - BOOST_REQUIRE( getter( "bob" ) == ASSET( bob " " asset ) ); \ - BOOST_REQUIRE( getter( "carol" ) == ASSET( carol " " asset ) ); \ - BOOST_REQUIRE( getter( db->get_treasury_name() ) == ASSET( treasury " " asset ) ) - - try - { - BOOST_TEST_MESSAGE( "Calling escrow_cleanup_test" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - fund( "alice", ASSET( "10.000 TESTS" ) ); //<- note! extra 0.1 is in form of vests - fund( "alice", ASSET( "10.100 TBD" ) ); //<- note! treasury will get extras from interest and sps-fund/inflation - generate_block(); - REQUIRE_BALANCE( "10.000", "0.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "10.100", "0.000", "0.000", "0.027", get_hbd_balance, "TBD" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - { - escrow_transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.hive_amount = ASSET( "10.000 TESTS" ); - op.hbd_amount = ASSET( "10.000 TBD" ); - op.fee = ASSET( "0.100 TBD" ); - op.json_meta = ""; - op.ratification_deadline = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 10 ); - op.escrow_expiration = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 20 ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "0.027", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer requested but neither receiver nor agent approved yet - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "10.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "10.136", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - { - escrow_approve_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "carol"; - tx.operations.push_back( op ); - sign( tx, carol_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "0.036", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer approved by agent but not by receiver - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "10.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "10.145", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - { - escrow_approve_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.100", "0.045", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer approved by all parties (agent got fee) but the transfer itself wasn't released yet - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.000", "10.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "0.100", "10.054", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - { - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "alice"; - op.receiver = "bob"; - op.hive_amount = ASSET( "2.000 TESTS" ); - op.hbd_amount = ASSET( "3.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "2.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "0.100", "0.054", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer released partially by sender prior to escrow expiration - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "2.000", "0.000", "8.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "0.100", "7.063", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - { - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "bob"; - op.receiver = "alice"; - op.hive_amount = ASSET( "2.000 TESTS" ); - op.hbd_amount = ASSET( "3.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "2.000", "2.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "3.000", "3.000", "0.100", "0.063", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer released partially by receiver prior to escrow expiration - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "2.000", "0.000", "8.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "0.100", "7.072", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - //after approvals it doesn't matter if the ratification expires - - { - escrow_dispute_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "2.000", "2.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "3.000", "3.000", "0.100", "0.072", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer disputed by sender - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "2.000", "0.000", "8.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "0.100", "7.081", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - //after dispute it doesn't matter if the escrow expires - - { - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "carol"; - op.receiver = "bob"; - op.hive_amount = ASSET( "2.000 TESTS" ); - op.hbd_amount = ASSET( "3.000 TBD" ); - tx.operations.push_back( op ); - - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "carol"; - op.receiver = "alice"; - op.hive_amount = ASSET( "2.000 TESTS" ); - op.hbd_amount = ASSET( "1.000 TBD" ); - tx.operations.push_back( op ); - - sign( tx, carol_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "4.000", "4.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "4.000", "6.000", "0.100", "0.081", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) != nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 1 ); - generate_block(); - - //escrow transfer released partially by agent to sender and partially to receiver - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "4.000", "0.000", "6.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "6.000", "0.100", "4.090", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - - { - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "carol"; - op.who = "carol"; - op.receiver = "bob"; - op.hive_amount = ASSET( "2.000 TESTS" ); - op.hbd_amount = ASSET( "0.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, carol_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "4.000", "6.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "4.000", "6.000", "0.100", "0.090", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - generate_block(); - - //escrow transfer released by agent to receiver and finished (transfer fully executed) - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "6.000", "0.000", "4.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "6.000", "0.100", "4.099", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_escrow( "alice", 30 ) == nullptr ); - BOOST_REQUIRE( db->get_account( "alice" ).pending_transfers == 0 ); - UNDO_CLEAR; - } - FC_LOG_AND_RETHROW() - -#undef REQUIRE_BALANCE - -} - -BOOST_AUTO_TEST_CASE( limit_order_cleanup_test ) -{ - -#define REQUIRE_BALANCE( alice, bob, treasury, getter, asset ) \ - BOOST_REQUIRE( getter( "alice" ) == ASSET( alice " " asset ) ); \ - BOOST_REQUIRE( getter( "bob" ) == ASSET( bob " " asset ) ); \ - BOOST_REQUIRE( getter( db->get_treasury_name() ) == ASSET( treasury " " asset ) ) - - try - { - BOOST_TEST_MESSAGE( "Calling limit_order_cleanup_test" ); - ACTORS( (alice)(bob) ) - generate_block(); - - fund( "alice", ASSET( "10.000 TESTS" ) ); //<- note! extra 0.1 is in form of vests - fund( "bob", ASSET( "5.000 TBD" ) ); //<- note! treasury will get extras from interest and sps-fund/inflation - generate_block(); - REQUIRE_BALANCE( "10.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "5.000", "0.027", get_hbd_balance, "TBD" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - { - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = ASSET( "5.000 TBD" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 20 ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "5.000", "0.027", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) != nullptr ); - generate_block(); - - //limit order set but not matched yet - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "0.000", "10.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "5.000", "0.036", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) == nullptr ); - UNDO_CLEAR; - - { - limit_order_create_operation op; - op.owner = "bob"; - op.amount_to_sell = ASSET( "2.000 TBD" ); - op.min_to_receive = ASSET( "3.500 TESTS" ); - op.fill_or_kill = true; - op.expiration = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 20 ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "4.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "2.000", "3.000", "0.036", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) != nullptr ); - generate_block(); - - //limit order partially matched - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "4.000", "6.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "2.045", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) == nullptr ); - UNDO_CLEAR; - - { - limit_order_create2_operation op; - op.owner = "bob"; - op.amount_to_sell = ASSET( "3.000 TBD" ); - op.exchange_rate = ASSET( "2.000 TBD" ) / ASSET( "5.000 TESTS" ); - op.fill_or_kill = true; - op.expiration = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 20 ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "4.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "2.000", "3.000", "0.045", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) != nullptr ); - generate_block(); - - //limit order partially matched after counter-order in fill_or_kill mode that failed (no change) - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "4.000", "6.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "3.000", "2.054", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) == nullptr ); - UNDO_CLEAR; - - { - limit_order_create2_operation op; - op.owner = "bob"; - op.amount_to_sell = ASSET( "3.000 TBD" ); - op.exchange_rate = ASSET( "2.000 TBD" ) / ASSET( "4.000 TESTS" ); - op.fill_or_kill = true; - op.expiration = db->head_block_time() + fc::seconds( HIVE_BLOCK_INTERVAL * 20 ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "10.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "5.000", "0.000", "0.054", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) == nullptr ); - generate_block(); - - //limit order fully matched - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "10.000", "0.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.000", "5.063", get_hbd_balance, "TBD" ); - BOOST_REQUIRE( db->find_limit_order( "alice", 0 ) == nullptr ); - UNDO_CLEAR; - } - FC_LOG_AND_RETHROW() - -#undef REQUIRE_BALANCE - -} - -BOOST_AUTO_TEST_CASE( convert_request_cleanup_test ) -{ - -#define REQUIRE_BALANCE( alice, treasury, getter, asset ) \ - BOOST_REQUIRE( getter( "alice" ) == ASSET( alice " " asset ) ); \ - BOOST_REQUIRE( getter( db->get_treasury_name() ) == ASSET( treasury " " asset ) ) - - try - { - BOOST_TEST_MESSAGE( "Calling convert_request_cleanup_test" ); - ACTORS( (alice) ) - generate_block(); - - //note! extra 0.1 TESTS is in form of vests - fund( "alice", ASSET( "5.000 TBD" ) ); //<- note! treasury will get extras from interest and sps-fund/inflation - generate_block(); - REQUIRE_BALANCE( "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "5.000", "0.027", get_hbd_balance, "TBD" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - { - convert_operation op; - op.owner = "alice"; - op.amount = ASSET( "5.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - REQUIRE_BALANCE( "0.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.027", get_hbd_balance, "TBD" ); - generate_block(); - - //conversion request created but not executed yet - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "0.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "5.036", get_hbd_balance, "TBD" ); - UNDO_CLEAR; - - generate_blocks( db->head_block_time() + HIVE_CONVERSION_DELAY ); - - REQUIRE_BALANCE( "5.000", "0.000", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.054", get_hbd_balance, "TBD" ); - generate_block(); - - //conversion request executed - CLEAR( "alice" ); - REQUIRE_BALANCE( "0.000", "5.100", get_balance, "TESTS" ); - REQUIRE_BALANCE( "0.000", "0.063", get_hbd_balance, "TBD" ); - UNDO_CLEAR; - } - FC_LOG_AND_RETHROW() - -#undef REQUIRE_BALANCE - -} - -BOOST_AUTO_TEST_CASE( hbd_test_01 ) -{ - try - { - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - db->clear_account( db->get_account( "alice" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - database_fixture::validate_database(); - - fund( "alice", ASSET( "1000.000 TBD" ) ); - auto alice_hbd = get_hbd_balance( "alice" ); - BOOST_REQUIRE( alice_hbd == ASSET( "1000.000 TBD" ) ); - db->clear_account( db->get_account( "alice" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( hbd_test_02 ) -{ - try - { - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - fund( "alice", ASSET( "1000.000 TBD" ) ); - auto start_time = db->get_account( "alice" ).hbd_seconds_last_update; - auto alice_hbd = get_hbd_balance( "alice" ); - BOOST_TEST_MESSAGE( "treasury_hbd = " << asset_to_string( db->get_treasury().get_hbd_balance() ) ); - BOOST_TEST_MESSAGE( "alice_hbd = " << asset_to_string( alice_hbd ) ); - BOOST_REQUIRE( alice_hbd == ASSET( "1000.000 TBD" ) ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC ), true ); - - { - signed_transaction tx; - transfer_operation transfer; - transfer.to = "bob"; - transfer.from = "alice"; - transfer.amount = ASSET( "1.000 TBD" ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( transfer ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - - auto& gpo = db->get_dynamic_global_properties(); - auto interest_op = get_last_operations( 1 )[0].get< interest_operation >(); - - BOOST_REQUIRE( gpo.get_hbd_interest_rate() > 0 ); - BOOST_REQUIRE( static_cast<uint64_t>(get_hbd_balance( "alice" ).amount.value) == - alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value + - ( ( ( ( uint128_t( alice_hbd.amount.value ) * ( db->head_block_time() - start_time ).to_seconds() ) / HIVE_SECONDS_PER_YEAR ) * - gpo.get_hbd_interest_rate() ) / HIVE_100_PERCENT ).to_uint64() ); - BOOST_REQUIRE( interest_op.owner == "alice" ); - BOOST_REQUIRE( interest_op.interest.amount.value == - get_hbd_balance( "alice" ).amount.value - ( alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value ) ); - database_fixture::validate_database(); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC ), true ); - - alice_hbd = get_hbd_balance( "alice" ); - BOOST_TEST_MESSAGE( "alice_hbd = " << asset_to_string( alice_hbd ) ); - BOOST_TEST_MESSAGE( "bob_hbd = " << asset_to_string( get_hbd_balance( "bob" ) ) ); - - db->clear_account( db->get_account( "alice" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( savings_test_01 ) -{ - try - { - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - fund( "alice", ASSET( "1000.000 TBD" ) ); - - signed_transaction tx; - transfer_to_savings_operation op; - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "1000.000 TBD" ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "1000.000 TBD" ) ); - db->clear_account( db->get_account( "alice" ) ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "0.000 TBD" ) ); - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( savings_test_02 ) -{ - try - { - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - fund( "alice", ASSET( "1000.000 TBD" ) ); - - signed_transaction tx; - transfer_to_savings_operation op; - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "1000.000 TBD" ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "1000.000 TBD" ) ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC ), true ); - - BOOST_TEST_MESSAGE( "alice_savings_hbd before clear = " << asset_to_string( get_hbd_savings( "alice" ) ) ); - db->clear_account( db->get_account( "alice" ) ); - BOOST_TEST_MESSAGE( "alice_savings_hbd after clear = " << asset_to_string( get_hbd_savings( "alice" ) ) ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "0.000 TBD" ) ); - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() - -#endif diff --git a/tests2/unit/tests/hf24_tests.cpp b/tests2/unit/tests/hf24_tests.cpp deleted file mode 100644 index 298ab61e83477c44339ae5e05da27132fdce73d2..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/hf24_tests.cpp +++ /dev/null @@ -1,317 +0,0 @@ -#ifdef IS_TEST_NET - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> -#include <hive/protocol/sps_operations.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> -#include <hive/chain/util/hf23_helper.hpp> - -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - - -BOOST_FIXTURE_TEST_SUITE( hf24_tests, hf24_database_fixture ) - -BOOST_AUTO_TEST_CASE( blocked_operations ) -{ - try - { - BOOST_TEST_MESSAGE( "Even after HF24 steem.dao is considered a treasury account" ); - - ACTORS( ( alice ) ) - generate_block(); - fund( "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "10.000 TBD" ) ); - generate_block(); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - //check transfer of non-HBD - { - transfer_operation op; - op.from = "alice"; - op.to = OBSOLETE_TREASURY_ACCOUNT; - op.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); //still blocked even though old is no longer active treasury - - tx.clear(); - op.to = NEW_HIVE_TREASURY_ACCOUNT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); //blocked for new treasury as well - } - tx.clear(); - - //check vesting of non-HBD - { - transfer_to_vesting_operation op; - op.from = "alice"; - op.to = OBSOLETE_TREASURY_ACCOUNT; - op.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.to = NEW_HIVE_TREASURY_ACCOUNT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - tx.clear(); - - //check withdraw vesting route - { - set_withdraw_vesting_route_operation op; - op.from_account = "alice"; - op.to_account = OBSOLETE_TREASURY_ACCOUNT; - op.percent = 50 * HIVE_1_PERCENT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.to_account = NEW_HIVE_TREASURY_ACCOUNT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - tx.clear(); - - //check transfer to savings - { - transfer_to_savings_operation op; - op.from = "alice"; - op.to = OBSOLETE_TREASURY_ACCOUNT; - op.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.amount = ASSET( "1.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.to = NEW_HIVE_TREASURY_ACCOUNT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.to = "alice"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( get_savings( "alice" ) == ASSET( "1.000 TESTS" ) ); - } - tx.clear(); - - //check transfer from savings of non-HBD - { - transfer_from_savings_operation op; - op.from = "alice"; - op.to = OBSOLETE_TREASURY_ACCOUNT; - op.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - tx.clear(); - op.to = NEW_HIVE_TREASURY_ACCOUNT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - tx.clear(); - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_beneficiary ) -{ - try - { - BOOST_TEST_MESSAGE( "After HF24 steem.dao as comment beneficiary gives directly to new treasury account" ); - - ACTORS( ( alice ) ) - generate_block(); - - db_plugin->debug_update( []( database& db ) - { - db.modify( db.get_dynamic_global_properties(), []( dynamic_global_property_object& gpo ) - { - gpo.sps_fund_percent = 0; - } ); - } ); - fund( "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "10.000 TBD" ) ); - generate_block(); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - { - comment_operation comment; - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "Hello world"; - tx.operations.push_back( comment ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - { - comment_options_operation op; - comment_payout_beneficiaries b; - b.beneficiaries.push_back( beneficiary_route_type( OBSOLETE_TREASURY_ACCOUNT, HIVE_100_PERCENT ) ); - op.author = "alice"; - op.permlink = "test"; - op.allow_curation_rewards = false; - op.extensions.insert( b ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - { - vote_operation vote; - vote.author = "alice"; - vote.permlink = "test"; - vote.voter = "alice"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - tx.clear(); - - asset initial_treasury_balance = db->get_treasury().get_hbd_balance(); - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time ); - BOOST_REQUIRE_EQUAL( get_hbd_balance( OBSOLETE_TREASURY_ACCOUNT ).amount.value, 0 ); - BOOST_REQUIRE_EQUAL( db->get_treasury().get_hbd_balance().amount.value, 1150 + initial_treasury_balance.amount.value ); - - database_fixture::validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( consolidate_balance ) -{ - try - { - BOOST_TEST_MESSAGE( "After HF24 even if steem.dao gets some funds they will be transfered to new treasury account" ); - generate_block(); - - //instead of trying to find a way to fund various balances of steem.dao, just write to them directly - asset vested_3, vested_7; - db_plugin->debug_update( [&]( database& db ) - { - auto& dgpo = db.get_dynamic_global_properties(); - db.adjust_supply( ASSET( "20.000 TESTS" ) ); - db.adjust_supply( ASSET( "10.000 TBD" ) ); - vested_3 = ASSET( "3.000 TESTS" ) * dgpo.get_vesting_share_price(); - vested_7 = ASSET( "7.000 TESTS" ) * dgpo.get_vesting_share_price(); - db.modify( dgpo, []( dynamic_global_property_object& gpo ) - { - gpo.sps_fund_percent = 0; - } ); - auto& old_treasury = db.get_account( OBSOLETE_TREASURY_ACCOUNT ); - db.create_vesting( old_treasury, ASSET( "7.000 TESTS" ) ); - db.create_vesting( old_treasury, ASSET( "3.000 TESTS" ), true ); - db.modify( old_treasury, [&]( account_object& t ) - { - t.balance = ASSET( "5.000 TESTS" ); - t.savings_balance = ASSET( "3.000 TESTS" ); - t.reward_hive_balance = ASSET( "2.000 TESTS" ); - t.hbd_balance = ASSET( "5.000 TBD" ); - t.savings_hbd_balance = ASSET( "3.000 TBD" ); - t.reward_hbd_balance = ASSET( "2.000 TBD" ); - } ); - } ); - database_fixture::validate_database(); - { - auto& old_treasury = db->get_account( OBSOLETE_TREASURY_ACCOUNT ); - BOOST_REQUIRE_EQUAL( old_treasury.get_balance().amount.value, 5000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_savings().amount.value, 3000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_rewards().amount.value, 2000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_balance().amount.value, 5000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_savings().amount.value, 3000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_rewards().amount.value, 2000 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_vesting().amount.value, vested_7.amount.value ); - BOOST_REQUIRE_EQUAL( old_treasury.get_vest_rewards().amount.value, vested_3.amount.value ); - } - - asset initial_treasury_balance = db->get_treasury().get_hbd_balance(); - generate_block(); - database_fixture::validate_database(); - - { - auto& old_treasury = db->get_account( OBSOLETE_TREASURY_ACCOUNT ); - BOOST_REQUIRE_EQUAL( old_treasury.get_balance().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_savings().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_rewards().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_balance().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_savings().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_hbd_rewards().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_vesting().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( old_treasury.get_vest_rewards().amount.value, 0 ); - } - { - auto& treasury = db->get_account( NEW_HIVE_TREASURY_ACCOUNT ); - BOOST_REQUIRE_EQUAL( treasury.get_balance().amount.value, 14999 ); //rounding during vest->hive conversion - BOOST_REQUIRE_EQUAL( treasury.get_savings().amount.value, 3000 ); - BOOST_REQUIRE_EQUAL( treasury.get_rewards().amount.value, 2000 ); - BOOST_REQUIRE_EQUAL( treasury.get_hbd_balance().amount.value, 5000 + initial_treasury_balance.amount.value ); - BOOST_REQUIRE_EQUAL( treasury.get_hbd_savings().amount.value, 3000 ); - BOOST_REQUIRE_EQUAL( treasury.get_hbd_rewards().amount.value, 2000 ); - BOOST_REQUIRE_EQUAL( treasury.get_vesting().amount.value, 0 ); - BOOST_REQUIRE_EQUAL( treasury.get_vest_rewards().amount.value, 0 ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() - -#endif diff --git a/tests2/unit/tests/main.cpp b/tests2/unit/tests/main.cpp deleted file mode 100644 index 6a51836f7d256f92d164c05eba9d30f3742690ac..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/main.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2015 Cryptonomex, Inc., and contributors. - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#define BOOST_TEST_MODULE chain_test -#include <BoostTestTargetConfig.h> - -#include <cstdlib> -#include <iostream> -#include <boost/test/included/unit_test.hpp> - -// extern uint32_t HIVE_TESTING_GENESIS_TIMESTAMP; - -/* -boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) -{ - std::srand(time(NULL)); - std::cout << "Random number generator seeded to " << time(NULL) << std::endl; - - const char* genesis_timestamp_str = getenv("HIVE_TESTING_GENESIS_TIMESTAMP"); - if( genesis_timestamp_str != nullptr ) - { - HIVE_TESTING_GENESIS_TIMESTAMP = std::stoul( genesis_timestamp_str ); - } - std::cout << "HIVE_TESTING_GENESIS_TIMESTAMP is " << HIVE_TESTING_GENESIS_TIMESTAMP << std::endl; - - return nullptr; -} -*/ diff --git a/tests2/unit/tests/operation_tests.cpp b/tests2/unit/tests/operation_tests.cpp deleted file mode 100644 index bd708cf7e964b23e5fc3b6665c9ea98e95f56124..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/operation_tests.cpp +++ /dev/null @@ -1,8922 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -#define VOTING_MANABAR( account ) db->get_account( account ).voting_manabar -#define DOWNVOTE_MANABAR( account ) db->get_account( account ).downvote_manabar - -inline uint16_t get_voting_power( const account_object& a ) -{ - return (uint16_t)( a.voting_manabar.current_mana / chain::util::get_effective_vesting_shares( a ) ); -} - -BOOST_FIXTURE_TEST_SUITE( operation_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( account_create_validate ) -{ - try - { - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_create_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_create_authorities" ); - - account_create_operation op; - op.creator = "alice"; - op.new_account_name = "bob"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - BOOST_TEST_MESSAGE( "--- Testing owner authority" ); - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - BOOST_TEST_MESSAGE( "--- Testing active authority" ); - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - BOOST_TEST_MESSAGE( "--- Testing posting authority" ); - expected.clear(); - auths.clear(); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_create_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_create_apply" ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& wso ) - { - wso.median_props.account_creation_fee = ASSET( "0.100 TESTS" ); - }); - }); - generate_block(); - - signed_transaction tx; - private_key_type priv_key = generate_private_key( "alice" ); - - const account_object& init = db->get_account( HIVE_INIT_MINER_NAME ); - asset init_starting_balance = init.get_balance(); - - account_create_operation op; - - op.new_account_name = "alice"; - op.creator = HIVE_INIT_MINER_NAME; - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - op.active = authority( 2, priv_key.get_public_key(), 2 ); - op.memo_key = priv_key.get_public_key(); - op.json_metadata = "{\"foo\":\"bar\"}"; - - BOOST_TEST_MESSAGE( "--- Test failure paying more than the fee" ); - op.fee = asset( 101, HIVE_SYMBOL ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, init_account_priv_key ); - tx.validate(); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test normal account creation" ); - op.fee = asset( 100, HIVE_SYMBOL ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, init_account_priv_key ); - tx.validate(); - db->push_transaction( tx, 0 ); - - const account_object& acct = db->get_account( "alice" ); - const account_authority_object& acct_auth = db->get< account_authority_object, by_account >( "alice" ); - - BOOST_REQUIRE( acct.name == "alice" ); - BOOST_REQUIRE( acct_auth.owner == authority( 1, priv_key.get_public_key(), 1 ) ); - BOOST_REQUIRE( acct_auth.active == authority( 2, priv_key.get_public_key(), 2 ) ); - BOOST_REQUIRE( acct.memo_key == priv_key.get_public_key() ); - BOOST_REQUIRE( acct.proxy == "" ); - BOOST_REQUIRE( acct.created == db->head_block_time() ); - BOOST_REQUIRE( acct.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( acct.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - BOOST_REQUIRE( acct.get_id().get_value() == acct_auth.get_id().get_value() ); - - BOOST_REQUIRE( acct.get_vesting().amount.value == 0 ); - BOOST_REQUIRE( acct.vesting_withdraw_rate.amount.value == ASSET( "0.000000 VESTS" ).amount.value ); - BOOST_REQUIRE( acct.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( ( init_starting_balance - ASSET( "0.100 TESTS" ) ).amount.value == init.get_balance().amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure of duplicate account creation" ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( acct.name == "alice" ); - BOOST_REQUIRE( acct_auth.owner == authority( 1, priv_key.get_public_key(), 1 ) ); - BOOST_REQUIRE( acct_auth.active == authority( 2, priv_key.get_public_key(), 2 ) ); - BOOST_REQUIRE( acct.memo_key == priv_key.get_public_key() ); - BOOST_REQUIRE( acct.proxy == "" ); - BOOST_REQUIRE( acct.created == db->head_block_time() ); - BOOST_REQUIRE( acct.get_balance().amount.value == ASSET( "0.000 TESTS " ).amount.value ); - BOOST_REQUIRE( acct.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - BOOST_REQUIRE( acct.get_vesting().amount.value == 0 ); - BOOST_REQUIRE( acct.vesting_withdraw_rate.amount.value == ASSET( "0.000000 VESTS" ).amount.value ); - BOOST_REQUIRE( acct.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( ( init_starting_balance - ASSET( "0.100 TESTS" ) ).amount.value == init.get_balance().amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when creator cannot cover fee" ); - tx.signatures.clear(); - tx.operations.clear(); - op.fee = asset( get_balance( HIVE_INIT_MINER_NAME ).amount + 1, HIVE_SYMBOL ); - op.new_account_name = "bob"; - tx.operations.push_back( op ); - sign( tx, init_account_priv_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure covering witness fee" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& wso ) - { - wso.median_props.account_creation_fee = ASSET( "10.000 TESTS" ); - }); - }); - generate_block(); - - tx.clear(); - op.fee = ASSET( "0.100 TESTS" ); - tx.operations.push_back( op ); - sign( tx, init_account_priv_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - fund( HIVE_TEMP_ACCOUNT, ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, HIVE_TEMP_ACCOUNT, ASSET( "10.000 TESTS" ) ); - - BOOST_TEST_MESSAGE( "--- Test account creation with temp account does not set recovery account" ); - op.creator = HIVE_TEMP_ACCOUNT; - op.fee = ASSET( "10.000 TESTS" ); - op.new_account_name = "bob"; - tx.clear(); - tx.operations.push_back( op ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_account( "bob" ).recovery_account == account_name_type() ); - validate_database(); - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update_validate" ); - - ACTORS( (alice) ) - - account_update_operation op; - op.account = "alice"; - op.posting = authority(); - op.posting->weight_threshold = 1; - op.posting->add_authorities( "abcdefghijklmnopq", 1 ); - - try - { - op.validate(); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_FAIL( "An exception was not thrown for an invalid account name" ); - } - catch( fc::exception& ) {} - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update_authorities" ); - - ACTORS( (alice)(bob) ) - private_key_type active_key = generate_private_key( "new_key" ); - - db->modify( db->get< account_authority_object, by_account >( "alice" ), [&]( account_authority_object& a ) - { - a.active = authority( 1, active_key.get_public_key(), 1 ); - }); - - account_update_operation op; - op.account = "alice"; - op.json_metadata = "{\"success\":true}"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( " Tests when owner authority is not updated ---" ); - BOOST_TEST_MESSAGE( "--- Test failure when no signature" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when wrong signature" ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when containing additional incorrect signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when containing duplicate signatures" ); - tx.signatures.clear(); - sign( tx, active_key ); - sign( tx, active_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test success on active key" ); - tx.signatures.clear(); - sign( tx, active_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test success on owner key alone" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( " Tests when owner authority is updated ---" ); - BOOST_TEST_MESSAGE( "--- Test failure when updating the owner authority with an active key" ); - tx.signatures.clear(); - tx.operations.clear(); - op.owner = authority( 1, active_key.get_public_key(), 1 ); - tx.operations.push_back( op ); - sign( tx, active_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_owner_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when owner key and active key are present" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0), tx_missing_owner_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate owner keys are present" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test success when updating the owner authority with an owner key" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update_apply" ); - - ACTORS( (alice) ) - private_key_type new_private_key = generate_private_key( "new_key" ); - - BOOST_TEST_MESSAGE( "--- Test normal update" ); - - account_update_operation op; - op.account = "alice"; - op.owner = authority( 1, new_private_key.get_public_key(), 1 ); - op.active = authority( 2, new_private_key.get_public_key(), 2 ); - op.memo_key = new_private_key.get_public_key(); - op.json_metadata = "{\"bar\":\"foo\"}"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const account_object& acct = db->get_account( "alice" ); - const account_authority_object& acct_auth = db->get< account_authority_object, by_account >( "alice" ); - - BOOST_REQUIRE( acct.name == "alice" ); - BOOST_REQUIRE( acct_auth.owner == authority( 1, new_private_key.get_public_key(), 1 ) ); - BOOST_REQUIRE( acct_auth.active == authority( 2, new_private_key.get_public_key(), 2 ) ); - BOOST_REQUIRE( acct.memo_key == new_private_key.get_public_key() ); - - /* This is being moved out of consensus - #ifndef IS_LOW_MEM - BOOST_REQUIRE( acct.json_metadata == "{\"bar\":\"foo\"}" ); - #else - BOOST_REQUIRE( acct.json_metadata == "" ); - #endif - */ - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when updating a non-existent account" ); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "bob"; - tx.operations.push_back( op ); - sign( tx, new_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ) - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test failure when account authority does not exist" ); - tx.clear(); - op = account_update_operation(); - op.account = "alice"; - op.posting = authority(); - op.posting->weight_threshold = 1; - op.posting->add_authorities( "dave", 1 ); - tx.operations.push_back( op ); - sign( tx, new_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: comment_validate" ); - - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: comment_authorities" ); - - ACTORS( (alice)(bob) ); - generate_blocks( 60 / HIVE_BLOCK_INTERVAL ); - - comment_operation op; - op.author = "alice"; - op.permlink = "lorem"; - op.parent_author = ""; - op.parent_permlink = "ipsum"; - op.title = "Lorem Ipsum"; - op.body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; - op.json_metadata = "{\"foo\":\"bar\"}"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_posting_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - sign( tx, alice_post_key ); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with post signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_posting_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: comment_apply" ); - - ACTORS( (alice)(bob)(sam) ) - generate_blocks( 60 / HIVE_BLOCK_INTERVAL ); - - comment_operation op; - op.author = "alice"; - op.permlink = "lorem"; - op.parent_author = ""; - op.parent_permlink = "ipsum"; - op.title = "Lorem Ipsum"; - op.body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; - op.json_metadata = "{\"foo\":\"bar\"}"; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test Alice posting a root comment" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const comment_object& alice_comment = db->get_comment( "alice", string( "lorem" ) ); - const comment_cashout_object* alice_comment_cashout = db->find_comment_cashout( alice_comment ); - - BOOST_REQUIRE( alice_comment.get_author_and_permlink_hash() == comment_object::compute_author_and_permlink_hash( get_account_id( "alice" ), "lorem" ) ); - BOOST_REQUIRE( alice_comment_cashout != nullptr ); - BOOST_CHECK_EQUAL( alice_comment_cashout->get_comment_id(), alice_comment.get_id() ); - BOOST_CHECK_EQUAL( alice_comment_cashout->author_id, get_account_id( op.author ) ); - BOOST_CHECK_EQUAL( to_string( alice_comment_cashout->permlink ), "lorem" ); - BOOST_REQUIRE( alice_comment.is_root() ); - BOOST_REQUIRE( alice_comment_cashout->active == db->head_block_time() ); - BOOST_REQUIRE( alice_comment_cashout->get_creation_time() == db->head_block_time() ); - BOOST_REQUIRE( alice_comment_cashout->net_rshares.value == 0 ); - BOOST_REQUIRE( alice_comment_cashout->abs_rshares.value == 0 ); - BOOST_REQUIRE( alice_comment_cashout->cashout_time == fc::time_point_sec( db->head_block_time() + fc::seconds( HIVE_CASHOUT_WINDOW_SECONDS ) ) ); - - #if !defined(IS_LOW_MEM) && defined(STORE_COMMENT_CONTENT) - const auto& alice_comment_content = db->get< comment_content_object, by_comment >( alice_comment.get_id() ); - BOOST_REQUIRE( to_string( alice_comment_content.title ) == op.title ); - BOOST_REQUIRE( to_string( alice_comment_content.body ) == op.body ); - BOOST_REQUIRE( to_string( alice_comment_content.json_metadata ) == op.json_metadata ); - #else - const auto* alice_comment_content = db->find< comment_content_object, by_comment >( alice_comment.get_id() ); - BOOST_REQUIRE( alice_comment_content == nullptr ); - #endif - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test Bob posting a comment on a non-existent comment" ); - op.author = "bob"; - op.permlink = "ipsum"; - op.parent_author = "alice"; - op.parent_permlink = "foobar"; - - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test Bob posting a comment on Alice's comment" ); - op.parent_permlink = "lorem"; - - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - const comment_object& bob_comment = db->get_comment( "bob", string( "ipsum" ) ); - const comment_cashout_object* bob_comment_cashout = db->find_comment_cashout( bob_comment ); - - BOOST_CHECK_EQUAL( bob_comment.get_author_and_permlink_hash(), comment_object::compute_author_and_permlink_hash( get_account_id( "bob" ), "ipsum" ) ); - BOOST_REQUIRE( bob_comment_cashout != nullptr ); - BOOST_CHECK_EQUAL( bob_comment_cashout->get_comment_id(), bob_comment.get_id() ); - BOOST_CHECK_EQUAL( bob_comment_cashout->author_id, get_account_id( "bob" ) ); - BOOST_CHECK_EQUAL( to_string( bob_comment_cashout->permlink ), "ipsum" ); - BOOST_REQUIRE( bob_comment.get_parent_id() == alice_comment.get_id() ); - BOOST_REQUIRE( bob_comment_cashout->active == db->head_block_time() ); - BOOST_REQUIRE( bob_comment_cashout->get_creation_time() == db->head_block_time() ); - BOOST_REQUIRE( bob_comment_cashout->net_rshares.value == 0 ); - BOOST_REQUIRE( bob_comment_cashout->abs_rshares.value == 0 ); - BOOST_REQUIRE( bob_comment_cashout->cashout_time == bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( bob_comment.get_root_id() == alice_comment.get_id() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test Sam posting a comment on Bob's comment" ); - - op.author = "sam"; - op.permlink = "dolor"; - op.parent_author = "bob"; - op.parent_permlink = "ipsum"; - - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - const comment_object& sam_comment = db->get_comment( "sam", string( "dolor" ) ); - const comment_cashout_object* sam_comment_cashout = db->find_comment_cashout( sam_comment ); - - BOOST_REQUIRE( sam_comment.get_author_and_permlink_hash() == comment_object::compute_author_and_permlink_hash( get_account_id( "sam" ), "dolor" ) ); - BOOST_REQUIRE( sam_comment_cashout != nullptr ); - BOOST_CHECK_EQUAL( sam_comment_cashout->get_comment_id(), sam_comment.get_id() ); - BOOST_CHECK_EQUAL( sam_comment_cashout->author_id, get_account_id( "sam" ) ); - BOOST_CHECK_EQUAL( to_string( sam_comment_cashout->permlink ), "dolor" ); - BOOST_REQUIRE( sam_comment.get_parent_id() == bob_comment.get_id() ); - BOOST_REQUIRE( sam_comment_cashout->active == db->head_block_time() ); - BOOST_REQUIRE( sam_comment_cashout->get_creation_time() == db->head_block_time() ); - BOOST_REQUIRE( sam_comment_cashout->net_rshares.value == 0 ); - BOOST_REQUIRE( sam_comment_cashout->abs_rshares.value == 0 ); - BOOST_REQUIRE( sam_comment_cashout->cashout_time == sam_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( sam_comment.get_root_id() == alice_comment.get_id() ); - validate_database(); - - generate_blocks( 60 * 5 / HIVE_BLOCK_INTERVAL + 1 ); - - BOOST_TEST_MESSAGE( "--- Test modifying a comment" ); - const auto& mod_sam_comment = db->get_comment( "sam", string( "dolor" ) ); - const auto& mod_bob_comment = db->get_comment( "bob", string( "ipsum" ) ); - const auto& mod_alice_comment = db->get_comment( "alice", string( "lorem" ) ); - - const comment_cashout_object* mod_sam_comment_cashout = db->find_comment_cashout( mod_sam_comment ); - - FC_UNUSED(mod_bob_comment, mod_alice_comment); - - fc::time_point_sec created = mod_sam_comment_cashout->get_creation_time(); - - db->modify( *mod_sam_comment_cashout, [&]( comment_cashout_object& com ) - { - com.net_rshares = 10; - com.abs_rshares = 10; - }); - - db->modify( db->get_dynamic_global_properties(), [&]( dynamic_global_property_object& o) - { - o.total_reward_shares2 = hive::chain::util::evaluate_reward_curve( 10 ); - }); - - tx.signatures.clear(); - tx.operations.clear(); - op.title = "foo"; - op.body = "bar"; - op.json_metadata = "{\"bar\":\"foo\"}"; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( mod_sam_comment.get_author_and_permlink_hash() == comment_object::compute_author_and_permlink_hash( get_account_id( "sam" ), "dolor" ) ); - BOOST_REQUIRE( mod_sam_comment_cashout != nullptr ); - BOOST_CHECK_EQUAL( mod_sam_comment_cashout->get_comment_id(), mod_sam_comment.get_id() ); - BOOST_CHECK_EQUAL( mod_sam_comment_cashout->author_id, get_account_id( "sam" ) ); - BOOST_CHECK_EQUAL( to_string( mod_sam_comment_cashout->permlink ), "dolor" ); - BOOST_REQUIRE( mod_sam_comment.get_parent_id() == mod_bob_comment.get_id() ); - BOOST_REQUIRE( mod_sam_comment_cashout->active == db->head_block_time() ); - BOOST_REQUIRE( mod_sam_comment_cashout->get_creation_time() == created ); - BOOST_REQUIRE( mod_sam_comment_cashout->cashout_time == mod_sam_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test comment edit rate limit" ); - op.body = "edit"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - generate_block(); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failure posting withing 1 minute" ); - - op.permlink = "sit"; - op.parent_author = ""; - op.parent_permlink = "test"; - tx.operations.clear(); - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( 60 * 5 / HIVE_BLOCK_INTERVAL ); - - op.permlink = "amet"; - tx.operations.clear(); - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - validate_database(); - - generate_block(); - db->push_transaction( tx, 0 ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_delete_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: comment_delete_apply" ); - ACTORS( (alice) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - signed_transaction tx; - comment_operation comment; - vote_operation vote; - - comment.author = "alice"; - comment.permlink = "test1"; - comment.title = "test"; - comment.body = "foo bar"; - comment.parent_permlink = "test"; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test1"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failue deleting a comment with positive rshares" ); - - delete_comment_operation op; - op.author = "alice"; - op.permlink = "test1"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test success deleting a comment with negative rshares" ); - - generate_block(); - vote.weight = -1 * HIVE_100_PERCENT; - tx.clear(); - tx.operations.push_back( vote ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto test_comment = db->find_comment( "alice", string( "test1" ) ); - BOOST_REQUIRE( test_comment == nullptr ); - - - BOOST_TEST_MESSAGE( "--- Test failure deleting a comment past cashout" ); - generate_blocks( HIVE_MIN_ROOT_COMMENT_INTERVAL.to_seconds() / HIVE_BLOCK_INTERVAL ); - - tx.clear(); - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( HIVE_CASHOUT_WINDOW_SECONDS / HIVE_BLOCK_INTERVAL ); - - const comment_object& _comment = db->get_comment( "alice", string( "test1" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test failure deleting a comment with a reply" ); - - comment.permlink = "test2"; - comment.parent_author = "alice"; - comment.parent_permlink = "test1"; - tx.clear(); - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( HIVE_MIN_ROOT_COMMENT_INTERVAL.to_seconds() / HIVE_BLOCK_INTERVAL ); - comment.permlink = "test3"; - comment.parent_permlink = "test2"; - tx.clear(); - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.permlink = "test2"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( vote_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: vote_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( vote_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: vote_authorities" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( vote_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: vote_apply" ); - - ACTORS( (alice)(bob)(sam)(dave) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - validate_database(); - vest( HIVE_INIT_MINER_NAME, "bob" , ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "sam" , ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "dave" , ASSET( "10.000 TESTS" ) ); - generate_block(); - - const auto& vote_idx = db->get_index< comment_vote_index >().indices().get< by_comment_voter >(); - - { - const auto& alice = db->get_account( "alice" ); - - signed_transaction tx; - comment_operation comment_op; - comment_op.author = "alice"; - comment_op.permlink = "foo"; - comment_op.parent_permlink = "test"; - comment_op.title = "bar"; - comment_op.body = "foo bar"; - tx.operations.push_back( comment_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Testing voting on a non-existent comment" ); - - tx.operations.clear(); - tx.signatures.clear(); - - vote_operation op; - op.voter = "alice"; - op.author = "bob"; - op.permlink = "foo"; - op.weight = HIVE_100_PERCENT; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Testing voting with a weight of 0" ); - - op.weight = (int16_t) 0; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Testing success" ); - - auto old_mana = alice.voting_manabar.current_mana; - - op.weight = HIVE_100_PERCENT; - op.author = "alice"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - auto& alice_comment = db->get_comment( "alice", string( "foo" ) ); - const comment_cashout_object* alice_comment_cashout = db->find_comment_cashout( alice_comment ); - - auto itr = vote_idx.find( boost::make_tuple( alice_comment.get_id(), alice.get_id() ) ); - int64_t max_vote_denom = ( db->get_dynamic_global_properties().vote_power_reserve_rate * HIVE_VOTING_MANA_REGENERATION_SECONDS ) / (60*60*24); - - BOOST_REQUIRE( alice.last_vote_time == db->head_block_time() ); - BOOST_REQUIRE( alice_comment_cashout->net_rshares.value == ( old_mana - alice.voting_manabar.current_mana ) - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( alice_comment_cashout->cashout_time == alice_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( itr->rshares == ( old_mana - alice.voting_manabar.current_mana ) - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( itr != vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test reduced power for quick voting" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_VOTE_INTERVAL_SEC ); - - util::manabar old_manabar = VOTING_MANABAR( "alice" ); - util::manabar_params params( util::get_effective_vesting_shares( db->get_account( "alice" ) ), HIVE_VOTING_MANA_REGENERATION_SECONDS ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - comment_op.author = "bob"; - comment_op.permlink = "foo"; - comment_op.title = "bar"; - comment_op.body = "foo bar"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( comment_op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - op.weight = HIVE_100_PERCENT / 2; - op.voter = "alice"; - op.author = "bob"; - op.permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const auto& bob_comment = db->get_comment( "bob", string( "foo" ) ); - const comment_cashout_object* bob_comment_cashout = db->find_comment_cashout( bob_comment ); - itr = vote_idx.find( boost::make_tuple( bob_comment.get_id(), alice.get_id() ) ); - - BOOST_REQUIRE( bob_comment_cashout->net_rshares.value == ( old_manabar.current_mana - db->get_account( "alice" ).voting_manabar.current_mana ) - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( bob_comment_cashout->cashout_time == bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( itr != vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test payout time extension on vote" ); - - old_mana = VOTING_MANABAR( "bob" ).current_mana; - auto old_abs_rshares = db->find_comment_cashout( db->get_comment( "alice", string( "foo" ) ) )->abs_rshares.value; - - generate_blocks( db->head_block_time() + fc::seconds( ( HIVE_CASHOUT_WINDOW_SECONDS / 2 ) ), true ); - - const auto& new_bob = db->get_account( "bob" ); - const auto& new_alice_comment = db->get_comment( "alice", string( "foo" ) ); - const comment_cashout_object* new_alice_comment_cashout = db->find_comment_cashout( new_alice_comment ); - - op.weight = HIVE_100_PERCENT; - op.voter = "bob"; - op.author = "alice"; - op.permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - itr = vote_idx.find( boost::make_tuple( new_alice_comment.get_id(), new_bob.get_id() ) ); - - BOOST_REQUIRE( new_alice_comment_cashout->net_rshares.value == old_abs_rshares + ( old_mana - new_bob.voting_manabar.current_mana ) - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( new_alice_comment_cashout->cashout_time == new_alice_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( itr != vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test negative vote" ); - - const auto& new_sam = db->get_account( "sam" ); - const auto& new_bob_comment = db->get_comment( "bob", string( "foo" ) ); - const comment_cashout_object* new_bob_comment_cashout = db->find_comment_cashout( new_bob_comment ); - - old_abs_rshares = new_bob_comment_cashout->abs_rshares.value; - - old_manabar = VOTING_MANABAR( "sam" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "sam" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - op.weight = -1 * HIVE_100_PERCENT / 2; - op.voter = "sam"; - op.author = "bob"; - op.permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - itr = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_sam.get_id() ) ); - - util::manabar old_downvote_manabar; - util::manabar_params downvote_params( util::get_effective_vesting_shares( db->get_account( "alice" ) ) / 4, HIVE_VOTING_MANA_REGENERATION_SECONDS ); - old_downvote_manabar.regenerate_mana( downvote_params, db->head_block_time() ); - int64_t sam_weight = old_downvote_manabar.current_mana - DOWNVOTE_MANABAR( "sam" ).current_mana - HIVE_VOTE_DUST_THRESHOLD; - - BOOST_REQUIRE( new_bob_comment_cashout->net_rshares.value == old_abs_rshares - sam_weight ); - BOOST_REQUIRE( new_bob_comment_cashout->abs_rshares.value == old_abs_rshares + sam_weight ); - BOOST_REQUIRE( new_bob_comment_cashout->cashout_time == new_bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( itr != vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test nested voting on nested comments" ); - - old_abs_rshares = new_alice_comment_cashout->children_abs_rshares.value; - int64_t regenerated_power = (HIVE_100_PERCENT * ( db->head_block_time() - db->get_account( "alice").last_vote_time ).to_seconds() ) / HIVE_VOTING_MANA_REGENERATION_SECONDS; - int64_t used_power = ( get_voting_power( db->get_account( "alice" ) ) + regenerated_power + max_vote_denom - 1 ) / max_vote_denom; - - comment_op.author = "sam"; - comment_op.permlink = "foo"; - comment_op.title = "bar"; - comment_op.body = "foo bar"; - comment_op.parent_author = "alice"; - comment_op.parent_permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( comment_op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - op.weight = HIVE_100_PERCENT; - op.voter = "alice"; - op.author = "sam"; - op.permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - int64_t new_rshares = ( ( fc::uint128_t( get_vesting( "alice" ).amount.value ) * used_power ) / HIVE_100_PERCENT ).to_uint64() - HIVE_VOTE_DUST_THRESHOLD; - - { - auto* alice_cashout = db->find_comment_cashout( db->get_comment( "alice", string( "foo" ) ) ); - BOOST_REQUIRE( alice_cashout->cashout_time == alice_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - } - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test increasing vote rshares" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_VOTE_INTERVAL_SEC ); - - auto& new_alice = db->get_account( "alice" ); - auto alice_bob_vote = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_alice.get_id() ) ); - auto old_vote_rshares = alice_bob_vote->rshares; - auto old_net_rshares = new_bob_comment_cashout->net_rshares.value; - old_abs_rshares = new_bob_comment_cashout->abs_rshares.value; - used_power = ( ( HIVE_1_PERCENT * 25 * ( get_voting_power( new_alice ) ) / HIVE_100_PERCENT ) + max_vote_denom - 1 ) / max_vote_denom; - auto alice_voting_power = get_voting_power( new_alice ) - used_power; - - old_manabar = VOTING_MANABAR( "alice" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - op.voter = "alice"; - op.weight = HIVE_1_PERCENT * 25; - op.author = "bob"; - op.permlink = "foo"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - alice_bob_vote = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_alice.get_id() ) ); - - new_rshares = old_manabar.current_mana - VOTING_MANABAR( "alice" ).current_mana - HIVE_VOTE_DUST_THRESHOLD; - - BOOST_REQUIRE( new_bob_comment_cashout->net_rshares == old_net_rshares - old_vote_rshares + new_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->abs_rshares == old_abs_rshares + new_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->cashout_time == new_bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( alice_bob_vote->rshares == new_rshares ); - BOOST_REQUIRE( alice_bob_vote->last_update == db->head_block_time() ); - BOOST_REQUIRE( alice_bob_vote->vote_percent == op.weight ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test decreasing vote rshares" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_VOTE_INTERVAL_SEC ); - - old_vote_rshares = new_rshares; - old_net_rshares = new_bob_comment_cashout->net_rshares.value; - old_abs_rshares = new_bob_comment_cashout->abs_rshares.value; - used_power = ( uint64_t( HIVE_1_PERCENT ) * 75 * uint64_t( alice_voting_power ) ) / HIVE_100_PERCENT; - used_power = ( used_power + max_vote_denom - 1 ) / max_vote_denom; - alice_voting_power -= used_power; - - old_manabar = VOTING_MANABAR( "alice" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - old_downvote_manabar = DOWNVOTE_MANABAR( "alice" ); - downvote_params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ) / 4; - old_downvote_manabar.regenerate_mana( downvote_params, db->head_block_time() ); - - op.weight = HIVE_1_PERCENT * -75; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - alice_bob_vote = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_alice.get_id() ) ); - - new_rshares = old_downvote_manabar.current_mana - DOWNVOTE_MANABAR( "alice" ).current_mana - HIVE_VOTE_DUST_THRESHOLD; - - BOOST_REQUIRE( new_bob_comment_cashout->net_rshares == old_net_rshares - old_vote_rshares - new_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->abs_rshares == old_abs_rshares + new_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->cashout_time == new_bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( alice_bob_vote->rshares == -1 * new_rshares ); - BOOST_REQUIRE( alice_bob_vote->last_update == db->head_block_time() ); - BOOST_REQUIRE( alice_bob_vote->vote_percent == op.weight ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test changing a vote to 0 weight (aka: removing a vote)" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_VOTE_INTERVAL_SEC ); - - old_vote_rshares = alice_bob_vote->rshares; - old_net_rshares = new_bob_comment_cashout->net_rshares.value; - old_abs_rshares = new_bob_comment_cashout->abs_rshares.value; - - op.weight = 0; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - alice_bob_vote = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_alice.get_id() ) ); - - BOOST_REQUIRE( new_bob_comment_cashout->net_rshares == old_net_rshares - old_vote_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->abs_rshares == old_abs_rshares ); - BOOST_REQUIRE( new_bob_comment_cashout->cashout_time == new_bob_comment_cashout->get_creation_time() + HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( alice_bob_vote->rshares == 0 ); - BOOST_REQUIRE( alice_bob_vote->last_update == db->head_block_time() ); - BOOST_REQUIRE( alice_bob_vote->vote_percent == op.weight ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test downvote overlap when downvote mana is low" ); - - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "alice" ), [&]( account_object& a ) - { - a.downvote_manabar.current_mana /= 30; - a.downvote_manabar.last_update_time = db.head_block_time().sec_since_epoch(); - }); - }); - - int64_t alice_weight = 0; - - { - const auto& alice = db->get_account( "alice" ); - old_downvote_manabar.current_mana = alice.downvote_manabar.current_mana; - old_downvote_manabar.last_update_time = alice.downvote_manabar.last_update_time; - old_manabar.current_mana = alice.voting_manabar.current_mana; - old_manabar.last_update_time = alice.voting_manabar.last_update_time; - old_manabar.regenerate_mana( params, db->head_block_time() ); - old_downvote_manabar.regenerate_mana( params, db->head_block_time() ); - alice_weight = old_manabar.current_mana * 60 * 60 * 24; - auto max_vote_denom = db->get_dynamic_global_properties().vote_power_reserve_rate * HIVE_VOTING_MANA_REGENERATION_SECONDS; - alice_weight = ( alice_weight + max_vote_denom - 1 ) / max_vote_denom; - - const auto& bob_comment = db->get_comment( "bob", string( "foo" ) ); - const comment_cashout_object* bob_comment_cashout = db->find_comment_cashout( bob_comment ); - - old_net_rshares = bob_comment_cashout->net_rshares.value; - old_abs_rshares = bob_comment_cashout->abs_rshares.value; - } - - op.weight = -1 * HIVE_100_PERCENT; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - alice_bob_vote = vote_idx.find( boost::make_tuple( new_bob_comment.get_id(), new_alice.get_id() ) ); - - { - const auto& bob_comment = db->get_comment( "bob", string( "foo" ) ); - const comment_cashout_object* bob_comment_cashout = db->find_comment_cashout( bob_comment ); - const auto& alice = db->get_account( "alice" ); - BOOST_REQUIRE( bob_comment_cashout->net_rshares == old_net_rshares - alice_weight + HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( bob_comment_cashout->abs_rshares == old_abs_rshares + alice_weight - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( alice_bob_vote->rshares == -1 * ( alice_weight - HIVE_VOTE_DUST_THRESHOLD ) ); - BOOST_REQUIRE( alice_bob_vote->last_update == db->head_block_time() ); - BOOST_REQUIRE( alice_bob_vote->vote_percent == op.weight ); - BOOST_REQUIRE( alice.downvote_manabar.current_mana == 0 ); - BOOST_REQUIRE( alice.voting_manabar.current_mana == old_manabar.current_mana - alice_weight + old_downvote_manabar.current_mana ); - validate_database(); - } - - BOOST_TEST_MESSAGE( "--- Test reduced effectiveness when increasing rshares within lockout period" ); - - generate_blocks( fc::time_point_sec( ( new_bob_comment_cashout->cashout_time - HIVE_UPVOTE_LOCKOUT_HF17 ).sec_since_epoch() + HIVE_BLOCK_INTERVAL ), true ); - - old_manabar = VOTING_MANABAR( "dave" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "dave" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - op.voter = "dave"; - op.weight = HIVE_100_PERCENT; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - new_rshares = old_manabar.current_mana - VOTING_MANABAR( "dave" ).current_mana - HIVE_VOTE_DUST_THRESHOLD; - new_rshares = ( new_rshares * ( HIVE_UPVOTE_LOCKOUT_SECONDS - HIVE_BLOCK_INTERVAL ) ) / HIVE_UPVOTE_LOCKOUT_SECONDS; - account_id_type dave_id = get_account_id( "dave" ); - comment_id_type bob_comment_id = db->get_comment( "bob", string( "foo" ) ).get_id(); - - { - auto& dave_bob_vote = db->get< comment_vote_object, by_comment_voter >( boost::make_tuple( bob_comment_id, dave_id ) ); - BOOST_REQUIRE_EQUAL( dave_bob_vote.rshares, new_rshares ); - } - validate_database(); - - /* - the following part of test never worked since its inception due to bugs (assignment used instead of comparison); - since then the mechanism changed a lot (downvote has its own mana pool f.e. but replacing code below with its use didn't fix the test) - and it doesn't look reasonable to just copy the equations from hf20_vote_evaluator - - BOOST_TEST_MESSAGE( "--- Test reduced effectiveness when reducing rshares within lockout period" ); - - generate_block(); - old_manabar = VOTING_MANABAR( "dave" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "dave" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - op.weight = -1 * HIVE_100_PERCENT; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - new_rshares = old_manabar.current_mana - VOTING_MANABAR( "dave" ).current_mana - HIVE_VOTE_DUST_THRESHOLD; - new_rshares = ( new_rshares * ( HIVE_UPVOTE_LOCKOUT_SECONDS - HIVE_BLOCK_INTERVAL - HIVE_BLOCK_INTERVAL ) ) / HIVE_UPVOTE_LOCKOUT_SECONDS; - - { - auto& dave_bob_vote = db->get< comment_vote_object, by_comment_voter >( boost::make_tuple( bob_comment_id, dave_id ) ); - BOOST_REQUIRE_EQUAL( dave_bob_vote.rshares, new_rshares ); - } - validate_database(); - */ - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_validate" ); - - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.memo = "Memo"; - op.amount = asset( 100, HIVE_SYMBOL ); - op.validate(); - - BOOST_TEST_MESSAGE( " --- Invalid from account" ); - op.from = "alice-"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.from = "alice"; - - BOOST_TEST_MESSAGE( " --- Invalid to account" ); - op.to = "bob-"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.to = "bob"; - - BOOST_TEST_MESSAGE( " --- Memo too long" ); - std::string memo; - for ( int i = 0; i < HIVE_MAX_MEMO_SIZE + 1; i++ ) - memo += "x"; - op.memo = memo; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.memo = "Memo"; - - BOOST_TEST_MESSAGE( " --- Negative amount" ); - op.amount = -op.amount; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = -op.amount; - - BOOST_TEST_MESSAGE( " --- Transferring vests" ); - op.amount = asset( 100, VESTS_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = asset( 100, HIVE_SYMBOL ); - - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_authorities ) -{ - try - { - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - BOOST_TEST_MESSAGE( "Testing: transfer_authorities" ); - - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = ASSET( "2.500 TESTS" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with witness signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( signature_stripping ) -{ - try - { - // Alice, Bob and Sam all have 2-of-3 multisig on corp. - // Legitimate tx signed by (Alice, Bob) goes through. - // Sam shouldn't be able to add or remove signatures to get the transaction to process multiple times. - - ACTORS( (alice)(bob)(sam)(corp) ) - fund( "corp", 10000 ); - - account_update_operation update_op; - update_op.account = "corp"; - update_op.active = authority( 2, "alice", 1, "bob", 1, "sam", 1 ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( update_op ); - - sign( tx, corp_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - transfer_operation transfer_op; - transfer_op.from = "corp"; - transfer_op.to = "sam"; - transfer_op.amount = ASSET( "1.000 TESTS" ); - - tx.operations.push_back( transfer_op ); - - sign( tx, alice_private_key ); - signature_type alice_sig = tx.signatures.back(); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - sign( tx, bob_private_key ); - signature_type bob_sig = tx.signatures.back(); - sign( tx, sam_private_key ); - signature_type sam_sig = tx.signatures.back(); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - tx.signatures.clear(); - tx.signatures.push_back( alice_sig ); - tx.signatures.push_back( bob_sig ); - db->push_transaction( tx, 0 ); - - tx.signatures.clear(); - tx.signatures.push_back( alice_sig ); - tx.signatures.push_back( sam_sig ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_apply" ); - - ACTORS( (alice)(bob) ) - generate_block(); - fund( "alice", 10000 ); - fund( "bob", ASSET( "1.000 TBD" ) ); - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == ASSET( "10.000 TESTS" ).amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == ASSET(" 0.000 TESTS" ).amount.value ); - - signed_transaction tx; - transfer_operation op; - - op.from = "alice"; - op.to = "bob"; - op.amount = ASSET( "5.000 TESTS" ); - - BOOST_TEST_MESSAGE( "--- Test normal transaction" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == ASSET( "5.000 TESTS" ).amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == ASSET( "5.000 TESTS" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Generating a block" ); - generate_block(); - - const auto& new_alice = db->get_account( "alice" ); - const auto& new_bob = db->get_account( "bob" ); - - BOOST_REQUIRE( new_alice.get_balance().amount.value == ASSET( "5.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "5.000 TESTS" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test emptying an account" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_REQUIRE( new_alice.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test transferring non-existent funds" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( new_alice.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure transfering HIVE to treasury" ); - op.from = "bob"; - op.to = db->get_treasury_name(); - op.amount = ASSET( "1.000 TESTS" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::exception ); - - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( db->get_treasury().get_balance() == ASSET( "0.000 TESTS" ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test transfering HBD to treasury" ); - auto treasury_hbd_balance = db->get_treasury().get_hbd_balance(); - op.amount = ASSET( "1.000 TBD" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx ); - - BOOST_REQUIRE( get_hbd_balance( "bob" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( db->get_treasury().get_hbd_balance() == treasury_hbd_balance + ASSET( "1.000 TBD" ) ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_vesting_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_vesting_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_vesting_authorities ) -{ - try - { - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - BOOST_TEST_MESSAGE( "Testing: transfer_to_vesting_authorities" ); - - transfer_to_vesting_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = ASSET( "2.500 TESTS" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with from signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_vesting_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_vesting_apply" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - const auto& gpo = db->get_dynamic_global_properties(); - - BOOST_REQUIRE( alice.get_balance() == ASSET( "10.000 TESTS" ) ); - - auto shares = asset( gpo.get_total_vesting_shares().amount, VESTS_SYMBOL ); - auto vests = asset( gpo.get_total_vesting_fund_hive().amount, HIVE_SYMBOL ); - auto alice_shares = alice.get_vesting(); - auto bob_shares = bob.get_vesting(); - - transfer_to_vesting_operation op; - op.from = "alice"; - op.to = db->get_treasury_name(); - op.amount = ASSET( "7.500 TESTS" ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - op.to = ""; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto new_vest = op.amount * ( shares / vests ); - shares += new_vest; - vests += op.amount; - alice_shares += new_vest; - - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "2.500 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_vesting().amount.value == alice_shares.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == vests.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == shares.amount.value ); - validate_database(); - - op.to = "bob"; - op.amount = asset( 2000, HIVE_SYMBOL ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - new_vest = asset( ( op.amount * ( shares / vests ) ).amount, VESTS_SYMBOL ); - shares += new_vest; - vests += op.amount; - bob_shares += new_vest; - - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "0.500 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_vesting().amount.value == alice_shares.amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_vesting().amount.value == bob_shares.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == vests.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == shares.amount.value ); - validate_database(); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "0.500 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_vesting().amount.value == alice_shares.amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_vesting().amount.value == bob_shares.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == vests.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == shares.amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( withdraw_vesting_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: withdraw_vesting_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( withdraw_vesting_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: withdraw_vesting_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - vest( "alice", 10000 ); - - withdraw_vesting_operation op; - op.account = "alice"; - op.vesting_shares = ASSET( "0.001000 VESTS" ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( withdraw_vesting_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: withdraw_vesting_apply" ); - - ACTORS( (alice)(bob) ) - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - - BOOST_TEST_MESSAGE( "--- Test failure withdrawing negative VESTS" ); - - { - const auto& alice = db->get_account( "alice" ); - - withdraw_vesting_operation op; - op.account = "alice"; - op.vesting_shares = asset( -1, VESTS_SYMBOL ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test withdraw of existing VESTS" ); - op.vesting_shares = asset( alice.get_vesting().amount / 2, VESTS_SYMBOL ); - - auto old_vesting_shares = alice.get_vesting(); - - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice.get_vesting().amount.value == old_vesting_shares.amount.value ); - BOOST_REQUIRE( alice.vesting_withdraw_rate.amount.value == ( old_vesting_shares.amount / ( HIVE_VESTING_WITHDRAW_INTERVALS * 2 ) ).value + 1 ); - BOOST_REQUIRE( alice.to_withdraw.value == op.vesting_shares.amount.value ); - BOOST_REQUIRE( alice.next_vesting_withdrawal == db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test changing vesting withdrawal" ); - tx.operations.clear(); - tx.signatures.clear(); - - op.vesting_shares = asset( alice.get_vesting().amount / 3, VESTS_SYMBOL ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice.get_vesting().amount.value == old_vesting_shares.amount.value ); - BOOST_REQUIRE( alice.vesting_withdraw_rate.amount.value == ( old_vesting_shares.amount / ( HIVE_VESTING_WITHDRAW_INTERVALS * 3 ) ).value + 1 ); - BOOST_REQUIRE( alice.to_withdraw.value == op.vesting_shares.amount.value ); - BOOST_REQUIRE( alice.next_vesting_withdrawal == db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test withdrawing more vests than available" ); - //auto old_withdraw_amount = alice.to_withdraw; - tx.operations.clear(); - tx.signatures.clear(); - - op.vesting_shares = asset( alice.get_vesting().amount * 2, VESTS_SYMBOL ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( alice.get_vesting().amount.value == old_vesting_shares.amount.value ); - BOOST_REQUIRE( alice.vesting_withdraw_rate.amount.value == ( old_vesting_shares.amount / ( HIVE_VESTING_WITHDRAW_INTERVALS * 3 ) ).value + 1 ); - BOOST_REQUIRE( alice.next_vesting_withdrawal == db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test withdrawing 0 to reset vesting withdraw" ); - tx.operations.clear(); - tx.signatures.clear(); - - op.vesting_shares = asset( 0, VESTS_SYMBOL ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice.get_vesting().amount.value == old_vesting_shares.amount.value ); - BOOST_REQUIRE( alice.vesting_withdraw_rate.amount.value == 0 ); - BOOST_REQUIRE( alice.to_withdraw.value == 0 ); - BOOST_REQUIRE( alice.next_vesting_withdrawal == fc::time_point_sec::maximum() ); - - - BOOST_TEST_MESSAGE( "--- Test cancelling a withdraw when below the account creation fee" ); - op.vesting_shares = alice.get_vesting(); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_block(); - } - - db_plugin->debug_update( [=]( database& db ) - { - auto& wso = db.get_witness_schedule_object(); - - db.modify( wso, [&]( witness_schedule_object& w ) - { - w.median_props.account_creation_fee = ASSET( "10.000 TESTS" ); - }); - - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.current_supply += wso.median_props.account_creation_fee - ASSET( "0.001 TESTS" ) - gpo.get_total_vesting_fund_hive(); - gpo.total_vesting_fund_hive = wso.median_props.account_creation_fee - ASSET( "0.001 TESTS" ); - }); - - db.update_virtual_supply(); - }, database::skip_witness_signature ); - - withdraw_vesting_operation op; - signed_transaction tx; - op.account = "alice"; - op.vesting_shares = ASSET( "0.000000 VESTS" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_account( "alice" ).vesting_withdraw_rate == ASSET( "0.000000 VESTS" ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test withdrawing minimal VESTS" ); - op.account = "bob"; - op.vesting_shares = get_vesting( "bob" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); // We do not need to test the result of this, simply that it works. - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_update_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: withness_update_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_update_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: witness_update_authorities" ); - - ACTORS( (alice)(bob) ); - fund( "alice", 10000 ); - - private_key_type signing_key = generate_private_key( "new_key" ); - - witness_update_operation op; - op.owner = "alice"; - op.url = "foo.bar"; - op.fee = ASSET( "1.000 TESTS" ); - op.block_signing_key = signing_key.get_public_key(); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with witness signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.signatures.clear(); - sign( tx, signing_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_update_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: witness_update_apply" ); - - ACTORS( (alice) ) - fund( "alice", 10000 ); - - private_key_type signing_key = generate_private_key( "new_key" ); - - BOOST_TEST_MESSAGE( "--- Test upgrading an account to a witness" ); - - witness_update_operation op; - op.owner = "alice"; - op.url = "foo.bar"; - op.fee = ASSET( "1.000 TESTS" ); - op.block_signing_key = signing_key.get_public_key(); - op.props.account_creation_fee = legacy_hive_asset::from_asset( asset(HIVE_MIN_ACCOUNT_CREATION_FEE + 10, HIVE_SYMBOL) ); - op.props.maximum_block_size = HIVE_MIN_BLOCK_SIZE_LIMIT + 100; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - const witness_object& alice_witness = db->get_witness( "alice" ); - - BOOST_REQUIRE( alice_witness.owner == "alice" ); - BOOST_REQUIRE( alice_witness.created == db->head_block_time() ); - BOOST_REQUIRE( to_string( alice_witness.url ) == op.url ); - BOOST_REQUIRE( alice_witness.signing_key == op.block_signing_key ); - BOOST_REQUIRE( alice_witness.props.account_creation_fee == op.props.account_creation_fee.to_asset<true>() ); - BOOST_REQUIRE( alice_witness.props.maximum_block_size == op.props.maximum_block_size ); - BOOST_REQUIRE( alice_witness.total_missed == 0 ); - BOOST_REQUIRE( alice_witness.last_aslot == 0 ); - BOOST_REQUIRE( alice_witness.last_confirmed_block_num == 0 ); - BOOST_REQUIRE( alice_witness.pow_worker == 0 ); - BOOST_REQUIRE( alice_witness.votes.value == 0 ); - BOOST_REQUIRE( alice_witness.virtual_last_update == 0 ); - BOOST_REQUIRE( alice_witness.virtual_position == 0 ); - BOOST_REQUIRE( alice_witness.virtual_scheduled_time == fc::uint128_t::max_value() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); // No fee - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test updating a witness" ); - - tx.signatures.clear(); - tx.operations.clear(); - op.url = "bar.foo"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice_witness.owner == "alice" ); - BOOST_REQUIRE( alice_witness.created == db->head_block_time() ); - BOOST_REQUIRE( to_string( alice_witness.url ) == "bar.foo" ); - BOOST_REQUIRE( alice_witness.signing_key == op.block_signing_key ); - BOOST_REQUIRE( alice_witness.props.account_creation_fee == op.props.account_creation_fee.to_asset<true>() ); - BOOST_REQUIRE( alice_witness.props.maximum_block_size == op.props.maximum_block_size ); - BOOST_REQUIRE( alice_witness.total_missed == 0 ); - BOOST_REQUIRE( alice_witness.last_aslot == 0 ); - BOOST_REQUIRE( alice_witness.last_confirmed_block_num == 0 ); - BOOST_REQUIRE( alice_witness.pow_worker == 0 ); - BOOST_REQUIRE( alice_witness.votes.value == 0 ); - BOOST_REQUIRE( alice_witness.virtual_last_update == 0 ); - BOOST_REQUIRE( alice_witness.virtual_position == 0 ); - BOOST_REQUIRE( alice_witness.virtual_scheduled_time == fc::uint128_t::max_value() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when upgrading a non-existent account" ); - - tx.signatures.clear(); - tx.operations.clear(); - op.owner = "bob"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_vote_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_vote_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_vote_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_vote_authorities" ); - - ACTORS( (alice)(bob)(sam) ) - - fund( "alice", 1000 ); - private_key_type alice_witness_key = generate_private_key( "alice_witness" ); - witness_create( "alice", alice_private_key, "foo.bar", alice_witness_key.get_public_key(), 1000 ); - - account_witness_vote_operation op; - op.account = "bob"; - op.witness = "alice"; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, bob_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with witness signature" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failure with proxy signature" ); - proxy( "bob", "sam" ); - tx.signatures.clear(); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_vote_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_vote_apply" ); - - ACTORS( (alice)(bob)(sam) ) - fund( "alice" , 5000 ); - vest( "alice", 5000 ); - fund( "sam", 1000 ); - - private_key_type sam_witness_key = generate_private_key( "sam_key" ); - witness_create( "sam", sam_private_key, "foo.bar", sam_witness_key.get_public_key(), 1000 ); - const witness_object& sam_witness = db->get_witness( "sam" ); - - const auto& witness_vote_idx = db->get_index< witness_vote_index >().indices().get< by_witness_account >(); - - BOOST_TEST_MESSAGE( "--- Test normal vote" ); - account_witness_vote_operation op; - op.account = "alice"; - op.witness = "sam"; - op.approve = true; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( sam_witness.votes == alice.get_real_vesting_shares() ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) != witness_vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test revoke vote" ); - op.approve = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( sam_witness.votes.value == 0 ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) == witness_vote_idx.end() ); - - BOOST_TEST_MESSAGE( "--- Test failure when attempting to revoke a non-existent vote" ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - BOOST_REQUIRE( sam_witness.votes.value == 0 ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) == witness_vote_idx.end() ); - - BOOST_TEST_MESSAGE( "--- Test proxied vote" ); - proxy( "alice", "bob" ); - tx.operations.clear(); - tx.signatures.clear(); - op.approve = true; - op.account = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( sam_witness.votes == ( bob.proxied_vsf_votes_total() + bob.get_real_vesting_shares() ) ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, bob.name ) ) != witness_vote_idx.end() ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) == witness_vote_idx.end() ); - - BOOST_TEST_MESSAGE( "--- Test vote from a proxied account" ); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "alice"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( sam_witness.votes == ( bob.proxied_vsf_votes_total() + bob.get_real_vesting_shares() ) ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, bob.name ) ) != witness_vote_idx.end() ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) == witness_vote_idx.end() ); - - BOOST_TEST_MESSAGE( "--- Test revoke proxied vote" ); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "bob"; - op.approve = false; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( sam_witness.votes.value == 0 ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, bob.name ) ) == witness_vote_idx.end() ); - BOOST_REQUIRE( witness_vote_idx.find( boost::make_tuple( sam_witness.owner, alice.name ) ) == witness_vote_idx.end() ); - - BOOST_TEST_MESSAGE( "--- Test failure when voting for a non-existent account" ); - tx.operations.clear(); - tx.signatures.clear(); - op.witness = "dave"; - op.approve = true; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when voting for an account that is not a witness" ); - tx.operations.clear(); - tx.signatures.clear(); - op.witness = "alice"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE(account_witness_vote_apply_delay) -{ - //copy of account_witness_vote_apply with extra checks to account for delayed voting effect - //note that call to generate_block() invalidates everything that was done by push_transaction, - //in particular local variables like `alice` and `sam_witness` that point to objects created - //by push_transaction (and thus present inside pending block state) become invalid; - //generate_block call first calls `undo` on pending block, then reapplies all transactions, - //so all the objects are present in chain, but have to be acquired again from final state - try - { - BOOST_TEST_MESSAGE("Testing: account_witness_vote_apply_delay"); - - ACTORS((alice)(bob)(sam)) - fund("alice", 5000); - vest("alice", 5000); - //vests are going to vote after HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS - //note that account creation also vests a bit for new account - fund("sam", 1000); - - private_key_type sam_witness_key = generate_private_key("sam_key"); - witness_create("sam", sam_private_key, "foo.bar", sam_witness_key.get_public_key(), 1000); - - generate_block(); - //above variables: alice/bob/sam are invalid past that point - //they need to be reacquired from chain - const account_object& _alice = db->get_account("alice"); - const account_object& _bob = db->get_account("bob"); - //const account_object& _sam = db->get_account("sam"); - const witness_object& _sam_witness = db->get_witness("sam"); - const auto& witness_vote_idx = db->get_index< witness_vote_index >().indices().get< by_witness_account >(); - - BOOST_TEST_MESSAGE("--- Test normal vote"); - account_witness_vote_operation op; - op.account = "alice"; - op.witness = "sam"; - op.approve = true; - - signed_transaction tx; - tx.set_expiration(db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION); - tx.operations.push_back(op); - sign(tx, alice_private_key); - - db->push_transaction(tx, 0); - - BOOST_REQUIRE(_sam_witness.votes == 0); - BOOST_REQUIRE(_alice.get_vesting().amount == _alice.sum_delayed_votes.value); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) != witness_vote_idx.end()); - validate_database(); - generate_blocks(db->head_block_time() + fc::seconds(HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS)); - BOOST_REQUIRE(_sam_witness.votes == _alice.get_vesting().amount); - BOOST_REQUIRE(_alice.sum_delayed_votes == 0); - validate_database(); - - BOOST_TEST_MESSAGE("--- Test revoke vote"); - tx.set_expiration(db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION); - op.approve = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back(op); - sign(tx, alice_private_key); - - db->push_transaction(tx, 0); - BOOST_REQUIRE(_sam_witness.votes.value == 0); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) == witness_vote_idx.end()); - - BOOST_TEST_MESSAGE("--- Test failure when attempting to revoke a non-existent vote"); - - HIVE_REQUIRE_THROW(db->push_transaction(tx, database::skip_transaction_dupe_check), fc::exception); - BOOST_REQUIRE(_sam_witness.votes.value == 0); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) == witness_vote_idx.end()); - - BOOST_TEST_MESSAGE("--- Test proxied vote"); - proxy("alice", "bob"); - tx.operations.clear(); - tx.signatures.clear(); - op.approve = true; - op.account = "bob"; - tx.operations.push_back(op); - sign(tx, bob_private_key); - - db->push_transaction(tx, 0); - - //since all vests are already mature voting has immediate effect - BOOST_REQUIRE(_alice.get_vesting().amount == _bob.proxied_vsf_votes_total()); - BOOST_REQUIRE(_sam_witness.votes == (_alice.get_vesting().amount + _bob.get_vesting().amount)); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _bob.name)) != witness_vote_idx.end()); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) == witness_vote_idx.end()); - validate_database(); - - BOOST_TEST_MESSAGE("--- Test vote from a proxied account"); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "alice"; - tx.operations.push_back(op); - sign(tx, alice_private_key); - HIVE_REQUIRE_THROW(db->push_transaction(tx, database::skip_transaction_dupe_check), fc::exception); - - BOOST_REQUIRE(_alice.get_vesting().amount == _bob.proxied_vsf_votes_total()); - BOOST_REQUIRE(_sam_witness.votes == (_alice.get_vesting().amount + _bob.get_vesting().amount)); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _bob.name)) != witness_vote_idx.end()); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) == witness_vote_idx.end()); - - BOOST_TEST_MESSAGE("--- Test revoke proxied vote"); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "bob"; - op.approve = false; - tx.operations.push_back(op); - sign(tx, bob_private_key); - - db->push_transaction(tx, 0); - - BOOST_REQUIRE(_sam_witness.votes.value == 0); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _bob.name)) == witness_vote_idx.end()); - BOOST_REQUIRE(witness_vote_idx.find(boost::make_tuple(_sam_witness.owner, _alice.name)) == witness_vote_idx.end()); - - BOOST_TEST_MESSAGE("--- Test failure when voting for a non-existent account"); - tx.operations.clear(); - tx.signatures.clear(); - op.witness = "dave"; - op.approve = true; - tx.operations.push_back(op); - sign(tx, bob_private_key); - - HIVE_REQUIRE_THROW(db->push_transaction(tx, 0), fc::exception); - validate_database(); - - BOOST_TEST_MESSAGE("--- Test failure when voting for an account that is not a witness"); - tx.operations.clear(); - tx.signatures.clear(); - op.witness = "alice"; - tx.operations.push_back(op); - sign(tx, bob_private_key); - - HIVE_REQUIRE_THROW(db->push_transaction(tx, 0), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_proxy_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_proxy_validate" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_proxy_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_proxy_authorities" ); - - ACTORS( (alice)(bob) ) - - account_witness_proxy_operation op; - op.account = "bob"; - op.proxy = "alice"; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, bob_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with witness signature" ); - tx.signatures.clear(); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failure with proxy signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_proxy_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_proxy_apply" ); - - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 1000 ); - vest( "alice", 1000 ); - fund( "bob", 3000 ); - vest( "bob", 3000 ); - fund( "sam", 5000 ); - vest( "sam", 5000 ); - fund( "dave", 7000 ); - vest( "dave", 7000 ); - - BOOST_TEST_MESSAGE( "--- Test setting proxy to another account from self." ); - // bob -> alice - - account_witness_proxy_operation op; - op.account = "bob"; - op.proxy = "alice"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( bob.proxy == "alice" ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( alice.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( alice.proxied_vsf_votes_total() == bob.get_real_vesting_shares() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test changing proxy" ); - // bob->sam - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "sam"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( bob.proxy == "sam" ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( sam.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( sam.proxied_vsf_votes_total().value == bob.get_real_vesting_shares() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when changing proxy to existing proxy" ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( bob.proxy == "sam" ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( sam.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( sam.proxied_vsf_votes_total() == bob.get_real_vesting_shares() ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test adding a grandparent proxy" ); - // bob->sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "dave"; - op.account = "sam"; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( bob.proxy == "sam" ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( sam.proxy == "dave" ); - BOOST_REQUIRE( sam.proxied_vsf_votes_total() == bob.get_real_vesting_shares() ); - BOOST_REQUIRE( dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( dave.proxied_vsf_votes_total() == ( sam.get_real_vesting_shares() + bob.get_real_vesting_shares() ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test adding a grandchild proxy" ); - // alice - // | - // bob-> sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "sam"; - op.account = "alice"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice.proxy == "sam" ); - BOOST_REQUIRE( alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( bob.proxy == "sam" ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( sam.proxy == "dave" ); - BOOST_REQUIRE( sam.proxied_vsf_votes_total() == ( bob.get_real_vesting_shares() + alice.get_real_vesting_shares() ) ); - BOOST_REQUIRE( dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( dave.proxied_vsf_votes_total() == ( sam.get_real_vesting_shares() + bob.get_real_vesting_shares() + alice.get_real_vesting_shares() ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test removing a grandchild proxy" ); - // alice->sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = HIVE_PROXY_TO_SELF_ACCOUNT; - op.account = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( alice.proxy == "sam" ); - BOOST_REQUIRE( alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( bob.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( sam.proxy == "dave" ); - BOOST_REQUIRE( sam.proxied_vsf_votes_total() == alice.get_real_vesting_shares() ); - BOOST_REQUIRE( dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( dave.proxied_vsf_votes_total() == ( sam.get_real_vesting_shares() + alice.get_real_vesting_shares() ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test votes are transferred when a proxy is added" ); - account_witness_vote_operation vote; - vote.account= "bob"; - vote.witness = HIVE_INIT_MINER_NAME; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.account = "alice"; - op.proxy = "bob"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_witness( HIVE_INIT_MINER_NAME ).votes == ( alice.get_real_vesting_shares() + bob.get_real_vesting_shares() ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test votes are removed when a proxy is removed" ); - op.proxy = HIVE_PROXY_TO_SELF_ACCOUNT; - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_witness( HIVE_INIT_MINER_NAME ).votes == bob.get_real_vesting_shares() ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_witness_proxy_apply_delay ) -{ - //copy of account_witness_proxy_apply with extra checks to account for delayed voting effect - //see comment in account_witness_vote_apply_delay - try - { - BOOST_TEST_MESSAGE( "Testing: account_witness_proxy_apply_delay" ); - - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 1000 ); - vest( "alice", 1000 ); - //vests are going to vote after HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS - //note that account creation also vests a bit for new account - fund( "bob", 3000 ); - vest( "bob", 3000 ); - fund( "sam", 5000 ); - vest( "sam", 5000 ); - fund( "dave", 7000 ); - vest( "dave", 7000 ); - - generate_block(); - //above variables: alice etc. are invalid past that point - //they need to be reacquired from chain - const account_object& _alice = db->get_account("alice"); - const account_object& _bob = db->get_account("bob"); - const account_object& _sam = db->get_account("sam"); - const account_object& _dave = db->get_account("dave"); - - BOOST_TEST_MESSAGE( "--- Test setting proxy to another account from self." ); - // bob -> alice - - account_witness_proxy_operation op; - op.account = "bob"; - op.proxy = "alice"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( _bob.proxy == "alice" ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _alice.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _alice.proxied_vsf_votes_total().value == 0 ); - validate_database(); - generate_blocks(db->head_block_time() + fc::seconds(HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS)); - BOOST_REQUIRE(_alice.proxied_vsf_votes_total() == _bob.get_vesting().amount); - - BOOST_TEST_MESSAGE( "--- Test changing proxy" ); - // bob->sam - - tx.set_expiration(db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION); - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "sam"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( _bob.proxy == "sam" ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _sam.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - //all vests are now mature so changes in voting power are immediate - BOOST_REQUIRE( _sam.proxied_vsf_votes_total().value == _bob.get_vesting().amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when changing proxy to existing proxy" ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( _bob.proxy == "sam" ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _sam.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _sam.proxied_vsf_votes_total() == _bob.get_vesting().amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test adding a grandparent proxy" ); - // bob->sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "dave"; - op.account = "sam"; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( _bob.proxy == "sam" ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _sam.proxy == "dave" ); - BOOST_REQUIRE( _sam.proxied_vsf_votes_total() == _bob.get_vesting().amount ); - BOOST_REQUIRE( _dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _dave.proxied_vsf_votes_total() == ( _sam.get_vesting() + _bob.get_vesting() ).amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test adding a grandchild proxy" ); - // alice - // | - // bob-> sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = "sam"; - op.account = "alice"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( _alice.proxy == "sam" ); - BOOST_REQUIRE( _alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _bob.proxy == "sam" ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _sam.proxy == "dave" ); - BOOST_REQUIRE( _sam.proxied_vsf_votes_total() == ( _bob.get_vesting() + _alice.get_vesting() ).amount ); - BOOST_REQUIRE( _dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _dave.proxied_vsf_votes_total() == ( _sam.get_vesting() + _bob.get_vesting() + _alice.get_vesting() ).amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test removing a grandchild proxy" ); - // alice->sam->dave - - tx.operations.clear(); - tx.signatures.clear(); - op.proxy = HIVE_PROXY_TO_SELF_ACCOUNT; - op.account = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( _alice.proxy == "sam" ); - BOOST_REQUIRE( _alice.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _bob.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _bob.proxied_vsf_votes_total().value == 0 ); - BOOST_REQUIRE( _sam.proxy == "dave" ); - BOOST_REQUIRE( _sam.proxied_vsf_votes_total() == _alice.get_vesting().amount ); - BOOST_REQUIRE( _dave.proxy == HIVE_PROXY_TO_SELF_ACCOUNT ); - BOOST_REQUIRE( _dave.proxied_vsf_votes_total() == ( _sam.get_vesting() + _alice.get_vesting() ).amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test votes are transferred when a proxy is added" ); - account_witness_vote_operation vote; - vote.account= "bob"; - vote.witness = HIVE_INIT_MINER_NAME; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.account = "alice"; - op.proxy = "bob"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_witness( HIVE_INIT_MINER_NAME ).votes == ( _alice.get_vesting() + _bob.get_vesting() ).amount ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test votes are removed when a proxy is removed" ); - op.proxy = HIVE_PROXY_TO_SELF_ACCOUNT; - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_witness( HIVE_INIT_MINER_NAME ).votes == _bob.get_vesting().amount ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( custom_authorities ) -{ - custom_operation op; - op.required_auths.insert( "alice" ); - op.required_auths.insert( "bob" ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - expected.insert( "bob" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); -} - -BOOST_AUTO_TEST_CASE( custom_json_authorities ) -{ - custom_json_operation op; - op.required_auths.insert( "alice" ); - op.required_posting_auths.insert( "bob" ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - auths.clear(); - expected.clear(); - expected.insert( "bob" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); -} - -BOOST_AUTO_TEST_CASE( custom_json_rate_limit ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: custom_json_rate_limit" ); - - ACTORS( (alice)(bob)(sam) ) - - BOOST_TEST_MESSAGE( "--- Testing 5 custom json ops as separate transactions" ); - - custom_json_operation op; - signed_transaction tx; - op.required_posting_auths.insert( "alice" ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - for( int i = 0; i < 5; i++ ) - { - op.json = fc::to_string( i ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - } - - - BOOST_TEST_MESSAGE( "--- Testing failure pushing 6th custom json op tx" ); - - op.json = "toomany"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), plugin_exception ); - - - BOOST_TEST_MESSAGE( "--- Testing 5 custom json ops in one transaction" ); - tx.clear(); - op.json = "foobar"; - op.required_posting_auths.clear(); - op.required_posting_auths.insert( "bob" ); - - for( int i = 0; i < 5; i++ ) - { - tx.operations.push_back( op ); - } - - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "--- Testing failure pushing 6th custom json op tx" ); - - op.json = "toomany"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), plugin_exception ); - - - BOOST_TEST_MESSAGE( "--- Testing failure of 6 custom json ops in one transaction" ); - tx.clear(); - op.required_posting_auths.clear(); - op.required_posting_auths.insert( "sam" ); - - for( int i = 0; i < 6; i++ ) - { - tx.operations.push_back( op ); - } - - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), plugin_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( custom_binary_authorities ) -{ - ACTORS( (alice) ) - - custom_binary_operation op; - op.required_owner_auths.insert( "alice" ); - op.required_active_auths.insert( "bob" ); - op.required_posting_auths.insert( "sam" ); - op.required_auths.push_back( db->get< account_authority_object, by_account >( "alice" ).posting ); - - flat_set< account_name_type > acc_auths; - flat_set< account_name_type > acc_expected; - vector< authority > auths; - vector< authority > expected; - - acc_expected.insert( "alice" ); - op.get_required_owner_authorities( acc_auths ); - BOOST_REQUIRE( acc_auths == acc_expected ); - - acc_auths.clear(); - acc_expected.clear(); - acc_expected.insert( "bob" ); - op.get_required_active_authorities( acc_auths ); - BOOST_REQUIRE( acc_auths == acc_expected ); - - acc_auths.clear(); - acc_expected.clear(); - acc_expected.insert( "sam" ); - op.get_required_posting_authorities( acc_auths ); - BOOST_REQUIRE( acc_auths == acc_expected ); - - expected.push_back( db->get< account_authority_object, by_account >( "alice" ).posting ); - op.get_required_authorities( auths ); - BOOST_REQUIRE( auths == expected ); -} - -BOOST_AUTO_TEST_CASE( feed_publish_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: feed_publish_validate" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( feed_publish_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: feed_publish_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - witness_create( "alice", alice_private_key, "foo.bar", alice_private_key.get_public_key(), 1000 ); - - feed_publish_operation op; - op.publisher = "alice"; - op.exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with witness account signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( feed_publish_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: feed_publish_apply" ); - - ACTORS( (alice) ) - fund( "alice", 10000 ); - witness_create( "alice", alice_private_key, "foo.bar", alice_private_key.get_public_key(), 1000 ); - - BOOST_TEST_MESSAGE( "--- Test publishing price feed" ); - feed_publish_operation op; - op.publisher = "alice"; - op.exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "1000.000 TESTS" ) ); // 1000 HIVE : 1 HBD - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - { - auto& alice_witness = db->get_witness( "alice" ); - - BOOST_REQUIRE( alice_witness.get_hbd_exchange_rate() == op.exchange_rate ); - BOOST_REQUIRE( alice_witness.get_last_hbd_exchange_update() == db->head_block_time() ); - validate_database(); - } - - BOOST_TEST_MESSAGE( "--- Test failure publishing to non-existent witness" ); - - tx.operations.clear(); - tx.signatures.clear(); - op.publisher = "bob"; - sign( tx, alice_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure publishing with HBD base symbol" ); - - tx.operations.clear(); - tx.signatures.clear(); - op.exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ); - sign( tx, alice_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test updating price feed" ); - - tx.operations.clear(); - tx.signatures.clear(); - op.exchange_rate = price( ASSET(" 1.000 TBD" ), ASSET( "1500.000 TESTS" ) ); - op.publisher = "alice"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - - auto& alice_witness = db->get_witness( "alice" ); - // BOOST_REQUIRE( std::abs( alice_witness.get_hbd_exchange_rate().to_real() - op.exchange_rate.to_real() ) < 0.0000005 ); - BOOST_REQUIRE( alice_witness.get_last_hbd_exchange_update() == db->head_block_time() ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( convert_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: convert_validate" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( convert_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: convert_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - convert( "alice", ASSET( "2.500 TESTS" ) ); - - validate_database(); - - convert_operation op; - op.owner = "alice"; - op.amount = ASSET( "2.500 TBD" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the account's authority" ); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test success with owner signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( convert_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: convert_apply" ); - ACTORS( (alice)(bob) ); - fund( "alice", 10000 ); - fund( "bob" , 10000 ); - - convert_operation op; - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - const auto& convert_request_idx = db->get_index< convert_request_index >().indices().get< by_owner >(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - convert( "alice", ASSET( "2.500 TESTS" ) ); - convert( "bob", ASSET( "7.000 TESTS" ) ); - - const auto& new_alice = db->get_account( "alice" ); - const auto& new_bob = db->get_account( "bob" ); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have the required TESTS" ); - op.owner = "bob"; - op.amount = ASSET( "5.000 TESTS" ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "3.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_hbd_balance().amount.value == ASSET( "7.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have the required TBD" ); - op.owner = "alice"; - op.amount = ASSET( "5.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( new_alice.get_balance().amount.value == ASSET( "7.500 TESTS" ).amount.value ); - BOOST_REQUIRE( new_alice.get_hbd_balance().amount.value == ASSET( "2.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not exist" ); - op.owner = "sam"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test success converting HBD to TESTS" ); - op.owner = "bob"; - op.amount = ASSET( "3.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "3.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_hbd_balance().amount.value == ASSET( "4.000 TBD" ).amount.value ); - - auto convert_request = convert_request_idx.find( boost::make_tuple( op.owner, op.requestid ) ); - BOOST_REQUIRE( convert_request != convert_request_idx.end() ); - BOOST_REQUIRE( convert_request->owner == op.owner ); - BOOST_REQUIRE( convert_request->requestid == op.requestid ); - BOOST_REQUIRE( convert_request->amount.amount.value == op.amount.amount.value ); - //BOOST_REQUIRE( convert_request->premium == 100000 ); - BOOST_REQUIRE( convert_request->conversion_date == db->head_block_time() + HIVE_CONVERSION_DELAY ); - - BOOST_TEST_MESSAGE( "--- Test failure from repeated id" ); - op.amount = ASSET( "2.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( new_bob.get_balance().amount.value == ASSET( "3.000 TESTS" ).amount.value ); - BOOST_REQUIRE( new_bob.get_hbd_balance().amount.value == ASSET( "4.000 TBD" ).amount.value ); - - convert_request = convert_request_idx.find( boost::make_tuple( op.owner, op.requestid ) ); - BOOST_REQUIRE( convert_request != convert_request_idx.end() ); - BOOST_REQUIRE( convert_request->owner == op.owner ); - BOOST_REQUIRE( convert_request->requestid == op.requestid ); - BOOST_REQUIRE( convert_request->amount.amount.value == ASSET( "3.000 TBD" ).amount.value ); - //BOOST_REQUIRE( convert_request->premium == 100000 ); - BOOST_REQUIRE( convert_request->conversion_date == db->head_block_time() + HIVE_CONVERSION_DELAY ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( fixture_convert_checks_balance ) -{ - // This actually tests the convert() method of the database fixture can't result in negative - // balances, see issue #1825 - try - { - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - ACTORS( (dany) ) - - fund( "dany", 5000 ); - HIVE_REQUIRE_THROW( convert( "dany", ASSET( "5000.000 TESTS" ) ), fc::exception ); - } - FC_LOG_AND_RETHROW() - -} - -BOOST_AUTO_TEST_CASE( limit_order_create_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create_validate" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_create_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = ASSET( "1.000 TBD" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_create_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create_apply" ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - ACTORS( (alice)(bob) ) - fund( "alice", 1000000 ); - fund( "bob", 1000000 ); - convert( "bob", ASSET("1000.000 TESTS" ) ); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have required funds" ); - limit_order_create_operation op; - signed_transaction tx; - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = ASSET( "10.000 TBD" ); - op.fill_or_kill = false; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "1000.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to receive is 0" ); - - op.owner = "alice"; - op.min_to_receive = ASSET( "0.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "1000.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to sell is 0" ); - - op.amount_to_sell = ASSET( "0.000 TESTS" ); - op.min_to_receive = ASSET( "10.000 TBD" ) ; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "1000.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when expiration is too long" ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = ASSET( "15.000 TBD" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION + 1 ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test success creating limit order that will not be filled" ); - - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == op.amount_to_sell.amount ); - BOOST_REQUIRE( limit_order->sell_price == price( op.amount_to_sell / op.min_to_receive ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure creating limit order with duplicate id" ); - - op.amount_to_sell = ASSET( "20.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 10000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "10.000 TESTS" ), op.min_to_receive ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test sucess killing an order that will not be filled" ); - - op.orderid = 2; - op.fill_or_kill = true; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test having a partial match to limit order" ); - // Alice has order for 15 HBD at a price of 2:3 - // Fill 5 HIVE for 7.5 HBD - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "7.500 TBD" ); - op.min_to_receive = ASSET( "5.000 TESTS" ); - op.fill_or_kill = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - auto recent_ops = get_last_operations( 1 ); - auto fill_order_op = recent_ops[0].get< fill_order_operation >(); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 5000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "10.000 TESTS" ), ASSET( "15.000 TBD" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "7.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "5.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "992.500 TBD" ).amount.value ); - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == ASSET( "5.000 TESTS").amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == ASSET( "7.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order fully, but the new order partially" ); - - op.amount_to_sell = ASSET( "15.000 TBD" ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 1 ); - BOOST_REQUIRE( limit_order->for_sale.value == 7500 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "15.000 TBD" ), ASSET( "10.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "15.000 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "977.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order and new order fully" ); - - op.owner = "alice"; - op.orderid = 3; - op.amount_to_sell = ASSET( "5.000 TESTS" ); - op.min_to_receive = ASSET( "7.500 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 3 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "985.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "22.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "15.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "977.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is better." ); - - op.owner = "alice"; - op.orderid = 4; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = ASSET( "11.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = ASSET( "12.000 TBD" ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 4 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "alice", 4 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 4 ); - BOOST_REQUIRE( limit_order->for_sale.value == 1000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "12.000 TBD" ), ASSET( "10.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "975.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "33.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "25.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "965.500 TBD" ).amount.value ); - validate_database(); - - limit_order_cancel_operation can; - can.owner = "bob"; - can.orderid = 4; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( can ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is worse." ); - - //auto& gpo = db->get_dynamic_global_properties(); - //auto start_hbd = gpo.get_current_hbd_supply(); - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.min_to_receive = ASSET( "22.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 5; - op.amount_to_sell = ASSET( "12.000 TBD" ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 5 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "bob", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == 5 ); - BOOST_REQUIRE( limit_order->for_sale.value == 9091 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "20.000 TESTS" ), ASSET( "22.000 TBD" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "955.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "45.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "35.909 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "954.500 TBD" ).amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_create2_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create2_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - limit_order_create2_operation op; - op.owner = "alice"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_create2_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create2_apply" ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - ACTORS( (alice)(bob) ) - fund( "alice", 1000000 ); - fund( "bob", 1000000 ); - convert( "bob", ASSET("1000.000 TESTS" ) ); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have required funds" ); - limit_order_create2_operation op; - signed_transaction tx; - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - op.fill_or_kill = false; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "1000.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when price is 0" ); - - /// First check validation on price constructor level: - { - price broken_price; - /// Invalid base value - HIVE_REQUIRE_THROW(broken_price=price(ASSET("0.000 TESTS"), ASSET("1.000 TBD")), - fc::exception); - /// Invalid quote value - HIVE_REQUIRE_THROW(broken_price=price(ASSET("1.000 TESTS"), ASSET("0.000 TBD")), - fc::exception); - /// Invalid symbol (same in base & quote) - HIVE_REQUIRE_THROW(broken_price=price(ASSET("1.000 TESTS"), ASSET("0.000 TESTS")), - fc::exception); - } - - op.owner = "alice"; - /** Here intentionally price has assigned its members directly, to skip validation - inside price constructor, and force the one performed at tx push. - */ - op.exchange_rate = price(); - op.exchange_rate.base = ASSET("0.000 TESTS"); - op.exchange_rate.quote = ASSET("1.000 TBD"); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "1000.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to sell is 0" ); - - op.amount_to_sell = ASSET( "0.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "1000.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when expiration is too long" ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "2.000 TESTS" ), ASSET( "3.000 TBD" ) ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION + 1 ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test success creating limit order that will not be filled" ); - - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == op.amount_to_sell.amount ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure creating limit order with duplicate id" ); - - op.amount_to_sell = ASSET( "20.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 10000 ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test sucess killing an order that will not be filled" ); - - op.orderid = 2; - op.fill_or_kill = true; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test having a partial match to limit order" ); - // Alice has order for 15 HBD at a price of 2:3 - // Fill 5 HIVE for 7.5 HBD - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "7.500 TBD" ); - op.exchange_rate = price( ASSET( "3.000 TBD" ), ASSET( "2.000 TESTS" ) ); - op.fill_or_kill = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - auto recent_ops = get_last_operations( 1 ); - auto fill_order_op = recent_ops[0].get< fill_order_operation >(); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 5000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "2.000 TESTS" ), ASSET( "3.000 TBD" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "7.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "5.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "992.500 TBD" ).amount.value ); - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == ASSET( "5.000 TESTS").amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == ASSET( "7.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order fully, but the new order partially" ); - - op.amount_to_sell = ASSET( "15.000 TBD" ); - op.exchange_rate = price( ASSET( "3.000 TBD" ), ASSET( "2.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 1 ); - BOOST_REQUIRE( limit_order->for_sale.value == 7500 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "3.000 TBD" ), ASSET( "2.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "990.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "15.000 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "977.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order and new order fully" ); - - op.owner = "alice"; - op.orderid = 3; - op.amount_to_sell = ASSET( "5.000 TESTS" ); - op.exchange_rate = price( ASSET( "2.000 TESTS" ), ASSET( "3.000 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 3 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "985.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "22.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "15.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "977.500 TBD" ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is better." ); - - op.owner = "alice"; - op.orderid = 4; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.100 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = ASSET( "12.000 TBD" ); - op.exchange_rate = price( ASSET( "1.200 TBD" ), ASSET( "1.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 4 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "alice", 4 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 4 ); - BOOST_REQUIRE( limit_order->for_sale.value == 1000 ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "975.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "33.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "25.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "965.500 TBD" ).amount.value ); - validate_database(); - - limit_order_cancel_operation can; - can.owner = "bob"; - can.orderid = 4; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( can ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is worse." ); - - //auto& gpo = db->get_dynamic_global_properties(); - //auto start_hbd = gpo.get_current_hbd_supply(); - - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.100 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 5; - op.amount_to_sell = ASSET( "12.000 TBD" ); - op.exchange_rate = price( ASSET( "1.200 TBD" ), ASSET( "1.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 5 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "bob", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == 5 ); - BOOST_REQUIRE( limit_order->for_sale.value == 9091 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "1.000 TESTS" ), ASSET( "1.100 TBD" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( HBD_SYMBOL, HIVE_SYMBOL ) ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "955.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "45.500 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "35.909 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "954.500 TBD" ).amount.value ); - - BOOST_TEST_MESSAGE( "--- Test filling best order with multiple matches." ); - ACTORS( (sam)(dave) ) - fund( "sam", 1000000 ); - fund( "dave", 1000000 ); - convert( "dave", ASSET("1000.000 TESTS" ) ); - - op.owner = "bob"; - op.orderid = 6; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "sam"; - op.orderid = 1; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "0.500 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "alice"; - op.orderid = 6; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), ASSET( "2.000 TBD" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "dave"; - op.orderid = 1; - op.amount_to_sell = ASSET( "25.000 TBD" ); - op.exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "0.010 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - recent_ops = get_last_operations( 3 ); - fill_order_op = recent_ops[2].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "sam" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays == ASSET( "20.000 TESTS") ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays == ASSET( "10.000 TBD" ) ); - - fill_order_op = recent_ops[0].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 6 ); - BOOST_REQUIRE( fill_order_op.open_pays == ASSET( "15.000 TESTS") ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays == ASSET( "15.000 TBD" ) ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 6 ) ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 6 ); - BOOST_REQUIRE( limit_order->for_sale.value == 5000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ) ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 6 ) ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == 6 ); - BOOST_REQUIRE( limit_order->for_sale.value == 20000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "1.000 TESTS" ), ASSET( "2.000 TBD" ) ) ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_cancel_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_cancel_validate" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_cancel_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_cancel_authorities" ); - - ACTORS( (alice)(bob) ) - fund( "alice", 10000 ); - - limit_order_create_operation c; - c.owner = "alice"; - c.orderid = 1; - c.amount_to_sell = ASSET( "1.000 TESTS" ); - c.min_to_receive = ASSET( "1.000 TBD" ); - c.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - signed_transaction tx; - tx.operations.push_back( c ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - limit_order_cancel_operation op; - op.owner = "alice"; - op.orderid = 1; - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( limit_order_cancel_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_cancel_apply" ); - - ACTORS( (alice) ) - fund( "alice", 10000 ); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test cancel non-existent order" ); - - limit_order_cancel_operation op; - signed_transaction tx; - - op.owner = "alice"; - op.orderid = 5; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test cancel order" ); - - limit_order_create_operation create; - create.owner = "alice"; - create.orderid = 5; - create.amount_to_sell = ASSET( "5.000 TESTS" ); - create.min_to_receive = ASSET( "7.500 TBD" ); - create.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( create ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 5 ) ) != limit_order_idx.end() ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( alice.get_balance().amount.value == ASSET( "10.000 TESTS" ).amount.value ); - BOOST_REQUIRE( alice.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( pow_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: pow_validate" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( pow_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: pow_authorities" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( pow_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: pow_apply" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_recovery ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account recovery" ); - - ACTORS( (alice) ); - fund( "alice", 1000000 ); - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& wso ) - { - wso.median_props.account_creation_fee = ASSET( "0.100 TESTS" ); - }); - }); - - generate_block(); - - BOOST_TEST_MESSAGE( "Creating account bob with alice" ); - - account_create_operation acc_create; - acc_create.fee = ASSET( "0.100 TESTS" ); - acc_create.creator = "alice"; - acc_create.new_account_name = "bob"; - acc_create.owner = authority( 1, generate_private_key( "bob_owner" ).get_public_key(), 1 ); - acc_create.active = authority( 1, generate_private_key( "bob_active" ).get_public_key(), 1 ); - acc_create.posting = authority( 1, generate_private_key( "bob_posting" ).get_public_key(), 1 ); - acc_create.memo_key = generate_private_key( "bob_memo" ).get_public_key(); - acc_create.json_metadata = ""; - - - signed_transaction tx; - tx.operations.push_back( acc_create ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - vest( HIVE_INIT_MINER_NAME, "bob", asset( 1000, HIVE_SYMBOL ) ); - - const auto& bob_auth = db->get< account_authority_object, by_account >( "bob" ); - BOOST_REQUIRE( bob_auth.owner == acc_create.owner ); - - - BOOST_TEST_MESSAGE( "Changing bob's owner authority" ); - - account_update_operation acc_update; - acc_update.account = "bob"; - acc_update.owner = authority( 1, generate_private_key( "bad_key" ).get_public_key(), 1 ); - acc_update.memo_key = acc_create.memo_key; - acc_update.json_metadata = ""; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( acc_update ); - sign( tx, generate_private_key( "bob_owner" ) ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( bob_auth.owner == *acc_update.owner ); - - - BOOST_TEST_MESSAGE( "Creating recover request for bob with alice" ); - - request_account_recovery_operation request; - request.recovery_account = "alice"; - request.account_to_recover = "bob"; - request.new_owner_authority = authority( 1, generate_private_key( "new_key" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( request ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( bob_auth.owner == *acc_update.owner ); - - - BOOST_TEST_MESSAGE( "Recovering bob's account with original owner auth and new secret" ); - - generate_blocks( db->head_block_time() + HIVE_OWNER_UPDATE_LIMIT ); - - recover_account_operation recover; - recover.account_to_recover = "bob"; - recover.new_owner_authority = request.new_owner_authority; - recover.recent_owner_authority = acc_create.owner; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - sign( tx, generate_private_key( "bob_owner" ) ); - sign( tx, generate_private_key( "new_key" ) ); - db->push_transaction( tx, 0 ); - const auto& owner1 = db->get< account_authority_object, by_account >("bob").owner; - - BOOST_REQUIRE( owner1 == recover.new_owner_authority ); - - - BOOST_TEST_MESSAGE( "Creating new recover request for a bogus key" ); - - request.new_owner_authority = authority( 1, generate_private_key( "foo bar" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( request ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "Testing failure when bob does not have new authority" ); - - generate_blocks( db->head_block_time() + HIVE_OWNER_UPDATE_LIMIT + fc::seconds( HIVE_BLOCK_INTERVAL ) ); - - recover.new_owner_authority = authority( 1, generate_private_key( "idontknow" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - sign( tx, generate_private_key( "bob_owner" ) ); - sign( tx, generate_private_key( "idontknow" ) ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - const auto& owner2 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner2 == authority( 1, generate_private_key( "new_key" ).get_public_key(), 1 ) ); - - - BOOST_TEST_MESSAGE( "Testing failure when bob does not have old authority" ); - - recover.recent_owner_authority = authority( 1, generate_private_key( "idontknow" ).get_public_key(), 1 ); - recover.new_owner_authority = authority( 1, generate_private_key( "foo bar" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - sign( tx, generate_private_key( "foo bar" ) ); - sign( tx, generate_private_key( "idontknow" ) ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - const auto& owner3 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner3 == authority( 1, generate_private_key( "new_key" ).get_public_key(), 1 ) ); - - - BOOST_TEST_MESSAGE( "Testing using the same old owner auth again for recovery" ); - - recover.recent_owner_authority = authority( 1, generate_private_key( "bob_owner" ).get_public_key(), 1 ); - recover.new_owner_authority = authority( 1, generate_private_key( "foo bar" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - sign( tx, generate_private_key( "bob_owner" ) ); - sign( tx, generate_private_key( "foo bar" ) ); - db->push_transaction( tx, 0 ); - - const auto& owner4 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner4 == recover.new_owner_authority ); - - BOOST_TEST_MESSAGE( "Creating a recovery request that will expire" ); - - request.new_owner_authority = authority( 1, generate_private_key( "expire" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( request ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const auto& request_idx = db->get_index< account_recovery_request_index >().indices(); - auto req_itr = request_idx.begin(); - - BOOST_REQUIRE( req_itr->account_to_recover == "bob" ); - BOOST_REQUIRE( req_itr->new_owner_authority == authority( 1, generate_private_key( "expire" ).get_public_key(), 1 ) ); - BOOST_REQUIRE( req_itr->expires == db->head_block_time() + HIVE_ACCOUNT_RECOVERY_REQUEST_EXPIRATION_PERIOD ); - auto expires = req_itr->expires; - ++req_itr; - BOOST_REQUIRE( req_itr == request_idx.end() ); - - generate_blocks( time_point_sec( expires - HIVE_BLOCK_INTERVAL ), true ); - - const auto& new_request_idx = db->get_index< account_recovery_request_index >().indices(); - BOOST_REQUIRE( new_request_idx.begin() != new_request_idx.end() ); - - generate_block(); - - BOOST_REQUIRE( new_request_idx.begin() == new_request_idx.end() ); - - recover.new_owner_authority = authority( 1, generate_private_key( "expire" ).get_public_key(), 1 ); - recover.recent_owner_authority = authority( 1, generate_private_key( "bob_owner" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - tx.set_expiration( db->head_block_time() ); - sign( tx, generate_private_key( "expire" ) ); - sign( tx, generate_private_key( "bob_owner" ) ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - const auto& owner5 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner5 == authority( 1, generate_private_key( "foo bar" ).get_public_key(), 1 ) ); - - BOOST_TEST_MESSAGE( "Expiring owner authority history" ); - - acc_update.owner = authority( 1, generate_private_key( "new_key" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( acc_update ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, generate_private_key( "foo bar" ) ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + ( HIVE_OWNER_AUTH_RECOVERY_PERIOD - HIVE_ACCOUNT_RECOVERY_REQUEST_EXPIRATION_PERIOD ) ); - generate_block(); - - request.new_owner_authority = authority( 1, generate_private_key( "last key" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( request ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - recover.new_owner_authority = request.new_owner_authority; - recover.recent_owner_authority = authority( 1, generate_private_key( "bob_owner" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, generate_private_key( "bob_owner" ) ); - sign( tx, generate_private_key( "last key" ) ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - const auto& owner6 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner6 == authority( 1, generate_private_key( "new_key" ).get_public_key(), 1 ) ); - - recover.recent_owner_authority = authority( 1, generate_private_key( "foo bar" ).get_public_key(), 1 ); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( recover ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, generate_private_key( "foo bar" ) ); - sign( tx, generate_private_key( "last key" ) ); - db->push_transaction( tx, 0 ); - const auto& owner7 = db->get< account_authority_object, by_account >("bob").owner; - BOOST_REQUIRE( owner7 == authority( 1, generate_private_key( "last key" ).get_public_key(), 1 ) ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( change_recovery_account ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing change_recovery_account_operation" ); - - ACTORS( (alice)(bob)(sam)(tyler) ) - - auto change_recovery_account = [&]( const std::string& account_to_recover, const std::string& new_recovery_account ) - { - change_recovery_account_operation op; - op.account_to_recover = account_to_recover; - op.new_recovery_account = new_recovery_account; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - }; - - auto recover_account = [&]( const std::string& account_to_recover, const fc::ecc::private_key& new_owner_key, const fc::ecc::private_key& recent_owner_key ) - { - recover_account_operation op; - op.account_to_recover = account_to_recover; - op.new_owner_authority = authority( 1, public_key_type( new_owner_key.get_public_key() ), 1 ); - op.recent_owner_authority = authority( 1, public_key_type( recent_owner_key.get_public_key() ), 1 ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, recent_owner_key ); - // only Alice -> throw - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - tx.signatures.clear(); - sign( tx, new_owner_key ); - // only Sam -> throw - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - sign( tx, recent_owner_key ); - // Alice+Sam -> OK - db->push_transaction( tx, 0 ); - }; - - auto request_account_recovery = [&]( const std::string& recovery_account, const fc::ecc::private_key& recovery_account_key, const std::string& account_to_recover, const public_key_type& new_owner_key ) - { - request_account_recovery_operation op; - op.recovery_account = recovery_account; - op.account_to_recover = account_to_recover; - op.new_owner_authority = authority( 1, new_owner_key, 1 ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, recovery_account_key ); - db->push_transaction( tx, 0 ); - }; - - auto change_owner = [&]( const std::string& account, const fc::ecc::private_key& old_private_key, const public_key_type& new_public_key ) - { - account_update_operation op; - op.account = account; - op.owner = authority( 1, new_public_key, 1 ); - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, old_private_key ); - db->push_transaction( tx, 0 ); - }; - - // if either/both users do not exist, we shouldn't allow it - HIVE_REQUIRE_THROW( change_recovery_account("alice", "nobody"), fc::exception ); - HIVE_REQUIRE_THROW( change_recovery_account("haxer", "sam" ), fc::exception ); - HIVE_REQUIRE_THROW( change_recovery_account("haxer", "nobody"), fc::exception ); - change_recovery_account("alice", "sam"); - - fc::ecc::private_key alice_priv1 = fc::ecc::private_key::regenerate( fc::sha256::hash( "alice_k1" ) ); - fc::ecc::private_key alice_priv2 = fc::ecc::private_key::regenerate( fc::sha256::hash( "alice_k2" ) ); - public_key_type alice_pub1 = public_key_type( alice_priv1.get_public_key() ); - - generate_blocks( db->head_block_time() + HIVE_OWNER_AUTH_RECOVERY_PERIOD - fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - // cannot request account recovery until recovery account is approved - HIVE_REQUIRE_THROW( request_account_recovery( "sam", sam_private_key, "alice", alice_pub1 ), fc::exception ); - generate_blocks(1); - // cannot finish account recovery until requested - HIVE_REQUIRE_THROW( recover_account( "alice", alice_priv1, alice_private_key ), fc::exception ); - // do the request - request_account_recovery( "sam", sam_private_key, "alice", alice_pub1 ); - // can't recover with the current owner key - HIVE_REQUIRE_THROW( recover_account( "alice", alice_priv1, alice_private_key ), fc::exception ); - // unless we change it! - change_owner( "alice", alice_private_key, public_key_type( alice_priv2.get_public_key() ) ); - recover_account( "alice", alice_priv1, alice_private_key ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_transfer_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_transfer_validate" ); - - escrow_transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.hbd_amount = ASSET( "1.000 TBD" ); - op.hive_amount = ASSET( "1.000 TESTS" ); - op.escrow_id = 0; - op.agent = "sam"; - op.fee = ASSET( "0.100 TESTS" ); - op.json_meta = ""; - op.ratification_deadline = db->head_block_time() + 100; - op.escrow_expiration = db->head_block_time() + 200; - - BOOST_TEST_MESSAGE( "--- failure when hbd symbol != HBD" ); - op.hbd_amount.symbol = HIVE_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when hive symbol != HIVE" ); - op.hbd_amount.symbol = HBD_SYMBOL; - op.hive_amount.symbol = HBD_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when fee symbol != HBD and fee symbol != HIVE" ); - op.hive_amount.symbol = HIVE_SYMBOL; - op.fee.symbol = VESTS_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when hbd == 0 and hive == 0" ); - op.fee.symbol = HIVE_SYMBOL; - op.hbd_amount.amount = 0; - op.hive_amount.amount = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when hbd < 0" ); - op.hbd_amount.amount = -100; - op.hive_amount.amount = 1000; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when hive < 0" ); - op.hbd_amount.amount = 1000; - op.hive_amount.amount = -100; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when fee < 0" ); - op.hive_amount.amount = 1000; - op.fee.amount = -100; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when ratification deadline == escrow expiration" ); - op.fee.amount = 100; - op.ratification_deadline = op.escrow_expiration; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when ratification deadline > escrow expiration" ); - op.ratification_deadline = op.escrow_expiration + 100; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- success" ); - op.ratification_deadline = op.escrow_expiration - 100; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_transfer_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_transfer_authorities" ); - - escrow_transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.hbd_amount = ASSET( "1.000 TBD" ); - op.hive_amount = ASSET( "1.000 TESTS" ); - op.escrow_id = 0; - op.agent = "sam"; - op.fee = ASSET( "0.100 TESTS" ); - op.json_meta = ""; - op.ratification_deadline = db->head_block_time() + 100; - op.escrow_expiration = db->head_block_time() + 200; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "alice" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_transfer_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_transfer_apply" ); - - ACTORS( (alice)(bob)(sam) ) - - fund( "alice", 10000 ); - - escrow_transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.hbd_amount = ASSET( "1.000 TBD" ); - op.hive_amount = ASSET( "1.000 TESTS" ); - op.escrow_id = 0; - op.agent = "sam"; - op.fee = ASSET( "0.100 TESTS" ); - op.json_meta = ""; - op.ratification_deadline = db->head_block_time() + 100; - op.escrow_expiration = db->head_block_time() + 200; - - BOOST_TEST_MESSAGE( "--- failure when from cannot cover hbd amount" ); - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- falure when from cannot cover amount + fee" ); - op.hbd_amount.amount = 0; - op.hive_amount.amount = 10000; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when ratification deadline is in the past" ); - op.hive_amount.amount = 1000; - op.ratification_deadline = db->head_block_time() - 200; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- failure when expiration is in the past" ); - op.escrow_expiration = db->head_block_time() - 100; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- success" ); - op.ratification_deadline = db->head_block_time() + 100; - op.escrow_expiration = db->head_block_time() + 200; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - - auto alice_hive_balance = alice.get_balance() - op.hive_amount - op.fee; - auto alice_hbd_balance = alice.get_hbd_balance() - op.hbd_amount; - auto bob_hive_balance = bob.get_balance(); - auto bob_hbd_balance = bob.get_hbd_balance(); - auto sam_hive_balance = sam.get_balance(); - auto sam_hbd_balance = sam.get_hbd_balance(); - - db->push_transaction( tx, 0 ); - - const auto& escrow = db->get_escrow( op.from, op.escrow_id ); - - BOOST_REQUIRE( escrow.escrow_id == op.escrow_id ); - BOOST_REQUIRE( escrow.from == op.from ); - BOOST_REQUIRE( escrow.to == op.to ); - BOOST_REQUIRE( escrow.agent == op.agent ); - BOOST_REQUIRE( escrow.ratification_deadline == op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == op.fee ); - BOOST_REQUIRE( !escrow.to_approved ); - BOOST_REQUIRE( !escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - BOOST_REQUIRE( alice.get_balance() == alice_hive_balance ); - BOOST_REQUIRE( alice.get_hbd_balance() == alice_hbd_balance ); - BOOST_REQUIRE( bob.get_balance() == bob_hive_balance ); - BOOST_REQUIRE( bob.get_hbd_balance() == bob_hbd_balance ); - BOOST_REQUIRE( sam.get_balance() == sam_hive_balance ); - BOOST_REQUIRE( sam.get_hbd_balance() == sam_hbd_balance ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_approve_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_approve_validate" ); - - escrow_approve_operation op; - - op.from = "alice"; - op.to = "bob"; - op.agent = "sam"; - op.who = "bob"; - op.escrow_id = 0; - op.approve = true; - - BOOST_TEST_MESSAGE( "--- failure when who is not to or agent" ); - op.who = "dave"; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- success when who is to" ); - op.who = op.to; - op.validate(); - - BOOST_TEST_MESSAGE( "--- success when who is agent" ); - op.who = op.agent; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_approve_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_approve_authorities" ); - - escrow_approve_operation op; - - op.from = "alice"; - op.to = "bob"; - op.agent = "sam"; - op.who = "bob"; - op.escrow_id = 0; - op.approve = true; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "bob" ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - op.who = "sam"; - op.get_required_active_authorities( auths ); - expected.insert( "sam" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_approve_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_approve_apply" ); - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - - escrow_transfer_operation et_op; - et_op.from = "alice"; - et_op.to = "bob"; - et_op.agent = "sam"; - et_op.hive_amount = ASSET( "1.000 TESTS" ); - et_op.fee = ASSET( "0.100 TESTS" ); - et_op.json_meta = ""; - et_op.ratification_deadline = db->head_block_time() + 100; - et_op.escrow_expiration = db->head_block_time() + 200; - - signed_transaction tx; - tx.operations.push_back( et_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - - BOOST_TEST_MESSAGE( "---failure when to does not match escrow" ); - escrow_approve_operation op; - op.from = "alice"; - op.to = "dave"; - op.agent = "sam"; - op.who = "dave"; - op.approve = true; - - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when agent does not match escrow" ); - op.to = "bob"; - op.agent = "dave"; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success approving to" ); - op.agent = "sam"; - op.who = "bob"; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - auto& escrow = db->get_escrow( op.from, op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( escrow.get_hive_balance() == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.100 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( !escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- failure on repeat approval" ); - tx.signatures.clear(); - - tx.set_expiration( db->head_block_time() + HIVE_BLOCK_INTERVAL ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( escrow.get_hive_balance() == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.100 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( !escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- failure trying to repeal after approval" ); - tx.signatures.clear(); - tx.operations.clear(); - - op.approve = false; - - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( escrow.get_hive_balance() == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.100 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( !escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- success refunding from because of repeal" ); - tx.signatures.clear(); - tx.operations.clear(); - - op.who = op.agent; - - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - HIVE_REQUIRE_THROW( db->get_escrow( op.from, op.escrow_id ), fc::exception ); - BOOST_REQUIRE( alice.get_balance() == ASSET( "10.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- test automatic refund when escrow is not ratified before deadline" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( et_op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( et_op.ratification_deadline + HIVE_BLOCK_INTERVAL, true ); - - HIVE_REQUIRE_THROW( db->get_escrow( op.from, op.escrow_id ), fc::exception ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- test ratification expiration when escrow is only approved by to" ); - tx.operations.clear(); - tx.signatures.clear(); - et_op.ratification_deadline = db->head_block_time() + 100; - et_op.escrow_expiration = db->head_block_time() + 200; - tx.operations.push_back( et_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.who = op.to; - op.approve = true; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( et_op.ratification_deadline + HIVE_BLOCK_INTERVAL, true ); - - HIVE_REQUIRE_THROW( db->get_escrow( op.from, op.escrow_id ), fc::exception ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- test ratification expiration when escrow is only approved by agent" ); - tx.operations.clear(); - tx.signatures.clear(); - et_op.ratification_deadline = db->head_block_time() + 100; - et_op.escrow_expiration = db->head_block_time() + 200; - tx.operations.push_back( et_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.who = op.agent; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( et_op.ratification_deadline + HIVE_BLOCK_INTERVAL, true ); - - HIVE_REQUIRE_THROW( db->get_escrow( op.from, op.escrow_id ), fc::exception ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success approving escrow" ); - tx.operations.clear(); - tx.signatures.clear(); - et_op.ratification_deadline = db->head_block_time() + 100; - et_op.escrow_expiration = db->head_block_time() + 200; - tx.operations.push_back( et_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.who = op.to; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.who = op.agent; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - { - const auto& escrow = db->get_escrow( op.from, op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( escrow.get_hive_balance() == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - } - - BOOST_REQUIRE( get_balance( "sam" ) == et_op.fee ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- ratification expiration does not remove an approved escrow" ); - - generate_blocks( et_op.ratification_deadline + HIVE_BLOCK_INTERVAL, true ); - { - const auto& escrow = db->get_escrow( op.from, op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( escrow.get_hive_balance() == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - } - - BOOST_REQUIRE( get_balance( "sam" ) == et_op.fee ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_dispute_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_dispute_validate" ); - escrow_dispute_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "alice"; - op.who = "alice"; - - BOOST_TEST_MESSAGE( "failure when who is not from or to" ); - op.who = "sam"; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "success" ); - op.who = "alice"; - op.validate(); - - op.who = "bob"; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_dispute_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_dispute_authorities" ); - escrow_dispute_operation op; - op.from = "alice"; - op.to = "bob"; - op.who = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "alice" ); - BOOST_REQUIRE( auths == expected ); - - auths.clear(); - expected.clear(); - op.who = "bob"; - op.get_required_active_authorities( auths ); - expected.insert( "bob" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_dispute_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_dispute_apply" ); - - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - - escrow_transfer_operation et_op; - et_op.from = "alice"; - et_op.to = "bob"; - et_op.agent = "sam"; - et_op.hive_amount = ASSET( "1.000 TESTS" ); - et_op.fee = ASSET( "0.100 TESTS" ); - et_op.ratification_deadline = db->head_block_time() + HIVE_BLOCK_INTERVAL; - et_op.escrow_expiration = db->head_block_time() + 2 * HIVE_BLOCK_INTERVAL; - - escrow_approve_operation ea_b_op; - ea_b_op.from = "alice"; - ea_b_op.to = "bob"; - ea_b_op.agent = "sam"; - ea_b_op.who = "bob"; - ea_b_op.approve = true; - - signed_transaction tx; - tx.operations.push_back( et_op ); - tx.operations.push_back( ea_b_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "--- failure when escrow has not been approved" ); - escrow_dispute_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "sam"; - op.who = "bob"; - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - const auto& escrow = db->get_escrow( et_op.from, et_op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == et_op.fee ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( !escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- failure when to does not match escrow" ); - escrow_approve_operation ea_s_op; - ea_s_op.from = "alice"; - ea_s_op.to = "bob"; - ea_s_op.agent = "sam"; - ea_s_op.who = "sam"; - ea_s_op.approve = true; - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( ea_s_op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - op.to = "dave"; - op.who = "alice"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- failure when agent does not match escrow" ); - op.to = "bob"; - op.who = "alice"; - op.agent = "dave"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - - - BOOST_TEST_MESSAGE( "--- failure when escrow is expired" ); - generate_blocks( 2 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.agent = "sam"; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - { - const auto& escrow = db->get_escrow( et_op.from, et_op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( !escrow.disputed ); - } - - - BOOST_TEST_MESSAGE( "--- success disputing escrow" ); - et_op.escrow_id = 1; - et_op.ratification_deadline = db->head_block_time() + HIVE_BLOCK_INTERVAL; - et_op.escrow_expiration = db->head_block_time() + 2 * HIVE_BLOCK_INTERVAL; - ea_b_op.escrow_id = et_op.escrow_id; - ea_s_op.escrow_id = et_op.escrow_id; - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( et_op ); - tx.operations.push_back( ea_b_op ); - tx.operations.push_back( ea_s_op ); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - op.escrow_id = et_op.escrow_id; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - { - const auto& escrow = db->get_escrow( et_op.from, et_op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( escrow.disputed ); - } - - - BOOST_TEST_MESSAGE( "--- failure when escrow is already under dispute" ); - tx.operations.clear(); - tx.signatures.clear(); - op.who = "bob"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - { - const auto& escrow = db->get_escrow( et_op.from, et_op.escrow_id ); - BOOST_REQUIRE( escrow.to == "bob" ); - BOOST_REQUIRE( escrow.agent == "sam" ); - BOOST_REQUIRE( escrow.ratification_deadline == et_op.ratification_deadline ); - BOOST_REQUIRE( escrow.escrow_expiration == et_op.escrow_expiration ); - BOOST_REQUIRE( escrow.get_hbd_balance() == et_op.hbd_amount ); - BOOST_REQUIRE( escrow.get_hive_balance() == et_op.hive_amount ); - BOOST_REQUIRE( escrow.get_fee() == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( escrow.to_approved ); - BOOST_REQUIRE( escrow.agent_approved ); - BOOST_REQUIRE( escrow.disputed ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_release_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow release validate" ); - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.who = "alice"; - op.agent = "sam"; - op.receiver = "bob"; - - - BOOST_TEST_MESSAGE( "--- failure when hive < 0" ); - op.hive_amount.amount = -1; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when hbd < 0" ); - op.hive_amount.amount = 0; - op.hbd_amount.amount = -1; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when hive == 0 and hbd == 0" ); - op.hbd_amount.amount = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when hbd is not HBD symbol" ); - op.hbd_amount = ASSET( "1.000 TESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when hive is not HIVE symbol" ); - op.hbd_amount.symbol = HBD_SYMBOL; - op.hive_amount = ASSET( "1.000 TBD" ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success" ); - op.hive_amount.symbol = HIVE_SYMBOL; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_release_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_release_authorities" ); - escrow_release_operation op; - op.from = "alice"; - op.to = "bob"; - op.who = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.who = "bob"; - auths.clear(); - expected.clear(); - expected.insert( "bob" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.who = "sam"; - auths.clear(); - expected.clear(); - expected.insert( "sam" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_release_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_release_apply" ); - - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - - escrow_transfer_operation et_op; - et_op.from = "alice"; - et_op.to = "bob"; - et_op.agent = "sam"; - et_op.hive_amount = ASSET( "1.000 TESTS" ); - et_op.fee = ASSET( "0.100 TESTS" ); - et_op.ratification_deadline = db->head_block_time() + HIVE_BLOCK_INTERVAL; - et_op.escrow_expiration = db->head_block_time() + 2 * HIVE_BLOCK_INTERVAL; - - signed_transaction tx; - tx.operations.push_back( et_op ); - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "--- failure releasing funds prior to approval" ); - escrow_release_operation op; - op.from = et_op.from; - op.to = et_op.to; - op.agent = et_op.agent; - op.who = et_op.from; - op.receiver = et_op.to; - op.hive_amount = ASSET( "0.100 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - escrow_approve_operation ea_b_op; - ea_b_op.from = "alice"; - ea_b_op.to = "bob"; - ea_b_op.agent = "sam"; - ea_b_op.who = "bob"; - - escrow_approve_operation ea_s_op; - ea_s_op.from = "alice"; - ea_s_op.to = "bob"; - ea_s_op.agent = "sam"; - ea_s_op.who = "sam"; - - tx.clear(); - tx.operations.push_back( ea_b_op ); - tx.operations.push_back( ea_s_op ); - sign( tx, bob_private_key ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- failure when 'agent' attempts to release non-disputed escrow to 'to'" ); - op.who = et_op.agent; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE("--- failure when 'agent' attempts to release non-disputed escrow to 'from' " ); - op.receiver = et_op.from; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'agent' attempt to release non-disputed escrow to not 'to' or 'from'" ); - op.receiver = "dave"; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when other attempts to release non-disputed escrow to 'to'" ); - op.receiver = et_op.to; - op.who = "dave"; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE("--- failure when other attempts to release non-disputed escrow to 'from' " ); - op.receiver = et_op.from; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when other attempt to release non-disputed escrow to not 'to' or 'from'" ); - op.receiver = "dave"; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attemtps to release non-disputed escrow to 'to'" ); - op.receiver = et_op.to; - op.who = et_op.to; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE("--- failure when 'to' attempts to release non-dispured escrow to 'agent' " ); - op.receiver = et_op.agent; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attempts to release non-disputed escrow to not 'from'" ); - op.receiver = "dave"; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed escrow to 'to' from 'from'" ); - op.receiver = et_op.from; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_escrow( op.from, op.escrow_id ).get_hive_balance() == ASSET( "0.900 TESTS" ) ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.000 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release non-disputed escrow to 'from'" ); - op.receiver = et_op.from; - op.who = et_op.from; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE("--- failure when 'from' attempts to release non-disputed escrow to 'agent'" ); - op.receiver = et_op.agent; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release non-disputed escrow to not 'from'" ); - op.receiver = "dave"; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed escrow to 'from' from 'to'" ); - op.receiver = et_op.to; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_escrow( op.from, op.escrow_id ).get_hive_balance() == ASSET( "0.800 TESTS" ) ); - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.100 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- failure when releasing more hbd than available" ); - op.hive_amount = ASSET( "1.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when releasing less hive than available" ); - op.hive_amount = ASSET( "0.000 TESTS" ); - op.hbd_amount = ASSET( "1.000 TBD" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attempts to release disputed escrow" ); - escrow_dispute_operation ed_op; - ed_op.from = "alice"; - ed_op.to = "bob"; - ed_op.agent = "sam"; - ed_op.who = "alice"; - - tx.clear(); - tx.operations.push_back( ed_op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.clear(); - op.from = et_op.from; - op.receiver = et_op.from; - op.who = et_op.to; - op.hive_amount = ASSET( "0.100 TESTS" ); - op.hbd_amount = ASSET( "0.000 TBD" ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release disputed escrow" ); - tx.clear(); - op.receiver = et_op.to; - op.who = et_op.from; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when releasing disputed escrow to an account not 'to' or 'from'" ); - tx.clear(); - op.who = et_op.agent; - op.receiver = "dave"; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when agent does not match escrow" ); - tx.clear(); - op.who = "dave"; - op.receiver = et_op.from; - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success releasing disputed escrow with agent to 'to'" ); - tx.clear(); - op.receiver = et_op.to; - op.who = et_op.agent; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.200 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.700 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- success releasing disputed escrow with agent to 'from'" ); - tx.clear(); - op.receiver = et_op.from; - op.who = et_op.agent; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.100 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.600 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attempts to release disputed expired escrow" ); - generate_blocks( 2 ); - - tx.clear(); - op.receiver = et_op.from; - op.who = et_op.to; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release disputed expired escrow" ); - tx.clear(); - op.receiver = et_op.to; - op.who = et_op.from; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success releasing disputed expired escrow with agent" ); - tx.clear(); - op.receiver = et_op.from; - op.who = et_op.agent; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.200 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.500 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- success deleting escrow when balances are both zero" ); - tx.clear(); - op.hive_amount = ASSET( "0.500 TESTS" ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.700 TESTS" ) ); - HIVE_REQUIRE_THROW( db->get_escrow( et_op.from, et_op.escrow_id ), fc::exception ); - - - tx.clear(); - et_op.ratification_deadline = db->head_block_time() + HIVE_BLOCK_INTERVAL; - et_op.escrow_expiration = db->head_block_time() + 2 * HIVE_BLOCK_INTERVAL; - tx.operations.push_back( et_op ); - tx.operations.push_back( ea_b_op ); - tx.operations.push_back( ea_s_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - generate_blocks( 2 ); - - - BOOST_TEST_MESSAGE( "--- failure when 'agent' attempts to release non-disputed expired escrow to 'to'" ); - tx.clear(); - op.receiver = et_op.to; - op.who = et_op.agent; - op.hive_amount = ASSET( "0.100 TESTS" ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'agent' attempts to release non-disputed expired escrow to 'from'" ); - tx.clear(); - op.receiver = et_op.from; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'agent' attempt to release non-disputed expired escrow to not 'to' or 'from'" ); - tx.clear(); - op.receiver = "dave"; - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attempts to release non-dispured expired escrow to 'agent'" ); - tx.clear(); - op.who = et_op.to; - op.receiver = et_op.agent; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'to' attempts to release non-disputed expired escrow to not 'from' or 'to'" ); - tx.clear(); - op.receiver = "dave"; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed expired escrow to 'to' from 'to'" ); - tx.clear(); - op.receiver = et_op.to; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.300 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.900 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed expired escrow to 'from' from 'to'" ); - tx.clear(); - op.receiver = et_op.from; - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "8.700 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.800 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release non-disputed expired escrow to 'agent'" ); - tx.clear(); - op.who = et_op.from; - op.receiver = et_op.agent; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure when 'from' attempts to release non-disputed expired escrow to not 'from' or 'to'" ); - tx.clear(); - op.receiver = "dave"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed expired escrow to 'to' from 'from'" ); - tx.clear(); - op.receiver = et_op.to; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.400 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.700 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- success release non-disputed expired escrow to 'from' from 'from'" ); - tx.clear(); - op.receiver = et_op.from; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "8.800 TESTS" ) ); - BOOST_REQUIRE( db->get_escrow( et_op.from, et_op.escrow_id ).get_hive_balance() == ASSET( "0.600 TESTS" ) ); - - - BOOST_TEST_MESSAGE( "--- success deleting escrow when balances are zero on non-disputed escrow" ); - tx.clear(); - op.hive_amount = ASSET( "0.600 TESTS" ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.400 TESTS" ) ); - HIVE_REQUIRE_THROW( db->get_escrow( et_op.from, et_op.escrow_id ), fc::exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( escrow_limit ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: escrow_limit" ); - - ACTORS((alice)(bob)(sam)) - fund( "alice", 10000 ); - generate_block(); - - escrow_transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.agent = "sam"; - op.hive_amount = ASSET( "0.001 TESTS" ); - op.fee = ASSET( "0.000 TESTS" ); - op.ratification_deadline = db->head_block_time() + 2 * ( HIVE_MAX_PENDING_TRANSFERS + 1 ) * HIVE_BLOCK_INTERVAL; - op.escrow_expiration = op.ratification_deadline + HIVE_MAX_PENDING_TRANSFERS * HIVE_BLOCK_INTERVAL; - - int i; - //create fresh escrow transfers from "alice", one per block, up to the limit - for( i = 0; i < HIVE_MAX_PENDING_TRANSFERS; ++i ) - { - signed_transaction tx; - op.escrow_id = i; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_block(); - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, i + 1 ); - } - - //another escrow transfer from "alice" should fail - { - signed_transaction tx; - op.escrow_id = i; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - generate_block(); - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, i ); - } - - escrow_approve_operation bob_approve, sam_approve; - bob_approve.from = sam_approve.from = "alice"; - bob_approve.to = sam_approve.to = "bob"; - bob_approve.agent = sam_approve.agent = "sam"; - bob_approve.who = "bob"; - sam_approve.who = "sam"; - - int declined = 0; - int expired = 0; - //approve or decline transfers - out of every 4 transfers: - //0. bob and sam approves - //1. bob approves, sam declines - //2. bob declines, sam has nothing to approve anymore - //3. skipped - it is left to expire unratified - for( i = 0; i < HIVE_MAX_PENDING_TRANSFERS; ++i ) - { - if( ( i % 4 ) == 3 ) - { - ++expired; - generate_block(); - continue; - } - - bob_approve.approve = ( i % 4 ) != 2; - sam_approve.approve = ( i % 4 ) != 1; - bob_approve.escrow_id = sam_approve.escrow_id = i; - - { - signed_transaction tx; - tx.operations.push_back( bob_approve ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - } - - if( !bob_approve.approve ) - { - ++declined; - } - else - { - signed_transaction tx; - tx.operations.push_back( sam_approve ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - if( !sam_approve.approve ) - ++declined; - } - - generate_block(); - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, HIVE_MAX_PENDING_TRANSFERS - declined ); - } - - generate_block(); - //unratified transfers should expire by now - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, HIVE_MAX_PENDING_TRANSFERS - declined - expired ); - - //every 4 of remaining transfers (only those with id divisible by 4 remain): - //0. alice disputes transfer - //4. alice completes transfer - //8. bob disputes transfer - //12. bob completes transfer - escrow_dispute_operation alice_dispute, bob_dispute; - escrow_release_operation alice_release, bob_release; - alice_dispute.from = bob_dispute.from = alice_release.from = bob_release.from = "alice"; - alice_dispute.to = bob_dispute.to = alice_release.to = bob_release.to = "bob"; - alice_dispute.agent = bob_dispute.agent = alice_release.agent = bob_release.agent = "sam"; - alice_dispute.who = alice_release.who = "alice"; - bob_dispute.who = bob_release.who = "bob"; - alice_release.receiver = "bob"; - bob_release.receiver = "alice"; - alice_release.hive_amount = bob_release.hive_amount = ASSET( "0.001 TESTS" ); - - int released = 0; - for( i = 0; i < HIVE_MAX_PENDING_TRANSFERS; i += 4 ) - { - alice_dispute.escrow_id = bob_dispute.escrow_id = alice_release.escrow_id = bob_release.escrow_id = i; - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - switch( i % 16 ) - { - case 0: - tx.operations.push_back( alice_dispute ); - sign( tx, alice_private_key ); - break; - case 4: - tx.operations.push_back( alice_release ); - sign( tx, alice_private_key ); - ++released; - break; - case 8: - tx.operations.push_back( bob_dispute ); - sign( tx, bob_private_key ); - break; - case 12: - tx.operations.push_back( bob_release ); - sign( tx, bob_private_key ); - ++released; - break; - } - - db->push_transaction( tx, 0 ); - generate_block(); - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, HIVE_MAX_PENDING_TRANSFERS - declined - expired - released ); - } - - //every 2 of remaining transfers (only those with id divisible by 8 remain): - //0. sam completes transfer to alice - //8. sam completes transfer to bob - alice_release.who = bob_release.who = "sam"; - alice_release.receiver = "alice"; - bob_release.receiver = "bob"; - - int remaining = HIVE_MAX_PENDING_TRANSFERS - declined - expired - released; - for( i = 0; i < HIVE_MAX_PENDING_TRANSFERS; i += 8 ) - { - alice_release.escrow_id = bob_release.escrow_id = i; - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - if( i % 16 ) - tx.operations.push_back( bob_release ); - else - tx.operations.push_back( alice_release ); - - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - --remaining; - - generate_block(); - BOOST_REQUIRE_EQUAL( db->get_account( "alice" ).pending_transfers, remaining ); - } - - BOOST_REQUIRE_EQUAL( remaining, 0 ); - validate_database(); - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_savings_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_savings_validate" ); - - transfer_to_savings_operation op; - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - - - BOOST_TEST_MESSAGE( "failure when 'from' is empty" ); - op.from = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "failure when 'to' is empty" ); - op.from = "alice"; - op.to = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "sucess when 'to' is not empty" ); - op.to = "bob"; - op.validate(); - - - BOOST_TEST_MESSAGE( "failure when amount is VESTS" ); - op.to = "alice"; - op.amount = ASSET( "1.000000 VESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "success when amount is HBD" ); - op.amount = ASSET( "1.000 TBD" ); - op.validate(); - - - BOOST_TEST_MESSAGE( "success when amount is HIVE" ); - op.amount = ASSET( "1.000 TESTS" ); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_savings_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_savings_authorities" ); - - transfer_to_savings_operation op; - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "alice" ); - BOOST_REQUIRE( auths == expected ); - - auths.clear(); - expected.clear(); - op.from = "bob"; - op.get_required_active_authorities( auths ); - expected.insert( "bob" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_to_savings_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_savings_apply" ); - - ACTORS( (alice)(bob) ); - generate_block(); - - fund( "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "10.000 TBD" ) ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "10.000 TBD" ) ); - - transfer_to_savings_operation op; - signed_transaction tx; - - BOOST_TEST_MESSAGE( "--- failure with insufficient funds" ); - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "20.000 TESTS" ); - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- failure when transferring to non-existent account" ); - op.to = "sam"; - op.amount = ASSET( "1.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Failure when transferring to treasury" ); - - op.to = db->get_treasury_name(); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - op.amount = ASSET( "1.000 TBD" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success transferring HIVE to self" ); - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "9.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "alice" ) == ASSET( "1.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success transferring HBD to self" ); - op.amount = ASSET( "1.000 TBD" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "9.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "1.000 TBD" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success transferring HIVE to other" ); - op.to = "bob"; - op.amount = ASSET( "1.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "8.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "bob" ) == ASSET( "1.000 TESTS" ) ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success transferring HBD to other" ); - op.amount = ASSET( "1.000 TBD" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "8.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_savings( "bob" ) == ASSET( "1.000 TBD" ) ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_from_savings_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_from_savings_validate" ); - - transfer_from_savings_operation op; - op.from = "alice"; - op.request_id = 0; - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - - - BOOST_TEST_MESSAGE( "failure when 'from' is empty" ); - op.from = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "failure when 'to' is empty" ); - op.from = "alice"; - op.to = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "sucess when 'to' is not empty" ); - op.to = "bob"; - op.validate(); - - - BOOST_TEST_MESSAGE( "failure when amount is VESTS" ); - op.to = "alice"; - op.amount = ASSET( "1.000000 VESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "success when amount is HBD" ); - op.amount = ASSET( "1.000 TBD" ); - op.validate(); - - - BOOST_TEST_MESSAGE( "success when amount is HIVE" ); - op.amount = ASSET( "1.000 TESTS" ); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_from_savings_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_from_savings_authorities" ); - - transfer_from_savings_operation op; - op.from = "alice"; - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "alice" ); - BOOST_REQUIRE( auths == expected ); - - auths.clear(); - expected.clear(); - op.from = "bob"; - op.get_required_active_authorities( auths ); - expected.insert( "bob" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( transfer_from_savings_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_from_savings_apply" ); - - ACTORS( (alice)(bob) ); - generate_block(); - - fund( "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "10.000 TBD" ) ); - - transfer_to_savings_operation save; - save.from = "alice"; - save.to = "alice"; - save.amount = ASSET( "10.000 TESTS" ); - - signed_transaction tx; - tx.operations.push_back( save ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - save.amount = ASSET( "10.000 TBD" ); - tx.clear(); - tx.operations.push_back( save ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "--- failure when account has insufficient funds" ); - transfer_from_savings_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = ASSET( "20.000 TESTS" ); - op.request_id = 0; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- failure withdrawing to non-existant account" ); - op.to = "sam"; - op.amount = ASSET( "1.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Failure withdrawing TESTS to treasury" ); - - op.to = db->get_treasury_name(); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Success withdrawing TBD to treasury" ); - - op.amount = ASSET( "1.000 TBD" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "9.000 TBD" ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- success withdrawing HIVE to self" ); - op.to = "alice"; - op.amount = ASSET( "1.000 TESTS" ); - op.request_id++; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "alice" ) == ASSET( "9.000 TESTS" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == op.request_id + 1 ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).from == op.from ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).to == op.to ); - BOOST_REQUIRE( to_string( db->get_savings_withdraw( "alice", op.request_id ).memo ) == op.memo ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).request_id == op.request_id ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).amount == op.amount ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).complete == db->head_block_time() + HIVE_SAVINGS_WITHDRAW_TIME ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success withdrawing HBD to self" ); - op.amount = ASSET( "1.000 TBD" ); - op.request_id++; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "8.000 TBD" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == op.request_id + 1 ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).from == op.from ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).to == op.to ); - BOOST_REQUIRE( to_string( db->get_savings_withdraw( "alice", op.request_id ).memo ) == op.memo ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).request_id == op.request_id ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).amount == op.amount ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).complete == db->head_block_time() + HIVE_SAVINGS_WITHDRAW_TIME ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- failure withdrawing with repeat request id" ); - op.amount = ASSET( "2.000 TESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- success withdrawing HIVE to other" ); - op.to = "bob"; - op.amount = ASSET( "1.000 TESTS" ); - op.request_id = 3; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "alice" ) == ASSET( "8.000 TESTS" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == op.request_id + 1 ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).from == op.from ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).to == op.to ); - BOOST_REQUIRE( to_string( db->get_savings_withdraw( "alice", op.request_id ).memo ) == op.memo ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).request_id == op.request_id ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).amount == op.amount ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).complete == db->head_block_time() + HIVE_SAVINGS_WITHDRAW_TIME ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- success withdrawing HBD to other" ); - op.amount = ASSET( "1.000 TBD" ); - op.request_id = 4; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_savings( "alice" ) == ASSET( "7.000 TBD" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == op.request_id + 1 ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).from == op.from ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).to == op.to ); - BOOST_REQUIRE( to_string( db->get_savings_withdraw( "alice", op.request_id ).memo ) == op.memo ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).request_id == op.request_id ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).amount == op.amount ); - BOOST_REQUIRE( db->get_savings_withdraw( "alice", op.request_id ).complete == db->head_block_time() + HIVE_SAVINGS_WITHDRAW_TIME ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- withdraw on timeout" ); - generate_blocks( db->head_block_time() + HIVE_SAVINGS_WITHDRAW_TIME - fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "bob" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == op.request_id + 1 ); - validate_database(); - - generate_block(); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "1.000 TBD" ) ); - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "bob" ) == ASSET( "1.000 TBD" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == 0 ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- savings withdraw request limit" ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - op.to = "alice"; - op.amount = ASSET( "0.001 TESTS" ); - - for( int i = 0; i < HIVE_SAVINGS_WITHDRAW_REQUEST_LIMIT; i++ ) - { - op.request_id = i; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == i + 1 ); - } - - op.request_id = HIVE_SAVINGS_WITHDRAW_REQUEST_LIMIT; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == HIVE_SAVINGS_WITHDRAW_REQUEST_LIMIT ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( cancel_transfer_from_savings_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: cancel_transfer_from_savings_validate" ); - - cancel_transfer_from_savings_operation op; - op.from = "alice"; - op.request_id = 0; - - - BOOST_TEST_MESSAGE( "--- failure when 'from' is empty" ); - op.from = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- sucess when 'from' is not empty" ); - op.from = "alice"; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( cancel_transfer_from_savings_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: cancel_transfer_from_savings_authorities" ); - - cancel_transfer_from_savings_operation op; - op.from = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - expected.insert( "alice" ); - BOOST_REQUIRE( auths == expected ); - - auths.clear(); - expected.clear(); - op.from = "bob"; - op.get_required_active_authorities( auths ); - expected.insert( "bob" ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( cancel_transfer_from_savings_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: cancel_transfer_from_savings_apply" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - fund( "alice", ASSET( "10.000 TESTS" ) ); - - transfer_to_savings_operation save; - save.from = "alice"; - save.to = "alice"; - save.amount = ASSET( "10.000 TESTS" ); - - transfer_from_savings_operation withdraw; - withdraw.from = "alice"; - withdraw.to = "bob"; - withdraw.request_id = 1; - withdraw.amount = ASSET( "3.000 TESTS" ); - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( save ); - tx.operations.push_back( withdraw ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == 1 ); - BOOST_REQUIRE( db->get_account( "bob" ).savings_withdraw_requests == 0 ); - - - BOOST_TEST_MESSAGE( "--- Failure when there is no pending request" ); - cancel_transfer_from_savings_operation op; - op.from = "alice"; - op.request_id = 0; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == 1 ); - BOOST_REQUIRE( db->get_account( "bob" ).savings_withdraw_requests == 0 ); - - - BOOST_TEST_MESSAGE( "--- Success" ); - op.request_id = 1; - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "alice" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( db->get_account( "alice" ).savings_withdraw_requests == 0 ); - BOOST_REQUIRE( get_balance( "bob" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_savings( "bob" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( db->get_account( "bob" ).savings_withdraw_requests == 0 ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline_voting_rights_authorities" ); - - decline_voting_rights_operation op; - op.account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( decline_voting_rights_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline_voting_rights_apply" ); - - ACTORS( (alice)(bob) ); - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob", ASSET( "10.000 TESTS" ) ); - generate_block(); - - account_witness_proxy_operation proxy; - proxy.account = "bob"; - proxy.proxy = "alice"; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( proxy ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - - decline_voting_rights_operation op; - op.account = "alice"; - - - BOOST_TEST_MESSAGE( "--- success" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const auto& request_idx = db->get_index< decline_voting_rights_request_index >().indices().get< by_account >(); - auto itr = request_idx.find( db->get_account( "alice" ).name ); - BOOST_REQUIRE( itr != request_idx.end() ); - BOOST_REQUIRE( itr->effective_date == db->head_block_time() + HIVE_OWNER_AUTH_RECOVERY_PERIOD ); - - - BOOST_TEST_MESSAGE( "--- failure revoking voting rights with existing request" ); - generate_block(); - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- successs cancelling a request" ); - op.decline = false; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - itr = request_idx.find( db->get_account( "alice" ).name ); - BOOST_REQUIRE( itr == request_idx.end() ); - - - BOOST_TEST_MESSAGE( "--- failure cancelling a request that doesn't exist" ); - generate_block(); - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- check account can vote during waiting period" ); - op.decline = true; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + HIVE_OWNER_AUTH_RECOVERY_PERIOD - fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - BOOST_REQUIRE( db->get_account( "alice" ).can_vote ); - witness_create( "alice", alice_private_key, "foo.bar", alice_private_key.get_public_key(), 0 ); - - account_witness_vote_operation witness_vote; - witness_vote.account = "alice"; - witness_vote.witness = "alice"; - tx.clear(); - tx.operations.push_back( witness_vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - comment_operation comment; - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "test"; - vote_operation vote; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - tx.clear(); - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- check account cannot vote after request is processed" ); - generate_block(); - BOOST_REQUIRE( !db->get_account( "alice" ).can_vote ); - validate_database(); - - itr = request_idx.find( db->get_account( "alice" ).name ); - BOOST_REQUIRE( itr == request_idx.end() ); - - const auto& witness_idx = db->get_index< witness_vote_index >().indices().get< by_account_witness >(); - auto witness_itr = witness_idx.find( boost::make_tuple( db->get_account( "alice" ).name, db->get_witness( "alice" ).owner ) ); - BOOST_REQUIRE( witness_itr == witness_idx.end() ); - - tx.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( witness_vote ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - db->get< comment_vote_object, by_comment_voter >( boost::make_tuple( db->get_comment( "alice", string( "test" ) ).get_id(), get_account_id( "alice" ) ) ); - - vote.weight = 0; - tx.clear(); - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - vote.weight = HIVE_1_PERCENT * 50; - tx.clear(); - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - proxy.account = "alice"; - proxy.proxy = "bob"; - tx.clear(); - tx.operations.push_back( proxy ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance_validate ) -{ - try - { - claim_reward_balance_operation op; - op.account = "alice"; - op.reward_hive = ASSET( "0.000 TESTS" ); - op.reward_hbd = ASSET( "0.000 TBD" ); - op.reward_vests = ASSET( "0.000000 VESTS" ); - - - BOOST_TEST_MESSAGE( "Testing all 0 amounts" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "Testing single reward claims" ); - op.reward_hive.amount = 1000; - op.validate(); - - op.reward_hive.amount = 0; - op.reward_hbd.amount = 1000; - op.validate(); - - op.reward_hbd.amount = 0; - op.reward_vests.amount = 1000; - op.validate(); - - op.reward_vests.amount = 0; - - - BOOST_TEST_MESSAGE( "Testing wrong HIVE symbol" ); - op.reward_hive = ASSET( "1.000 TBD" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "Testing wrong HBD symbol" ); - op.reward_hive = ASSET( "1.000 TESTS" ); - op.reward_hbd = ASSET( "1.000 TESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "Testing wrong VESTS symbol" ); - op.reward_hbd = ASSET( "1.000 TBD" ); - op.reward_vests = ASSET( "1.000 TESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "Testing a single negative amount" ); - op.reward_hive.amount = 1000; - op.reward_hbd.amount = -1000; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline_voting_rights_authorities" ); - - claim_reward_balance_operation op; - op.account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_create_with_delegation_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_create_with_delegation_authorities" ); - - account_create_with_delegation_operation op; - op.creator = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() - -} - -BOOST_AUTO_TEST_CASE( account_create_with_delegation_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_create_with_delegation_apply" ); - signed_transaction tx; - ACTORS( (alice) ); - // 150 * fee = ( 5 * HIVE ) + SP - //auto& gpo = db->get_dynamic_global_properties(); - generate_blocks(1); - fund( "alice", ASSET("1510.000 TESTS") ); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET("1000.000 TESTS") ); - - private_key_type priv_key = generate_private_key( "temp_key" ); - - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& w ) - { - w.median_props.account_creation_fee = ASSET( "1.000 TESTS" ); - }); - }); - - generate_block(); - - // This test passed pre HF20 - BOOST_TEST_MESSAGE( "--- Test deprecation. " ); - account_create_with_delegation_operation op; - op.fee = ASSET( "10.000 TESTS" ); - op.delegation = ASSET( "100000000.000000 VESTS" ); - op.creator = "alice"; - op.new_account_name = "bob"; - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - op.active = authority( 2, priv_key.get_public_key(), 2 ); - op.memo_key = priv_key.get_public_key(); - op.json_metadata = "{\"foo\":\"bar\"}"; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: claim_reward_balance_apply" ); - BOOST_TEST_MESSAGE( "--- Setting up test state" ); - - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - db_plugin->debug_update( []( database& db ) - { - db.modify( db.get_account( "alice" ), []( account_object& a ) - { - a.reward_hive_balance = ASSET( "10.000 TESTS" ); - a.reward_hbd_balance = ASSET( "10.000 TBD" ); - a.reward_vesting_balance = ASSET( "10.000000 VESTS" ); - a.reward_vesting_hive = ASSET( "10.000 TESTS" ); - }); - - db.modify( db.get_dynamic_global_properties(), []( dynamic_global_property_object& gpo ) - { - gpo.current_supply += ASSET( "20.000 TESTS" ); - gpo.current_hbd_supply += ASSET( "10.000 TBD" ); - gpo.virtual_supply += ASSET( "20.000 TESTS" ); - gpo.pending_rewarded_vesting_shares += ASSET( "10.000000 VESTS" ); - gpo.pending_rewarded_vesting_hive += ASSET( "10.000 TESTS" ); - }); - }); - - generate_block(); - validate_database(); - - auto alice_hive = get_balance( "alice" ); - auto alice_hbd = get_hbd_balance( "alice" ); - auto alice_vests = get_vesting( "alice" ); - - - BOOST_TEST_MESSAGE( "--- Attempting to claim more HIVE than exists in the reward balance." ); - - claim_reward_balance_operation op; - signed_transaction tx; - - op.account = "alice"; - op.reward_hive = ASSET( "20.000 TESTS" ); - op.reward_hbd = ASSET( "0.000 TBD" ); - op.reward_vests = ASSET( "0.000000 VESTS" ); - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Claiming a partial reward balance" ); - - op.reward_hive = ASSET( "0.000 TESTS" ); - op.reward_vests = ASSET( "5.000000 VESTS" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == alice_hive + op.reward_hive ); - BOOST_REQUIRE( get_rewards( "alice" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == alice_hbd + op.reward_hbd ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ) == ASSET( "10.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( "alice" ) == alice_vests + op.reward_vests ); - BOOST_REQUIRE( get_vest_rewards( "alice" ) == ASSET( "5.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "alice" ) == ASSET( "5.000 TESTS" ) ); - validate_database(); - - alice_vests += op.reward_vests; - - - BOOST_TEST_MESSAGE( "--- Claiming the full reward balance" ); - - op.reward_hive = ASSET( "10.000 TESTS" ); - op.reward_hbd = ASSET( "10.000 TBD" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_balance( "alice" ) == alice_hive + op.reward_hive ); - BOOST_REQUIRE( get_rewards( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == alice_hbd + op.reward_hbd ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( "alice" ) == alice_vests + op.reward_vests ); - BOOST_REQUIRE( get_vest_rewards( "alice" ) == ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "alice" ) == ASSET( "0.000 TESTS" ) ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delegate_vesting_shares_validate ) -{ - try - { - delegate_vesting_shares_operation op; - - op.delegator = "alice"; - op.delegatee = "bob"; - op.vesting_shares = asset( -1, VESTS_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delegate_vesting_shares_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delegate_vesting_shares_authorities" ); - signed_transaction tx; - ACTORS( (alice)(bob) ) - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10000.000 TESTS" ) ); - - delegate_vesting_shares_operation op; - op.vesting_shares = ASSET( "300.000000 VESTS"); - op.delegator = "alice"; - op.delegatee = "bob"; - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signatures" ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with witness signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test failure when duplicate signatures" ); - tx.operations.clear(); - tx.signatures.clear(); - op.delegatee = "sam"; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by an additional signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, init_account_priv_key ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure when signed by a signature not in the creator's authority" ); - tx.signatures.clear(); - sign( tx, init_account_priv_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( delegate_vesting_shares_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: delegate_vesting_shares_apply" ); - signed_transaction tx; - ACTORS( (alice)(bob)(charlie) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& w ) - { - w.median_props.account_creation_fee = ASSET( "1.000 TESTS" ); - }); - }); - - generate_block(); - - delegate_vesting_shares_operation op; - op.vesting_shares = ASSET( "10000000.000000 VESTS"); - op.delegator = "alice"; - op.delegatee = "bob"; - - util::manabar old_manabar = VOTING_MANABAR( "alice" ); - util::manabar_params params( util::get_effective_vesting_shares( db->get_account( "alice" ) ), HIVE_VOTING_MANA_REGENERATION_SECONDS ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - util::manabar old_downvote_manabar = DOWNVOTE_MANABAR( "alice" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ) / 4; - old_downvote_manabar.regenerate_mana( params, db->head_block_time() ); - - util::manabar old_bob_manabar = VOTING_MANABAR( "bob" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "bob" ) ); - old_bob_manabar.regenerate_mana( params, db->head_block_time() ); - - util::manabar old_bob_downvote_manabar = DOWNVOTE_MANABAR( "bob" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "bob" ) ) / 4; - old_bob_downvote_manabar.regenerate_mana( params, db->head_block_time() ); - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_blocks( 1 ); - const account_object& alice_acc = db->get_account( "alice" ); - const account_object& bob_acc = db->get_account( "bob" ); - - BOOST_REQUIRE( alice_acc.get_delegated_vesting() == ASSET( "10000000.000000 VESTS" ) ); - BOOST_REQUIRE( alice_acc.voting_manabar.current_mana == old_manabar.current_mana - op.vesting_shares.amount.value ); - BOOST_REQUIRE( alice_acc.downvote_manabar.current_mana == old_downvote_manabar.current_mana - op.vesting_shares.amount.value / 4 ); - BOOST_REQUIRE( bob_acc.get_received_vesting() == ASSET( "10000000.000000 VESTS" ) ); - BOOST_REQUIRE( bob_acc.voting_manabar.current_mana == old_bob_manabar.current_mana + op.vesting_shares.amount.value ); - BOOST_REQUIRE( bob_acc.downvote_manabar.current_mana == old_bob_downvote_manabar.current_mana + op.vesting_shares.amount.value / 4 ); - - BOOST_TEST_MESSAGE( "--- Test that the delegation object is correct. " ); - auto delegation = db->find< vesting_delegation_object, by_delegation >( boost::make_tuple( op.delegator, op.delegatee ) ); - - - BOOST_REQUIRE( delegation != nullptr ); - BOOST_REQUIRE( delegation->delegator == op.delegator); - BOOST_REQUIRE( delegation->get_vesting() == ASSET( "10000000.000000 VESTS")); - - old_manabar = VOTING_MANABAR( "alice" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - old_downvote_manabar = DOWNVOTE_MANABAR( "alice" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "alice" ) ) / 4; - old_downvote_manabar.regenerate_mana( params, db->head_block_time() ); - - old_bob_manabar = VOTING_MANABAR( "bob" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "bob" ) ); - old_bob_manabar.regenerate_mana( params, db->head_block_time() ); - - old_bob_downvote_manabar = DOWNVOTE_MANABAR( "bob" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "bob" ) ) / 4; - old_bob_downvote_manabar.regenerate_mana( params, db->head_block_time() ); - - int64_t delta = 10000000000000; - - validate_database(); - tx.clear(); - op.vesting_shares.amount += delta; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_blocks(1); - - idump( (alice_acc.voting_manabar)(old_manabar)(delta) ); - - BOOST_REQUIRE( delegation != nullptr ); - BOOST_REQUIRE( delegation->delegator == op.delegator); - BOOST_REQUIRE( delegation->get_vesting() == ASSET( "20000000.000000 VESTS")); - BOOST_REQUIRE( alice_acc.get_delegated_vesting() == ASSET( "20000000.000000 VESTS")); - BOOST_REQUIRE( alice_acc.voting_manabar.current_mana == old_manabar.current_mana - delta ); - BOOST_REQUIRE( alice_acc.downvote_manabar.current_mana == old_downvote_manabar.current_mana - delta / 4 ); - BOOST_REQUIRE( bob_acc.get_received_vesting() == ASSET( "20000000.000000 VESTS")); - BOOST_REQUIRE( bob_acc.voting_manabar.current_mana == old_bob_manabar.current_mana + delta ); - BOOST_REQUIRE( bob_acc.downvote_manabar.current_mana == old_bob_downvote_manabar.current_mana + delta / 4 ); - - BOOST_TEST_MESSAGE( "--- Test failure delegating delgated VESTS." ); - - op.delegator = "bob"; - op.delegatee = "charlie"; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - - BOOST_TEST_MESSAGE( "--- Test that effective vesting shares is accurate and being applied." ); - tx.operations.clear(); - tx.signatures.clear(); - - old_manabar = VOTING_MANABAR( "bob" ); - params.max_mana = util::get_effective_vesting_shares( db->get_account( "bob" ) ); - old_manabar.regenerate_mana( params, db->head_block_time() ); - - comment_operation comment_op; - comment_op.author = "alice"; - comment_op.permlink = "foo"; - comment_op.parent_permlink = "test"; - comment_op.title = "bar"; - comment_op.body = "foo bar"; - tx.operations.push_back( comment_op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - tx.signatures.clear(); - tx.operations.clear(); - vote_operation vote_op; - vote_op.voter = "bob"; - vote_op.author = "alice"; - vote_op.permlink = "foo"; - vote_op.weight = HIVE_100_PERCENT; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( vote_op ); - sign( tx, bob_private_key ); - - db->push_transaction( tx, 0 ); - generate_blocks(1); - - const auto& vote_idx = db->get_index< comment_vote_index >().indices().get< by_comment_voter >(); - - auto& alice_comment = db->get_comment( "alice", string( "foo" ) ); - const comment_cashout_object* alice_comment_cashout = db->find_comment_cashout( alice_comment ); - auto itr = vote_idx.find( boost::make_tuple( alice_comment.get_id(), bob_acc.get_id() ) ); - BOOST_REQUIRE( alice_comment_cashout->net_rshares.value == old_manabar.current_mana - db->get_account( "bob" ).voting_manabar.current_mana - HIVE_VOTE_DUST_THRESHOLD ); - BOOST_REQUIRE( itr->rshares == old_manabar.current_mana - db->get_account( "bob" ).voting_manabar.current_mana - HIVE_VOTE_DUST_THRESHOLD ); - - generate_block(); - ACTORS( (sam)(dave) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "sam", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - auto sam_vest = get_vesting( "sam" ); - - BOOST_TEST_MESSAGE( "--- Test failure when delegating 0 VESTS" ); - tx.clear(); - op.delegator = "sam"; - op.delegatee = "dave"; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Testing failure delegating more vesting shares than account has." ); - tx.clear(); - op.vesting_shares = asset( sam_vest.amount + 1, VESTS_SYMBOL ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing failure delegating when there is not enough mana" ); - - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "sam" ), [&]( account_object& a ) - { - a.voting_manabar.current_mana = a.downvote_manabar.current_mana * 3 / 4; - a.voting_manabar.last_update_time = db.head_block_time().sec_since_epoch(); - }); - }); - - op.vesting_shares = sam_vest; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing failure delegating when there is not enough downvote mana" ); - - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "sam" ), [&]( account_object& a ) - { - a.voting_manabar.current_mana = util::get_effective_vesting_shares( a ); - a.voting_manabar.last_update_time = db.head_block_time().sec_since_epoch(); - a.downvote_manabar.current_mana = a.downvote_manabar.current_mana * 3 / 4; - a.downvote_manabar.last_update_time = db.head_block_time().sec_since_epoch(); - }); - }); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test failure delegating vesting shares that are part of a power down" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "sam" ), [&]( account_object& a ) - { - a.downvote_manabar.current_mana = util::get_effective_vesting_shares( a ) / 4; - a.downvote_manabar.last_update_time = db.head_block_time().sec_since_epoch(); - }); - }); - - tx.clear(); - sam_vest = asset( sam_vest.amount / 2, VESTS_SYMBOL ); - withdraw_vesting_operation withdraw; - withdraw.account = "sam"; - withdraw.vesting_shares = sam_vest; - tx.operations.push_back( withdraw ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.clear(); - op.vesting_shares = asset( sam_vest.amount + 2, VESTS_SYMBOL ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - tx.clear(); - withdraw.vesting_shares = ASSET( "0.000000 VESTS" ); - tx.operations.push_back( withdraw ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_TEST_MESSAGE( "--- Test failure powering down vesting shares that are delegated" ); - sam_vest.amount += 1000; - op.vesting_shares = sam_vest; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.clear(); - withdraw.vesting_shares = asset( sam_vest.amount, VESTS_SYMBOL ); - tx.operations.push_back( withdraw ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Remove a delegation and ensure it is returned after 1 week" ); - - util::manabar old_sam_manabar = VOTING_MANABAR( "sam" ); - util::manabar old_sam_downvote_manabar = DOWNVOTE_MANABAR( "sam" ); - util::manabar old_dave_manabar = VOTING_MANABAR( "dave" ); - util::manabar old_dave_downvote_manabar = DOWNVOTE_MANABAR( "dave" ); - - util::manabar_params sam_params( util::get_effective_vesting_shares( db->get_account( "sam" ) ), HIVE_VOTING_MANA_REGENERATION_SECONDS ); - util::manabar_params dave_params( util::get_effective_vesting_shares( db->get_account( "dave" ) ), HIVE_VOTING_MANA_REGENERATION_SECONDS ); - - tx.clear(); - op.vesting_shares = ASSET( "0.000000 VESTS" ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - auto exp_obj = db->get_index< vesting_delegation_expiration_index, by_id >().begin(); - auto end = db->get_index< vesting_delegation_expiration_index, by_id >().end(); - auto& gpo = db->get_dynamic_global_properties(); - - BOOST_REQUIRE( gpo.delegation_return_period == HIVE_DELEGATION_RETURN_PERIOD_HF20 ); - - BOOST_REQUIRE( exp_obj != end ); - BOOST_REQUIRE( exp_obj->delegator == "sam" ); - BOOST_REQUIRE( exp_obj->get_vesting() == sam_vest ); - BOOST_REQUIRE( exp_obj->expiration == db->head_block_time() + gpo.delegation_return_period ); - BOOST_REQUIRE( db->get_account( "sam" ).get_delegated_vesting() == sam_vest ); - BOOST_REQUIRE( db->get_account( "dave" ).get_received_vesting() == ASSET( "0.000000 VESTS" ) ); - delegation = db->find< vesting_delegation_object, by_delegation >( boost::make_tuple( op.delegator, op.delegatee ) ); - BOOST_REQUIRE( delegation == nullptr ); - - old_sam_manabar.regenerate_mana( sam_params, db->head_block_time() ); - sam_params.max_mana /= 4; - old_sam_downvote_manabar.regenerate_mana( sam_params, db->head_block_time() ); - - old_dave_manabar.regenerate_mana( dave_params, db->head_block_time() ); - dave_params.max_mana /= 4; - old_dave_downvote_manabar.regenerate_mana( dave_params, db->head_block_time() ); - - BOOST_REQUIRE( VOTING_MANABAR( "sam" ).current_mana == old_sam_manabar.current_mana ); - BOOST_REQUIRE( DOWNVOTE_MANABAR( "sam" ).current_mana == old_sam_downvote_manabar.current_mana ); - BOOST_REQUIRE( VOTING_MANABAR( "dave" ).current_mana == old_dave_manabar.current_mana - sam_vest.amount.value ); - BOOST_REQUIRE( DOWNVOTE_MANABAR( "dave" ).current_mana == old_dave_downvote_manabar.current_mana - sam_vest.amount.value / 4 ); - - old_sam_manabar = VOTING_MANABAR( "sam" ); - old_sam_downvote_manabar = DOWNVOTE_MANABAR( "sam" ); - old_dave_manabar = VOTING_MANABAR( "dave" ); - old_dave_downvote_manabar = DOWNVOTE_MANABAR( "dave" ); - - sam_params.max_mana = util::get_effective_vesting_shares( db->get_account( "sam" ) ); - dave_params.max_mana = util::get_effective_vesting_shares( db->get_account( "dave" ) ); - - generate_blocks( exp_obj->expiration + HIVE_BLOCK_INTERVAL ); - - old_sam_manabar.regenerate_mana( sam_params, db->head_block_time() ); - sam_params.max_mana /= 4; - old_sam_downvote_manabar.regenerate_mana( sam_params, db->head_block_time() ); - - old_dave_manabar.regenerate_mana( dave_params, db->head_block_time() ); - dave_params.max_mana /= 4; - old_dave_downvote_manabar.regenerate_mana( dave_params, db->head_block_time() ); - - exp_obj = db->get_index< vesting_delegation_expiration_index, by_id >().begin(); - end = db->get_index< vesting_delegation_expiration_index, by_id >().end(); - - BOOST_REQUIRE( exp_obj == end ); - BOOST_REQUIRE( db->get_account( "sam" ).get_delegated_vesting() == ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( VOTING_MANABAR( "sam" ).current_mana == old_sam_manabar.current_mana + sam_vest.amount.value ); - BOOST_REQUIRE( DOWNVOTE_MANABAR( "sam" ).current_mana == old_sam_downvote_manabar.current_mana + sam_vest.amount.value / 4 ); - BOOST_REQUIRE( VOTING_MANABAR( "dave" ).current_mana == old_dave_manabar.current_mana ); - BOOST_REQUIRE( DOWNVOTE_MANABAR( "dave" ).current_mana == old_dave_downvote_manabar.current_mana ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( issue_971_vesting_removal ) -{ - // This is a regression test specifically for issue #971 - try - { - BOOST_TEST_MESSAGE( "Test Issue 971 Vesting Removal" ); - ACTORS( (alice)(bob) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& w ) - { - w.median_props.account_creation_fee = ASSET( "1.000 TESTS" ); - }); - }); - - generate_block(); - - signed_transaction tx; - delegate_vesting_shares_operation op; - op.vesting_shares = ASSET( "10000000.000000 VESTS"); - op.delegator = "alice"; - op.delegatee = "bob"; - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_block(); - const account_object& alice_acc = db->get_account( "alice" ); - const account_object& bob_acc = db->get_account( "bob" ); - - BOOST_REQUIRE( alice_acc.get_delegated_vesting() == ASSET( "10000000.000000 VESTS")); - BOOST_REQUIRE( bob_acc.get_received_vesting() == ASSET( "10000000.000000 VESTS")); - - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& w ) - { - w.median_props.account_creation_fee = ASSET( "100.000 TESTS" ); - }); - }); - - generate_block(); - - op.vesting_shares = ASSET( "0.000000 VESTS" ); - - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_block(); - - BOOST_REQUIRE( alice_acc.get_delegated_vesting() == ASSET( "10000000.000000 VESTS")); - BOOST_REQUIRE( bob_acc.get_received_vesting() == ASSET( "0.000000 VESTS")); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_beneficiaries_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Test Comment Beneficiaries Validate" ); - comment_options_operation op; - - op.author = "alice"; - op.permlink = "test"; - - BOOST_TEST_MESSAGE( "--- Testing more than 100% weight on a single route" ); - comment_payout_beneficiaries b; - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "bob" ), HIVE_100_PERCENT + 1 ) ); - op.extensions.insert( b ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing more than 100% total weight" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "bob" ), HIVE_1_PERCENT * 75 ) ); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "sam" ), HIVE_1_PERCENT * 75 ) ); - op.extensions.clear(); - op.extensions.insert( b ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing maximum number of routes" ); - b.beneficiaries.clear(); - for( size_t i = 0; i < 127; i++ ) - { - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "foo" + fc::to_string( i ) ), 1 ) ); - } - - op.extensions.clear(); - std::sort( b.beneficiaries.begin(), b.beneficiaries.end() ); - op.extensions.insert( b ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Testing one too many routes" ); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "bar" ), 1 ) ); - std::sort( b.beneficiaries.begin(), b.beneficiaries.end() ); - op.extensions.clear(); - op.extensions.insert( b ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Testing duplicate accounts" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( "bob", HIVE_1_PERCENT * 2 ) ); - b.beneficiaries.push_back( beneficiary_route_type( "bob", HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing incorrect account sort order" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( "bob", HIVE_1_PERCENT ) ); - b.beneficiaries.push_back( beneficiary_route_type( "alice", HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing correct account sort order" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( "alice", HIVE_1_PERCENT ) ); - b.beneficiaries.push_back( beneficiary_route_type( "bob", HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_beneficiaries_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Test Comment Beneficiaries" ); - ACTORS( (alice)(bob)(sam)(dave) ) - generate_block(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [=]( dynamic_global_property_object& gpo ) - { - gpo.sps_fund_percent = 0; - }); - - db.modify( db.get_treasury(), [=]( account_object& a ) - { - a.hbd_balance.amount.value = 0; - }); - }); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - comment_operation comment; - vote_operation vote; - comment_options_operation op; - comment_payout_beneficiaries b; - signed_transaction tx; - - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "foobar"; - - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MIN_TRANSACTION_EXPIRATION_LIMIT ); - sign( tx, alice_private_key ); - db->push_transaction( tx ); - - BOOST_TEST_MESSAGE( "--- Test failure on more than 8 benefactors" ); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "bob" ), HIVE_1_PERCENT ) ); - - for( size_t i = 0; i < 8; i++ ) - { - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( HIVE_INIT_MINER_NAME + fc::to_string( i ) ), HIVE_1_PERCENT ) ); - } - - op.author = "alice"; - op.permlink = "test"; - op.allow_curation_rewards = false; - op.extensions.insert( b ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), chain::plugin_exception ); - - - BOOST_TEST_MESSAGE( "--- Test specifying a non-existent benefactor" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "doug" ), HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test setting when comment has been voted on" ); - vote.author = "alice"; - vote.permlink = "test"; - vote.voter = "bob"; - vote.weight = HIVE_100_PERCENT; - - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "bob" ), 25 * HIVE_1_PERCENT ) ); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( db->get_treasury_name() ), 10 * HIVE_1_PERCENT ) ); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "sam" ), 50 * HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - - tx.clear(); - tx.operations.push_back( vote ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test success" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx ); - - - BOOST_TEST_MESSAGE( "--- Test setting when there are already beneficiaries" ); - b.beneficiaries.clear(); - b.beneficiaries.push_back( beneficiary_route_type( account_name_type( "dave" ), 25 * HIVE_1_PERCENT ) ); - op.extensions.clear(); - op.extensions.insert( b ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Payout and verify rewards were split properly" ); - tx.clear(); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time - HIVE_BLOCK_INTERVAL ); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [=]( dynamic_global_property_object& gpo ) - { - gpo.current_supply -= gpo.get_total_reward_fund_hive(); - gpo.total_reward_fund_hive = ASSET( "100.000 TESTS" ); - gpo.current_supply += gpo.get_total_reward_fund_hive(); - }); - }); - - generate_block(); - - //note: below we are mixing HIVE and HBD but it works due to use of amount instead of whole asset plus the exchange rate is 1-1 - const comment_object& _comment = db->get_comment( "alice", string( "test" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - - BOOST_REQUIRE( ( get_hbd_rewards( "alice" ).amount + get_vest_rewards_as_hive( "alice" ).amount + db->get_treasury().get_hbd_balance().amount ) == get_vest_rewards_as_hive( "bob" ).amount + get_hbd_rewards( "bob" ).amount + 1 ); - BOOST_REQUIRE( ( get_hbd_rewards( "alice" ).amount + get_vest_rewards_as_hive( "alice" ).amount + db->get_treasury().get_hbd_balance().amount ) == ( get_vest_rewards_as_hive( "sam" ).amount + get_hbd_rewards( "sam" ).amount ) / 2 + 1 ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "bob" ).amount == get_hbd_rewards( "bob" ).amount + 1 ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "sam" ).amount == get_hbd_rewards( "sam" ).amount + 1 ); - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_set_properties_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: witness_set_properties_validate" ); - - ACTORS( (alice) ) - fund( "alice", 10000 ); - private_key_type signing_key = generate_private_key( "old_key" ); - - witness_update_operation op; - op.owner = "alice"; - op.url = "foo.bar"; - op.fee = ASSET( "1.000 TESTS" ); - op.block_signing_key = signing_key.get_public_key(); - op.props.account_creation_fee = legacy_hive_asset::from_asset( asset(HIVE_MIN_ACCOUNT_CREATION_FEE + 10, HIVE_SYMBOL) ); - op.props.maximum_block_size = HIVE_MIN_BLOCK_SIZE_LIMIT + 100; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - generate_block(); - - BOOST_TEST_MESSAGE( "--- failure when signing key is not present" ); - witness_set_properties_operation prop_op; - prop_op.owner = "alice"; - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- success when signing key is present" ); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- failure when setting account_creation_fee with incorrect symbol" ); - prop_op.props[ "account_creation_fee" ] = fc::raw::pack_to_vector( ASSET( "2.000 TBD" ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting maximum_block_size below HIVE_MIN_BLOCK_SIZE_LIMIT" ); - prop_op.props.erase( "account_creation_fee" ); - prop_op.props[ "maximum_block_size" ] = fc::raw::pack_to_vector( HIVE_MIN_BLOCK_SIZE_LIMIT - 1 ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting hbd_interest_rate with negative number" ); - prop_op.props.erase( "maximum_block_size" ); - prop_op.props[ "sbd_interest_rate" ] = fc::raw::pack_to_vector( -700 ); - //ABW: works also with outdated "sbd_interest_rate" instead of "hbd_interest_rate" - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting hbd_interest_rate to HIVE_100_PERCENT + 1" ); - prop_op.props.erase( "sbd_interest_rate" ); - prop_op.props[ "hbd_interest_rate" ] = fc::raw::pack_to_vector( HIVE_100_PERCENT + 1 ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting new hbd_exchange_rate with HBD / HIVE" ); - prop_op.props.erase( "hbd_interest_rate" ); - prop_op.props[ "sbd_exchange_rate" ] = fc::raw::pack_to_vector( price( ASSET( "1.000 TESTS" ), ASSET( "10.000 TBD" ) ) ); - //ABW: works also with outdated "sbd_exchange_rate" instead of "hbd_exchange_rate" - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting new url with length of zero" ); - prop_op.props.erase( "sbd_exchange_rate" ); - prop_op.props[ "url" ] = fc::raw::pack_to_vector( "" ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when setting new url with non UTF-8 character" ); - prop_op.props[ "url" ].clear(); - prop_op.props[ "url" ] = fc::raw::pack_to_vector( "\xE0\x80\x80" ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- success when account subsidy rate is reasonable" ); - prop_op.props.clear(); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( 5000 ) ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- failure when budget is zero" ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( 0 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when budget is negative" ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( -5000 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- success when budget is just under too big" ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( 268435455 ) ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- failure when account subsidy budget is just a little too big" ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( 268435456 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when account subsidy budget is enormous" ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( int32_t( 0x50000000 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- success when account subsidy decay is reasonable" ); - prop_op.props.clear(); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( 300000 ) ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- failure when account subsidy decay is zero" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( 0 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- failure when account subsidy decay is very small" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( 40 ) ); - HIVE_REQUIRE_THROW( prop_op.validate(), fc::assert_exception ); - - uint64_t unit = uint64_t(1) << HIVE_RD_DECAY_DENOM_SHIFT; - - BOOST_TEST_MESSAGE( "--- success when account subsidy decay is one year" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( unit / HIVE_BLOCKS_PER_YEAR ) ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- success when account subsidy decay is one day" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( unit / HIVE_BLOCKS_PER_DAY ) ); - prop_op.validate(); - - BOOST_TEST_MESSAGE( "--- success when account subsidy decay is one hour" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( uint32_t( unit / ((60*60)/HIVE_BLOCK_INTERVAL) ) ); - prop_op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_set_properties_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: witness_set_properties_authorities" ); - - witness_set_properties_operation op; - op.owner = "alice"; - op.props[ "key" ] = fc::raw::pack_to_vector( generate_private_key( "key" ).get_public_key() ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - vector< authority > key_auths; - vector< authority > expected_keys; - expected_keys.push_back( authority( 1, generate_private_key( "key" ).get_public_key(), 1 ) ); - op.get_required_authorities( key_auths ); - BOOST_REQUIRE( key_auths == expected_keys ); - - op.props.erase( "key" ); - key_auths.clear(); - expected_keys.clear(); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected_keys.push_back( authority( 1, HIVE_NULL_ACCOUNT, 1 ) ); - op.get_required_authorities( key_auths ); - BOOST_REQUIRE( key_auths == expected_keys ); - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( witness_set_properties_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: witness_set_properties_apply" ); - - ACTORS( (alice) ) - fund( "alice", 10000 ); - private_key_type signing_key = generate_private_key( "old_key" ); - - witness_update_operation op; - op.owner = "alice"; - op.url = "foo.bar"; - op.fee = ASSET( "1.000 TESTS" ); - op.block_signing_key = signing_key.get_public_key(); - op.props.account_creation_fee = legacy_hive_asset::from_asset( asset(HIVE_MIN_ACCOUNT_CREATION_FEE + 10, HIVE_SYMBOL) ); - op.props.maximum_block_size = HIVE_MIN_BLOCK_SIZE_LIMIT + 100; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test setting runtime parameters" ); - - // Setting account_creation_fee - const witness_object& alice_witness = db->get_witness( "alice" ); - witness_set_properties_operation prop_op; - prop_op.owner = "alice"; - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.props[ "account_creation_fee" ] = fc::raw::pack_to_vector( ASSET( "2.000 TESTS" ) ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.props.account_creation_fee == ASSET( "2.000 TESTS" ) ); - - // Setting maximum_block_size - prop_op.props.erase( "account_creation_fee" ); - prop_op.props[ "maximum_block_size" ] = fc::raw::pack_to_vector( HIVE_MIN_BLOCK_SIZE_LIMIT + 1 ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.props.maximum_block_size == HIVE_MIN_BLOCK_SIZE_LIMIT + 1 ); - - // Setting hbd_interest_rate - prop_op.props.erase( "maximum_block_size" ); - prop_op.props[ "hbd_interest_rate" ] = fc::raw::pack_to_vector( 700 ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.props.hbd_interest_rate == 700 ); - - // Setting new signing_key - private_key_type old_signing_key = signing_key; - signing_key = generate_private_key( "new_key" ); - public_key_type alice_pub = signing_key.get_public_key(); - prop_op.props.erase( "hbd_interest_rate" ); - prop_op.props[ "new_signing_key" ] = fc::raw::pack_to_vector( alice_pub ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, old_signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.signing_key == alice_pub ); - - // Setting new hbd_exchange_rate - prop_op.props.erase( "new_signing_key" ); - prop_op.props[ "key" ].clear(); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.props[ "sbd_exchange_rate" ] = fc::raw::pack_to_vector( price( ASSET(" 1.000 TBD" ), ASSET( "100.000 TESTS" ) ) ); - //ABW: works also with outdated "sbd_exchange_rate" instead of "hbd_exchange_rate" - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.get_hbd_exchange_rate() == price( ASSET( "1.000 TBD" ), ASSET( "100.000 TESTS" ) ) ); - BOOST_REQUIRE( alice_witness.get_last_hbd_exchange_update() == db->head_block_time() ); - - // Setting new url - prop_op.props.erase( "sbd_exchange_rate" ); - prop_op.props[ "url" ] = fc::raw::pack_to_vector( "foo.bar" ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.url == "foo.bar" ); - - // Setting new extranious_property - prop_op.props[ "extraneous_property" ] = fc::raw::pack_to_vector( "foo" ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Testing failure when 'key' does not match witness signing key" ); - prop_op.props.erase( "extranious_property" ); - prop_op.props[ "key" ].clear(); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( old_signing_key.get_public_key() ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, old_signing_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Testing setting account subsidy rate" ); - prop_op.props[ "key" ].clear(); - prop_op.props[ "key" ] = fc::raw::pack_to_vector( signing_key.get_public_key() ); - prop_op.props[ "account_subsidy_budget" ] = fc::raw::pack_to_vector( HIVE_ACCOUNT_SUBSIDY_PRECISION ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.props.account_subsidy_budget == HIVE_ACCOUNT_SUBSIDY_PRECISION ); - - BOOST_TEST_MESSAGE( "--- Testing setting account subsidy pool cap" ); - uint64_t day_decay = ( uint64_t(1) << HIVE_RD_DECAY_DENOM_SHIFT ) / HIVE_BLOCKS_PER_DAY; - prop_op.props.erase( "account_subsidy_decay" ); - prop_op.props[ "account_subsidy_decay" ] = fc::raw::pack_to_vector( day_decay ); - tx.clear(); - tx.operations.push_back( prop_op ); - sign( tx, signing_key ); - db->push_transaction( tx, 0 ); - BOOST_REQUIRE( alice_witness.props.account_subsidy_decay == day_decay ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_account_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: claim_account_validate" ); - - claim_account_operation op; - op.creator = "alice"; - op.fee = ASSET( "1.000 TESTS" ); - - BOOST_TEST_MESSAGE( "--- Test failure with invalid account name" ); - op.creator = "aA0"; - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test failure with invalid fee symbol" ); - op.creator = "alice"; - op.fee = ASSET( "1.000 TBD" ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test failure with negative fee" ); - op.fee = ASSET( "-1.000 TESTS" ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test failure with non-zero extensions" ); - op.fee = ASSET( "1.000 TESTS" ); - op.extensions.insert( future_extensions( void_t() ) ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test success" ); - op.extensions.clear(); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_account_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: claim_account_authorities" ); - - claim_account_operation op; - op.creator = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_account_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: claim_account_apply" ); - ACTORS( (alice) ) - generate_block(); - - fund( "alice", ASSET( "20.000 TESTS" ) ); - generate_block(); - - auto set_subsidy_budget = [&]( int32_t budget, uint32_t decay ) - { - flat_map< string, vector<char> > props; - props["account_subsidy_budget"] = fc::raw::pack_to_vector( budget ); - props["account_subsidy_decay"] = fc::raw::pack_to_vector( decay ); - set_witness_props( props ); - }; - - auto get_subsidy_pools = [&]( int64_t& con_subs, int64_t &ncon_subs ) - { - // get consensus and non-consensus subsidies - con_subs = db->get_dynamic_global_properties().available_account_subsidies; - ncon_subs = db->get< plugins::rc::rc_pool_object >().pool_array[ plugins::rc::resource_new_accounts ]; - }; - - // set_subsidy_budget creates a lot of blocks, so there should be enough for a few accounts - // half-life of 10 minutes - set_subsidy_budget( 5000, 249617279 ); - - // generate a half hour worth of blocks to warm up the per-witness pools, etc. - generate_blocks( HIVE_BLOCKS_PER_HOUR / 2 ); - - signed_transaction tx; - claim_account_operation op; - - BOOST_TEST_MESSAGE( "--- Test failure when creator cannot cover fee" ); - op.creator = "alice"; - op.fee = ASSET( "30.000 TESTS" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test success claiming an account" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_witness_schedule_object(), [&]( witness_schedule_object& wso ) - { - wso.median_props.account_creation_fee = ASSET( "5.000 TESTS" ); - }); - }); - generate_block(); - - int64_t prev_c_subs = 0, prev_nc_subs = 0, - c_subs = 0, nc_subs = 0; - - get_subsidy_pools( prev_c_subs, prev_nc_subs ); - op.fee = ASSET( "5.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - get_subsidy_pools( c_subs, nc_subs ); - - BOOST_REQUIRE( db->get_account( "alice" ).pending_claimed_accounts == 1 ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "15.000 TESTS" ) ); - BOOST_REQUIRE( get_balance( HIVE_NULL_ACCOUNT ) == ASSET( "5.000 TESTS" ) ); - BOOST_CHECK_EQUAL( c_subs, prev_c_subs ); - BOOST_CHECK_EQUAL( nc_subs, prev_nc_subs ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test claiming from a non-existent account" ); - op.creator = "bob"; - tx.clear(); - tx.operations.push_back( op ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test failure claiming account with an excess fee" ); - generate_block(); - op.creator = "alice"; - op.fee = ASSET( "10.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test success claiming a second account" ); - generate_block(); - get_subsidy_pools( prev_c_subs, prev_nc_subs ); - op.fee = ASSET( "5.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - get_subsidy_pools( c_subs, nc_subs ); - - BOOST_REQUIRE( db->get_account( "alice" ).pending_claimed_accounts == 2 ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( c_subs == prev_c_subs ); - BOOST_REQUIRE( nc_subs == prev_nc_subs ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test success claiming a subsidized account" ); - generate_block(); // Put all previous test transactions into a block - - while( true ) - { - account_name_type next_witness = db->get_scheduled_witness( 1 ); - if( db->get_witness( next_witness ).schedule == witness_object::elected ) - break; - generate_block(); - } - - get_subsidy_pools( prev_c_subs, prev_nc_subs ); - op.creator = "alice"; - op.fee = ASSET( "0.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - ilog( "Pushing transaction: ${t}", ("t", tx) ); - db->push_transaction( tx, 0 ); - get_subsidy_pools( c_subs, nc_subs ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 3 ); - BOOST_CHECK( get_balance( "alice" ) == ASSET( "10.000 TESTS" ) ); - // Non-consensus isn't updated until end of block - BOOST_CHECK_EQUAL( c_subs, prev_c_subs - HIVE_ACCOUNT_SUBSIDY_PRECISION ); - BOOST_CHECK_EQUAL( nc_subs, prev_nc_subs ); - - generate_block(); - - // RC update at the end of the block - get_subsidy_pools( c_subs, nc_subs ); - block_id_type hbid = db->head_block_id(); - optional<signed_block> block = db->fetch_block_by_id(hbid); - BOOST_REQUIRE( block.valid() ); - BOOST_CHECK_EQUAL( block->transactions.size(), 1 ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 3 ); - - int64_t new_value = prev_c_subs - HIVE_ACCOUNT_SUBSIDY_PRECISION; // Usage applied before decay - new_value = new_value - + 5000 // Budget - - ((new_value*249617279) >> HIVE_RD_DECAY_DENOM_SHIFT); // Decay - - BOOST_CHECK_EQUAL( c_subs, new_value ); - BOOST_CHECK_EQUAL( nc_subs, new_value ); - - BOOST_TEST_MESSAGE( "--- Test failure claiming a partial subsidized account" ); - op.fee = ASSET( "2.500 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test failure with no available subsidized accounts" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.available_account_subsidies = 0; - }); - }); - generate_block(); - op.fee = ASSET( "0.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - - BOOST_TEST_MESSAGE( "--- Test failure on claim overflow" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "alice" ), [&]( account_object& a ) - { - a.pending_claimed_accounts = std::numeric_limits< int64_t >::max(); - }); - }); - generate_block(); - - op.fee = ASSET( "5.000 TESTS" ); - tx.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_claimed_account_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create_claimed_account_validate" ); - - private_key_type priv_key = generate_private_key( "alice" ); - - create_claimed_account_operation op; - op.creator = "alice"; - op.new_account_name = "bob"; - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - op.active = authority( 1, priv_key.get_public_key(), 1 ); - op.posting = authority( 1, priv_key.get_public_key(), 1 ); - op.memo_key = priv_key.get_public_key(); - - BOOST_TEST_MESSAGE( "--- Test invalid creator name" ); - op.creator = "aA0"; - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test invalid new account name" ); - op.creator = "alice"; - op.new_account_name = "aA0"; - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test invalid account name in owner authority" ); - op.new_account_name = "bob"; - op.owner = authority( 1, "aA0", 1 ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test invalid account name in active authority" ); - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - op.active = authority( 1, "aA0", 1 ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test invalid account name in posting authority" ); - op.active = authority( 1, priv_key.get_public_key(), 1 ); - op.posting = authority( 1, "aA0", 1 ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test invalid JSON metadata" ); - op.posting = authority( 1, priv_key.get_public_key(), 1 ); - op.json_metadata = "{\"foo\",\"bar\"}"; - BOOST_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test non UTF-8 JSON metadata" ); - op.json_metadata = "{\"foo\":\"\xa0\xa1\"}"; - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test failure with non-zero extensions" ); - op.json_metadata = ""; - op.extensions.insert( future_extensions( void_t() ) ); - BOOST_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Test success" ); - op.extensions.clear(); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_claimed_account_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create_claimed_account_authorities" ); - - create_claimed_account_operation op; - op.creator = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_claimed_account_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create_claimed_account_apply" ); - - ACTORS( (alice) ) - vest( HIVE_INIT_MINER_NAME, HIVE_TEMP_ACCOUNT, ASSET( "10.000 TESTS" ) ); - generate_block(); - - signed_transaction tx; - create_claimed_account_operation op; - private_key_type priv_key = generate_private_key( "bob" ); - - BOOST_TEST_MESSAGE( "--- Test failure when creator has not claimed an account" ); - op.creator = "alice"; - op.new_account_name = "bob"; - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - op.active = authority( 2, priv_key.get_public_key(), 2 ); - op.posting = authority( 3, priv_key.get_public_key(), 3 ); - op.memo_key = priv_key.get_public_key(); - op.json_metadata = "{\"foo\":\"bar\"}"; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure creating account with non-existent account auth" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "alice" ), [&]( account_object& a ) - { - a.pending_claimed_accounts = 2; - }); - }); - generate_block(); - op.owner = authority( 1, "bob", 1 ); - tx.clear(); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test success creating claimed account" ); - op.owner = authority( 1, priv_key.get_public_key(), 1 ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const auto& bob = db->get_account( "bob" ); - const auto& bob_auth = db->get< account_authority_object, by_account >( "bob" ); - - BOOST_REQUIRE( bob.name == "bob" ); - BOOST_REQUIRE( bob_auth.owner == authority( 1, priv_key.get_public_key(), 1 ) ); - BOOST_REQUIRE( bob_auth.active == authority( 2, priv_key.get_public_key(), 2 ) ); - BOOST_REQUIRE( bob_auth.posting == authority( 3, priv_key.get_public_key(), 3 ) ); - BOOST_REQUIRE( bob.memo_key == priv_key.get_public_key() ); -#ifndef IS_LOW_MEM // json_metadata is not stored on low memory nodes - const auto& bob_meta = db->get< account_metadata_object, by_account >( bob.get_id() ); - BOOST_REQUIRE( bob_meta.json_metadata == "{\"foo\":\"bar\"}" ); -#endif - BOOST_REQUIRE( bob.proxy == "" ); - BOOST_REQUIRE( bob.recovery_account == "alice" ); - BOOST_REQUIRE( bob.created == db->head_block_time() ); - BOOST_REQUIRE( bob.get_balance().amount.value == ASSET( "0.000 TESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_hbd_balance().amount.value == ASSET( "0.000 TBD" ).amount.value ); - BOOST_REQUIRE( bob.get_vesting().amount.value == ASSET( "0.000000 VESTS" ).amount.value ); - BOOST_REQUIRE( bob.get_id().get_value() == bob_auth.get_id().get_value() ); - - BOOST_REQUIRE( db->get_account( "alice" ).pending_claimed_accounts == 1 ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test failure creating duplicate account name" ); - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - BOOST_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test account creation with temp account does not set recovery account" ); - generate_block(); - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( HIVE_TEMP_ACCOUNT ), [&]( account_object& a ) - { - a.pending_claimed_accounts = 1; - }); - }); - generate_block(); - op.creator = HIVE_TEMP_ACCOUNT; - op.new_account_name = "charlie"; - tx.clear(); - tx.operations.push_back( op ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_account( "charlie" ).recovery_account == account_name_type() ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_auth_tests ) -{ - try - { - ACTORS( (alice)(bob)(charlie) ) - generate_block(); - - fund( "alice", ASSET( "20.000 TESTS" ) ); - fund( "bob", ASSET( "20.000 TESTS" ) ); - fund( "charlie", ASSET( "20.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "alice" , ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob" , ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "charlie" , ASSET( "10.000 TESTS" ) ); - generate_block(); - - private_key_type bob_active_private_key = bob_private_key; - private_key_type bob_posting_private_key = generate_private_key( "bob_posting" ); - private_key_type charlie_active_private_key = charlie_private_key; - private_key_type charlie_posting_private_key = generate_private_key( "charlie_posting" ); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get< account_authority_object, by_account >( "alice"), [&]( account_authority_object& auth ) - { - auth.active.add_authority( "bob", 1 ); - auth.posting.add_authority( "charlie", 1 ); - }); - - db.modify( db.get< account_authority_object, by_account >( "bob" ), [&]( account_authority_object& auth ) - { - auth.posting = authority( 1, bob_posting_private_key.get_public_key(), 1 ); - }); - - db.modify( db.get< account_authority_object, by_account >( "charlie" ), [&]( account_authority_object& auth ) - { - auth.posting = authority( 1, charlie_posting_private_key.get_public_key(), 1 ); - }); - }); - - generate_block(); - - signed_transaction tx; - transfer_operation transfer; - - transfer.from = "alice"; - transfer.to = "bob"; - transfer.amount = ASSET( "1.000 TESTS" ); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, bob_active_private_key ); - db->push_transaction( tx, 0 ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, bob_posting_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, charlie_active_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, charlie_posting_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_active_auth ); - - custom_json_operation json; - json.required_posting_auths.insert( "alice" ); - json.json = "{\"foo\":\"bar\"}"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( json ); - sign( tx, bob_active_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_posting_auth ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, bob_posting_private_key ); - db->push_transaction( tx, 0 ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, charlie_active_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), tx_missing_posting_auth ); - - generate_block(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.signatures.clear(); - sign( tx, charlie_posting_private_key ); - db->push_transaction( tx, 0 ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update2_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update2_validate" ); - - BOOST_TEST_MESSAGE( " -- Testing failure when account name is not valid" ); - account_update2_operation op; - op.account = "invalid_account"; - - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Testing failure when json_metadata is not json" ); - op.account = "alice"; - op.json_metadata = "not json"; - - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Testing failure when posting_json_metadata is not json" ); - op.json_metadata.clear(); - op.posting_json_metadata = "not json"; - - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.posting_json_metadata.clear(); - - op.json_metadata = "{\"success\":true}"; - op.posting_json_metadata = "{\"success\":true}"; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update2_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update2_authorities" ); - - BOOST_TEST_MESSAGE( " -- Testing account only case" ); - account_update2_operation op; - op.account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing owner case" ); - op.account = "alice"; - op.owner = authority(); - - expected.insert( "alice" ); - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing active case" ); - op = account_update2_operation(); - op.account = "alice"; - op.active = authority(); - op.active->weight_threshold = 1; - op.active->add_authorities( "alice", 1 ); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing posting case" ); - op = account_update2_operation(); - op.account = "alice"; - op.posting = authority(); - op.posting->weight_threshold = 1; - op.posting->add_authorities( "alice", 1 ); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing memo_key case" ); - op = account_update2_operation(); - op.account = "alice"; - op.memo_key = public_key_type(); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing json_metadata case" ); - op = account_update2_operation(); - op.account = "alice"; - op.json_metadata = "{\"success\":true}"; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing posting_json_metadata case" ); - op = account_update2_operation(); - op.account = "alice"; - op.posting_json_metadata = "{\"success\":true}"; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - expected.clear(); - auths.clear(); - - BOOST_TEST_MESSAGE( " -- Testing full operation cases" ); - - op = account_update2_operation(); - op.account = "alice"; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.posting_json_metadata = "{\"success\":true}"; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.json_metadata = "{\"success\":true}"; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.memo_key = public_key_type(); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.posting = authority(); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.active = authority(); - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.owner = authority(); - - expected.insert( "alice" ); - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - auths.clear(); - expected.clear(); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_update2_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_update2_apply" ); - - ACTORS( (alice)(sam) ) - private_key_type new_private_key = generate_private_key( "new_key" ); - - BOOST_TEST_MESSAGE( "--- Test normal update" ); - - account_update2_operation op; - op.account = "alice"; - op.owner = authority( 1, new_private_key.get_public_key(), 1 ); - op.active = authority( 2, new_private_key.get_public_key(), 2 ); - op.memo_key = new_private_key.get_public_key(); - op.json_metadata = "{\"bar\":\"foo\"}"; - op.posting_json_metadata = "{\"success\":true}"; - - signed_transaction tx; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const account_object& acct = db->get_account( "alice" ); - const account_authority_object& acct_auth = db->get< account_authority_object, by_account >( "alice" ); - - BOOST_REQUIRE( acct.name == "alice" ); - BOOST_REQUIRE( acct_auth.owner == authority( 1, new_private_key.get_public_key(), 1 ) ); - BOOST_REQUIRE( acct_auth.active == authority( 2, new_private_key.get_public_key(), 2 ) ); - BOOST_REQUIRE( acct.memo_key == new_private_key.get_public_key() ); - -#ifndef IS_LOW_MEM - const account_metadata_object& acct_metadata = db->get< account_metadata_object, by_account >( acct.get_id() ); - BOOST_REQUIRE( acct_metadata.json_metadata == "{\"bar\":\"foo\"}" ); - BOOST_REQUIRE( acct_metadata.posting_json_metadata == "{\"success\":true}" ); -#endif - - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when updating a non-existent account" ); - tx.operations.clear(); - tx.signatures.clear(); - op.account = "bob"; - tx.operations.push_back( op ); - sign( tx, new_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ) - validate_database(); - - - BOOST_TEST_MESSAGE( "--- Test failure when account authority does not exist" ); - tx.clear(); - op = account_update2_operation(); - op.account = "alice"; - op.posting = authority(); - op.posting->weight_threshold = 1; - op.posting->add_authorities( "dave", 1 ); - tx.operations.push_back( op ); - sign( tx, new_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/operation_time_tests.cpp b/tests2/unit/tests/operation_time_tests.cpp deleted file mode 100644 index 2f10111e05422edf4da47c2d858d68fc8ca9c349..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/operation_time_tests.cpp +++ /dev/null @@ -1,3109 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/block_summary_object.hpp> -#include <hive/chain/database.hpp> -#include <hive/chain/history_object.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <hive/plugins/debug_node/debug_node_plugin.hpp> -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> - -using namespace hive; -using namespace hive::chain; -using namespace hive::chain::util; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( operation_time_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( comment_payout_equalize ) -{ - try - { - ACTORS( (alice)(bob)(dave) - (ulysses)(vivian)(wendy) ) - - struct author_actor - { - author_actor( - const std::string& n, - fc::ecc::private_key pk, - fc::optional<asset> mpay = fc::optional<asset>() ) - : name(n), private_key(pk), max_accepted_payout(mpay) {} - std::string name; - fc::ecc::private_key private_key; - fc::optional< asset > max_accepted_payout; - }; - - struct voter_actor - { - voter_actor( const std::string& n, fc::ecc::private_key pk, std::string fa ) - : name(n), private_key(pk), favorite_author(fa) {} - std::string name; - fc::ecc::private_key private_key; - std::string favorite_author; - }; - - - std::vector< author_actor > authors; - std::vector< voter_actor > voters; - - authors.emplace_back( "alice", alice_private_key ); - authors.emplace_back( "bob" , bob_private_key, ASSET( "0.000 TBD" ) ); - authors.emplace_back( "dave" , dave_private_key ); - voters.emplace_back( "ulysses", ulysses_private_key, "alice"); - voters.emplace_back( "vivian" , vivian_private_key , "bob" ); - voters.emplace_back( "wendy" , wendy_private_key , "dave" ); - - // A,B,D : posters - // U,V,W : voters - - // set a ridiculously high HIVE price ($1 / satoshi) to disable dust threshold - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "0.001 TESTS" ) ) ); - - for( const auto& voter : voters ) - { - fund( voter.name, 10000 ); - vest( voter.name, 10000 ); - } - - // authors all write in the same block, but Bob declines payout - for( const auto& author : authors ) - { - signed_transaction tx; - comment_operation com; - com.author = author.name; - com.permlink = "mypost"; - com.parent_author = HIVE_ROOT_POST_PARENT; - com.parent_permlink = "test"; - com.title = "Hello from "+author.name; - com.body = "Hello, my name is "+author.name; - tx.operations.push_back( com ); - - if( author.max_accepted_payout.valid() ) - { - comment_options_operation copt; - copt.author = com.author; - copt.permlink = com.permlink; - copt.max_accepted_payout = *(author.max_accepted_payout); - tx.operations.push_back( copt ); - } - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, author.private_key ); - db->push_transaction( tx, 0 ); - } - - generate_blocks(1); - - // voters all vote in the same block with the same stake - for( const auto& voter : voters ) - { - signed_transaction tx; - vote_operation vote; - vote.voter = voter.name; - vote.author = voter.favorite_author; - vote.permlink = "mypost"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter.private_key ); - db->push_transaction( tx, 0 ); - } - - //auto& reward_hive = db->get_dynamic_global_properties().get_total_reward_fund_hive(); - - // generate a few blocks to seed the reward fund - generate_blocks(10); - //const auto& rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - //idump( (rf) ); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "mypost" ) ) )->cashout_time, true ); - /* - for( const auto& author : authors ) - { - const account_object& a = db->get_account(author.name); - ilog( "${n} : ${hive} ${hbd}", ("n", author.name)("hive", a.get_rewards())("hbd", a.get_hbd_rewards()) ); - } - for( const auto& voter : voters ) - { - const account_object& a = db->get_account(voter.name); - ilog( "${n} : ${hive} ${hbd}", ("n", voter.name)("hive", a.get_rewards())("hbd", a.get_hbd_rewards()) ); - } - */ - - const account_object& alice_account = db->get_account("alice"); - const account_object& bob_account = db->get_account("bob"); - const account_object& dave_account = db->get_account("dave"); - - BOOST_CHECK( alice_account.get_hbd_rewards() == ASSET( "6236.000 TBD" ) ); - BOOST_CHECK( bob_account.get_hbd_rewards() == ASSET( "0.000 TBD" ) ); - BOOST_CHECK( dave_account.get_hbd_rewards() == alice_account.get_hbd_rewards() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_payout_dust ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: comment_payout_dust" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob", ASSET( "10.000 TESTS" ) ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - generate_block(); - validate_database(); - - comment_operation comment; - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "test"; - - signed_transaction tx; - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - comment.author = "bob"; - - tx.clear(); - tx.operations.push_back( comment ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - generate_blocks( db->head_block_time() + db->get_dynamic_global_properties().reverse_auction_seconds ); - - vote_operation vote; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = 81 * HIVE_1_PERCENT; - - tx.clear(); - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - vote.voter = "bob"; - vote.author = "bob"; - vote.weight = 59 * HIVE_1_PERCENT; - - tx.clear(); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time ); - - // If comments are paid out independent of order, then the last satoshi of HIVE cannot be divided among them - const auto& rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - BOOST_REQUIRE( rf.reward_balance == ASSET( "0.001 TESTS" ) ); - - validate_database(); - - BOOST_TEST_MESSAGE( "Done" ); - } - FC_LOG_AND_RETHROW() -} - -/* -BOOST_AUTO_TEST_CASE( reward_funds ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: reward_funds" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ) ); - generate_block(); - - comment_operation comment; - vote_operation vote; - signed_transaction tx; - - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "foo"; - comment.body = "bar"; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( 5 ); - - comment.author = "bob"; - comment.parent_author = "alice"; - vote.voter = "bob"; - vote.author = "bob"; - tx.clear(); - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->get_comment( "alice", string( "test" ) ).cashout_time ); - - { - const auto& post_rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - const auto& comment_rf = db->get< reward_fund_object, by_name >( HIVE_COMMENT_REWARD_FUND_NAME ); - - BOOST_REQUIRE( post_rf.reward_balance.amount == 0 ); - BOOST_REQUIRE( comment_rf.reward_balance.amount > 0 ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ).amount > 0 ); - BOOST_REQUIRE( get_hbd_rewards( "bob" ).amount == 0 ); - validate_database(); - } - - generate_blocks( db->get_comment( "bob", string( "test" ) ).cashout_time ); - - { - const auto& post_rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - const auto& comment_rf = db->get< reward_fund_object, by_name >( HIVE_COMMENT_REWARD_FUND_NAME ); - - BOOST_REQUIRE( post_rf.reward_balance.amount > 0 ); - BOOST_REQUIRE( comment_rf.reward_balance.amount == 0 ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ).amount > 0 ); - BOOST_REQUIRE( get_hbd_rewards( "bob" ).amount > 0 ); - validate_database(); - } - } - FC_LOG_AND_RETHROW() -} -*/ - -BOOST_AUTO_TEST_CASE( recent_claims_decay ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: recent_rshares_2decay" ); - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - comment_operation comment; - vote_operation vote; - signed_transaction tx; - - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "foo"; - comment.body = "bar"; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto alice_vshares = util::evaluate_reward_curve( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->net_rshares.value, - db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ).author_reward_curve, - db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ).content_constant ); - - generate_blocks( 5 ); - - comment.author = "bob"; - vote.voter = "bob"; - vote.author = "bob"; - tx.clear(); - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time ); - - { - const auto& post_rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - - BOOST_REQUIRE( post_rf.recent_claims == alice_vshares ); - validate_database(); - } - - auto bob_cashout_time = db->find_comment_cashout( db->get_comment( "bob", string( "test" ) ) )->cashout_time; - auto bob_vshares = util::evaluate_reward_curve( db->find_comment_cashout( db->get_comment( "bob", string( "test" ) ) )->net_rshares.value, - db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ).author_reward_curve, - db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ).content_constant ); - - generate_block(); - - while( db->head_block_time() < bob_cashout_time ) - { - alice_vshares -= ( alice_vshares * HIVE_BLOCK_INTERVAL ) / HIVE_RECENT_RSHARES_DECAY_TIME_HF19.to_seconds(); - const auto& post_rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - - BOOST_REQUIRE( post_rf.recent_claims == alice_vshares ); - - generate_block(); - - } - - { - alice_vshares -= ( alice_vshares * HIVE_BLOCK_INTERVAL ) / HIVE_RECENT_RSHARES_DECAY_TIME_HF19.to_seconds(); - const auto& post_rf = db->get< reward_fund_object, by_name >( HIVE_POST_REWARD_FUND_NAME ); - - BOOST_REQUIRE( post_rf.recent_claims == alice_vshares + bob_vshares ); - validate_database(); - } - } - FC_LOG_AND_RETHROW() -} - -/* -BOOST_AUTO_TEST_CASE( comment_payout ) -{ - try - { - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - vest( "alice", 10000 ); - fund( "bob", 7500 ); - vest( "bob", 7500 ); - fund( "sam", 8000 ); - vest( "sam", 8000 ); - fund( "dave", 5000 ); - vest( "dave", 5000 ); - - price exchange_rate( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - set_price_feed( exchange_rate ); - - signed_transaction tx; - - BOOST_TEST_MESSAGE( "Creating comments." ); - - comment_operation com; - com.author = "alice"; - com.permlink = "test"; - com.parent_author = ""; - com.parent_permlink = "test"; - com.title = "foo"; - com.body = "bar"; - tx.operations.push_back( com ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - com.author = "bob"; - tx.operations.push_back( com ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - BOOST_TEST_MESSAGE( "Voting for comments." ); - - vote_operation vote; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - vote.voter = "sam"; - vote.author = "alice"; - tx.operations.push_back( vote ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - vote.voter = "bob"; - vote.author = "bob"; - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - vote.voter = "dave"; - vote.author = "bob"; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Generate blocks up until first payout" ); - - //generate_blocks( db->get_comment( "bob", string( "test" ) ).cashout_time - HIVE_BLOCK_INTERVAL, true ); - - auto reward_hive = db->get_dynamic_global_properties().get_total_reward_fund_hive() + ASSET( "1.667 TESTS" ); - auto total_rshares2 = db->get_dynamic_global_properties().total_reward_shares2; - auto bob_comment_rshares = db->get_comment( "bob", string( "test" ) ).net_rshares; - auto bob_vest_shares = get_vesting( "bob" ); - auto bob_hbd_balance = get_hbd_balance( "bob" ); - - auto bob_comment_payout = asset( ( ( uint128_t( bob_comment_rshares.value ) * bob_comment_rshares.value * reward_hive.amount.value ) / total_rshares2 ).to_uint64(), HIVE_SYMBOL ); - auto bob_comment_discussion_rewards = asset( bob_comment_payout.amount / 4, HIVE_SYMBOL ); - bob_comment_payout -= bob_comment_discussion_rewards; - auto bob_comment_hbd_reward = db->to_hbd( asset( bob_comment_payout.amount / 2, HIVE_SYMBOL ) ); - auto bob_comment_vesting_reward = ( bob_comment_payout - asset( bob_comment_payout.amount / 2, HIVE_SYMBOL) ) * db->get_dynamic_global_properties().get_vesting_share_price(); - - BOOST_TEST_MESSAGE( "Cause first payout" ); - - generate_block(); - - BOOST_REQUIRE( db->get_dynamic_global_properties().get_total_reward_fund_hive() == reward_hive - bob_comment_payout ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).total_payout_value == bob_comment_vesting_reward * db->get_dynamic_global_properties().get_vesting_share_price() + bob_comment_hbd_reward * exchange_rate ); - BOOST_REQUIRE( get_vesting( "bob" ) == bob_vest_shares + bob_comment_vesting_reward ); - BOOST_REQUIRE( get_hbd_balance( "bob" ) == bob_hbd_balance + bob_comment_hbd_reward ); - - BOOST_TEST_MESSAGE( "Testing no payout when less than $0.02" ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "alice"; - vote.author = "alice"; - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "dave"; - vote.author = "bob"; - vote.weight = HIVE_1_PERCENT; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->get_comment( "bob", string( "test" ) ).cashout_time - HIVE_BLOCK_INTERVAL, true ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "bob"; - vote.author = "alice"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "sam"; - tx.operations.push_back( vote ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "dave"; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - bob_vest_shares = get_vesting( "bob" ); - bob_hbd_balance = get_hbd_balance( "bob" ); - - validate_database(); - - generate_block(); - - BOOST_REQUIRE( bob_vest_shares.amount.value == get_vesting( "bob" ).amount.value ); - BOOST_REQUIRE( bob_hbd_balance.amount.value == get_hbd_balance( "bob" ).amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -}*/ - -/* -BOOST_AUTO_TEST_CASE( comment_payout ) -{ - try - { - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - vest( "alice", 10000 ); - fund( "bob", 7500 ); - vest( "bob", 7500 ); - fund( "sam", 8000 ); - vest( "sam", 8000 ); - fund( "dave", 5000 ); - vest( "dave", 5000 ); - - price exchange_rate( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - set_price_feed( exchange_rate ); - - auto& gpo = db->get_dynamic_global_properties(); - - signed_transaction tx; - - BOOST_TEST_MESSAGE( "Creating comments. " ); - - comment_operation com; - com.author = "alice"; - com.permlink = "test"; - com.parent_permlink = "test"; - com.title = "foo"; - com.body = "bar"; - tx.operations.push_back( com ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - com.author = "bob"; - tx.operations.push_back( com ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "First round of votes." ); - - tx.operations.clear(); - tx.signatures.clear(); - vote_operation vote; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "dave"; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "bob"; - vote.author = "bob"; - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "sam"; - tx.operations.push_back( vote ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Generating blocks..." ); - - generate_blocks( fc::time_point_sec( db->head_block_time().sec_since_epoch() + HIVE_CASHOUT_WINDOW_SECONDS / 2 ), true ); - - BOOST_TEST_MESSAGE( "Second round of votes." ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "alice"; - vote.author = "bob"; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( vote ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "bob"; - vote.author = "alice"; - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "sam"; - tx.operations.push_back( vote ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Generating more blocks..." ); - - generate_blocks( db->get_comment( "bob", string( "test" ) ).cashout_time - ( HIVE_BLOCK_INTERVAL / 2 ), true ); - - BOOST_TEST_MESSAGE( "Check comments have not been paid out." ); - - const auto& vote_idx = db->get_index< comment_vote_index >().indices().get< by_comment_voter >(); - - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "sam" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "dave" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).net_rshares.value > 0 ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).net_rshares.value > 0 ); - validate_database(); - - auto reward_hive = db->get_dynamic_global_properties().get_total_reward_fund_hive() + ASSET( "2.000 TESTS" ); - auto total_rshares2 = db->get_dynamic_global_properties().total_reward_shares2; - auto bob_comment_vote_total = db->get_comment( "bob", string( "test" ) ).total_vote_weight; - auto bob_comment_rshares = db->get_comment( "bob", string( "test" ) ).net_rshares; - auto bob_hbd_balance = get_hbd_balance( "bob" ); - auto alice_vest_shares = get_vesting( "alice" ); - auto bob_vest_shares = get_vesting( "bob" ); - auto sam_vest_shares = get_vesting( "sam" ); - auto dave_vest_shares = get_vesting( "dave" ); - - auto bob_comment_payout = asset( ( ( uint128_t( bob_comment_rshares.value ) * bob_comment_rshares.value * reward_hive.amount.value ) / total_rshares2 ).to_uint64(), HIVE_SYMBOL ); - auto bob_comment_vote_rewards = asset( bob_comment_payout.amount / 2, HIVE_SYMBOL ); - bob_comment_payout -= bob_comment_vote_rewards; - auto bob_comment_hbd_reward = asset( bob_comment_payout.amount / 2, HIVE_SYMBOL ) * exchange_rate; - auto bob_comment_vesting_reward = ( bob_comment_payout - asset( bob_comment_payout.amount / 2, HIVE_SYMBOL ) ) * db->get_dynamic_global_properties().get_vesting_share_price(); - auto unclaimed_payments = bob_comment_vote_rewards; - auto alice_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) )->weight ) * bob_comment_vote_rewards.amount.value ) / bob_comment_vote_total ), HIVE_SYMBOL ); - auto alice_vote_vesting = alice_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - auto bob_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) )->weight ) * bob_comment_vote_rewards.amount.value ) / bob_comment_vote_total ), HIVE_SYMBOL ); - auto bob_vote_vesting = bob_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - auto sam_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) )->weight ) * bob_comment_vote_rewards.amount.value ) / bob_comment_vote_total ), HIVE_SYMBOL ); - auto sam_vote_vesting = sam_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - unclaimed_payments -= ( alice_vote_reward + bob_vote_reward + sam_vote_reward ); - - BOOST_TEST_MESSAGE( "Generate one block to cause a payout" ); - - generate_block(); - - auto bob_comment_reward = get_last_operations( 1 )[0].get< comment_reward_operation >(); - - BOOST_REQUIRE( db->get_dynamic_global_properties().get_total_reward_fund_hive().amount.value == reward_hive.amount.value - ( bob_comment_payout + bob_comment_vote_rewards - unclaimed_payments ).amount.value ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).total_payout_value.amount.value == ( ( bob_comment_vesting_reward * db->get_dynamic_global_properties().get_vesting_share_price() ) + ( bob_comment_hbd_reward * exchange_rate ) ).amount.value ); - BOOST_REQUIRE( get_hbd_balance( "bob" ).amount.value == ( bob_hbd_balance + bob_comment_hbd_reward ).amount.value ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).net_rshares.value > 0 ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).net_rshares.value == 0 ); - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == ( alice_vest_shares + alice_vote_vesting ).amount.value ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == ( bob_vest_shares + bob_vote_vesting + bob_comment_vesting_reward ).amount.value ); - BOOST_REQUIRE( get_vesting( "sam" ).amount.value == ( sam_vest_shares + sam_vote_vesting ).amount.value ); - BOOST_REQUIRE( get_vesting( "dave" ).amount.value == dave_vest_shares.amount.value ); - BOOST_REQUIRE( bob_comment_reward.author == "bob" ); - BOOST_REQUIRE( bob_comment_reward.permlink == "test" ); - BOOST_REQUIRE( bob_comment_reward.payout.amount.value == bob_comment_hbd_reward.amount.value ); - BOOST_REQUIRE( bob_comment_reward.vesting_payout.amount.value == bob_comment_vesting_reward.amount.value ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "sam" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "dave" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) ) == vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "Generating blocks up to next comment payout" ); - - generate_blocks( db->get_comment( "alice", string( "test" ) ).cashout_time - ( HIVE_BLOCK_INTERVAL / 2 ), true ); - - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "sam" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "dave" ) ).id ) ) != vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).net_rshares.value > 0 ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).net_rshares.value == 0 ); - validate_database(); - - BOOST_TEST_MESSAGE( "Generate block to cause payout" ); - - reward_hive = db->get_dynamic_global_properties().get_total_reward_fund_hive() + ASSET( "2.000 TESTS" ); - total_rshares2 = db->get_dynamic_global_properties().total_reward_shares2; - auto alice_comment_vote_total = db->get_comment( "alice", string( "test" ) ).total_vote_weight; - auto alice_comment_rshares = db->get_comment( "alice", string( "test" ) ).net_rshares; - auto alice_hbd_balance = get_hbd_balance( "alice" ); - alice_vest_shares = get_vesting( "alice" ); - bob_vest_shares = get_vesting( "bob" ); - sam_vest_shares = get_vesting( "sam" ); - dave_vest_shares = get_vesting( "dave" ); - - u256 rs( alice_comment_rshares.value ); - u256 rf( reward_hive.amount.value ); - u256 trs2 = total_rshares2.hi; - trs2 = ( trs2 << 64 ) + total_rshares2.lo; - auto rs2 = rs*rs; - - auto alice_comment_payout = asset( static_cast< uint64_t >( ( rf * rs2 ) / trs2 ), HIVE_SYMBOL ); - auto alice_comment_vote_rewards = asset( alice_comment_payout.amount / 2, HIVE_SYMBOL ); - alice_comment_payout -= alice_comment_vote_rewards; - auto alice_comment_hbd_reward = asset( alice_comment_payout.amount / 2, HIVE_SYMBOL ) * exchange_rate; - auto alice_comment_vesting_reward = ( alice_comment_payout - asset( alice_comment_payout.amount / 2, HIVE_SYMBOL ) ) * db->get_dynamic_global_properties().get_vesting_share_price(); - unclaimed_payments = alice_comment_vote_rewards; - alice_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) )->weight ) * alice_comment_vote_rewards.amount.value ) / alice_comment_vote_total ), HIVE_SYMBOL ); - alice_vote_vesting = alice_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - bob_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) )->weight ) * alice_comment_vote_rewards.amount.value ) / alice_comment_vote_total ), HIVE_SYMBOL ); - bob_vote_vesting = bob_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - sam_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "sam" ) ).id ) )->weight ) * alice_comment_vote_rewards.amount.value ) / alice_comment_vote_total ), HIVE_SYMBOL ); - sam_vote_vesting = sam_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - auto dave_vote_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "dave" ) ).id ) )->weight ) * alice_comment_vote_rewards.amount.value ) / alice_comment_vote_total ), HIVE_SYMBOL ); - auto dave_vote_vesting = dave_vote_reward * db->get_dynamic_global_properties().get_vesting_share_price(); - unclaimed_payments -= ( alice_vote_reward + bob_vote_reward + sam_vote_reward + dave_vote_reward ); - - generate_block(); - auto alice_comment_reward = get_last_operations( 1 )[0].get< comment_reward_operation >(); - - BOOST_REQUIRE( ( db->get_dynamic_global_properties().get_total_reward_fund_hive() + alice_comment_payout + alice_comment_vote_rewards - unclaimed_payments ).amount.value == reward_hive.amount.value ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).total_payout_value.amount.value == ( ( alice_comment_vesting_reward * db->get_dynamic_global_properties().get_vesting_share_price() ) + ( alice_comment_hbd_reward * exchange_rate ) ).amount.value ); - BOOST_REQUIRE( get_hbd_balance( "alice" ).amount.value == ( alice_hbd_balance + alice_comment_hbd_reward ).amount.value ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).net_rshares.value == 0 ); - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).net_rshares.value == 0 ); - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == ( alice_vest_shares + alice_vote_vesting + alice_comment_vesting_reward ).amount.value ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == ( bob_vest_shares + bob_vote_vesting ).amount.value ); - BOOST_REQUIRE( get_vesting( "sam" ).amount.value == ( sam_vest_shares + sam_vote_vesting ).amount.value ); - BOOST_REQUIRE( get_vesting( "dave" ).amount.value == ( dave_vest_shares + dave_vote_vesting ).amount.value ); - BOOST_REQUIRE( alice_comment_reward.author == "alice" ); - BOOST_REQUIRE( alice_comment_reward.permlink == "test" ); - BOOST_REQUIRE( alice_comment_reward.payout.amount.value == alice_comment_hbd_reward.amount.value ); - BOOST_REQUIRE( alice_comment_reward.vesting_payout.amount.value == alice_comment_vesting_reward.amount.value ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "sam" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "dave" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) ) == vote_idx.end() ); - validate_database(); - - BOOST_TEST_MESSAGE( "Testing no payout when less than $0.02" ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "alice"; - vote.author = "alice"; - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "dave"; - vote.author = "bob"; - vote.weight = HIVE_1_PERCENT; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->get_comment( "bob", string( "test" ) ).cashout_time - HIVE_BLOCK_INTERVAL, true ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "bob"; - vote.author = "alice"; - vote.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "sam"; - tx.operations.push_back( vote ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote.voter = "dave"; - tx.operations.push_back( vote ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - bob_vest_shares = get_vesting( "bob" ); - auto bob_hbd = get_hbd_balance( "bob" ); - - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "dave" ) ).id ) ) != vote_idx.end() ); - validate_database(); - - generate_block(); - - BOOST_REQUIRE( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "dave" ) ).id ) ) == vote_idx.end() ); - BOOST_REQUIRE( bob_vest_shares.amount.value == get_vesting( "bob" ).amount.value ); - BOOST_REQUIRE( bob_hbd.amount.value == get_hbd_balance( "bob" ).amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -OOST_AUTO_TEST_CASE( nested_comments ) -{ - try - { - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - vest( "alice", 10000 ); - fund( "bob", 10000 ); - vest( "bob", 10000 ); - fund( "sam", 10000 ); - vest( "sam", 10000 ); - fund( "dave", 10000 ); - vest( "dave", 10000 ); - - price exchange_rate( ASSET( "1.000 TESTS" ), ASSET( "1.000 TBD" ) ); - set_price_feed( exchange_rate ); - - signed_transaction tx; - comment_operation comment_op; - comment_op.author = "alice"; - comment_op.permlink = "test"; - comment_op.parent_permlink = "test"; - comment_op.title = "foo"; - comment_op.body = "bar"; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( comment_op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - comment_op.author = "bob"; - comment_op.parent_author = "alice"; - comment_op.parent_permlink = "test"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( comment_op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - comment_op.author = "sam"; - comment_op.parent_author = "bob"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( comment_op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - comment_op.author = "dave"; - comment_op.parent_author = "sam"; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( comment_op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - vote_operation vote_op; - vote_op.voter = "alice"; - vote_op.author = "alice"; - vote_op.permlink = "test"; - vote_op.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote_op ); - vote_op.author = "bob"; - tx.operations.push_back( vote_op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote_op.voter = "bob"; - vote_op.author = "alice"; - tx.operations.push_back( vote_op ); - vote_op.author = "bob"; - tx.operations.push_back( vote_op ); - vote_op.author = "dave"; - vote_op.weight = HIVE_1_PERCENT * 20; - tx.operations.push_back( vote_op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - vote_op.voter = "sam"; - vote_op.author = "bob"; - vote_op.weight = HIVE_100_PERCENT; - tx.operations.push_back( vote_op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->get_comment( "alice", string( "test" ) ).cashout_time - fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - auto& gpo = db->get_dynamic_global_properties(); - uint128_t reward_hive = gpo.get_total_reward_fund_hive().amount.value + ASSET( "2.000 TESTS" ).amount.value; - uint128_t total_rshares2 = gpo.total_reward_shares2; - - auto alice_comment = db->get_comment( "alice", string( "test" ) ); - auto bob_comment = db->get_comment( "bob", string( "test" ) ); - auto sam_comment = db->get_comment( "sam", string( "test" ) ); - auto dave_comment = db->get_comment( "dave", string( "test" ) ); - - const auto& vote_idx = db->get_index< comment_vote_index >().indices().get< by_comment_voter >(); - - // Calculate total comment rewards and voting rewards. - auto alice_comment_reward = ( ( reward_hive * alice_comment.net_rshares.value * alice_comment.net_rshares.value ) / total_rshares2 ).to_uint64(); - total_rshares2 -= uint128_t( alice_comment.net_rshares.value ) * ( alice_comment.net_rshares.value ); - reward_hive -= alice_comment_reward; - auto alice_comment_vote_rewards = alice_comment_reward / 2; - alice_comment_reward -= alice_comment_vote_rewards; - - auto alice_vote_alice_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "alice" ) ).id ) )->weight ) * alice_comment_vote_rewards ) / alice_comment.total_vote_weight ), HIVE_SYMBOL ); - auto bob_vote_alice_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "alice", string( "test" ).id, db->get_account( "bob" ) ).id ) )->weight ) * alice_comment_vote_rewards ) / alice_comment.total_vote_weight ), HIVE_SYMBOL ); - reward_hive += alice_comment_vote_rewards - ( alice_vote_alice_reward + bob_vote_alice_reward ).amount.value; - - auto bob_comment_reward = ( ( reward_hive * bob_comment.net_rshares.value * bob_comment.net_rshares.value ) / total_rshares2 ).to_uint64(); - total_rshares2 -= uint128_t( bob_comment.net_rshares.value ) * bob_comment.net_rshares.value; - reward_hive -= bob_comment_reward; - auto bob_comment_vote_rewards = bob_comment_reward / 2; - bob_comment_reward -= bob_comment_vote_rewards; - - auto alice_vote_bob_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "alice" ) ).id ) )->weight ) * bob_comment_vote_rewards ) / bob_comment.total_vote_weight ), HIVE_SYMBOL ); - auto bob_vote_bob_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "bob" ) ).id ) )->weight ) * bob_comment_vote_rewards ) / bob_comment.total_vote_weight ), HIVE_SYMBOL ); - auto sam_vote_bob_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "bob", string( "test" ).id, db->get_account( "sam" ) ).id ) )->weight ) * bob_comment_vote_rewards ) / bob_comment.total_vote_weight ), HIVE_SYMBOL ); - reward_hive += bob_comment_vote_rewards - ( alice_vote_bob_reward + bob_vote_bob_reward + sam_vote_bob_reward ).amount.value; - - auto dave_comment_reward = ( ( reward_hive * dave_comment.net_rshares.value * dave_comment.net_rshares.value ) / total_rshares2 ).to_uint64(); - total_rshares2 -= uint128_t( dave_comment.net_rshares.value ) * dave_comment.net_rshares.value; - reward_hive -= dave_comment_reward; - auto dave_comment_vote_rewards = dave_comment_reward / 2; - dave_comment_reward -= dave_comment_vote_rewards; - - auto bob_vote_dave_reward = asset( static_cast< uint64_t >( ( u256( vote_idx.find( boost::make_tuple( db->get_comment( "dave", string( "test" ).id, db->get_account( "bob" ) ).id ) )->weight ) * dave_comment_vote_rewards ) / dave_comment.total_vote_weight ), HIVE_SYMBOL ); - reward_hive += dave_comment_vote_rewards - bob_vote_dave_reward.amount.value; - - // Calculate rewards paid to parent posts - auto alice_pays_alice_hbd = alice_comment_reward / 2; - auto alice_pays_alice_vest = alice_comment_reward - alice_pays_alice_hbd; - auto bob_pays_bob_hbd = bob_comment_reward / 2; - auto bob_pays_bob_vest = bob_comment_reward - bob_pays_bob_hbd; - auto dave_pays_dave_hbd = dave_comment_reward / 2; - auto dave_pays_dave_vest = dave_comment_reward - dave_pays_dave_hbd; - - auto bob_pays_alice_hbd = bob_pays_bob_hbd / 2; - auto bob_pays_alice_vest = bob_pays_bob_vest / 2; - bob_pays_bob_hbd -= bob_pays_alice_hbd; - bob_pays_bob_vest -= bob_pays_alice_vest; - - auto dave_pays_sam_hbd = dave_pays_dave_hbd / 2; - auto dave_pays_sam_vest = dave_pays_dave_vest / 2; - dave_pays_dave_hbd -= dave_pays_sam_hbd; - dave_pays_dave_vest -= dave_pays_sam_vest; - auto dave_pays_bob_hbd = dave_pays_sam_hbd / 2; - auto dave_pays_bob_vest = dave_pays_sam_vest / 2; - dave_pays_sam_hbd -= dave_pays_bob_hbd; - dave_pays_sam_vest -= dave_pays_bob_vest; - auto dave_pays_alice_hbd = dave_pays_bob_hbd / 2; - auto dave_pays_alice_vest = dave_pays_bob_vest / 2; - dave_pays_bob_hbd -= dave_pays_alice_hbd; - dave_pays_bob_vest -= dave_pays_alice_vest; - - // Calculate total comment payouts - auto alice_comment_total_payout = db->to_hbd( asset( alice_pays_alice_hbd + alice_pays_alice_vest, HIVE_SYMBOL ) ); - alice_comment_total_payout += db->to_hbd( asset( bob_pays_alice_hbd + bob_pays_alice_vest, HIVE_SYMBOL ) ); - alice_comment_total_payout += db->to_hbd( asset( dave_pays_alice_hbd + dave_pays_alice_vest, HIVE_SYMBOL ) ); - auto bob_comment_total_payout = db->to_hbd( asset( bob_pays_bob_hbd + bob_pays_bob_vest, HIVE_SYMBOL ) ); - bob_comment_total_payout += db->to_hbd( asset( dave_pays_bob_hbd + dave_pays_bob_vest, HIVE_SYMBOL ) ); - auto sam_comment_total_payout = db->to_hbd( asset( dave_pays_sam_hbd + dave_pays_sam_vest, HIVE_SYMBOL ) ); - auto dave_comment_total_payout = db->to_hbd( asset( dave_pays_dave_hbd + dave_pays_dave_vest, HIVE_SYMBOL ) ); - - auto alice_starting_vesting = get_vesting( "alice" ); - auto alice_starting_hbd = get_hbd_balance( "alice" ); - auto bob_starting_vesting = get_vesting( "bob" ); - auto bob_starting_hbd = get_hbd_balance( "bob" ); - auto sam_starting_vesting = get_vesting( "sam" ); - auto sam_starting_hbd = get_hbd_balance( "sam" ); - auto dave_starting_vesting = get_vesting( "dave" ); - auto dave_starting_hbd = get_hbd_balance( "dave" ); - - generate_block(); - - // Calculate vesting share rewards from voting. - auto alice_vote_alice_vesting = alice_vote_alice_reward * gpo.get_vesting_share_price(); - auto bob_vote_alice_vesting = bob_vote_alice_reward * gpo.get_vesting_share_price(); - auto alice_vote_bob_vesting = alice_vote_bob_reward * gpo.get_vesting_share_price(); - auto bob_vote_bob_vesting = bob_vote_bob_reward * gpo.get_vesting_share_price(); - auto sam_vote_bob_vesting = sam_vote_bob_reward * gpo.get_vesting_share_price(); - auto bob_vote_dave_vesting = bob_vote_dave_reward * gpo.get_vesting_share_price(); - - BOOST_REQUIRE( db->get_comment( "alice", string( "test" ) ).total_payout_value.amount.value == alice_comment_total_payout.amount.value ); - BOOST_REQUIRE( db->get_comment( "bob", string( "test" ) ).total_payout_value.amount.value == bob_comment_total_payout.amount.value ); - BOOST_REQUIRE( db->get_comment( "sam", string( "test" ) ).total_payout_value.amount.value == sam_comment_total_payout.amount.value ); - BOOST_REQUIRE( db->get_comment( "dave", string( "test" ) ).total_payout_value.amount.value == dave_comment_total_payout.amount.value ); - - // ops 0-3, 5-6, and 10 are comment reward ops - auto ops = get_last_operations( 13 ); - - BOOST_TEST_MESSAGE( "Checking Virtual Operation Correctness" ); - - curate_reward_operation cur_vop; - comment_reward_operation com_vop = ops[0].get< comment_reward_operation >(); - - BOOST_REQUIRE( com_vop.author == "alice" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "dave" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == dave_pays_alice_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == dave_pays_alice_vest ); - - com_vop = ops[1].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "bob" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "dave" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == dave_pays_bob_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == dave_pays_bob_vest ); - - com_vop = ops[2].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "sam" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "dave" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == dave_pays_sam_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == dave_pays_sam_vest ); - - com_vop = ops[3].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "dave" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "dave" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == dave_pays_dave_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == dave_pays_dave_vest ); - - cur_vop = ops[4].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "bob" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == bob_vote_dave_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "dave" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - com_vop = ops[5].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "alice" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "bob" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == bob_pays_alice_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == bob_pays_alice_vest ); - - com_vop = ops[6].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "bob" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "bob" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == bob_pays_bob_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == bob_pays_bob_vest ); - - cur_vop = ops[7].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "sam" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == sam_vote_bob_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "bob" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - cur_vop = ops[8].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "bob" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == bob_vote_bob_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "bob" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - cur_vop = ops[9].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "alice" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == alice_vote_bob_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "bob" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - com_vop = ops[10].get< comment_reward_operation >(); - BOOST_REQUIRE( com_vop.author == "alice" ); - BOOST_REQUIRE( com_vop.permlink == "test" ); - BOOST_REQUIRE( com_vop.originating_author == "alice" ); - BOOST_REQUIRE( com_vop.originating_permlink == "test" ); - BOOST_REQUIRE( com_vop.payout.amount.value == alice_pays_alice_hbd ); - BOOST_REQUIRE( ( com_vop.vesting_payout * gpo.get_vesting_share_price() ).amount.value == alice_pays_alice_vest ); - - cur_vop = ops[11].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "bob" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == bob_vote_alice_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "alice" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - cur_vop = ops[12].get< curate_reward_operation >(); - BOOST_REQUIRE( cur_vop.curator == "alice" ); - BOOST_REQUIRE( cur_vop.reward.amount.value == alice_vote_alice_vesting.amount.value ); - BOOST_REQUIRE( cur_vop.comment_author == "alice" ); - BOOST_REQUIRE( cur_vop.comment_permlink == "test" ); - - BOOST_TEST_MESSAGE( "Checking account balances" ); - - auto alice_total_hbd = alice_starting_hbd + asset( alice_pays_alice_hbd + bob_pays_alice_hbd + dave_pays_alice_hbd, HIVE_SYMBOL ) * exchange_rate; - auto alice_total_vesting = alice_starting_vesting + asset( alice_pays_alice_vest + bob_pays_alice_vest + dave_pays_alice_vest + alice_vote_alice_reward.amount + alice_vote_bob_reward.amount, HIVE_SYMBOL ) * gpo.get_vesting_share_price(); - BOOST_REQUIRE( get_hbd_balance( "alice" ).amount.value == alice_total_hbd.amount.value ); - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == alice_total_vesting.amount.value ); - - auto bob_total_hbd = bob_starting_hbd + asset( bob_pays_bob_hbd + dave_pays_bob_hbd, HIVE_SYMBOL ) * exchange_rate; - auto bob_total_vesting = bob_starting_vesting + asset( bob_pays_bob_vest + dave_pays_bob_vest + bob_vote_alice_reward.amount + bob_vote_bob_reward.amount + bob_vote_dave_reward.amount, HIVE_SYMBOL ) * gpo.get_vesting_share_price(); - BOOST_REQUIRE( get_hbd_balance( "bob" ).amount.value == bob_total_hbd.amount.value ); - BOOST_REQUIRE( get_vesting( "bob" ).amount.value == bob_total_vesting.amount.value ); - - auto sam_total_hbd = sam_starting_hbd + asset( dave_pays_sam_hbd, HIVE_SYMBOL ) * exchange_rate; - auto sam_total_vesting = bob_starting_vesting + asset( dave_pays_sam_vest + sam_vote_bob_reward.amount, HIVE_SYMBOL ) * gpo.get_vesting_share_price(); - BOOST_REQUIRE( get_hbd_balance( "sam" ).amount.value == sam_total_hbd.amount.value ); - BOOST_REQUIRE( get_vesting( "sam" ).amount.value == sam_total_vesting.amount.value ); - - auto dave_total_hbd = dave_starting_hbd + asset( dave_pays_dave_hbd, HIVE_SYMBOL ) * exchange_rate; - auto dave_total_vesting = dave_starting_vesting + asset( dave_pays_dave_vest, HIVE_SYMBOL ) * gpo.get_vesting_share_price(); - BOOST_REQUIRE( get_hbd_balance( "dave" ).amount.value == dave_total_hbd.amount.value ); - BOOST_REQUIRE( get_vesting( "dave" ).amount.value == dave_total_vesting.amount.value ); - } - FC_LOG_AND_RETHROW() -} -*/ - - -BOOST_AUTO_TEST_CASE( vesting_withdrawals ) -{ - try - { - ACTORS( (alice) ) - fund( "alice", 100000 ); - vest( "alice", 100000 ); - - const auto& new_alice = db->get_account( "alice" ); - - BOOST_TEST_MESSAGE( "Setting up withdrawal" ); - - signed_transaction tx; - withdraw_vesting_operation op; - op.account = "alice"; - op.vesting_shares = asset( new_alice.get_vesting().amount / 2, VESTS_SYMBOL ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto next_withdrawal = db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS; - asset vesting_shares = new_alice.get_vesting(); - asset original_vesting = vesting_shares; - asset withdraw_rate = new_alice.vesting_withdraw_rate; - - BOOST_TEST_MESSAGE( "Generating block up to first withdrawal" ); - generate_blocks( next_withdrawal - ( HIVE_BLOCK_INTERVAL / 2 ), true); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == vesting_shares.amount.value ); - - BOOST_TEST_MESSAGE( "Generating block to cause withdrawal" ); - generate_block(); - - auto fill_op = get_last_operations( 1 )[0].get< fill_vesting_withdraw_operation >(); - auto& gpo = db->get_dynamic_global_properties(); - - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == ( vesting_shares - withdraw_rate ).amount.value ); - BOOST_REQUIRE( ( withdraw_rate * gpo.get_vesting_share_price() ).amount.value - get_balance( "alice" ).amount.value <= 1 ); // Check a range due to differences in the share price - BOOST_REQUIRE( fill_op.from_account == "alice" ); - BOOST_REQUIRE( fill_op.to_account == "alice" ); - BOOST_REQUIRE( fill_op.withdrawn.amount.value == withdraw_rate.amount.value ); - BOOST_REQUIRE( std::abs( ( fill_op.deposited - fill_op.withdrawn * gpo.get_vesting_share_price() ).amount.value ) <= 1 ); - validate_database(); - - BOOST_TEST_MESSAGE( "Generating the rest of the blocks in the withdrawal" ); - - vesting_shares = get_vesting( "alice" ); - auto balance = get_balance( "alice" ); - auto old_next_vesting = db->get_account( "alice" ).next_vesting_withdrawal; - - for( int i = 1; i < HIVE_VESTING_WITHDRAW_INTERVALS - 1; i++ ) - { - generate_blocks( db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS ); - - const auto& alice = db->get_account( "alice" ); - - //`delayed_voting_operation` is triggered for all witnesses + `alice` after `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ( 30 days ) - const int shift = ( i == 4 ) ? ( HIVE_MAX_WITNESSES + 1/*alice*/ ) : 0; - fill_op = get_last_operations( 2 + shift )[ 1 + shift ].get< fill_vesting_withdraw_operation >(); - - BOOST_REQUIRE( alice.get_vesting().amount.value == ( vesting_shares - withdraw_rate ).amount.value ); - BOOST_REQUIRE( balance.amount.value + ( withdraw_rate * gpo.get_vesting_share_price() ).amount.value - alice.get_balance().amount.value <= 1 ); - BOOST_REQUIRE( fill_op.from_account == "alice" ); - BOOST_REQUIRE( fill_op.to_account == "alice" ); - BOOST_REQUIRE( fill_op.withdrawn.amount.value == withdraw_rate.amount.value ); - BOOST_REQUIRE( std::abs( ( fill_op.deposited - fill_op.withdrawn * gpo.get_vesting_share_price() ).amount.value ) <= 1 ); - - if ( i == HIVE_VESTING_WITHDRAW_INTERVALS - 1 ) - BOOST_REQUIRE( alice.next_vesting_withdrawal == fc::time_point_sec::maximum() ); - else - BOOST_REQUIRE( alice.next_vesting_withdrawal.sec_since_epoch() == ( old_next_vesting + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS ).sec_since_epoch() ); - - validate_database(); - - vesting_shares = alice.get_vesting(); - balance = alice.get_balance(); - old_next_vesting = alice.next_vesting_withdrawal; - } - - BOOST_TEST_MESSAGE( "Generating one more block to finish vesting withdrawal" ); - generate_blocks( db->head_block_time() + HIVE_VESTING_WITHDRAW_INTERVAL_SECONDS, true ); - - BOOST_REQUIRE( db->get_account( "alice" ).next_vesting_withdrawal.sec_since_epoch() == fc::time_point_sec::maximum().sec_since_epoch() ); - BOOST_REQUIRE( get_vesting( "alice" ).amount.value == ( original_vesting - op.vesting_shares ).amount.value ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( vesting_withdraw_route ) -{ - try - { - ACTORS( (alice)(bob)(sam) ) - - auto original_vesting = alice.get_vesting(); - - fund( "alice", 1040000 ); - vest( "alice", 1040000 ); - - auto withdraw_amount = alice.get_vesting() - original_vesting; - - BOOST_TEST_MESSAGE( "Setup vesting withdraw" ); - withdraw_vesting_operation wv; - wv.account = "alice"; - wv.vesting_shares = withdraw_amount; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( wv ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - BOOST_TEST_MESSAGE( "Setting up bob destination" ); - set_withdraw_vesting_route_operation op; - op.from_account = "alice"; - op.to_account = "bob"; - op.percent = HIVE_1_PERCENT * 50; - op.auto_vest = true; - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "Setting up sam destination" ); - op.to_account = "sam"; - op.percent = HIVE_1_PERCENT * 30; - op.auto_vest = false; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Setting up first withdraw" ); - - auto vesting_withdraw_rate = alice.vesting_withdraw_rate; - auto old_alice_balance = alice.get_balance(); - auto old_alice_vesting = alice.get_vesting(); - auto old_bob_balance = bob.get_balance(); - auto old_bob_vesting = bob.get_vesting(); - auto old_sam_balance = sam.get_balance(); - auto old_sam_vesting = sam.get_vesting(); - generate_blocks( alice.next_vesting_withdrawal, true ); - - { - const auto& alice = db->get_account( "alice" ); - const auto& bob = db->get_account( "bob" ); - const auto& sam = db->get_account( "sam" ); - - BOOST_REQUIRE( alice.get_vesting() == old_alice_vesting - vesting_withdraw_rate ); - BOOST_REQUIRE( alice.get_balance() == old_alice_balance + asset( ( vesting_withdraw_rate.amount * HIVE_1_PERCENT * 20 ) / HIVE_100_PERCENT, VESTS_SYMBOL ) * db->get_dynamic_global_properties().get_vesting_share_price() ); - BOOST_REQUIRE( bob.get_vesting() == old_bob_vesting + asset( ( vesting_withdraw_rate.amount * HIVE_1_PERCENT * 50 ) / HIVE_100_PERCENT, VESTS_SYMBOL ) ); - BOOST_REQUIRE( bob.get_balance() == old_bob_balance ); - BOOST_REQUIRE( sam.get_vesting() == old_sam_vesting ); - BOOST_REQUIRE( sam.get_balance() == old_sam_balance + asset( ( vesting_withdraw_rate.amount * HIVE_1_PERCENT * 30 ) / HIVE_100_PERCENT, VESTS_SYMBOL ) * db->get_dynamic_global_properties().get_vesting_share_price() ); - - old_alice_balance = alice.get_balance(); - old_alice_vesting = alice.get_vesting(); - old_bob_balance = bob.get_balance(); - old_bob_vesting = bob.get_vesting(); - old_sam_balance = sam.get_balance(); - old_sam_vesting = sam.get_vesting(); - } - - BOOST_TEST_MESSAGE( "Test failure with greater than 100% destination assignment" ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.to_account = "sam"; - op.percent = HIVE_1_PERCENT * 50 + 1; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "Test from_account receiving no withdraw" ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.to_account = "sam"; - op.percent = HIVE_1_PERCENT * 50; - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->get_account( "alice" ).next_vesting_withdrawal, true ); - { - const auto& alice = db->get_account( "alice" ); - const auto& bob = db->get_account( "bob" ); - const auto& sam = db->get_account( "sam" ); - - BOOST_REQUIRE( alice.get_vesting() == old_alice_vesting - vesting_withdraw_rate ); - BOOST_REQUIRE( alice.get_balance() == old_alice_balance ); - BOOST_REQUIRE( bob.get_vesting() == old_bob_vesting + asset( ( vesting_withdraw_rate.amount * HIVE_1_PERCENT * 50 ) / HIVE_100_PERCENT, VESTS_SYMBOL ) ); - BOOST_REQUIRE( bob.get_balance() == old_bob_balance ); - BOOST_REQUIRE( sam.get_vesting() == old_sam_vesting ); - BOOST_REQUIRE( sam.get_balance() == old_sam_balance + asset( ( vesting_withdraw_rate.amount * HIVE_1_PERCENT * 50 ) / HIVE_100_PERCENT, VESTS_SYMBOL ) * db->get_dynamic_global_properties().get_vesting_share_price() ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( feed_publish_mean ) -{ - try - { - resize_shared_mem( 1024 * 1024 * 32 ); - - ACTORS( (alice0)(alice1)(alice2)(alice3)(alice4)(alice5)(alice6) ) - - BOOST_TEST_MESSAGE( "Setup" ); - - generate_blocks( 30 / HIVE_BLOCK_INTERVAL ); - - vector< string > accounts; - accounts.push_back( "alice0" ); - accounts.push_back( "alice1" ); - accounts.push_back( "alice2" ); - accounts.push_back( "alice3" ); - accounts.push_back( "alice4" ); - accounts.push_back( "alice5" ); - accounts.push_back( "alice6" ); - - vector< private_key_type > keys; - keys.push_back( alice0_private_key ); - keys.push_back( alice1_private_key ); - keys.push_back( alice2_private_key ); - keys.push_back( alice3_private_key ); - keys.push_back( alice4_private_key ); - keys.push_back( alice5_private_key ); - keys.push_back( alice6_private_key ); - - vector< feed_publish_operation > ops; - vector< signed_transaction > txs; - - // Upgrade accounts to witnesses - for( int i = 0; i < 7; i++ ) - { - transfer( HIVE_INIT_MINER_NAME, accounts[i], asset( 10000, HIVE_SYMBOL ) ); - witness_create( accounts[i], keys[i], "foo.bar", keys[i].get_public_key(), 1000 ); - - ops.push_back( feed_publish_operation() ); - ops[i].publisher = accounts[i]; - - txs.push_back( signed_transaction() ); - } - - ops[0].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 100000, HIVE_SYMBOL ) ); - ops[1].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 105000, HIVE_SYMBOL ) ); - ops[2].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 98000, HIVE_SYMBOL ) ); - ops[3].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 97000, HIVE_SYMBOL ) ); - ops[4].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 99000, HIVE_SYMBOL ) ); - ops[5].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 97500, HIVE_SYMBOL ) ); - ops[6].exchange_rate = price( asset( 1000, HBD_SYMBOL ), asset( 102000, HIVE_SYMBOL ) ); - - for( int i = 0; i < 7; i++ ) - { - txs[i].set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - txs[i].operations.push_back( ops[i] ); - sign( txs[i], keys[i] ); - db->push_transaction( txs[i], 0 ); - } - - BOOST_TEST_MESSAGE( "Jump forward an hour" ); - - generate_blocks( HIVE_BLOCKS_PER_HOUR ); // Jump forward 1 hour - BOOST_TEST_MESSAGE( "Get feed history object" ); - auto& feed_history = db->get_feed_history(); - BOOST_TEST_MESSAGE( "Check state" ); - BOOST_REQUIRE( feed_history.current_median_history == price( asset( 1000, HBD_SYMBOL ), asset( 99000, HIVE_SYMBOL) ) ); - BOOST_REQUIRE( feed_history.price_history[ 0 ] == price( asset( 1000, HBD_SYMBOL ), asset( 99000, HIVE_SYMBOL) ) ); - validate_database(); - - for ( int i = 0; i < 23; i++ ) - { - BOOST_TEST_MESSAGE( "Updating ops" ); - - for( int j = 0; j < 7; j++ ) - { - txs[j].operations.clear(); - txs[j].signatures.clear(); - ops[j].exchange_rate = price( ops[j].exchange_rate.base, asset( ops[j].exchange_rate.quote.amount + 10, HIVE_SYMBOL ) ); - txs[j].set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - txs[j].operations.push_back( ops[j] ); - sign( txs[j], keys[j] ); - db->push_transaction( txs[j], 0 ); - } - - BOOST_TEST_MESSAGE( "Generate Blocks" ); - - generate_blocks( HIVE_BLOCKS_PER_HOUR ); // Jump forward 1 hour - - BOOST_TEST_MESSAGE( "Check feed_history" ); - - auto& feed_history = db->get(feed_history_id_type()); - BOOST_REQUIRE( feed_history.current_median_history == feed_history.price_history[ ( i + 1 ) / 2 ] ); - BOOST_REQUIRE( feed_history.price_history[ i + 1 ] == ops[4].exchange_rate ); - validate_database(); - } - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( convert_delay ) -{ - try - { - ACTORS( (alice) ) - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "25.000 TBD" ) ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.250 TESTS" ) ) ); - - convert_operation op; - signed_transaction tx; - - auto start_balance = ASSET( "25.000 TBD" ); - - BOOST_TEST_MESSAGE( "Setup conversion to TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - op.owner = "alice"; - op.amount = asset( 2000, HBD_SYMBOL ); - op.requestid = 2; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Generating Blocks up to conversion block" ); - generate_blocks( db->head_block_time() + HIVE_CONVERSION_DELAY - fc::seconds( HIVE_BLOCK_INTERVAL / 2 ), true ); - - BOOST_TEST_MESSAGE( "Verify conversion is not applied" ); - const auto& alice_2 = db->get_account( "alice" ); - const auto& convert_request_idx = db->get_index< convert_request_index >().indices().get< by_owner >(); - auto convert_request = convert_request_idx.find( boost::make_tuple( "alice", 2 ) ); - - BOOST_REQUIRE( convert_request != convert_request_idx.end() ); - BOOST_REQUIRE( alice_2.get_balance().amount.value == 0 ); - BOOST_REQUIRE( alice_2.get_hbd_balance().amount.value == ( start_balance - op.amount ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "Generate one more block" ); - generate_block(); - - BOOST_TEST_MESSAGE( "Verify conversion applied" ); - const auto& alice_3 = db->get_account( "alice" ); - auto vop = get_last_operations( 1 )[0].get< fill_convert_request_operation >(); - - convert_request = convert_request_idx.find( boost::make_tuple( "alice", 2 ) ); - BOOST_REQUIRE( convert_request == convert_request_idx.end() ); - BOOST_REQUIRE( alice_3.get_balance().amount.value == 2500 ); - BOOST_REQUIRE( alice_3.get_hbd_balance().amount.value == ( start_balance - op.amount ).amount.value ); - BOOST_REQUIRE( vop.owner == "alice" ); - BOOST_REQUIRE( vop.requestid == 2 ); - BOOST_REQUIRE( vop.amount_in.amount.value == ASSET( "2.000 TBD" ).amount.value ); - BOOST_REQUIRE( vop.amount_out.amount.value == ASSET( "2.500 TESTS" ).amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( hive_inflation ) -{ - try - { - /* - BOOST_TEST_MESSAGE( "Testing HIVE Inflation until the vesting start block" ); - - auto& gpo = db->get_dynamic_global_properties(); - auto virtual_supply = gpo.virtual_supply; - auto witness_name = db->get_scheduled_witness(1); - auto old_witness_balance = get_balance( witness_name ); - auto old_witness_shares = get_vesting( witness_name ); - - auto new_rewards = std::max( HIVE_MIN_CONTENT_REWARD, asset( ( HIVE_CONTENT_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ) - + std::max( HIVE_MIN_CURATE_REWARD, asset( ( HIVE_CURATE_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - auto witness_pay = std::max( HIVE_MIN_PRODUCER_REWARD, asset( ( HIVE_PRODUCER_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - auto witness_pay_shares = asset( 0, VESTS_SYMBOL ); - auto new_vesting_hive = asset( 0, HIVE_SYMBOL ); - auto new_vesting_shares = gpo.get_total_vesting_shares(); - - if ( get_vesting( witness_name ).amount.value == 0 ) - { - new_vesting_hive += witness_pay; - new_vesting_shares += witness_pay * ( gpo.get_total_vesting_shares() / gpo.get_total_vesting_fund_hive() ); - } - - auto new_supply = gpo.get_current_supply() + new_rewards + witness_pay + new_vesting_hive; - new_rewards += gpo.get_total_reward_fund_hive(); - new_vesting_hive += gpo.get_total_vesting_fund_hive(); - - generate_block(); - - BOOST_REQUIRE( gpo.get_current_supply().amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.virtual_supply.amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.get_total_reward_fund_hive().amount.value == new_rewards.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == new_vesting_hive.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == new_vesting_shares.amount.value ); - BOOST_REQUIRE( get_balance( witness_name ).amount.value == ( old_witness_balance + witness_pay ).amount.value ); - - validate_database(); - - while( db->head_block_num() < HIVE_START_VESTING_BLOCK - 1) - { - virtual_supply = gpo.virtual_supply; - witness_name = db->get_scheduled_witness(1); - old_witness_balance = get_balance( witness_name ); - old_witness_shares = get_vesting( witness_name ); - - - new_rewards = std::max( HIVE_MIN_CONTENT_REWARD, asset( ( HIVE_CONTENT_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ) - + std::max( HIVE_MIN_CURATE_REWARD, asset( ( HIVE_CURATE_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - witness_pay = std::max( HIVE_MIN_PRODUCER_REWARD, asset( ( HIVE_PRODUCER_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - new_vesting_hive = asset( 0, HIVE_SYMBOL ); - new_vesting_shares = gpo.get_total_vesting_shares(); - - if ( get_vesting( witness_name ).amount.value == 0 ) - { - new_vesting_hive += witness_pay; - witness_pay_shares = witness_pay * gpo.get_vesting_share_price(); - new_vesting_shares += witness_pay_shares; - new_supply += witness_pay; - witness_pay = asset( 0, HIVE_SYMBOL ); - } - - new_supply = gpo.get_current_supply() + new_rewards + witness_pay + new_vesting_hive; - new_rewards += gpo.get_total_reward_fund_hive(); - new_vesting_hive += gpo.get_total_vesting_fund_hive(); - - generate_block(); - - BOOST_REQUIRE( gpo.get_current_supply().amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.virtual_supply.amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.get_total_reward_fund_hive().amount.value == new_rewards.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == new_vesting_hive.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == new_vesting_shares.amount.value ); - BOOST_REQUIRE( get_balance( witness_name ).amount.value == ( old_witness_balance + witness_pay ).amount.value ); - BOOST_REQUIRE( get_vesting( witness_name ).amount.value == ( old_witness_shares + witness_pay_shares ).amount.value ); - - validate_database(); - } - - BOOST_TEST_MESSAGE( "Testing up to the start block for miner voting" ); - - while( db->head_block_num() < HIVE_START_MINER_VOTING_BLOCK - 1 ) - { - virtual_supply = gpo.virtual_supply; - witness_name = db->get_scheduled_witness(1); - old_witness_balance = get_balance( witness_name ); - - new_rewards = std::max( HIVE_MIN_CONTENT_REWARD, asset( ( HIVE_CONTENT_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ) - + std::max( HIVE_MIN_CURATE_REWARD, asset( ( HIVE_CURATE_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - witness_pay = std::max( HIVE_MIN_PRODUCER_REWARD, asset( ( HIVE_PRODUCER_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - auto witness_pay_shares = asset( 0, VESTS_SYMBOL ); - new_vesting_hive = asset( ( witness_pay + new_rewards ).amount * 9, HIVE_SYMBOL ); - new_vesting_shares = gpo.get_total_vesting_shares(); - - if ( get_vesting( witness_name ).amount.value == 0 ) - { - new_vesting_hive += witness_pay; - witness_pay_shares = witness_pay * gpo.get_vesting_share_price(); - new_vesting_shares += witness_pay_shares; - new_supply += witness_pay; - witness_pay = asset( 0, HIVE_SYMBOL ); - } - - new_supply = gpo.get_current_supply() + new_rewards + witness_pay + new_vesting_hive; - new_rewards += gpo.get_total_reward_fund_hive(); - new_vesting_hive += gpo.get_total_vesting_fund_hive(); - - generate_block(); - - BOOST_REQUIRE( gpo.get_current_supply().amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.virtual_supply.amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.get_total_reward_fund_hive().amount.value == new_rewards.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == new_vesting_hive.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == new_vesting_shares.amount.value ); - BOOST_REQUIRE( get_balance( witness_name ).amount.value == ( old_witness_balance + witness_pay ).amount.value ); - BOOST_REQUIRE( get_vesting( witness_name ).amount.value == ( old_witness_shares + witness_pay_shares ).amount.value ); - - validate_database(); - } - - for( int i = 0; i < HIVE_BLOCKS_PER_DAY; i++ ) - { - virtual_supply = gpo.virtual_supply; - witness_name = db->get_scheduled_witness(1); - old_witness_balance = get_balance( witness_name ); - - new_rewards = std::max( HIVE_MIN_CONTENT_REWARD, asset( ( HIVE_CONTENT_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ) - + std::max( HIVE_MIN_CURATE_REWARD, asset( ( HIVE_CURATE_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - witness_pay = std::max( HIVE_MIN_PRODUCER_REWARD, asset( ( HIVE_PRODUCER_APR * gpo.virtual_supply.amount ) / ( HIVE_BLOCKS_PER_YEAR * 100 ), HIVE_SYMBOL ) ); - witness_pay_shares = witness_pay * gpo.get_vesting_share_price(); - new_vesting_hive = asset( ( witness_pay + new_rewards ).amount * 9, HIVE_SYMBOL ) + witness_pay; - new_vesting_shares = gpo.get_total_vesting_shares() + witness_pay_shares; - new_supply = gpo.get_current_supply() + new_rewards + new_vesting_hive; - new_rewards += gpo.get_total_reward_fund_hive(); - new_vesting_hive += gpo.get_total_vesting_fund_hive(); - - generate_block(); - - BOOST_REQUIRE( gpo.get_current_supply().amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.virtual_supply.amount.value == new_supply.amount.value ); - BOOST_REQUIRE( gpo.get_total_reward_fund_hive().amount.value == new_rewards.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_fund_hive().amount.value == new_vesting_hive.amount.value ); - BOOST_REQUIRE( gpo.get_total_vesting_shares().amount.value == new_vesting_shares.amount.value ); - BOOST_REQUIRE( get_vesting( witness_name ).amount.value == ( old_witness_shares + witness_pay_shares ).amount.value ); - - validate_database(); - } - - virtual_supply = gpo.virtual_supply; - vesting_shares = gpo.get_total_vesting_shares(); - vesting_hive = gpo.get_total_vesting_fund_hive(); - reward_hive = gpo.get_total_reward_fund_hive(); - - witness_name = db->get_scheduled_witness(1); - old_witness_shares = get_vesting( witness_name ); - - generate_block(); - - gpo = db->get_dynamic_global_properties(); - - BOOST_REQUIRE_EQUAL( gpo.get_total_vesting_fund_hive().amount.value, - ( vesting_hive.amount.value - + ( ( ( uint128_t( virtual_supply.amount.value ) / 10 ) / HIVE_BLOCKS_PER_YEAR ) * 9 ) - + ( uint128_t( virtual_supply.amount.value ) / 100 / HIVE_BLOCKS_PER_YEAR ) ).to_uint64() ); - BOOST_REQUIRE_EQUAL( gpo.get_total_reward_fund_hive().amount.value, - reward_hive.amount.value + virtual_supply.amount.value / 10 / HIVE_BLOCKS_PER_YEAR + virtual_supply.amount.value / 10 / HIVE_BLOCKS_PER_DAY ); - BOOST_REQUIRE_EQUAL( get_vesting( witness_name ).amount.value, - old_witness_shares.amount.value + ( asset( ( ( virtual_supply.amount.value / HIVE_BLOCKS_PER_YEAR ) * HIVE_1_PERCENT ) / HIVE_100_PERCENT, HIVE_SYMBOL ) * ( vesting_shares / vesting_hive ) ).amount.value ); - validate_database(); - */ - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( hbd_interest ) -{ - try - { - ACTORS( (alice)(bob) ) - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob", ASSET( "10.000 TESTS" ) ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - BOOST_TEST_MESSAGE( "Testing interest over smallest interest period" ); - - convert_operation op; - signed_transaction tx; - - fund( "alice", ASSET( "31.903 TBD" ) ); - - auto start_time = db->get_account( "alice" ).hbd_seconds_last_update; - auto alice_hbd = get_hbd_balance( "alice" ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC ), true ); - - transfer_operation transfer; - transfer.to = "bob"; - transfer.from = "alice"; - transfer.amount = ASSET( "1.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( transfer ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - auto& gpo = db->get_dynamic_global_properties(); - auto interest_op = get_last_operations( 1 )[0].get< interest_operation >(); - - BOOST_REQUIRE( gpo.get_hbd_interest_rate() > 0 ); - BOOST_REQUIRE( static_cast<uint64_t>(get_hbd_balance( "alice" ).amount.value) == alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value + ( ( ( ( uint128_t( alice_hbd.amount.value ) * ( db->head_block_time() - start_time ).to_seconds() ) / HIVE_SECONDS_PER_YEAR ) * gpo.get_hbd_interest_rate() ) / HIVE_100_PERCENT ).to_uint64() ); - BOOST_REQUIRE( interest_op.owner == "alice" ); - BOOST_REQUIRE( interest_op.interest.amount.value == get_hbd_balance( "alice" ).amount.value - ( alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "Testing interest under interest period" ); - - start_time = db->get_account( "alice" ).hbd_seconds_last_update; - alice_hbd = get_hbd_balance( "alice" ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC / 2 ), true ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( get_hbd_balance( "alice" ).amount.value == alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value ); - validate_database(); - - auto alice_coindays = uint128_t( alice_hbd.amount.value ) * ( db->head_block_time() - start_time ).to_seconds(); - alice_hbd = get_hbd_balance( "alice" ); - start_time = db->get_account( "alice" ).hbd_seconds_last_update; - - BOOST_TEST_MESSAGE( "Testing longer interest period" ); - - generate_blocks( db->head_block_time() + fc::seconds( ( HIVE_HBD_INTEREST_COMPOUND_INTERVAL_SEC * 7 ) / 3 ), true ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( static_cast<uint64_t>(get_hbd_balance( "alice" ).amount.value) == alice_hbd.amount.value - ASSET( "1.000 TBD" ).amount.value + ( ( ( ( uint128_t( alice_hbd.amount.value ) * ( db->head_block_time() - start_time ).to_seconds() + alice_coindays ) / HIVE_SECONDS_PER_YEAR ) * gpo.get_hbd_interest_rate() ) / HIVE_100_PERCENT ).to_uint64() ); - validate_database(); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( liquidity_rewards ) -{ - using std::abs; - - try - { - db->liquidity_rewards_enabled = false; - - ACTORS( (alice)(bob)(sam)(dave) ) - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "sam", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "dave", ASSET( "10.000 TESTS" ) ); - - BOOST_TEST_MESSAGE( "Rewarding Bob with TESTS" ); - - auto exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "1.250 TESTS" ) ); - set_price_feed( exchange_rate ); - - signed_transaction tx; - - fund( "alice", ASSET( "25.522 TBD" ) ); - asset alice_hbd = get_hbd_balance( "alice" ); - - generate_block(); - - fund( "alice", alice_hbd.amount ); - fund( "bob", alice_hbd.amount ); - fund( "sam", alice_hbd.amount ); - fund( "dave", alice_hbd.amount ); - - int64_t alice_hbd_volume = 0; - int64_t alice_hive_volume = 0; - time_point_sec alice_reward_last_update = fc::time_point_sec::min(); - int64_t bob_hbd_volume = 0; - int64_t bob_hive_volume = 0; - time_point_sec bob_reward_last_update = fc::time_point_sec::min(); - int64_t sam_hbd_volume = 0; - int64_t sam_hive_volume = 0; - time_point_sec sam_reward_last_update = fc::time_point_sec::min(); - int64_t dave_hbd_volume = 0; - int64_t dave_hive_volume = 0; - time_point_sec dave_reward_last_update = fc::time_point_sec::min(); - - BOOST_TEST_MESSAGE( "Creating Limit Order for HIVE that will stay on the books for 30 minutes exactly." ); - - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = asset( alice_hbd.amount.value / 20, HBD_SYMBOL ) ; - op.min_to_receive = op.amount_to_sell * exchange_rate; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - op.orderid = 1; - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 10 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for HBD that will be filled immediately." ); - - op.owner = "bob"; - op.min_to_receive = op.amount_to_sell; - op.amount_to_sell = op.min_to_receive * exchange_rate; - op.fill_or_kill = false; - op.orderid = 2; - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_hive_volume += ( asset( alice_hbd.amount / 20, HBD_SYMBOL ) * exchange_rate ).amount.value; - alice_reward_last_update = db->head_block_time(); - bob_hive_volume -= ( asset( alice_hbd.amount / 20, HBD_SYMBOL ) * exchange_rate ).amount.value; - bob_reward_last_update = db->head_block_time(); - - auto ops = get_last_operations( 1 ); - const auto& liquidity_idx = db->get_index< liquidity_reward_balance_index >().indices().get< by_owner >(); - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - auto reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - auto fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_hbd.amount.value / 20, HBD_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 2 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == ( asset( alice_hbd.amount.value / 20, HBD_SYMBOL ) * exchange_rate ).amount.value ); - - BOOST_CHECK( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_CHECK( limit_order_idx.find( boost::make_tuple( "bob", 2 ) ) == limit_order_idx.end() ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for HBD that will stay on the books for 60 minutes." ); - - op.owner = "sam"; - op.amount_to_sell = asset( ( alice_hbd.amount.value / 20 ), HIVE_SYMBOL ); - op.min_to_receive = asset( ( alice_hbd.amount.value / 20 ), HBD_SYMBOL ); - op.orderid = 3; - - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 10 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for HBD that will stay on the books for 30 minutes." ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = asset( ( alice_hbd.amount.value / 10 ) * 3 - alice_hbd.amount.value / 20, HIVE_SYMBOL ); - op.min_to_receive = asset( ( alice_hbd.amount.value / 10 ) * 3 - alice_hbd.amount.value / 20, HBD_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 30 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Filling both limit orders." ); - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = asset( ( alice_hbd.amount.value / 10 ) * 3, HBD_SYMBOL ); - op.min_to_receive = asset( ( alice_hbd.amount.value / 10 ) * 3, HIVE_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_hbd_volume -= ( alice_hbd.amount.value / 10 ) * 3; - alice_reward_last_update = db->head_block_time(); - sam_hbd_volume += alice_hbd.amount.value / 20; - sam_reward_last_update = db->head_block_time(); - bob_hbd_volume += ( alice_hbd.amount.value / 10 ) * 3 - ( alice_hbd.amount.value / 20 ); - bob_reward_last_update = db->head_block_time(); - ops = get_last_operations( 4 ); - - fill_order_op = ops[1].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 4 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( ( alice_hbd.amount.value / 10 ) * 3 - alice_hbd.amount.value / 20, HIVE_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 5 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( ( alice_hbd.amount.value / 10 ) * 3 - alice_hbd.amount.value / 20, HBD_SYMBOL ).amount.value ); - - fill_order_op = ops[3].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "sam" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 3 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_hbd.amount.value / 20, HIVE_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 5 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_hbd.amount.value / 20, HBD_SYMBOL ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - BOOST_TEST_MESSAGE( "Testing a partial fill before minimum time and full fill after minimum time" ); - - op.orderid = 6; - op.amount_to_sell = asset( alice_hbd.amount.value / 20 * 2, HBD_SYMBOL ); - op.min_to_receive = asset( alice_hbd.amount.value / 20 * 2, HIVE_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10.to_seconds() / 2 ), true ); - - op.owner = "bob"; - op.orderid = 7; - op.amount_to_sell = asset( alice_hbd.amount.value / 20, HIVE_SYMBOL ); - op.min_to_receive = asset( alice_hbd.amount.value / 20, HBD_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10.to_seconds() / 2 ), true ); - - ops = get_last_operations( 4 ); - fill_order_op = ops[3].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 6 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_hbd.amount.value / 20, HBD_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 7 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_hbd.amount.value / 20, HIVE_SYMBOL ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "sam"; - op.orderid = 8; - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - alice_hive_volume += alice_hbd.amount.value / 20; - alice_reward_last_update = db->head_block_time(); - sam_hive_volume -= alice_hbd.amount.value / 20; - sam_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 2 ); - fill_order_op = ops[1].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 6 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_hbd.amount.value / 20, HBD_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "sam" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 8 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_hbd.amount.value / 20, HIVE_SYMBOL ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - BOOST_TEST_MESSAGE( "Trading to give Alice and Bob positive volumes to receive rewards" ); - - transfer_operation transfer; - transfer.to = "dave"; - transfer.from = "alice"; - transfer.amount = asset( alice_hbd.amount / 2, HBD_SYMBOL ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "alice"; - op.amount_to_sell = asset( 8 * ( alice_hbd.amount.value / 20 ), HIVE_SYMBOL ); - op.min_to_receive = asset( op.amount_to_sell.amount, HBD_SYMBOL ); - op.orderid = 9; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "dave"; - op.amount_to_sell = asset( 7 * ( alice_hbd.amount.value / 20 ), HBD_SYMBOL );; - op.min_to_receive = asset( op.amount_to_sell.amount, HIVE_SYMBOL ); - op.orderid = 10; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - alice_hbd_volume += op.amount_to_sell.amount.value; - alice_reward_last_update = db->head_block_time(); - dave_hbd_volume -= op.amount_to_sell.amount.value; - dave_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 9 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == 7 * ( alice_hbd.amount.value / 20 ) ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 10 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == 7 * ( alice_hbd.amount.value / 20 ) ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - op.owner = "bob"; - op.amount_to_sell.amount = alice_hbd.amount / 20; - op.min_to_receive.amount = op.amount_to_sell.amount; - op.orderid = 11; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_hbd_volume += op.amount_to_sell.amount.value; - alice_reward_last_update = db->head_block_time(); - bob_hbd_volume -= op.amount_to_sell.amount.value; - bob_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 9 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == alice_hbd.amount.value / 20 ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 11 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == alice_hbd.amount.value / 20 ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - transfer.to = "bob"; - transfer.from = "alice"; - transfer.amount = asset( alice_hbd.amount / 5, HBD_SYMBOL ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 12; - op.amount_to_sell = asset( 3 * ( alice_hbd.amount / 40 ), HBD_SYMBOL ); - op.min_to_receive = asset( op.amount_to_sell.amount, HIVE_SYMBOL ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "dave"; - op.orderid = 13; - op.amount_to_sell = op.min_to_receive; - op.min_to_receive.symbol = HBD_SYMBOL; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - bob_hive_volume += op.amount_to_sell.amount.value; - bob_reward_last_update = db->head_block_time(); - dave_hive_volume -= op.amount_to_sell.amount.value; - dave_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 12 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == 3 * ( alice_hbd.amount.value / 40 ) ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 13 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == 3 * ( alice_hbd.amount.value / 40 ) ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - auto alice_balance = get_balance( "alice" ); - auto bob_balance = get_balance( "bob" ); - auto sam_balance = get_balance( "sam" ); - auto dave_balance = get_balance( "dave" ); - - BOOST_TEST_MESSAGE( "Generating Blocks to trigger liquidity rewards" ); - - db->liquidity_rewards_enabled = true; - generate_blocks( HIVE_LIQUIDITY_REWARD_BLOCKS - ( db->head_block_num() % HIVE_LIQUIDITY_REWARD_BLOCKS ) - 1 ); - - BOOST_REQUIRE( db->head_block_num() % HIVE_LIQUIDITY_REWARD_BLOCKS == HIVE_LIQUIDITY_REWARD_BLOCKS - 1 ); - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - generate_block(); - - //alice_balance += HIVE_MIN_LIQUIDITY_REWARD; - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - ops = get_last_operations( 1 ); - - HIVE_REQUIRE_THROW( ops[0].get< liquidity_reward_operation>(), fc::exception ); - //BOOST_REQUIRE( ops[0].get< liquidity_reward_operation>().payout.amount.value == HIVE_MIN_LIQUIDITY_REWARD.amount.value ); - - generate_blocks( HIVE_LIQUIDITY_REWARD_BLOCKS ); - - //bob_balance += HIVE_MIN_LIQUIDITY_REWARD; - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - ops = get_last_operations( 1 ); - - HIVE_REQUIRE_THROW( ops[0].get< liquidity_reward_operation>(), fc::exception ); - //BOOST_REQUIRE( ops[0].get< liquidity_reward_operation>().payout.amount.value == HIVE_MIN_LIQUIDITY_REWARD.amount.value ); - - alice_hive_volume = 0; - alice_hbd_volume = 0; - bob_hive_volume = 0; - bob_hbd_volume = 0; - - BOOST_TEST_MESSAGE( "Testing liquidity timeout" ); - - generate_blocks( sam_reward_last_update + HIVE_LIQUIDITY_TIMEOUT_SEC - fc::seconds( HIVE_BLOCK_INTERVAL / 2 ) - HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC, true ); - - op.owner = "sam"; - op.orderid = 14; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = ASSET( "1.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + ( HIVE_BLOCK_INTERVAL / 2 ) + HIVE_LIQUIDITY_TIMEOUT_SEC, true ); - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - /*BOOST_REQUIRE( reward == liquidity_idx.end() ); - BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - generate_block(); - - op.owner = "alice"; - op.orderid = 15; - op.amount_to_sell.symbol = HBD_SYMBOL; - op.min_to_receive.symbol = HIVE_SYMBOL; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - sam_hbd_volume = ASSET( "1.000 TBD" ).amount.value; - sam_hive_volume = 0; - sam_reward_last_update = db->head_block_time(); - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - /*BOOST_REQUIRE( reward == liquidity_idx.end() ); - BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_hbd_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( post_rate_limit ) -{ - try - { - ACTORS( (alice) ) - - fund( "alice", 10000 ); - vest( "alice", 10000 ); - - comment_operation op; - op.author = "alice"; - op.permlink = "test1"; - op.parent_author = ""; - op.parent_permlink = "test"; - op.body = "test"; - - signed_transaction tx; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test1" ) ) )->reward_weight == HIVE_100_PERCENT ); - - tx.operations.clear(); - tx.signatures.clear(); - - generate_blocks( db->head_block_time() + HIVE_MIN_ROOT_COMMENT_INTERVAL + fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - op.permlink = "test2"; - - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test2" ) ) )->reward_weight == HIVE_100_PERCENT ); - - generate_blocks( db->head_block_time() + HIVE_MIN_ROOT_COMMENT_INTERVAL + fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.permlink = "test3"; - - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test3" ) ) )->reward_weight == HIVE_100_PERCENT ); - - generate_blocks( db->head_block_time() + HIVE_MIN_ROOT_COMMENT_INTERVAL + fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.permlink = "test4"; - - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test4" ) ) )->reward_weight == HIVE_100_PERCENT ); - - generate_blocks( db->head_block_time() + HIVE_MIN_ROOT_COMMENT_INTERVAL + fc::seconds( HIVE_BLOCK_INTERVAL ), true ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.permlink = "test5"; - - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test5" ) ) )->reward_weight == HIVE_100_PERCENT ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_freeze ) -{ - try - { - ACTORS( (alice)(bob)(sam)(dave) ) - fund( "alice", 10000 ); - fund( "bob", 10000 ); - fund( "sam", 10000 ); - fund( "dave", 10000 ); - - vest( "alice", 10000 ); - vest( "bob", 10000 ); - vest( "sam", 10000 ); - vest( "dave", 10000 ); - - auto exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "1.250 TESTS" ) ); - set_price_feed( exchange_rate ); - - signed_transaction tx; - - comment_operation comment; - comment.author = "alice"; - comment.parent_author = ""; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.body = "test"; - - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - comment.body = "test2"; - - generate_block(); - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( comment ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - vote_operation vote; - vote.weight = HIVE_100_PERCENT; - vote.voter = "bob"; - vote.author = "alice"; - vote.permlink = "test"; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->last_payout == fc::time_point_sec::min() ); - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time != fc::time_point_sec::min() ); - BOOST_REQUIRE( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time != fc::time_point_sec::maximum() ); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time, true ); - - { - const comment_object& _comment = db->get_comment( "alice", string( "test" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - } - - vote.voter = "sam"; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - { - const comment_object& _comment = db->get_comment( "alice", string( "test" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - } - - vote.voter = "bob"; - vote.weight = HIVE_100_PERCENT * -1; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - { - const comment_object& _comment = db->get_comment( "alice", string( "test" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - } - - vote.voter = "dave"; - vote.weight = 0; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, dave_private_key ); - - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - { - const comment_object& _comment = db->get_comment( "alice", string( "test" ) ); - const comment_cashout_object* _comment_cashout = db->find_comment_cashout( _comment ); - BOOST_REQUIRE( _comment_cashout == nullptr ); - } - - comment.body = "test4"; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( comment ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); // Works now in #1714 - } - FC_LOG_AND_RETHROW() -} - -// This test is too intensive without optimizations. Disable it when we build in debug -BOOST_AUTO_TEST_CASE( hbd_stability ) -{ - #ifndef DEBUG - try - { - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.sps_fund_percent = 0; - gpo.content_reward_percent = 75 * HIVE_1_PERCENT; - }); - }, database::skip_witness_signature ); - - resize_shared_mem( 1024 * 1024 * 512 ); // Due to number of blocks in the test, it requires a large file. (64 MB) - - auto debug_key = "5JdouSvkK75TKWrJixYufQgePT21V7BAVWbNUWt3ktqhPmy8Z78"; //get_dev_key debug node - - ACTORS( (alice)(bob)(sam)(dave)(greg) ); - - fund( "alice", 10000 ); - fund( "bob", 10000 ); - - vest( "alice", 10000 ); - vest( "bob", 10000 ); - - auto exchange_rate = price( ASSET( "1.000 TBD" ), ASSET( "10.000 TESTS" ) ); - set_price_feed( exchange_rate ); - - BOOST_REQUIRE( db->get_dynamic_global_properties().get_hbd_print_rate() == HIVE_100_PERCENT ); - - comment_operation comment; - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "test"; - - signed_transaction tx; - tx.operations.push_back( comment ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - vote_operation vote; - vote.voter = "bob"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - - tx.operations.clear(); - tx.signatures.clear(); - - tx.operations.push_back( vote ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Generating blocks up to comment payout" ); - - db_plugin->debug_generate_blocks_until( debug_key, fc::time_point_sec( db->find_comment_cashout( db->get_comment( comment.author, comment.permlink ) )->cashout_time.sec_since_epoch() - 2 * HIVE_BLOCK_INTERVAL ), true, database::skip_witness_signature ); - - auto& gpo = db->get_dynamic_global_properties(); - - BOOST_TEST_MESSAGE( "Changing sam and gpo to set up market cap conditions" ); - - asset hbd_balance = asset( ( gpo.virtual_supply.amount * ( gpo.hbd_stop_percent + 112 ) ) / HIVE_100_PERCENT, HIVE_SYMBOL ) * exchange_rate; - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( "sam" ), [&]( account_object& a ) - { - a.hbd_balance = hbd_balance; - }); - }, database::skip_witness_signature ); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.current_hbd_supply = hbd_balance + db.get_treasury().get_hbd_balance(); - gpo.virtual_supply = gpo.virtual_supply + hbd_balance * exchange_rate; - }); - }, database::skip_witness_signature ); - - validate_database(); - - db_plugin->debug_generate_blocks( debug_key, 1, database::skip_witness_signature ); - - auto comment_reward = ( gpo.get_total_reward_fund_hive().amount + 2000 ) - ( ( gpo.get_total_reward_fund_hive().amount + 2000 ) * 25 * HIVE_1_PERCENT ) / HIVE_100_PERCENT ; - comment_reward /= 2; - auto hbd_reward = ( comment_reward * gpo.get_hbd_print_rate() ) / HIVE_100_PERCENT; - auto alice_hbd = get_hbd_balance( "alice" ) + get_hbd_rewards( "alice" ) + asset( hbd_reward, HIVE_SYMBOL ) * exchange_rate; - auto alice_hive = get_balance( "alice" ) + get_rewards( "alice" ) ; - - BOOST_TEST_MESSAGE( "Checking printing HBD has slowed" ); - BOOST_REQUIRE( db->get_dynamic_global_properties().get_hbd_print_rate() < HIVE_100_PERCENT ); - - BOOST_TEST_MESSAGE( "Pay out comment and check rewards are paid as HIVE" ); - db_plugin->debug_generate_blocks( debug_key, 1, database::skip_witness_signature ); - - validate_database(); - - BOOST_REQUIRE( get_hbd_balance( "alice" ) + get_hbd_rewards( "alice" ) == alice_hbd ); - BOOST_REQUIRE( get_balance( "alice" ) + get_rewards( "alice" ) > alice_hive ); - - BOOST_TEST_MESSAGE( "Letting percent market cap fall to hbd_start_percent to verify printing of HBD turns back on" ); - - // Get close to hbd_start_percent for printing HBD to start again, but not all the way - db_plugin->debug_update( [&]( database& db ) - { - db.modify( db.get_account( "sam" ), [&]( account_object& a ) - { - a.hbd_balance = asset( ( ( gpo.hbd_start_percent - 9 ) * hbd_balance.amount ) / gpo.hbd_stop_percent, HBD_SYMBOL ); - }); - }, database::skip_witness_signature ); - - auto current_hbd_supply = alice_hbd + asset( ( ( gpo.hbd_start_percent - 9 ) * hbd_balance.amount ) / gpo.hbd_stop_percent, HBD_SYMBOL ) + db->get_treasury().get_hbd_balance(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.current_hbd_supply = current_hbd_supply; - }); - }, database::skip_witness_signature ); - - db_plugin->debug_generate_blocks( debug_key, 1, database::skip_witness_signature ); - validate_database(); - - BOOST_REQUIRE( db->get_dynamic_global_properties().get_hbd_print_rate() < HIVE_100_PERCENT ); - - auto last_print_rate = db->get_dynamic_global_properties().get_hbd_print_rate(); - - // Keep producing blocks until printing HBD is back - while( ( db->get_dynamic_global_properties().get_current_hbd_supply() * exchange_rate ).amount >= ( db->get_dynamic_global_properties().virtual_supply.amount * db->get_dynamic_global_properties().hbd_start_percent ) / HIVE_100_PERCENT ) - { - auto& gpo = db->get_dynamic_global_properties(); - BOOST_REQUIRE( gpo.get_hbd_print_rate() >= last_print_rate ); - last_print_rate = gpo.get_hbd_print_rate(); - db_plugin->debug_generate_blocks( debug_key, 1, database::skip_witness_signature ); - if( db->head_block_num() % 1000 == 0 ) - validate_database(); - } - - validate_database(); - - BOOST_REQUIRE( db->get_dynamic_global_properties().get_hbd_print_rate() == HIVE_100_PERCENT ); - } - FC_LOG_AND_RETHROW() - #endif -} - -BOOST_AUTO_TEST_CASE( hbd_price_feed_limit ) -{ - try - { - ACTORS( (alice) ); - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - - price exchange_rate( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ); - set_price_feed( exchange_rate ); - - comment_operation comment; - comment.author = "alice"; - comment.permlink = "test"; - comment.parent_permlink = "test"; - comment.title = "test"; - comment.body = "test"; - - vote_operation vote; - vote.voter = "alice"; - vote.author = "alice"; - vote.permlink = "test"; - vote.weight = HIVE_100_PERCENT; - - signed_transaction tx; - tx.operations.push_back( comment ); - tx.operations.push_back( vote ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->find_comment_cashout( db->get_comment( "alice", string( "test" ) ) )->cashout_time, true ); - - BOOST_TEST_MESSAGE( "Setting HBD percent to greater than 10% market cap." ); - - db->skip_price_feed_limit_check = false; - const auto& gpo = db->get_dynamic_global_properties(); - auto new_exchange_rate = price( gpo.get_current_hbd_supply(), asset( ( HIVE_100_PERCENT ) * gpo.get_current_supply().amount, HIVE_SYMBOL ) ); - set_price_feed( new_exchange_rate ); - set_price_feed( new_exchange_rate ); - - BOOST_REQUIRE( db->get_feed_history().current_median_history > new_exchange_rate && db->get_feed_history().current_median_history < exchange_rate ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( clear_null_account ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing clearing the null account's balances on block" ); - - ACTORS( (alice) ); - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - fund( "alice", ASSET( "10.000 TESTS" ) ); - fund( "alice", ASSET( "10.000 TBD" ) ); - - transfer_operation transfer1; - transfer1.from = "alice"; - transfer1.to = HIVE_NULL_ACCOUNT; - transfer1.amount = ASSET( "1.000 TESTS" ); - - transfer_operation transfer2; - transfer2.from = "alice"; - transfer2.to = HIVE_NULL_ACCOUNT; - transfer2.amount = ASSET( "2.000 TBD" ); - - transfer_to_vesting_operation vest; - vest.from = "alice"; - vest.to = HIVE_NULL_ACCOUNT; - vest.amount = ASSET( "3.000 TESTS" ); - - transfer_to_savings_operation save1; - save1.from = "alice"; - save1.to = HIVE_NULL_ACCOUNT; - save1.amount = ASSET( "4.000 TESTS" ); - - transfer_to_savings_operation save2; - save2.from = "alice"; - save2.to = HIVE_NULL_ACCOUNT; - save2.amount = ASSET( "5.000 TBD" ); - - BOOST_TEST_MESSAGE( "--- Transferring to NULL Account" ); - - signed_transaction tx; - tx.operations.push_back( transfer1 ); - tx.operations.push_back( transfer2 ); - tx.operations.push_back( vest ); - tx.operations.push_back( save1); - tx.operations.push_back( save2 ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - validate_database(); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get_account( HIVE_NULL_ACCOUNT ), [&]( account_object& a ) - { - a.reward_hive_balance = ASSET( "1.000 TESTS" ); - a.reward_hbd_balance = ASSET( "1.000 TBD" ); - a.reward_vesting_balance = ASSET( "1.000000 VESTS" ); - a.reward_vesting_hive = ASSET( "1.000 TESTS" ); - }); - - db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) - { - gpo.current_supply += ASSET( "2.000 TESTS" ); - gpo.virtual_supply += ASSET( "3.000 TESTS" ); - gpo.current_hbd_supply += ASSET( "1.000 TBD" ); - gpo.pending_rewarded_vesting_shares += ASSET( "1.000000 VESTS" ); - gpo.pending_rewarded_vesting_hive += ASSET( "1.000 TESTS" ); - }); - }); - - validate_database(); - - BOOST_REQUIRE( get_balance( HIVE_NULL_ACCOUNT ) == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( HIVE_NULL_ACCOUNT ) == ASSET( "2.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( HIVE_NULL_ACCOUNT ) > ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( get_savings( HIVE_NULL_ACCOUNT ) == ASSET( "4.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_savings( HIVE_NULL_ACCOUNT ) == ASSET( "5.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "1.000 TBD" ) ); - BOOST_REQUIRE( get_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( get_vest_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "1.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( HIVE_NULL_ACCOUNT ) == ASSET( "1.000 TESTS" ) ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "2.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "3.000 TBD" ) ); - - BOOST_TEST_MESSAGE( "--- Generating block to clear balances" ); - generate_block(); - validate_database(); - - BOOST_REQUIRE( get_balance( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( HIVE_NULL_ACCOUNT ) == ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( get_savings( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_savings( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_vest_rewards( HIVE_NULL_ACCOUNT ) == ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( HIVE_NULL_ACCOUNT ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_balance( "alice" ) == ASSET( "2.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == ASSET( "3.000 TBD" ) ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generate_account_subsidies ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generate_account_subsidies" ); - - // The purpose of this test is to validate the dynamics of available_account_subsidies. - - // set_subsidy_budget creates a lot of blocks, so there should be enough for a few accounts - // half-life of 10 minutes - flat_map< string, vector<char> > props; - props["account_subsidy_budget"] = fc::raw::pack_to_vector( int32_t( 5123 ) ); - props["account_subsidy_decay"] = fc::raw::pack_to_vector( uint32_t( 249617279 ) ); - set_witness_props( props ); - - while( true ) - { - const witness_schedule_object& wso = db->get_witness_schedule_object(); - if( (wso.account_subsidy_rd.budget_per_time_unit == 5123) - && (wso.account_subsidy_rd.decay_params.decay_per_time_unit == 249617279) ) - break; - generate_block(); - } - - auto is_pool_in_equilibrium = []( int64_t pool, int32_t budget, const rd_decay_params& decay_params ) -> bool - { - int64_t decay = rd_compute_pool_decay( decay_params, pool, 1 ); - return (decay == budget); - }; - - const witness_schedule_object& wso = db->get_witness_schedule_object(); - BOOST_CHECK_EQUAL( wso.account_subsidy_rd.resource_unit, HIVE_ACCOUNT_SUBSIDY_PRECISION ); - BOOST_CHECK_EQUAL( wso.account_subsidy_rd.budget_per_time_unit, 5123 ); - BOOST_CHECK( is_pool_in_equilibrium( int64_t( wso.account_subsidy_rd.pool_eq ) , wso.account_subsidy_rd.budget_per_time_unit, wso.account_subsidy_rd.decay_params ) ); - BOOST_CHECK( !is_pool_in_equilibrium( int64_t( wso.account_subsidy_rd.pool_eq )-1, wso.account_subsidy_rd.budget_per_time_unit, wso.account_subsidy_rd.decay_params ) ); - - int64_t pool = db->get_dynamic_global_properties().available_account_subsidies; - - while( true ) - { - const dynamic_global_property_object& gpo = db->get_dynamic_global_properties(); - BOOST_CHECK_EQUAL( pool, gpo.available_account_subsidies ); - if( gpo.available_account_subsidies >= 100 * HIVE_ACCOUNT_SUBSIDY_PRECISION ) - break; - generate_block(); - pool = pool + 5123 - ((249617279 * pool) >> HIVE_RD_DECAY_DENOM_SHIFT); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( account_subsidy_witness_limits ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: account_subsidy_witness_limits" ); - - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - claim_account_operation op; - signed_transaction tx; - - BOOST_TEST_MESSAGE( "--- Test rejecting claim account when block is generated by a timeshare witness" ); - - // set_subsidy_budget creates a lot of blocks, so there should be enough for a few accounts - // half-life of 10 minutes - flat_map< string, vector<char> > props; - props["account_subsidy_budget"] = fc::raw::pack_to_vector( int32_t( 5000 ) ); - props["account_subsidy_decay"] = fc::raw::pack_to_vector( uint32_t( 249617279 ) ); - set_witness_props( props ); - - while( true ) - { - const dynamic_global_property_object& gpo = db->get_dynamic_global_properties(); - if( gpo.available_account_subsidies >= 100 * HIVE_ACCOUNT_SUBSIDY_PRECISION ) - break; - generate_block(); - } - - // Verify the timeshare witness can't create subsidized accounts - while( db->get< witness_object, by_name >( db->get_scheduled_witness( 1 ) ).schedule != witness_object::timeshare ) - { - generate_block(); - } - - op.creator = "alice"; - op.fee = ASSET( "0.000 TESTS" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 0 ); - BOOST_CHECK( db->_pending_tx.size() == 0 ); - - // Pushes successfully - db->push_transaction( tx, 0 ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 1 ); - BOOST_CHECK( db->_pending_tx.size() == 1 ); - - do - { - generate_block(); - - // The transaction fails in generate_block(), meaning it is removed from the local node's transaction list - BOOST_CHECK_EQUAL( db->fetch_block_by_number( db->head_block_num() )->transactions.size(), 0 ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 0 ); - BOOST_CHECK_EQUAL( db->_pending_tx.size(), 0 ); - } while( db->get< witness_object, by_name >( db->get_scheduled_witness( 1 ) ).schedule == witness_object::timeshare ); - - db->push_transaction( tx, 0 ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 1 ); - BOOST_CHECK( db->_pending_tx.size() == 1 ); - // But generate another block, as a non-time-share witness, and it works - generate_block(); - BOOST_CHECK_EQUAL( db->fetch_block_by_number( db->head_block_num() )->transactions.size(), 1 ); - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == 1 ); - BOOST_CHECK_EQUAL( db->_pending_tx.size(), 0 ); - - while( db->get< witness_object, by_name >( db->get_scheduled_witness( 1 ) ).schedule == witness_object::timeshare ) - { - generate_block(); - } - - fc::time_point_sec expiration = db->head_block_time() + fc::seconds(60); - size_t n = size_t( db->get< witness_object, by_name >( db->get_scheduled_witness( 1 ) ).available_witness_account_subsidies / HIVE_ACCOUNT_SUBSIDY_PRECISION ); - - ilog( "Creating ${np1} transactions", ("np1", n+1) ); - // Create n+1 transactions - for( size_t i=0; i<=n; i++ ) - { - tx.signatures.clear(); - tx.set_expiration( expiration ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - expiration += fc::seconds(3); - } - BOOST_CHECK( db->get_account( "alice" ).pending_claimed_accounts == n+2 ); - BOOST_CHECK_EQUAL( db->_pending_tx.size(), n+1 ); - generate_block(); - BOOST_CHECK_EQUAL( db->fetch_block_by_number( db->head_block_num() )->transactions.size(), n ); - BOOST_CHECK_EQUAL( db->_pending_tx.size(), 1 ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/operation_vistitor.cpp b/tests2/unit/tests/operation_vistitor.cpp deleted file mode 100644 index 20b23d6f16e288c91e8bd53ecc8a9a9f8d92a3b4..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/operation_vistitor.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include <boost/test/unit_test.hpp> - -#include <fc/variant.hpp> -#include <fc/variant_object.hpp> - -#include <hive/protocol/operations.hpp> - -#include <chrono> - -BOOST_AUTO_TEST_SUITE( operation_visitor ) - -struct stub_visitor -{ - typedef void result_type; - - template<typename Type> - result_type operator()( const Type& op )const { return;} -}; - -BOOST_AUTO_TEST_CASE( visit_performance ) { - try { - hive::protocol::operation operation_under_test; - stub_visitor visitor; - - BOOST_TEST_MESSAGE( "Start of visit_performance test" ); - for ( auto type_id = 0; type_id < operation_under_test.count(); ++type_id) - { - operation_under_test.set_which(type_id); - auto start = std::chrono::high_resolution_clock::now(); - for (auto j = 0; j < 100'000'000; j++) { - operation_under_test.visit(visitor); - } - auto end = std::chrono::high_resolution_clock::now(); - BOOST_TEST_MESSAGE( "element " << type_id << " [ns] :" << std::chrono::duration_cast< std::chrono::nanoseconds >(end - start).count() ); - } - BOOST_TEST_MESSAGE( "End of visit_performance test" ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests2/unit/tests/proposal_tests.cpp b/tests2/unit/tests/proposal_tests.cpp deleted file mode 100644 index 762639364cc4cef994bdb27072c33df0b1cb38de..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/proposal_tests.cpp +++ /dev/null @@ -1,3244 +0,0 @@ -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> -#include <hive/protocol/sps_operations.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <hive/plugins/rc/rc_objects.hpp> -#include <hive/plugins/rc/resource_count.hpp> - -#include <hive/chain/sps_objects.hpp> -#include <hive/chain/util/sps_processor.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -template< typename PROPOSAL_IDX > -int64_t calc_proposals( const PROPOSAL_IDX& proposal_idx, const std::vector< int64_t >& proposals_id ) -{ - auto cnt = 0; - for( auto pid : proposals_id ) - cnt += proposal_idx.find( pid ) != proposal_idx.end() ? 1 : 0; - return cnt; -} - -template< typename PROPOSAL_IDX > -uint64_t calc_total_votes( const PROPOSAL_IDX& proposal_idx, uint64_t proposal_id ) -{ - auto found = proposal_idx.find( proposal_id ); - - if( found == proposal_idx.end() ) - return 0; - else - return found->total_votes; -} - -template< typename PROPOSAL_VOTE_IDX > -int64_t calc_proposal_votes( const PROPOSAL_VOTE_IDX& proposal_vote_idx, uint64_t proposal_id ) -{ - auto cnt = 0; - auto found = proposal_vote_idx.find( proposal_id ); - while( found != proposal_vote_idx.end() && found->proposal_id == proposal_id ) - { - ++cnt; - ++found; - } - return cnt; -} - -template< typename PROPOSAL_VOTE_IDX > -int64_t calc_votes( const PROPOSAL_VOTE_IDX& proposal_vote_idx, const std::vector< int64_t >& proposals_id ) -{ - auto cnt = 0; - for( auto id : proposals_id ) - cnt += calc_proposal_votes( proposal_vote_idx, id ); - return cnt; -} - -BOOST_FIXTURE_TEST_SUITE( proposal_tests, sps_proposal_database_fixture ) - -BOOST_AUTO_TEST_CASE( inactive_proposals_have_votes ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: proposals before activation can have votes" ); - - ACTORS( (alice)(bob)(carol)(dan) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - uint64_t found_votes_00 = 0; - uint64_t found_votes_01 = 0; - - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time(); - - auto daily_pay = ASSET( "48.000 TBD" ); - auto hourly_pay = ASSET( "1.996 TBD" );// hourly_pay != ASSET( "2.000 TBD" ) because lack of rounding - - FUND( creator, ASSET( "160.000 TESTS" ) ); - FUND( creator, ASSET( "80.000 TBD" ) ); - FUND( db->get_treasury_name(), ASSET( "5000.000 TBD" ) ); - - auto voter_00 = "carol"; - auto voter_01 = "dan"; - - vest(HIVE_INIT_MINER_NAME, voter_00, ASSET( "1.000 TESTS" )); - vest(HIVE_INIT_MINER_NAME, voter_01, ASSET( "3.100 TESTS" )); - - //Due to the `delaying votes` algorithm, generate blocks for 30 days in order to activate whole votes' pool ( take a look at `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ) - start_date += fc::seconds( HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - generate_blocks( start_date ); - - start_date = db->head_block_time(); - - auto start_date_02 = start_date + fc::hours( 24 ); - - auto end_date = start_date + fc::hours( 48 ); - auto end_date_02 = start_date_02 + fc::hours( 48 ); - //=====================preparing===================== - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - - //Needed basic operations - int64_t id_proposal_00 = create_proposal( creator, receiver, start_date, end_date, daily_pay, alice_private_key ); - generate_blocks( 1 ); - int64_t id_proposal_01 = create_proposal( creator, receiver, start_date_02, end_date_02, daily_pay, alice_private_key ); - generate_blocks( 1 ); - - /* - proposal_00 - `start_date` = (now) -> `end_date` (now + 48h) - - proposal_01 - start_date` = (now + 24h) ` -> `end_date` (now + 72h) - */ - { - found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, 0 ); - BOOST_REQUIRE_EQUAL( found_votes_01, 0 ); - } - - vote_proposal( voter_00, { id_proposal_00 }, true/*approve*/, carol_private_key ); - generate_blocks( 1 ); - - { - found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, 0 ); - BOOST_REQUIRE_EQUAL( found_votes_01, 0 ); - } - - vote_proposal( voter_01, { id_proposal_01 }, true/*approve*/, dan_private_key ); - generate_blocks( 1 ); - - { - found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, 0 ); - BOOST_REQUIRE_EQUAL( found_votes_01, 0 ); - } - - //skipping interest generating is necessary - transfer( HIVE_INIT_MINER_NAME, receiver, ASSET( "0.001 TBD" )); - generate_block( 5 ); - transfer( HIVE_INIT_MINER_NAME, db->get_treasury_name(), ASSET( "0.001 TBD" ) ); - generate_block( 5 ); - - const auto& dgpo = db->get_dynamic_global_properties(); - auto old_hbd_supply = dgpo.current_hbd_supply; - - - const account_object& _creator = db->get_account( creator ); - const account_object& _receiver = db->get_account( receiver ); - const account_object& _voter_01 = db->get_account( voter_01 ); - const account_object& _treasury = db->get_treasury(); - - { - BOOST_TEST_MESSAGE( "---Payment---" ); - - auto before_creator_hbd_balance = _creator.hbd_balance; - auto before_receiver_hbd_balance = _receiver.hbd_balance; - auto before_voter_01_hbd_balance = _voter_01.hbd_balance; - auto before_treasury_hbd_balance = _treasury.hbd_balance; - - auto next_block = get_nr_blocks_until_maintenance_block(); - generate_blocks( next_block - 1 ); - generate_blocks( 1 ); - - auto treasury_hbd_inflation = dgpo.current_hbd_supply - old_hbd_supply; - auto after_creator_hbd_balance = _creator.hbd_balance; - auto after_receiver_hbd_balance = _receiver.hbd_balance; - auto after_voter_01_hbd_balance = _voter_01.hbd_balance; - auto after_treasury_hbd_balance = _treasury.hbd_balance; - - BOOST_REQUIRE( before_creator_hbd_balance == after_creator_hbd_balance ); - BOOST_REQUIRE( before_receiver_hbd_balance == after_receiver_hbd_balance - hourly_pay ); - BOOST_REQUIRE( before_voter_01_hbd_balance == after_voter_01_hbd_balance ); - BOOST_REQUIRE( before_treasury_hbd_balance == after_treasury_hbd_balance - treasury_hbd_inflation + hourly_pay ); - } - /* - Reminder: - - proposal_00 - `start_date` = (now) -> `end_date` (now + 48h) - - proposal_01 - start_date` = (now + 24h) ` -> `end_date` (now + 72h) - */ - { - //Passed ~1h - one reward for `proposal_00` was paid out - found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_GT( found_votes_00, 0 ); - BOOST_REQUIRE_GT( found_votes_01, 0 ); - } - { - auto time_movement = start_date + fc::hours( 24 ); - generate_blocks( time_movement ); - - //Passed ~25h - both proposals have `total_votes` - auto _found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - auto _found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, _found_votes_00 ); - BOOST_REQUIRE_EQUAL( found_votes_01, _found_votes_01 ); - } - { - auto time_movement = start_date + fc::hours( 27 ); - generate_blocks( time_movement ); - - //Passed ~28h - both proposals have `total_votes` - auto _found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - auto _found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, _found_votes_00 ); - BOOST_REQUIRE_EQUAL( found_votes_01, _found_votes_01 ); - } - { - auto time_movement = start_date + fc::hours( 47 ); - generate_blocks( time_movement ); - - //Passed ~28h - both proposals have `total_votes` - auto _found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - auto _found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, _found_votes_00 ); - BOOST_REQUIRE_EQUAL( found_votes_01, _found_votes_01 ); - } - { - auto time_movement = start_date + fc::hours( 71 ); - generate_blocks( time_movement ); - - //Passed ~28h - both proposals have `total_votes` - auto _found_votes_00 = calc_total_votes( proposal_idx, id_proposal_00 ); - auto _found_votes_01 = calc_total_votes( proposal_idx, id_proposal_01 ); - BOOST_REQUIRE_EQUAL( found_votes_00, _found_votes_00 ); - BOOST_REQUIRE_EQUAL( found_votes_01, _found_votes_01 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generating_payments ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generating payments" ); - - ACTORS( (alice)(bob)(carol) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time(); - - auto daily_pay = ASSET( "48.000 TBD" ); - auto hourly_pay = ASSET( "1.996 TBD" );// hourly_pay != ASSET( "2.000 TBD" ) because lack of rounding - - FUND( creator, ASSET( "160.000 TESTS" ) ); - FUND( creator, ASSET( "80.000 TBD" ) ); - FUND( db->get_treasury_name(), ASSET( "5000.000 TBD" ) ); - - auto voter_01 = "carol"; - - vest(HIVE_INIT_MINER_NAME, voter_01, ASSET( "1.000 TESTS" )); - - //Due to the `delaying votes` algorithm, generate blocks for 30 days in order to activate whole votes' pool ( take a look at `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ) - start_date += fc::seconds( HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - generate_blocks( start_date ); - - auto end_date = start_date + fc::days( 2 ); - //=====================preparing===================== - - //Needed basic operations - int64_t id_proposal_00 = create_proposal( creator, receiver, start_date, end_date, daily_pay, alice_private_key ); - generate_blocks( 1 ); - - vote_proposal( voter_01, { id_proposal_00 }, true/*approve*/, carol_private_key ); - generate_blocks( 1 ); - - //skipping interest generating is necessary - transfer( HIVE_INIT_MINER_NAME, receiver, ASSET( "0.001 TBD" )); - generate_block( 5 ); - transfer( HIVE_INIT_MINER_NAME, db->get_treasury_name(), ASSET( "0.001 TBD" ) ); - generate_block( 5 ); - - const auto& dgpo = db->get_dynamic_global_properties(); - auto old_hbd_supply = dgpo.get_current_hbd_supply(); - - - const account_object& _creator = db->get_account( creator ); - const account_object& _receiver = db->get_account( receiver ); - const account_object& _voter_01 = db->get_account( voter_01 ); - const account_object& _treasury = db->get_treasury(); - - { - BOOST_TEST_MESSAGE( "---Payment---" ); - - auto before_creator_hbd_balance = _creator.get_hbd_balance(); - auto before_receiver_hbd_balance = _receiver.get_hbd_balance(); - auto before_voter_01_hbd_balance = _voter_01.get_hbd_balance(); - auto before_treasury_hbd_balance = _treasury.get_hbd_balance(); - - auto next_block = get_nr_blocks_until_maintenance_block(); - generate_blocks( next_block - 1 ); - generate_blocks( 1 ); - - auto treasury_hbd_inflation = dgpo.get_current_hbd_supply() - old_hbd_supply; - auto after_creator_hbd_balance = _creator.get_hbd_balance(); - auto after_receiver_hbd_balance = _receiver.get_hbd_balance(); - auto after_voter_01_hbd_balance = _voter_01.get_hbd_balance(); - auto after_treasury_hbd_balance = _treasury.get_hbd_balance(); - - BOOST_REQUIRE( before_creator_hbd_balance == after_creator_hbd_balance ); - BOOST_REQUIRE( before_receiver_hbd_balance == after_receiver_hbd_balance - hourly_pay ); - BOOST_REQUIRE( before_voter_01_hbd_balance == after_voter_01_hbd_balance ); - BOOST_REQUIRE( before_treasury_hbd_balance == after_treasury_hbd_balance - treasury_hbd_inflation + hourly_pay ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generating_payments_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generating payments" ); - - ACTORS( (tester001)(tester002)(tester003)(tester004)(tester005) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - const auto nr_proposals = 5; - std::vector< int64_t > proposals_id; - flat_map< std::string, asset > before_tbds; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"tester001", tester001_private_key }, - {"tester002", tester002_private_key }, - {"tester003", tester003_private_key }, - {"tester004", tester004_private_key }, - {"tester005", tester005_private_key }, - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "400.000 TESTS" ) ); - FUND( item.account, ASSET( "400.000 TBD" ) ); - vest(HIVE_INIT_MINER_NAME, item.account, ASSET( "300.000 TESTS" )); - } - - auto start_date = db->head_block_time(); - const auto end_time_shift = fc::hours( 5 ); - - //Due to the `delaying votes` algorithm, generate blocks for 30 days in order to activate whole votes' pool ( take a look at `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ) - start_date += fc::seconds( HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - generate_blocks( start_date ); - - auto end_date = start_date + end_time_shift; - - auto daily_pay = ASSET( "24.000 TBD" ); - auto paid = ASSET( "4.990 TBD" );// paid != ASSET( "5.000 TBD" ) because lack of rounding - - FUND( db->get_treasury_name(), ASSET( "5000000.000 TBD" ) ); - //=====================preparing===================== - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - proposals_id.push_back( create_proposal( item.account, item.account, start_date, end_date, daily_pay, item.key ) ); - generate_block(); - } - - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - vote_proposal( item.account, proposals_id, true/*approve*/, item.key ); - generate_block(); - } - - for( auto item : inits ) - { - const account_object& account = db->get_account( item.account ); - before_tbds[ item.account ] = account.get_hbd_balance(); - } - - generate_blocks( start_date + end_time_shift + fc::seconds( 10 ), false ); - - for( auto item : inits ) - { - const account_object& account = db->get_account( item.account ); - auto after_tbd = account.get_hbd_balance(); - auto before_tbd = before_tbds[ item.account ]; - BOOST_REQUIRE( before_tbd == after_tbd - paid ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generating_payments_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generating payments, but proposal are removed" ); - - ACTORS( - (a00)(a01)(a02)(a03)(a04)(a05)(a06)(a07)(a08)(a09) - (a10)(a11)(a12)(a13)(a14)(a15)(a16)(a17)(a18)(a19) - (a20)(a21)(a22)(a23)(a24)(a25)(a26)(a27)(a28)(a29) - (a30)(a31)(a32)(a33)(a34)(a35)(a36)(a37)(a38)(a39) - (a40)(a41)(a42)(a43)(a44)(a45)(a46)(a47)(a48)(a49) - ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - flat_map< std::string, asset > before_tbds; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, {"a01", a01_private_key }, {"a02", a02_private_key }, {"a03", a03_private_key }, {"a04", a04_private_key }, - {"a05", a05_private_key }, {"a06", a06_private_key }, {"a07", a07_private_key }, {"a08", a08_private_key }, {"a09", a09_private_key }, - {"a10", a10_private_key }, {"a11", a11_private_key }, {"a12", a12_private_key }, {"a13", a13_private_key }, {"a14", a14_private_key }, - {"a15", a15_private_key }, {"a16", a16_private_key }, {"a17", a17_private_key }, {"a18", a18_private_key }, {"a19", a19_private_key }, - {"a20", a20_private_key }, {"a21", a21_private_key }, {"a22", a22_private_key }, {"a23", a23_private_key }, {"a24", a24_private_key }, - {"a25", a25_private_key }, {"a26", a26_private_key }, {"a27", a27_private_key }, {"a28", a28_private_key }, {"a29", a29_private_key }, - {"a30", a30_private_key }, {"a31", a31_private_key }, {"a32", a32_private_key }, {"a33", a33_private_key }, {"a34", a34_private_key }, - {"a35", a35_private_key }, {"a36", a36_private_key }, {"a37", a37_private_key }, {"a38", a38_private_key }, {"a39", a39_private_key }, - {"a40", a40_private_key }, {"a41", a41_private_key }, {"a42", a42_private_key }, {"a43", a43_private_key }, {"a44", a44_private_key }, - {"a45", a45_private_key }, {"a46", a46_private_key }, {"a47", a47_private_key }, {"a48", a48_private_key }, {"a49", a49_private_key } - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "400.000 TESTS" ) ); - FUND( item.account, ASSET( "400.000 TBD" ) ); - vest(HIVE_INIT_MINER_NAME, item.account, ASSET( "300.000 TESTS" )); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto start_date = db->head_block_time() + fc::hours( 2 ); - auto end_date = start_date + fc::days( 15 ); - - const auto block_interval = fc::seconds( HIVE_BLOCK_INTERVAL ); - - FUND( db->get_treasury_name(), ASSET( "5000000.000 TBD" ) ); - //=====================preparing===================== - auto item_creator = inits[ 0 ]; - create_proposal( item_creator.account, item_creator.account, start_date, end_date, ASSET( "24.000 TBD" ), item_creator.key ); - generate_block(); - - for( auto item : inits ) - { - vote_proposal( item.account, {0}, true/*approve*/, item.key); - - generate_block(); - - const account_object& account = db->get_account( item.account ); - before_tbds[ item.account ] = account.get_hbd_balance(); - } - - generate_blocks( start_date, false ); - generate_blocks( db->get_dynamic_global_properties().next_maintenance_time - block_interval, false ); - - { - remove_proposal( item_creator.account, {0}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, {0} ); - auto found_votes = calc_proposal_votes( proposal_vote_idx, 0 ); - BOOST_REQUIRE( found_proposals == 1 ); - BOOST_REQUIRE( found_votes == 30 ); - } - - { - generate_block(); - auto found_proposals = calc_proposals( proposal_idx, {0} ); - auto found_votes = calc_proposal_votes( proposal_vote_idx, 0 ); - BOOST_REQUIRE( found_proposals == 1 ); - BOOST_REQUIRE( found_votes == 10 ); - } - - for( auto item : inits ) - { - const account_object& account = db->get_account( item.account ); - auto after_tbd = account.get_hbd_balance(); - auto before_tbd = before_tbds[ item.account ]; - BOOST_REQUIRE( before_tbd == after_tbd ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generating_payments_03 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generating payments" ); - - std::string tester00_account = "tester00"; - std::string tester01_account = "tester01"; - std::string tester02_account = "tester02"; - - ACTORS( (tester00)(tester01)(tester02) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - std::vector< int64_t > proposals_id; - flat_map< std::string, asset > before_tbds; - - flat_map< std::string, fc::ecc::private_key > inits; - inits[ "tester00" ] = tester00_private_key; - inits[ "tester01" ] = tester01_private_key; - inits[ "tester02" ] = tester02_private_key; - - for( auto item : inits ) - { - if( item.first == tester02_account ) - { - FUND( item.first, ASSET( "41.000 TESTS" ) ); - FUND( item.first, ASSET( "41.000 TBD" ) ); - vest(HIVE_INIT_MINER_NAME, item.first, ASSET( "31.000 TESTS" )); - } - else - { - FUND( item.first, ASSET( "40.000 TESTS" ) ); - FUND( item.first, ASSET( "40.000 TBD" ) ); - vest(HIVE_INIT_MINER_NAME, item.first, ASSET( "30.000 TESTS" )); - } - } - - auto start_date = db->head_block_time(); - - //Due to the `delaying votes` algorithm, generate blocks for 30 days in order to activate whole votes' pool ( take a look at `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ) - start_date += fc::seconds( HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - generate_blocks( start_date ); - generate_block(); - - uint16_t interval = 0; - std::vector< fc::microseconds > end_time_shift = { fc::hours( 1 ), fc::hours( 2 ), fc::hours( 3 ), fc::hours( 4 ) }; - auto end_date = start_date + end_time_shift[ 3 ]; - - auto huge_daily_pay = ASSET( "50000001.000 TBD" ); - auto daily_pay = ASSET( "24.000 TBD" ); - - FUND( db->get_treasury_name(), ASSET( "5000000.000 TBD" ) ); - //=====================preparing===================== - uint16_t i = 0; - for( auto item : inits ) - { - auto _pay = ( item.first == tester02_account ) ? huge_daily_pay : daily_pay; - proposals_id.push_back( create_proposal( item.first, item.first, start_date, end_date, _pay, item.second ) ); - generate_block(); - - if( item.first == tester02_account ) - continue; - - vote_proposal( item.first, {i++}, true/*approve*/, item.second ); - generate_block(); - } - - for( auto item : inits ) - { - const account_object& account = db->get_account( item.first ); - before_tbds[ item.first ] = account.get_hbd_balance(); - } - - auto payment_checker = [&]( const std::vector< asset >& payouts ) - { - idump( (inits) ); - idump( (payouts) ); - uint16_t i = 0; - for( const auto& item : inits ) - { - const account_object& account = db->get_account( item.first ); - auto after_tbd = account.get_hbd_balance(); - auto before_tbd = before_tbds[ item.first ]; - idump( (before_tbd) ); - idump( (after_tbd) ); - idump( (payouts[i]) ); - //idump( (after_tbd - payouts[i++]) ); - BOOST_REQUIRE( before_tbd == after_tbd - payouts[i++] ); - } - }; - - /* - Initial conditions. - `tester00` has own proposal id = 0 : voted for it - `tester01` has own proposal id = 1 : voted for it - `tester02` has own proposal id = 2 : lack of votes - */ - - generate_blocks( start_date + end_time_shift[ interval++ ] + fc::seconds( 10 ), false ); - /* - `tester00` - got payout - `tester01` - got payout - `tester02` - no payout, because of lack of votes - */ - ilog(""); - payment_checker( { ASSET( "0.998 TBD" ), ASSET( "0.998 TBD" ), ASSET( "0.000 TBD" ) } ); - //ideally: ASSET( "1.000 TBD" ), ASSET( "1.000 TBD" ), ASSET( "0.000 TBD" ) but there is lack of rounding - - { - BOOST_TEST_MESSAGE( "Setting proxy. The account `tester01` don't want to vote. Every decision is made by account `tester00`" ); - account_witness_proxy_operation op; - op.account = tester01_account; - op.proxy = tester00_account; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, inits[ tester01_account ] ); - db->push_transaction( tx, 0 ); - } - - generate_blocks( start_date + end_time_shift[ interval++ ] + fc::seconds( 10 ), false ); - /* - `tester00` - got payout - `tester01` - no payout, because this account set proxy - `tester02` - no payout, because of lack of votes - */ - ilog(""); - payment_checker( { ASSET( "1.996 TBD" ), ASSET( "0.998 TBD" ), ASSET( "0.000 TBD" ) } ); - //ideally: ASSET( "2.000 TBD" ), ASSET( "1.000 TBD" ), ASSET( "0.000 TBD" ) but there is lack of rounding - - vote_proposal( tester02_account, {2}, true/*approve*/, inits[ tester02_account ] ); - generate_block(); - - generate_blocks( start_date + end_time_shift[ interval++ ] + fc::seconds( 10 ), false ); - /* - `tester00` - got payout, `tester02` has less votes than `tester00` - `tester01` - no payout, because this account set proxy - `tester02` - got payout, because voted for his proposal - */ - ilog(""); - payment_checker( { ASSET( "2.994 TBD" ), ASSET( "0.998 TBD" ), ASSET( "2082.369 TBD" ) } ); - //ideally: ASSET( "3.000 TBD" ), ASSET( "1.000 TBD" ), ASSET( "2082.346 TBD" ) but there is lack of rounding - - { - BOOST_TEST_MESSAGE( "Proxy doesn't exist. Now proposal with id = 3 has the most votes. This proposal grabs all payouts." ); - account_witness_proxy_operation op; - op.account = tester01_account; - op.proxy = ""; - - signed_transaction tx; - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, inits[ tester01_account ] ); - db->push_transaction( tx, 0 ); - } - - generate_blocks( start_date + end_time_shift[ interval++ ] + fc::seconds( 10 ), false ); - /* - `tester00` - no payout, because is not enough money. `tester01` removed proxy and the most votes has `tester02`. Whole payout goes to `tester02` - `tester01` - no payout, because is not enough money - `tester02` - got payout, because voted for his proposal - */ - ilog(""); - payment_checker( { ASSET( "2.994 TBD" ), ASSET( "0.998 TBD" ), ASSET( "4164.874 TBD" ) } ); - //ideally: ASSET( "3.000 TBD" ), ASSET( "1.000 TBD" ), ASSET( "4164.824 TBD" ) but there is lack of rounding - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_maintenance) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing inactive proposals" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto creator = "alice"; - auto receiver = "bob"; - - auto start_time = db->head_block_time(); - - auto start_date_00 = start_time + fc::seconds( 30 ); - auto end_date_00 = start_time + fc::minutes( 10 ); - - auto start_date_01 = start_time + fc::seconds( 40 ); - auto end_date_01 = start_time + fc::minutes( 30 ); - - auto start_date_02 = start_time + fc::seconds( 50 ); - auto end_date_02 = start_time + fc::minutes( 20 ); - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - FUND( creator, ASSET( "100.000 TBD" ) ); - //=====================preparing===================== - - int64_t id_proposal_00 = create_proposal( creator, receiver, start_date_00, end_date_00, daily_pay, alice_private_key ); - generate_block(); - - int64_t id_proposal_01 = create_proposal( creator, receiver, start_date_01, end_date_01, daily_pay, alice_private_key ); - generate_block(); - - int64_t id_proposal_02 = create_proposal( creator, receiver, start_date_02, end_date_02, daily_pay, alice_private_key ); - generate_block(); - - { - BOOST_REQUIRE( exist_proposal( id_proposal_00 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_01 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_02 ) ); - - generate_blocks( start_time + fc::seconds( HIVE_PROPOSAL_MAINTENANCE_CLEANUP ) ); - start_time = db->head_block_time(); - - BOOST_REQUIRE( exist_proposal( id_proposal_00 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_01 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_02 ) ); - - generate_blocks( start_time + fc::minutes( 11 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_00 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_01 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_02 ) ); - - generate_blocks( start_time + fc::minutes( 21 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_00 ) ); - BOOST_REQUIRE( exist_proposal( id_proposal_01 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_02 ) ); - - generate_blocks( start_time + fc::minutes( 31 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_00 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_01 ) ); - BOOST_REQUIRE( !exist_proposal( id_proposal_02 ) ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - - -BOOST_AUTO_TEST_CASE( proposal_object_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create_proposal_operation" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto fee = asset( HIVE_TREASURY_FEE, HBD_SYMBOL ); - - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time() + fc::days( 1 ); - auto end_date = start_date + fc::days( 2 ); - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - auto subject = "hello"; - auto permlink = "somethingpermlink"; - - post_comment(creator, permlink, "title", "body", "test", alice_private_key); - - FUND( creator, ASSET( "80.000 TBD" ) ); - - signed_transaction tx; - - const account_object& before_treasury_account = db->get_treasury(); - const account_object& before_alice_account = db->get_account( creator ); - const account_object& before_bob_account = db->get_account( receiver ); - - auto before_alice_hbd_balance = before_alice_account.get_hbd_balance(); - auto before_bob_hbd_balance = before_bob_account.get_hbd_balance(); - auto before_treasury_balance = before_treasury_account.get_hbd_balance(); - - create_proposal_operation op; - - op.creator = creator; - op.receiver = receiver; - - op.start_date = start_date; - op.end_date = end_date; - - op.daily_pay = daily_pay; - - op.subject = subject; - op.permlink = permlink; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - const auto& after_treasury_account = db->get_treasury(); - const account_object& after_alice_account = db->get_account( creator ); - const account_object& after_bob_account = db->get_account( receiver ); - - auto after_alice_hbd_balance = after_alice_account.get_hbd_balance(); - auto after_bob_hbd_balance = after_bob_account.get_hbd_balance(); - auto after_treasury_balance = after_treasury_account.get_hbd_balance(); - - BOOST_REQUIRE( before_alice_hbd_balance == after_alice_hbd_balance + fee ); - BOOST_REQUIRE( before_bob_hbd_balance == after_bob_hbd_balance ); - /// Fee shall be paid to treasury account. - BOOST_REQUIRE(before_treasury_balance == after_treasury_balance - fee); - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - - BOOST_REQUIRE( found->creator == creator ); - BOOST_REQUIRE( found->receiver == receiver ); - BOOST_REQUIRE( found->start_date == start_date ); - BOOST_REQUIRE( found->end_date == end_date ); - BOOST_REQUIRE( found->daily_pay == daily_pay ); - BOOST_REQUIRE( found->subject == subject ); - BOOST_REQUIRE( found->permlink == permlink ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposal_vote_object_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: proposal_vote_object_operation" ); - - ACTORS( (alice)(bob)(carol)(dan) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time() + fc::days( 1 ); - auto end_date = start_date + fc::days( 2 ); - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - FUND( creator, ASSET( "80.000 TBD" ) ); - - int64_t id_proposal_00 = create_proposal( creator, receiver, start_date, end_date, daily_pay, alice_private_key ); - - signed_transaction tx; - update_proposal_votes_operation op; - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_voter_proposal >(); - - auto voter_01 = "carol"; - auto voter_01_key = carol_private_key; - - { - BOOST_TEST_MESSAGE( "---Voting for proposal( `id_proposal_00` )---" ); - op.voter = voter_01; - op.proposal_ids.insert( id_proposal_00 ); - op.approve = true; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - auto found = proposal_vote_idx.find( boost::make_tuple( voter_01, id_proposal_00 ) ); - BOOST_REQUIRE( found->voter == voter_01 ); - BOOST_REQUIRE( found->proposal_id == id_proposal_00 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting proposal( `id_proposal_00` )---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_00 ); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - auto found = proposal_vote_idx.find( boost::make_tuple( voter_01, id_proposal_00 ) ); - BOOST_REQUIRE( found == proposal_vote_idx.end() ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposal_vote_object_01_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: proposal_vote_object_operation" ); - - ACTORS( (alice)(bob)(carol)(dan) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time() + fc::days( 1 ); - auto end_date = start_date + fc::days( 2 ); - - auto daily_pay_00 = asset( 100, HBD_SYMBOL ); - auto daily_pay_01 = asset( 101, HBD_SYMBOL ); - auto daily_pay_02 = asset( 102, HBD_SYMBOL ); - - FUND( creator, ASSET( "80.000 TBD" ) ); - - int64_t id_proposal_00 = create_proposal( creator, receiver, start_date, end_date, daily_pay_00, alice_private_key ); - int64_t id_proposal_01 = create_proposal( creator, receiver, start_date, end_date, daily_pay_01, alice_private_key ); - - signed_transaction tx; - update_proposal_votes_operation op; - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_voter_proposal >(); - - std::string voter_01 = "carol"; - auto voter_01_key = carol_private_key; - - { - BOOST_TEST_MESSAGE( "---Voting by `voter_01` for proposals( `id_proposal_00`, `id_proposal_01` )---" ); - op.voter = voter_01; - op.proposal_ids.insert( id_proposal_00 ); - op.proposal_ids.insert( id_proposal_01 ); - op.approve = true; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 2 ); - } - - int64_t id_proposal_02 = create_proposal( creator, receiver, start_date, end_date, daily_pay_02, alice_private_key ); - std::string voter_02 = "dan"; - auto voter_02_key = dan_private_key; - - { - BOOST_TEST_MESSAGE( "---Voting by `voter_02` for proposals( `id_proposal_00`, `id_proposal_01`, `id_proposal_02` )---" ); - op.voter = voter_02; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_02 ); - op.proposal_ids.insert( id_proposal_00 ); - op.proposal_ids.insert( id_proposal_01 ); - op.approve = true; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_02_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_02 ); - while( found != proposal_vote_idx.end() && found->voter == voter_02 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 3 ); - } - - { - BOOST_TEST_MESSAGE( "---Voting by `voter_02` for proposals( `id_proposal_00` )---" ); - op.voter = voter_02; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_00 ); - op.approve = true; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_02_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_02 ); - while( found != proposal_vote_idx.end() && found->voter == voter_02 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 3 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting by `voter_01` proposals( `id_proposal_02` )---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_02 ); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 2 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting by `voter_01` proposals( `id_proposal_00` )---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_00 ); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 1 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting by `voter_02` proposals( `id_proposal_00`, `id_proposal_01`, `id_proposal_02` )---" ); - op.voter = voter_02; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_02 ); - op.proposal_ids.insert( id_proposal_01 ); - op.proposal_ids.insert( id_proposal_00 ); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_02_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_02 ); - while( found != proposal_vote_idx.end() && found->voter == voter_02 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 0 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting by `voter_01` proposals( `id_proposal_01` )---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.proposal_ids.insert( id_proposal_01 ); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 0 ); - } - - { - BOOST_TEST_MESSAGE( "---Voting by `voter_01` for nothing---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.approve = true; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - HIVE_REQUIRE_THROW(db->push_transaction( tx, 0 ), fc::exception); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 0 ); - } - - { - BOOST_TEST_MESSAGE( "---Unvoting by `voter_01` nothing---" ); - op.voter = voter_01; - op.proposal_ids.clear(); - op.approve = false; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, voter_01_key ); - HIVE_REQUIRE_THROW(db->push_transaction( tx, 0 ), fc::exception); - tx.operations.clear(); - tx.signatures.clear(); - - int32_t cnt = 0; - auto found = proposal_vote_idx.find( voter_01 ); - while( found != proposal_vote_idx.end() && found->voter == voter_01 ) - { - ++cnt; - ++found; - } - BOOST_REQUIRE( cnt == 0 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_000 ) -{ - try { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - all args are ok" ); - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto creator = "alice"; - auto receiver = "bob"; - auto start_date = db->head_block_time() + fc::days( 1 ); - auto end_date = start_date + fc::days( 2 ); - auto daily_pay = asset( 100, HBD_SYMBOL ); - - FUND( creator, ASSET( "80.000 TBD" ) ); - { - int64_t proposal = create_proposal( creator, receiver, start_date, end_date, daily_pay, alice_private_key ); - BOOST_REQUIRE( proposal >= 0 ); - } - validate_database(); - } FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_001 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid creator" ); - { - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - HIVE_REQUIRE_THROW( create_proposal( "", cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ), fc::exception); - - } - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_002 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid receiver" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - HIVE_REQUIRE_THROW(create_proposal( cpd.creator, "", cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_003 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid start date" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - cpd.start_date = cpd.end_date + fc::days(2); - HIVE_REQUIRE_THROW(create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_004 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid end date" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - cpd.end_date = cpd.start_date - fc::days(2); - HIVE_REQUIRE_THROW(create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_005 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid subject(empty)" ); - ACTORS( (alice)(bob) ) - generate_block(); - create_proposal_operation cpo; - cpo.creator = "alice"; - cpo.receiver = "bob"; - cpo.start_date = db->head_block_time() + fc::days( 1 ); - cpo.end_date = cpo.start_date + fc::days( 2 ); - cpo.daily_pay = asset( 100, HBD_SYMBOL ); - cpo.subject = ""; - cpo.permlink = "http:://something.html"; - FUND( cpo.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - signed_transaction tx; - tx.operations.push_back( cpo ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW(db->push_transaction( tx, 0 ), fc::exception); - tx.operations.clear(); - tx.signatures.clear(); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_006 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid subject(too long)" ); - ACTORS( (alice)(bob) ) - generate_block(); - create_proposal_operation cpo; - cpo.creator = "alice"; - cpo.receiver = "bob"; - cpo.start_date = db->head_block_time() + fc::days( 1 ); - cpo.end_date = cpo.start_date + fc::days( 2 ); - cpo.daily_pay = asset( 100, HBD_SYMBOL ); - cpo.subject = "very very very very very very long long long long long long subject subject subject subject subject subject"; - cpo.permlink = "http:://something.html"; - FUND( cpo.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - signed_transaction tx; - tx.operations.push_back( cpo ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW(db->push_transaction( tx, 0 ), fc::exception); - tx.operations.clear(); - tx.signatures.clear(); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_007 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: authorization test" ); - ACTORS( (alice)(bob) ) - generate_block(); - create_proposal_operation cpo; - cpo.creator = "alice"; - cpo.receiver = "bob"; - cpo.start_date = db->head_block_time() + fc::days( 1 ); - cpo.end_date = cpo.start_date + fc::days( 2 ); - cpo.daily_pay = asset( 100, HBD_SYMBOL ); - cpo.subject = "subject"; - cpo.permlink = "http:://something.html"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - cpo.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - cpo.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - cpo.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( create_proposal_008 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: create proposal: opration arguments validation - invalid daily payement (negative value)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - generate_block(); - cpd.end_date = cpd.start_date + fc::days(20); - cpd.daily_pay = asset( -10, HBD_SYMBOL ); - HIVE_REQUIRE_THROW(create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_000 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - all ok (approve true)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - std::vector< int64_t > proposals = {proposal_1}; - vote_proposal("carol", proposals, true, carol_private_key); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_001 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - all ok (approve false)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - std::vector< int64_t > proposals = {proposal_1}; - vote_proposal("carol", proposals, false, carol_private_key); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_002 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - all ok (empty array)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - std::vector< int64_t > proposals; - HIVE_REQUIRE_THROW( vote_proposal("carol", proposals, true, carol_private_key), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_003 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - all ok (array with negative digits)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - std::vector< int64_t > proposals = {-1, -2, -3, -4, -5}; - vote_proposal("carol", proposals, true, carol_private_key); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_004 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - invalid voter" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - std::vector< int64_t > proposals = {proposal_1}; - HIVE_REQUIRE_THROW(vote_proposal("urp", proposals, false, carol_private_key), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_005 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: opration arguments validation - invalid id array (array with greater number of digits than allowed)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - std::vector< int64_t > proposals; - for(int i = 0; i <= HIVE_PROPOSAL_MAX_IDS_NUMBER; i++) { - proposals.push_back(i); - } - HIVE_REQUIRE_THROW(vote_proposal("carol", proposals, true, carol_private_key), fc::exception); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_votes_006 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: update proposal votes: authorization test" ); - ACTORS( (alice)(bob) ) - generate_block(); - update_proposal_votes_operation upv; - upv.voter = "alice"; - upv.proposal_ids = {0}; - upv.approve = true; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - upv.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - upv.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - upv.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_000 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proposal removal (only one)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 1 ); - - flat_set<int64_t> proposals = { proposal_1 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_001 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proposal removal (one from many)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - int64_t proposal_2 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - int64_t proposal_3 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - BOOST_REQUIRE(proposal_2 >= 0); - BOOST_REQUIRE(proposal_3 >= 0); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 3 ); - - flat_set<int64_t> proposals = { proposal_1 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); //two left - BOOST_REQUIRE( proposal_idx.size() == 2 ); - - proposals.clear(); - proposals.insert(proposal_2); - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); //one left - BOOST_REQUIRE( proposal_idx.size() == 1 ); - - proposals.clear(); - proposals.insert(proposal_3); - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); //none - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_002 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proposal removal (n from many in two steps)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal = -1; - std::vector<int64_t> proposals; - - for(int i = 0; i < 6; i++) { - proposal = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal >= 0); - proposals.push_back(proposal); - } - BOOST_REQUIRE(proposals.size() == 6); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE(proposal_idx.size() == 6); - - flat_set<int64_t> proposals_to_erase = {proposals[0], proposals[1], proposals[2], proposals[3]}; - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 2 ); - - proposals_to_erase.clear(); - proposals_to_erase.insert(proposals[4]); - proposals_to_erase.insert(proposals[5]); - - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_003 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proper proposal deletion check (one at time)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal = -1; - std::vector<int64_t> proposals; - - for(int i = 0; i < 2; i++) { - proposal = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal >= 0); - proposals.push_back(proposal); - } - BOOST_REQUIRE(proposals.size() == 2); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE(proposal_idx.size() == 2); - - flat_set<int64_t> proposals_to_erase = {proposals[0]}; - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( found->proposal_id == proposals[1]); - BOOST_REQUIRE( proposal_idx.size() == 1 ); - - proposals_to_erase.clear(); - proposals_to_erase.insert(proposals[1]); - - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_004 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proper proposal deletion check (two at one time)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal = -1; - std::vector<int64_t> proposals; - - for(int i = 0; i < 6; i++) { - proposal = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal >= 0); - proposals.push_back(proposal); - } - BOOST_REQUIRE(proposals.size() == 6); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE(proposal_idx.size() == 6); - - flat_set<int64_t> proposals_to_erase = {proposals[0], proposals[5]}; - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - for(auto& it : proposal_idx) { - BOOST_REQUIRE( it.proposal_id != proposals[0] ); - BOOST_REQUIRE( it.proposal_id != proposals[5] ); - } - BOOST_REQUIRE( proposal_idx.size() == 4 ); - - proposals_to_erase.clear(); - proposals_to_erase.insert(proposals[1]); - proposals_to_erase.insert(proposals[4]); - - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - found = proposal_idx.find( cpd.creator ); - for(auto& it : proposal_idx) { - BOOST_REQUIRE( it.proposal_id != proposals[0] ); - BOOST_REQUIRE( it.proposal_id != proposals[1] ); - BOOST_REQUIRE( it.proposal_id != proposals[4] ); - BOOST_REQUIRE( it.proposal_id != proposals[5] ); - } - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 2 ); - - proposals_to_erase.clear(); - proposals_to_erase.insert(proposals[2]); - proposals_to_erase.insert(proposals[3]); - remove_proposal(cpd.creator, proposals_to_erase, alice_private_key); - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_005 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - proposal with votes removal (only one)." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 1 ); - - std::vector<int64_t> vote_proposals = {proposal_1}; - - vote_proposal( "bob", vote_proposals, true, bob_private_key ); - BOOST_REQUIRE( find_vote_for_proposal("bob", proposal_1) ); - - flat_set<int64_t> proposals = { proposal_1 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_006 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - remove proposal with votes and one voteless at same time." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - int64_t proposal_2 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - BOOST_REQUIRE(proposal_2 >= 0); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 2 ); - - std::vector<int64_t> vote_proposals = {proposal_1}; - - vote_proposal( "bob", vote_proposals, true, bob_private_key ); - BOOST_REQUIRE( find_vote_for_proposal("bob", proposal_1) ); - - flat_set<int64_t> proposals = { proposal_1, proposal_2 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_007 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: basic verification operation - remove proposals with votes at same time." ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob)(carol) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - int64_t proposal_2 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - BOOST_REQUIRE(proposal_1 >= 0); - BOOST_REQUIRE(proposal_2 >= 0); - - auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.size() == 2 ); - - std::vector<int64_t> vote_proposals = {proposal_1}; - vote_proposal( "bob", vote_proposals, true, bob_private_key ); - BOOST_REQUIRE( find_vote_for_proposal("bob", proposal_1) ); - vote_proposals.clear(); - vote_proposals.push_back(proposal_2); - vote_proposal( "carol", vote_proposals, true, carol_private_key ); - BOOST_REQUIRE( find_vote_for_proposal("carol", proposal_2) ); - - flat_set<int64_t> proposals = { proposal_1, proposal_2 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - - found = proposal_idx.find( cpd.creator ); - BOOST_REQUIRE( found == proposal_idx.end() ); - BOOST_REQUIRE( proposal_idx.empty() ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_008 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: opration arguments validation - all ok" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - flat_set<int64_t> proposals = { 0 }; - remove_proposal(cpd.creator, proposals, alice_private_key); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_009 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: opration arguments validation - invalid deleter" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - int64_t proposal_1 = create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key ); - flat_set<int64_t> proposals = { proposal_1 }; - HIVE_REQUIRE_THROW(remove_proposal(cpd.receiver, proposals, bob_private_key), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_010 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: opration arguments validation - invalid array(empty array)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - flat_set<int64_t> proposals; - HIVE_REQUIRE_THROW(remove_proposal(cpd.creator, proposals, bob_private_key), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_011 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: opration arguments validation - invalid array(array with greater number of digits than allowed)" ); - create_proposal_data cpd(db->head_block_time()); - ACTORS( (alice)(bob) ) - generate_block(); - FUND( cpd.creator, ASSET( "80.000 TBD" ) ); - generate_block(); - flat_set<int64_t> proposals; - for(int i = 0; i <= HIVE_PROPOSAL_MAX_IDS_NUMBER; i++) { - proposals.insert(create_proposal( cpd.creator, cpd.receiver, cpd.start_date, cpd.end_date, cpd.daily_pay, alice_private_key )); - } - HIVE_REQUIRE_THROW(remove_proposal(cpd.creator, proposals, bob_private_key), fc::exception); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( remove_proposal_012 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: remove proposal: authorization test" ); - ACTORS( (alice)(bob) ) - generate_block(); - remove_proposal_operation rpo; - rpo.proposal_owner = "alice"; - rpo.proposal_ids = {1,2,3}; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - rpo.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - rpo.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - rpo.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( update_proposal_000 ) -{ - try { - BOOST_TEST_MESSAGE( "Testing: update proposal - update subject" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - auto creator = "alice"; - auto receiver = "bob"; - - auto start_date = db->head_block_time() + fc::days( 1 ); - auto end_date = start_date + fc::days( 2 ); - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - auto subject = "hello"; - auto permlink = "somethingpermlink"; - - post_comment(creator, permlink, "title", "body", "test", alice_private_key); - - FUND( creator, ASSET( "80.000 TBD" ) ); - - signed_transaction tx; - - BOOST_TEST_MESSAGE("-- creating"); - create_proposal_operation op; - - op.creator = creator; - op.receiver = receiver; - - op.start_date = start_date; - op.end_date = end_date; - - op.daily_pay = daily_pay; - - op.subject = subject; - op.permlink = permlink; - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_creator >(); - auto found = proposal_idx.find( creator ); - BOOST_REQUIRE( found != proposal_idx.end() ); - - BOOST_REQUIRE( found->creator == creator ); - BOOST_REQUIRE( found->receiver == receiver ); - BOOST_REQUIRE( found->start_date == start_date ); - BOOST_REQUIRE( found->end_date == end_date ); - BOOST_REQUIRE( found->daily_pay == daily_pay ); - BOOST_REQUIRE( found->subject == subject ); - BOOST_REQUIRE( found->permlink == permlink ); - - BOOST_TEST_MESSAGE("-- updating"); - update_proposal(found->proposal_id, creator, daily_pay, "Other subject", permlink, alice_private_key); - generate_block(); - found = proposal_idx.find( creator ); - BOOST_REQUIRE( found->subject == "Other subject" ); - - validate_database(); - } FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_maintenance_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of old proposals using threshold" ); - - ACTORS( (a00)(a01)(a02)(a03)(a04) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::hours( 11 ); - const auto end_time_shift = fc::hours( 10 ); - const auto block_interval = fc::seconds( HIVE_BLOCK_INTERVAL ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 200; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, - {"a01", a01_private_key }, - {"a02", a02_private_key }, - {"a03", a03_private_key }, - {"a04", a04_private_key }, - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - proposals_id.push_back( create_proposal( item.account, receiver, start_date_00, end_date_00, daily_pay, item.key ) ); - generate_block(); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - generate_blocks( start_time + fc::seconds( HIVE_PROPOSAL_MAINTENANCE_CLEANUP ) ); - start_time = db->head_block_time(); - - generate_blocks( start_time + ( start_time_shift + end_time_shift - block_interval ) ); - - auto threshold = db->get_sps_remove_threshold(); - auto nr_stages = current_active_proposals / threshold; - - for( auto i = 0; i < nr_stages; ++i ) - { - generate_block(); - - current_active_proposals -= threshold; - auto found = calc_proposals( proposal_idx, proposals_id ); - - BOOST_REQUIRE( current_active_proposals == found ); - } - - BOOST_REQUIRE( current_active_proposals == 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_maintenance_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of old proposals + votes using threshold" ); - - ACTORS( (a00)(a01)(a02)(a03)(a04) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::hours( 11 ); - const auto end_time_shift = fc::hours( 10 ); - const auto block_interval = fc::seconds( HIVE_BLOCK_INTERVAL ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 10; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, - {"a01", a01_private_key }, - {"a02", a02_private_key }, - {"a03", a03_private_key }, - {"a04", a04_private_key }, - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - for( auto i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - proposals_id.push_back( create_proposal( item.account, receiver, start_date_00, end_date_00, daily_pay, item.key ) ); - generate_block(); - } - - auto itr_begin_2 = proposals_id.begin() + HIVE_PROPOSAL_MAX_IDS_NUMBER; - std::vector< int64_t > v1( proposals_id.begin(), itr_begin_2 ); - std::vector< int64_t > v2( itr_begin_2, proposals_id.end() ); - - for( auto item : inits ) - { - vote_proposal( item.account, v1, true/*approve*/, item.key); - generate_blocks( 1 ); - vote_proposal( item.account, v2, true/*approve*/, item.key); - generate_blocks( 1 ); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - auto current_active_votes = current_active_proposals * static_cast< int16_t > ( inits.size() ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == current_active_votes ); - - generate_blocks( start_time + fc::seconds( HIVE_PROPOSAL_MAINTENANCE_CLEANUP ) ); - start_time = db->head_block_time(); - - generate_blocks( start_time + ( start_time_shift + end_time_shift - block_interval ) ); - - auto threshold = db->get_sps_remove_threshold(); - auto current_active_anything = current_active_proposals + current_active_votes; - auto nr_stages = current_active_anything / threshold; - - for( auto i = 0; i < nr_stages; ++i ) - { - generate_block(); - - current_active_anything -= threshold; - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - - BOOST_REQUIRE( current_active_anything == found_proposals + found_votes ); - } - - BOOST_REQUIRE( current_active_anything == 0 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_removing_with_threshold ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of old proposals + votes using threshold" ); - - ACTORS( (a00)(a01)(a02)(a03)(a04) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::days( 100 ); - const auto end_time_shift = fc::days( 101 ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 5; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, - {"a01", a01_private_key }, - {"a02", a02_private_key }, - {"a03", a03_private_key }, - {"a04", a04_private_key }, - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - auto item_creator = inits[ 0 ]; - for( auto i = 0; i < nr_proposals; ++i ) - { - proposals_id.push_back( create_proposal( item_creator.account, receiver, start_date_00, end_date_00, daily_pay, item_creator.key ) ); - generate_block(); - } - - for( auto item : inits ) - { - vote_proposal( item.account, proposals_id, true/*approve*/, item.key); - generate_blocks( 1 ); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - auto current_active_votes = current_active_proposals * static_cast< int16_t > ( inits.size() ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == current_active_votes ); - - auto threshold = db->get_sps_remove_threshold(); - BOOST_REQUIRE( threshold == 20 ); - - flat_set< int64_t > _proposals_id( proposals_id.begin(), proposals_id.end() ); - - { - remove_proposal( item_creator.account, _proposals_id, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_proposals == 2 ); - BOOST_REQUIRE( found_votes == 8 ); - generate_blocks( 1 ); - } - - { - remove_proposal( item_creator.account, _proposals_id, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_proposals == 0 ); - BOOST_REQUIRE( found_votes == 0 ); - generate_blocks( 1 ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_removing_with_threshold_01 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of old proposals/votes using threshold " ); - - ACTORS( (a00)(a01)(a02)(a03)(a04)(a05) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::days( 100 ); - const auto end_time_shift = fc::days( 101 ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 10; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, - {"a01", a01_private_key }, - {"a02", a02_private_key }, - {"a03", a03_private_key }, - {"a04", a04_private_key }, - {"a05", a05_private_key }, - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - auto item_creator = inits[ 0 ]; - for( auto i = 0; i < nr_proposals; ++i ) - { - proposals_id.push_back( create_proposal( item_creator.account, receiver, start_date_00, end_date_00, daily_pay, item_creator.key ) ); - generate_block(); - } - - auto itr_begin_2 = proposals_id.begin() + HIVE_PROPOSAL_MAX_IDS_NUMBER; - std::vector< int64_t > v1( proposals_id.begin(), itr_begin_2 ); - std::vector< int64_t > v2( itr_begin_2, proposals_id.end() ); - - for( auto item : inits ) - { - vote_proposal( item.account, v1, true/*approve*/, item.key); - generate_block(); - vote_proposal( item.account, v2, true/*approve*/, item.key); - generate_block(); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - auto current_active_votes = current_active_proposals * static_cast< int16_t > ( inits.size() ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == current_active_votes ); - - auto threshold = db->get_sps_remove_threshold(); - BOOST_REQUIRE( threshold == 20 ); - - /* - nr_proposals = 10 - nr_votes_per_proposal = 6 - - Info: - Pn - number of proposal - vn - number of vote - xx - elements removed in given block - oo - elements removed earlier - rr - elements with status `removed` - - Below in matrix is situation before removal any element. - - P0 P1 P2 P3 P4 P5 P6 P7 P8 P9 - - v0 v0 v0 v0 v0 v0 v0 v0 v0 v0 - v1 v1 v1 v1 v1 v1 v1 v1 v1 v1 - v2 v2 v2 v2 v2 v2 v2 v2 v2 v2 - v3 v3 v3 v3 v3 v3 v3 v3 v3 v3 - v4 v4 v4 v4 v4 v4 v4 v4 v4 v4 - v5 v5 v5 v5 v5 v5 v5 v5 v5 v5 - - Total number of elements to be removed: - Total = nr_proposals * nr_votes_per_proposal + nr_proposals = 10 * 6 + 10 = 70 - */ - - /* - P0 P1 P2 xx P4 P5 P6 P7 P8 P9 - - v0 v0 v0 xx v0 v0 v0 v0 v0 v0 - v1 v1 v1 xx v1 v1 v1 v1 v1 v1 - v2 v2 v2 xx v2 v2 v2 v2 v2 v2 - v3 v3 v3 xx v3 v3 v3 v3 v3 v3 - v4 v4 v4 xx v4 v4 v4 v4 v4 v4 - v5 v5 v5 xx v5 v5 v5 v5 v5 v5 - */ - { - remove_proposal( item_creator.account, {3}, item_creator.key ); - generate_block(); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_proposals == 9 ); - BOOST_REQUIRE( found_votes == 54 ); - - int32_t cnt = 0; - for( auto id : proposals_id ) - cnt += ( id != 3 ) ? calc_proposal_votes( proposal_vote_idx, id ) : 0; - BOOST_REQUIRE( cnt == found_votes ); - } - - /* - P0 xx xx oo P4 P5 P6 rr P8 P9 - - v0 xx xx oo v0 v0 v0 xx v0 v0 - v1 xx xx oo v1 v1 v1 xx v1 v1 - v2 xx xx oo v2 v2 v2 xx v2 v2 - v3 xx xx oo v3 v3 v3 xx v3 v3 - v4 xx xx oo v4 v4 v4 xx v4 v4 - v5 xx xx oo v5 v5 v5 xx v5 v5 - */ - { - remove_proposal( item_creator.account, {1,2,7}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 7 ) && find_proposal( 7 )->removed ); - BOOST_REQUIRE( found_proposals == 7 ); - BOOST_REQUIRE( found_votes == 36 ); - } - - - /* - P0 oo oo oo P4 P5 P6 xx P8 P9 - - v0 oo oo oo v0 v0 v0 oo v0 v0 - v1 oo oo oo v1 v1 v1 oo v1 v1 - v2 oo oo oo v2 v2 v2 oo v2 v2 - v3 oo oo oo v3 v3 v3 oo v3 v3 - v4 oo oo oo v4 v4 v4 oo v4 v4 - v5 oo oo oo v5 v5 v5 oo v5 v5 - */ - { - //Only the proposal P7 is removed. - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 7 ) ); - BOOST_REQUIRE( found_proposals == 6 ); - BOOST_REQUIRE( found_votes == 36 ); - } - - /* - P0 oo oo oo P4 xx xx oo rr rr - - v0 oo oo oo v0 xx xx oo xx rr - v1 oo oo oo v1 xx xx oo xx rr - v2 oo oo oo v2 xx xx oo xx rr - v3 oo oo oo v3 xx xx oo xx rr - v4 oo oo oo v4 xx xx oo xx rr - v5 oo oo oo v5 xx xx oo xx rr - */ - { - remove_proposal( item_creator.account, {5,6,7/*doesn't exist*/,8,9}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 8 ) && find_proposal( 8 )->removed ); - BOOST_REQUIRE( found_proposals == 4 ); - BOOST_REQUIRE( found_votes == 18 ); - - int32_t cnt = 0; - for( auto id : proposals_id ) - cnt += ( id == 0 || id == 4 || id == 8 || id == 9 ) ? calc_proposal_votes( proposal_vote_idx, id ) : 0; - BOOST_REQUIRE( cnt == found_votes ); - } - - /* - xx oo oo oo xx oo oo oo xx rr - - xx oo oo oo xx oo oo oo oo rr - xx oo oo oo xx oo oo oo oo xx - xx oo oo oo xx oo oo oo oo xx - xx oo oo oo xx oo oo oo oo xx - xx oo oo oo xx oo oo oo oo xx - xx oo oo oo xx oo oo oo oo xx - */ - { - remove_proposal( item_creator.account, {0,4,8,9}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 9 ) && find_proposal( 9 )->removed ); - BOOST_REQUIRE( found_proposals == 1 ); - BOOST_REQUIRE( found_votes == 1 ); - } - - /* - oo oo oo oo oo oo oo oo oo xx - - oo oo oo oo oo oo oo oo oo xx - oo oo oo oo oo oo oo oo oo oo - oo oo oo oo oo oo oo oo oo oo - oo oo oo oo oo oo oo oo oo oo - oo oo oo oo oo oo oo oo oo oo - oo oo oo oo oo oo oo oo oo oo - */ - { - //Only the proposal P9 is removed. - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_proposals == 0 ); - BOOST_REQUIRE( found_votes == 0 ); - } - - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( proposals_removing_with_threshold_02 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of old proposals/votes using threshold " ); - - ACTORS( - (a00)(a01)(a02)(a03)(a04)(a05)(a06)(a07)(a08)(a09) - (a10)(a11)(a12)(a13)(a14)(a15)(a16)(a17)(a18)(a19) - (a20)(a21)(a22)(a23)(a24)(a25)(a26)(a27)(a28)(a29) - (a30)(a31)(a32)(a33)(a34)(a35)(a36)(a37)(a38)(a39) - (a40)(a41)(a42)(a43)(a44)(a45)(a46)(a47)(a48)(a49) - ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::days( 100 ); - const auto end_time_shift = fc::days( 101 ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 5; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - std::vector< initial_data > inits = { - {"a00", a00_private_key }, {"a01", a01_private_key }, {"a02", a02_private_key }, {"a03", a03_private_key }, {"a04", a04_private_key }, - {"a05", a05_private_key }, {"a06", a06_private_key }, {"a07", a07_private_key }, {"a08", a08_private_key }, {"a09", a09_private_key }, - {"a10", a10_private_key }, {"a11", a11_private_key }, {"a12", a12_private_key }, {"a13", a13_private_key }, {"a14", a14_private_key }, - {"a15", a15_private_key }, {"a16", a16_private_key }, {"a17", a17_private_key }, {"a18", a18_private_key }, {"a19", a19_private_key }, - {"a20", a20_private_key }, {"a21", a21_private_key }, {"a22", a22_private_key }, {"a23", a23_private_key }, {"a24", a24_private_key }, - {"a25", a25_private_key }, {"a26", a26_private_key }, {"a27", a27_private_key }, {"a28", a28_private_key }, {"a29", a29_private_key }, - {"a30", a30_private_key }, {"a31", a31_private_key }, {"a32", a32_private_key }, {"a33", a33_private_key }, {"a34", a34_private_key }, - {"a35", a35_private_key }, {"a36", a36_private_key }, {"a37", a37_private_key }, {"a38", a38_private_key }, {"a39", a39_private_key }, - {"a40", a40_private_key }, {"a41", a41_private_key }, {"a42", a42_private_key }, {"a43", a43_private_key }, {"a44", a44_private_key }, - {"a45", a45_private_key }, {"a46", a46_private_key }, {"a47", a47_private_key }, {"a48", a48_private_key }, {"a49", a49_private_key } - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - auto item_creator = inits[ 0 ]; - for( auto i = 0; i < nr_proposals; ++i ) - { - proposals_id.push_back( create_proposal( item_creator.account, receiver, start_date_00, end_date_00, daily_pay, item_creator.key ) ); - generate_block(); - } - - for( auto item : inits ) - { - vote_proposal( item.account, proposals_id, true/*approve*/, item.key); - generate_block(); - } - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - auto current_active_votes = current_active_proposals * static_cast< int16_t > ( inits.size() ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == current_active_votes ); - - auto threshold = db->get_sps_remove_threshold(); - BOOST_REQUIRE( threshold == 20 ); - - /* - nr_proposals = 5 - nr_votes_per_proposal = 50 - - Info: - Pn - number of proposal - vn - number of vote - xx - elements removed in given block - oo - elements removed earlier - rr - elements with status `removed` - - Below in matrix is situation before removal any element. - - P0 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P1 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P3 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - - Total number of elements to be removed: - Total = nr_proposals * nr_votes_per_proposal + nr_proposals = 5 * 50 + 5 = 255 - */ - - /* - rr xx xx xx xx xx xx xx xx xx xx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - P1 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - rr xx xx xx xx xx xx xx xx xx xx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - remove_proposal( item_creator.account, {0,3}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 0 ) && find_proposal( 0 )->removed ); - BOOST_REQUIRE( exist_proposal( 3 ) && find_proposal( 3 )->removed ); - BOOST_REQUIRE( found_proposals == 5 ); - BOOST_REQUIRE( found_votes == 230 ); - } - - /* - rr xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - P1 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - rr xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 0 ) && find_proposal( 0 )->removed ); - BOOST_REQUIRE( exist_proposal( 3 ) && find_proposal( 3 )->removed ); - BOOST_REQUIRE( found_proposals == 5 ); - BOOST_REQUIRE( found_votes == 210 ); - } - - /* - xx oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx - P1 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - xx oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - generate_block(); - generate_block(); - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 0 ) ); - BOOST_REQUIRE( !exist_proposal( 3 ) ); - BOOST_REQUIRE( found_proposals == 3 ); - BOOST_REQUIRE( found_votes == 150 ); - } - - /* - nothing changed - the same state as in previous block - - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P1 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 0 ) ); - BOOST_REQUIRE( !exist_proposal( 3 ) ); - BOOST_REQUIRE( found_proposals == 3 ); - BOOST_REQUIRE( found_votes == 150 ); - } - - /* - nothing changed - the same state as in previous block - */ - { - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 0 ) ); - BOOST_REQUIRE( !exist_proposal( 3 ) ); - BOOST_REQUIRE( found_proposals == 3 ); - BOOST_REQUIRE( found_votes == 150 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - rr xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - P2 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - remove_proposal( item_creator.account, {1}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 1 ) && find_proposal( 1 )->removed ); - BOOST_REQUIRE( found_proposals == 3 ); - BOOST_REQUIRE( found_votes == 130 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - rr xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - rr xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr rrr - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - remove_proposal( item_creator.account, {2}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 1 ) && find_proposal( 1 )->removed ); - BOOST_REQUIRE( exist_proposal( 2 ) && find_proposal( 2 )->removed ); - BOOST_REQUIRE( found_proposals == 3 ); - BOOST_REQUIRE( found_votes == 110 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - rr oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo rrr - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - generate_block(); - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 1 ) ); - BOOST_REQUIRE( exist_proposal( 2 ) && find_proposal( 2 )->removed ); - BOOST_REQUIRE( found_proposals == 2 ); - BOOST_REQUIRE( found_votes == 51 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - xx oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo xxx - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 1 ) ); - BOOST_REQUIRE( !exist_proposal( 2 ) ); - BOOST_REQUIRE( found_proposals == 1 ); - BOOST_REQUIRE( found_votes == 50 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - xx oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo xxx - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 xx xx xx xx xx xx xx xx xx xx xxx xxx xxx xxx xxx xxx xxx xxx xxx xxx v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - remove_proposal( item_creator.account, {4}, item_creator.key ); - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( exist_proposal( 4 ) && find_proposal( 4 )->removed ); - BOOST_REQUIRE( found_proposals == 1 ); - BOOST_REQUIRE( found_votes == 30 ); - - for( auto item : inits ) - vote_proposal( item.account, {4}, true/*approve*/, item.key); - - found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_votes == 30 ); - } - - /* - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - rr oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo rrr - oo oo oo oo oo oo oo oo oo oo oo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo - P4 v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 v12 v13 v14 v15 v16 v17 v18 v19 v20 v21 v22 v23 v24 v25 v26 v27 v28 v29 v30 v31 v32 v33 v34 v35 v36 v37 v38 v39 v40 v41 v42 v43 v44 v45 v46 v47 v48 v49 - */ - { - generate_block(); - generate_block(); - - auto found_proposals = calc_proposals( proposal_idx, proposals_id ); - auto found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( !exist_proposal( 4 ) ); - BOOST_REQUIRE( found_proposals == 0 ); - BOOST_REQUIRE( found_votes == 0 ); - - for( auto item : inits ) - vote_proposal( item.account, {4}, true/*approve*/, item.key); - - found_votes = calc_votes( proposal_vote_idx, proposals_id ); - BOOST_REQUIRE( found_votes == 0 ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() - - -BOOST_FIXTURE_TEST_SUITE( proposal_tests_performance, sps_proposal_database_fixture_performance ) - -int32_t get_time( database& db, const std::string& name ) -{ - int32_t benchmark_time = -1; - - db.get_benchmark_dumper().dump(); - - fc::path benchmark_file( "advanced_benchmark.json" ); - - if( !fc::exists( benchmark_file ) ) - return benchmark_time; - - /* - { - "total_time": 1421, - "items": [{ - "op_name": "sps_processor", - "time": 80 - },... - */ - auto file = fc::json::from_file( benchmark_file ).as< fc::variant >(); - if( file.is_object() ) - { - auto vo = file.get_object(); - if( vo.contains( "items" ) ) - { - auto items = vo[ "items" ]; - if( items.is_array() ) - { - auto v = items.as< std::vector< fc::variant > >(); - for( auto& item : v ) - { - if( !item.is_object() ) - continue; - - auto vo_item = item.get_object(); - if( vo_item.contains( "op_name" ) && vo_item[ "op_name" ].is_string() ) - { - std::string str = vo_item[ "op_name" ].as_string(); - if( str == name ) - { - if( vo_item.contains( "time" ) && vo_item[ "time" ].is_uint64() ) - { - benchmark_time = vo_item[ "time" ].as_int64(); - break; - } - } - } - } - } - } - } - return benchmark_time; -} - -struct initial_data -{ - std::string account; - - fc::ecc::private_key key; - - initial_data( database_fixture* db, const std::string& _account ): account( _account ) - { - key = db->generate_private_key( account ); - - db->account_create( account, key.get_public_key(), db->generate_private_key( account + "_post" ).get_public_key() ); - } -}; - -std::vector< initial_data > generate_accounts( database_fixture* db, int32_t number_accounts ) -{ - const std::string basic_name = "tester"; - - std::vector< initial_data > res; - - for( int32_t i = 0; i< number_accounts; ++i ) - { - std::string name = basic_name + std::to_string( i ); - res.push_back( initial_data( db, name ) ); - - if( ( i + 1 ) % 100 == 0 ) - db->generate_block(); - - if( ( i + 1 ) % 1000 == 0 ) - ilog( "Created: ${accs} accounts",( "accs", i+1 ) ); - } - - db->validate_database(); - db->generate_block(); - - return res; -} - -BOOST_AUTO_TEST_CASE( proposals_removing_with_threshold_03 ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: removing of all proposals/votes in one block using threshold = -1" ); - - std::vector< initial_data > inits = generate_accounts( this, 200 ); - - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - auto receiver = db->get_treasury_name(); - - auto start_time = db->head_block_time(); - - const auto start_time_shift = fc::hours( 20 ); - const auto end_time_shift = fc::hours( 6 ); - const auto block_interval = fc::seconds( HIVE_BLOCK_INTERVAL ); - - auto start_date_00 = start_time + start_time_shift; - auto end_date_00 = start_date_00 + end_time_shift; - - auto daily_pay = asset( 100, HBD_SYMBOL ); - - const auto nr_proposals = 200; - std::vector< int64_t > proposals_id; - - struct initial_data - { - std::string account; - fc::ecc::private_key key; - }; - - for( auto item : inits ) - { - FUND( item.account, ASSET( "10000.000 TBD" ) ); - } - //=====================preparing===================== - - for( auto i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i ]; - proposals_id.push_back( create_proposal( item.account, receiver, start_date_00, end_date_00, daily_pay, item.key ) ); - if( ( i + 1 ) % 10 == 0 ) - generate_block(); - } - generate_block(); - - std::vector< int64_t > ids; - uint32_t i = 0; - for( auto id : proposals_id ) - { - ids.push_back( id ); - if( ids.size() == HIVE_PROPOSAL_MAX_IDS_NUMBER ) - { - for( auto item : inits ) - { - ++i; - vote_proposal( item.account, ids, true/*approve*/, item.key ); - if( ( i + 1 ) % 10 == 0 ) - generate_block(); - } - ids.clear(); - } - } - generate_block(); - - const auto& proposal_idx = db->get_index< proposal_index >().indices().get< by_proposal_id >(); - const auto& proposal_vote_idx = db->get_index< proposal_vote_index >().indices().get< by_proposal_voter >(); - - auto current_active_proposals = nr_proposals; - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == current_active_proposals ); - - auto current_active_votes = current_active_proposals * static_cast< int16_t > ( inits.size() ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == current_active_votes ); - - auto threshold = db->get_sps_remove_threshold(); - BOOST_REQUIRE( threshold == -1 ); - - generate_blocks( start_time + fc::seconds( HIVE_PROPOSAL_MAINTENANCE_CLEANUP ) ); - start_time = db->head_block_time(); - - generate_blocks( start_time + ( start_time_shift + end_time_shift - block_interval ) ); - - generate_blocks( 1 ); - - BOOST_REQUIRE( calc_proposals( proposal_idx, proposals_id ) == 0 ); - BOOST_REQUIRE( calc_votes( proposal_vote_idx, proposals_id ) == 0 ); - - int32_t benchmark_time = get_time( *db, sps_processor::get_removing_name() ); - idump( (benchmark_time) ); - BOOST_REQUIRE( benchmark_time == -1 || benchmark_time < 100 ); - - /* - Local test: 4 cores/16 MB RAM - nr objects to be removed: `40200` - time of removing: 80 ms - speed of removal: ~502/ms - */ - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( generating_payments ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: generating payments for a lot of accounts" ); - - std::vector< initial_data > inits = generate_accounts( this, 30000 ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - generate_block(); - - //=====================preparing===================== - const auto nr_proposals = 5; - std::vector< int64_t > proposals_id; - flat_map< std::string, asset > before_tbds; - - auto call = [&]( uint32_t& i, uint32_t max, const std::string& info ) - { - ++i; - if( i % max == 0 ) - generate_block(); - - if( i % 1000 == 0 ) - ilog( info.c_str(),( "x", i ) ); - }; - - uint32_t i = 0; - for( auto item : inits ) - { - if( i < 5 ) - { - FUND( item.account, ASSET( "11.000 TBD" ) ); - } - vest(HIVE_INIT_MINER_NAME, item.account, ASSET( "30.000 TESTS" )); - - call( i, 50, "${x} accounts got VESTS" ); - } - - auto start_time = db->head_block_time(); - //Due to the `delaying votes` algorithm, generate blocks for 30 days in order to activate whole votes' pool ( take a look at `HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS` ) - start_time += fc::seconds( HIVE_DELAYED_VOTING_TOTAL_INTERVAL_SECONDS ); - generate_blocks( start_time ); - - const auto start_time_shift = fc::hours( 10 ); - const auto end_time_shift = fc::hours( 1 ); - const auto block_interval = fc::seconds( HIVE_BLOCK_INTERVAL ); - - auto start_date = start_time + start_time_shift; - auto end_date = start_date + end_time_shift; - - auto daily_pay = ASSET( "24.000 TBD" ); - auto paid = ASSET( "1.000 TBD" );//because only 1 hour - - FUND( db->get_treasury_name(), ASSET( "5000000.000 TBD" ) ); - //=====================preparing===================== - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - proposals_id.push_back( create_proposal( item.account, item.account, start_date, end_date, daily_pay, item.key ) ); - generate_block(); - } - - i = 0; - for( auto item : inits ) - { - vote_proposal( item.account, proposals_id, true/*approve*/, item.key ); - - call( i, 100, "${x} accounts voted" ); - } - - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - const account_object& account = db->get_account( item.account ); - before_tbds[ item.account ] = account.get_hbd_balance(); - } - - generate_blocks( start_time + ( start_time_shift - block_interval ) ); - start_time = db->head_block_time(); - generate_blocks( start_time + end_time_shift + block_interval ); - - for( int32_t i = 0; i < nr_proposals; ++i ) - { - auto item = inits[ i % inits.size() ]; - const account_object& account = db->get_account( item.account ); - - auto after_tbd = account.get_hbd_balance(); - auto before_tbd = before_tbds[ item.account ]; - idump( (before_tbd) ); - idump( (after_tbd) ); - idump( (paid) ); - BOOST_REQUIRE( before_tbd == after_tbd - paid ); - } - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests2/unit/tests/serialization_tests.cpp b/tests2/unit/tests/serialization_tests.cpp deleted file mode 100644 index 072816e97ea2b4f13a17406891b83f7cf34be110..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/serialization_tests.cpp +++ /dev/null @@ -1,729 +0,0 @@ -/* - * Copyright (c) 2015 Cryptonomex, Inc., and contributors. - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/database.hpp> - -#include <hive/plugins/condenser_api/condenser_api_legacy_asset.hpp> -#include <hive/plugins/condenser_api/condenser_api_legacy_objects.hpp> - -#include <fc/crypto/digest.hpp> -#include <fc/crypto/elliptic.hpp> -#include <fc/reflect/variant.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( serialization_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( serialization_raw_test ) -{ - try { - ACTORS( (alice)(bob) ) - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = asset(100,HIVE_SYMBOL); - - trx.operations.push_back( op ); - auto packed = fc::raw::pack_to_vector( trx ); - signed_transaction unpacked = fc::raw::unpack_from_vector<signed_transaction>(packed); - unpacked.validate(); - BOOST_CHECK( trx.digest() == unpacked.digest() ); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( serialization_json_test ) -{ - try { - ACTORS( (alice)(bob) ) - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = asset(100,HIVE_SYMBOL); - - fc::variant test(op.amount); - auto tmp = test.as<asset>(); - BOOST_REQUIRE( tmp == op.amount ); - - trx.operations.push_back( op ); - fc::variant packed(trx); - signed_transaction unpacked = packed.as<signed_transaction>(); - unpacked.validate(); - BOOST_CHECK( trx.digest() == unpacked.digest() ); - } catch (fc::exception& e) { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( legacy_asset_test ) -{ - try - { - using hive::plugins::condenser_api::legacy_asset; - - BOOST_CHECK_EQUAL( legacy_asset().symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( legacy_asset().to_string(), "0.000 TESTS" ); - - BOOST_TEST_MESSAGE( "Asset Test" ); - legacy_asset hive = legacy_asset::from_string( "123.456 TESTS" ); - legacy_asset hbd = legacy_asset::from_string( "654.321 TBD" ); - legacy_asset tmp = legacy_asset::from_string( "0.456 TESTS" ); - BOOST_CHECK_EQUAL( tmp.amount.value, 456 ); - tmp = legacy_asset::from_string( "0.056 TESTS" ); - BOOST_CHECK_EQUAL( tmp.amount.value, 56 ); - - BOOST_CHECK_EQUAL( hive.amount.value, 123456 ); - BOOST_CHECK_EQUAL( hive.symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( hive.to_string(), "123.456 TESTS" ); - BOOST_CHECK( hive.symbol == HIVE_SYMBOL ); - BOOST_CHECK_EQUAL( legacy_asset::from_asset( asset( 50, HIVE_SYMBOL ) ).to_string(), "0.050 TESTS" ); - BOOST_CHECK_EQUAL( legacy_asset::from_asset( asset(50000, HIVE_SYMBOL ) ) .to_string(), "50.000 TESTS" ); - - BOOST_CHECK_EQUAL( hbd.amount.value, 654321 ); - BOOST_CHECK_EQUAL( hbd.symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( hbd.to_string(), "654.321 TBD" ); - BOOST_CHECK( hbd.symbol == HBD_SYMBOL ); - BOOST_CHECK_EQUAL( legacy_asset::from_asset( asset(50, HBD_SYMBOL ) ).to_string(), "0.050 TBD" ); - BOOST_CHECK_EQUAL( legacy_asset::from_asset( asset(50000, HBD_SYMBOL ) ).to_string(), "50.000 TBD" ); - - BOOST_CHECK_THROW( legacy_asset::from_string( "1.00000000000000000000 TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1.000TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1. 333 TESTS" ), fc::exception ); // Fails because symbol is '333 TESTS', which is too long - BOOST_CHECK_THROW( legacy_asset::from_string( "1 .333 TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1. 333 X" ), fc::exception ); // Not a system asset - BOOST_CHECK_THROW( legacy_asset::from_string( "1 .333 X" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1 .333" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1 1.1" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "11111111111111111111111111111111111111111111111 TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1.1.1 TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1.abc TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( " TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "TESTS" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1.333" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "1.333 " ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "" ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( " " ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( " " ), fc::exception ); - BOOST_CHECK_THROW( legacy_asset::from_string( "100 TESTS" ), fc::exception ); // Does not match system asset precision - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( asset_test ) -{ - try - { - fc::string s; - - BOOST_CHECK_EQUAL( asset().symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset() ), "{\"amount\":\"0\",\"precision\":3,\"nai\":\"@@000000021\"}" ); - - asset hive = fc::json::from_string( "{\"amount\":\"123456\", \"precision\":3, \"nai\":\"@@000000021\"}" ).as< asset >(); - asset hbd = fc::json::from_string( "{\"amount\":\"654321\", \"precision\":3, \"nai\":\"@@000000013\"}" ).as< asset >(); - asset vests = fc::json::from_string( "{\"amount\":\"123456789\", \"precision\":6, \"nai\":\"@@000000037\"}" ).as< asset >(); - asset tmp = fc::json::from_string( "{\"amount\":\"456\", \"precision\":3, \"nai\":\"@@000000021\"}" ).as< asset >(); - BOOST_CHECK_EQUAL( tmp.amount.value, 456 ); - tmp = fc::json::from_string( "{\"amount\":\"56\", \"precision\":3, \"nai\":\"@@000000021\"}" ).as< asset >(); - BOOST_CHECK_EQUAL( tmp.amount.value, 56 ); - - BOOST_CHECK_EQUAL( hive.amount.value, 123456 ); - BOOST_CHECK_EQUAL( hive.symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( fc::json::to_string( hive ), "{\"amount\":\"123456\",\"precision\":3,\"nai\":\"@@000000021\"}" ); - BOOST_CHECK( hive.symbol.asset_num == HIVE_ASSET_NUM_HIVE ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50, HIVE_SYMBOL ) ), "{\"amount\":\"50\",\"precision\":3,\"nai\":\"@@000000021\"}" ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50000, HIVE_SYMBOL ) ), "{\"amount\":\"50000\",\"precision\":3,\"nai\":\"@@000000021\"}" ); - - BOOST_CHECK_EQUAL( hbd.amount.value, 654321 ); - BOOST_CHECK_EQUAL( hbd.symbol.decimals(), 3 ); - BOOST_CHECK_EQUAL( fc::json::to_string( hbd ), "{\"amount\":\"654321\",\"precision\":3,\"nai\":\"@@000000013\"}" ); - BOOST_CHECK( hbd.symbol.asset_num == HIVE_ASSET_NUM_HBD ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50, HBD_SYMBOL ) ), "{\"amount\":\"50\",\"precision\":3,\"nai\":\"@@000000013\"}" ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50000, HBD_SYMBOL ) ), "{\"amount\":\"50000\",\"precision\":3,\"nai\":\"@@000000013\"}" ); - - BOOST_CHECK_EQUAL( vests.amount.value, 123456789 ); - BOOST_CHECK_EQUAL( vests.symbol.decimals(), 6 ); - BOOST_CHECK_EQUAL( fc::json::to_string( vests ), "{\"amount\":\"123456789\",\"precision\":6,\"nai\":\"@@000000037\"}" ); - BOOST_CHECK( vests.symbol.asset_num == HIVE_ASSET_NUM_VESTS ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50, VESTS_SYMBOL ) ), "{\"amount\":\"50\",\"precision\":6,\"nai\":\"@@000000037\"}" ); - BOOST_CHECK_EQUAL( fc::json::to_string( asset( 50000, VESTS_SYMBOL ) ), "{\"amount\":\"50000\",\"precision\":6,\"nai\":\"@@000000037\"}" ); - - // amount overflow - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"9223372036854775808\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - // amount underflow - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"-1\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - - // precision overflow - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"10\",\"precision\":256,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - // precision underflow - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"10\",\"precision\":-1,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - - // Check wrong size tuple - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"0\",3]" ).as< asset >(), fc::exception ); - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"0\",\"precision\":3,\"nai\":\"@@000000021\",1}" ).as< asset >(), fc::exception ); - - // Check non-numeric characters in amount - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"foobar\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"10a\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"10a00\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - - // Check hex value - BOOST_CHECK_THROW( fc::json::from_string( "{\"amount\":\"0x8000\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >(), fc::exception ); - - // Check octal value - BOOST_CHECK_EQUAL( fc::json::from_string( "{\"amount\":\"08000\",\"precision\":3,\"nai\":\"@@000000021\"}" ).as< asset >().amount.value, 8000 ); - } - FC_LOG_AND_RETHROW() -} - -template< typename T > -std::string hex_bytes( const T& obj ) -{ - std::vector<char> data = fc::raw::pack_to_vector( obj ); - std::ostringstream ss; - static const char hexdigits[] = "0123456789abcdef"; - - for( char c : data ) - { - ss << hexdigits[((c >> 4) & 0x0F)] << hexdigits[c & 0x0F] << ' '; - } - return ss.str(); -} - -void old_pack_symbol(vector<char>& v, asset_symbol_type sym) -{ - if( sym == HIVE_SYMBOL ) - { - v.push_back('\x03'); v.push_back('T' ); v.push_back('E' ); v.push_back('S' ); - v.push_back('T' ); v.push_back('S' ); v.push_back('\0'); v.push_back('\0'); - // 03 54 45 53 54 53 00 00 - } - else if( sym == HBD_SYMBOL ) - { - v.push_back('\x03'); v.push_back('T' ); v.push_back('B' ); v.push_back('D' ); - v.push_back('\0' ); v.push_back('\0'); v.push_back('\0'); v.push_back('\0'); - // 03 54 42 44 00 00 00 00 - } - else if( sym == VESTS_SYMBOL ) - { - v.push_back('\x06'); v.push_back('V' ); v.push_back('E' ); v.push_back('S' ); - v.push_back('T' ); v.push_back('S' ); v.push_back('\0'); v.push_back('\0'); - // 06 56 45 53 54 53 00 00 - } - else - { - FC_ASSERT( false, "This method cannot serialize this symbol" ); - } - return; -} - -void old_pack_asset( vector<char>& v, const asset& a ) -{ - uint64_t x = uint64_t( a.amount.value ); - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); x >>= 8; - v.push_back( char( x & 0xFF ) ); - old_pack_symbol( v, a.symbol ); - return; -} - -std::string old_json_asset( const asset& a ) -{ - size_t decimal_places = 0; - if( (a.symbol == HIVE_SYMBOL) || (a.symbol == HBD_SYMBOL) ) - decimal_places = 3; - else if( a.symbol == VESTS_SYMBOL ) - decimal_places = 6; - std::ostringstream ss; - ss << std::setfill('0') << std::setw(decimal_places+1) << a.amount.value; - std::string result = ss.str(); - result.insert( result.length() - decimal_places, 1, '.' ); - if( a.symbol == HIVE_SYMBOL ) - result += " TESTS"; - else if( a.symbol == HBD_SYMBOL ) - result += " TBD"; - else if( a.symbol == VESTS_SYMBOL ) - result += " VESTS"; - result.insert(0, 1, '"'); - result += '"'; - return result; -} - -BOOST_AUTO_TEST_CASE( asset_raw_test ) -{ - try - { - BOOST_CHECK( HBD_SYMBOL < HIVE_SYMBOL ); - BOOST_CHECK( HIVE_SYMBOL < VESTS_SYMBOL ); - - // get a bunch of random bits - fc::sha256 h = fc::sha256::hash(""); - - std::vector< share_type > amounts; - - for( int i=0; i<64; i++ ) - { - uint64_t s = (uint64_t(1) << i); - uint64_t x = (h._hash[0] & (s-1)) | s; - if( x >= HIVE_MAX_SHARE_SUPPLY ) - break; - amounts.push_back( share_type( x ) ); - } - // ilog( "h0:${h0}", ("h0", h._hash[0]) ); - - std::vector< asset_symbol_type > symbols; - - symbols.push_back( HIVE_SYMBOL ); - symbols.push_back( HBD_SYMBOL ); - symbols.push_back( VESTS_SYMBOL ); - - for( const share_type& amount : amounts ) - { - for( const asset_symbol_type& symbol : symbols ) - { - // check raw::pack() works - asset a = asset( amount, symbol ); - vector<char> v_old; - old_pack_asset( v_old, a ); - vector<char> v_cur = fc::raw::pack_to_vector(a); - // ilog( "${a} : ${d}", ("a", a)("d", hex_bytes( v_old )) ); - // ilog( "${a} : ${d}", ("a", a)("d", hex_bytes( v_cur )) ); - BOOST_CHECK( v_cur == v_old ); - - // check raw::unpack() works - std::istringstream ss( string(v_cur.begin(), v_cur.end()) ); - asset a2; - fc::raw::unpack( ss, a2 ); - BOOST_CHECK( a == a2 ); - - // check conversion to JSON works - //std::string json_old = old_json_asset(a); - //std::string json_cur = fc::json::to_string(a); - // ilog( "json_old: ${j}", ("j", json_old) ); - // ilog( "json_cur: ${j}", ("j", json_cur) ); - //BOOST_CHECK( json_cur == json_old ); - - // check JSON serialization is symmetric - std::string json_cur = fc::json::to_string(a); - a2 = fc::json::from_string(json_cur).as< asset >(); - BOOST_CHECK( a == a2 ); - } - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( json_tests ) -{ - try { - auto var = fc::json::variants_from_string( "10.6 " ); - var = fc::json::variants_from_string( "10.5" ); - } catch ( const fc::exception& e ) - { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( extended_private_key_type_test ) -{ - try - { - fc::ecc::extended_private_key key = fc::ecc::extended_private_key( fc::ecc::private_key::generate(), - fc::sha256(), - 0, 0, 0 ); - extended_private_key_type type = extended_private_key_type( key ); - std::string packed = std::string( type ); - extended_private_key_type unpacked = extended_private_key_type( packed ); - BOOST_CHECK( type == unpacked ); - } catch ( const fc::exception& e ) - { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( extended_public_key_type_test ) -{ - try - { - fc::ecc::extended_public_key key = fc::ecc::extended_public_key( fc::ecc::private_key::generate().get_public_key(), - fc::sha256(), - 0, 0, 0 ); - extended_public_key_type type = extended_public_key_type( key ); - std::string packed = std::string( type ); - extended_public_key_type unpacked = extended_public_key_type( packed ); - BOOST_CHECK( type == unpacked ); - } catch ( const fc::exception& e ) - { - edump((e.to_detail_string())); - throw; - } -} - -BOOST_AUTO_TEST_CASE( version_test ) -{ - try - { - BOOST_REQUIRE_EQUAL( string( version( 1, 2, 3) ), "1.2.3" ); - - fc::variant ver_str( "3.0.0" ); - version ver; - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == version( 3, 0 , 0 ) ); - - ver_str = fc::variant( "0.0.0" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == version() ); - - ver_str = fc::variant( "1.0.1" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == version( 1, 0, 1 ) ); - - ver_str = fc::variant( "1_0_1" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == version( 1, 0, 1 ) ); - - ver_str = fc::variant( "12.34.56" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == version( 12, 34, 56 ) ); - - ver_str = fc::variant( "256.0.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "0.256.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "0.0.65536" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "1.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "1.0.0.1" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( hardfork_version_test ) -{ - try - { - BOOST_REQUIRE_EQUAL( string( hardfork_version( 1, 2 ) ), "1.2.0" ); - - fc::variant ver_str( "3.0.0" ); - hardfork_version ver; - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version( 3, 0 ) ); - - ver_str = fc::variant( "0.0.0" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version() ); - - ver_str = fc::variant( "1.0.0" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version( 1, 0 ) ); - - ver_str = fc::variant( "1_0_0" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version( 1, 0 ) ); - - ver_str = fc::variant( "12.34.00" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version( 12, 34 ) ); - - ver_str = fc::variant( "256.0.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "0.256.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "0.0.1" ); - fc::from_variant( ver_str, ver ); - BOOST_REQUIRE( ver == hardfork_version( 0, 0 ) ); - - ver_str = fc::variant( "1.0" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - - ver_str = fc::variant( "1.0.0.1" ); - HIVE_REQUIRE_THROW( fc::from_variant( ver_str, ver ), fc::exception ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( min_block_size ) -{ - signed_block b; - while( b.witness.length() < HIVE_MIN_ACCOUNT_NAME_LENGTH ) - b.witness += 'a'; - size_t min_size = fc::raw::pack_size( b ); - BOOST_CHECK( min_size == HIVE_MIN_BLOCK_SIZE ); -} - -BOOST_AUTO_TEST_CASE( legacy_signed_transaction ) -{ - using hive::plugins::condenser_api::legacy_signed_transaction; - - signed_transaction tx; - vote_operation op; - op.voter = "alice"; - op.author = "bob"; - op.permlink = "foobar"; - op.weight = HIVE_100_PERCENT; - tx.ref_block_num = 4000; - tx.ref_block_prefix = 4000000000; - tx.expiration = fc::time_point_sec( 1514764800 ); - tx.operations.push_back( op ); - - signed_transaction tx2 = signed_transaction( fc::json::from_string( "{\"ref_block_num\":4000,\"ref_block_prefix\":4000000000,\"expiration\":\"2018-01-01T00:00:00\",\"operations\":[[\"vote\",{\"voter\":\"alice\",\"author\":\"bob\",\"permlink\":\"foobar\",\"weight\":10000}]],\"extensions\":[],\"signatures\":[\"\"]}" ).as< legacy_signed_transaction >() ); - - BOOST_REQUIRE( tx.id() == tx2.id() ); -} - -BOOST_AUTO_TEST_CASE( static_variant_json_test ) -{ - try - { - typedef static_variant< - transfer_operation, - comment_operation - > test_operation; - - test_operation op; - op = transfer_operation(); - - auto json_str = fc::json::to_string( op ); - BOOST_CHECK_EQUAL( json_str, "{\"type\":\"transfer_operation\",\"value\":{\"from\":\"\",\"to\":\"\",\"amount\":{\"amount\":\"0\",\"precision\":3,\"nai\":\"@@000000021\"},\"memo\":\"\"}}" ); - - json_str = "{\"type\":\"transfer_operation\",\"value\":{\"from\":\"foo\",\"to\":\"bar\",\"amount\":{\"amount\":\"1000\",\"precision\":3,\"nai\":\"@@000000021\"},\"memo\":\"\"}}"; - from_variant( fc::json::from_string( json_str ), op ); - BOOST_CHECK_EQUAL( op.which(), 0 ); - - transfer_operation t = op.get< transfer_operation >(); - BOOST_CHECK( t.from == "foo" ); - BOOST_CHECK( t.to == "bar" ); - BOOST_CHECK( t.amount == asset( 1000, HIVE_SYMBOL ) ); - BOOST_CHECK( t.memo == "" ); - - json_str = "{\"type\":1,\"value\":{\"parent_author\":\"foo\",\"parent_permlink\":\"bar\",\"author\":\"foo1\",\"permlink\":\"bar1\",\"title\":\"\",\"body\":\"\",\"json_metadata\":\"\"}}"; - - from_variant( fc::json::from_string( json_str ), op ); - BOOST_CHECK_EQUAL( op.which(), 1 ); - - comment_operation c = op.get< comment_operation >(); - BOOST_CHECK( c.parent_author == "foo" ); - BOOST_CHECK( c.parent_permlink == "bar" ); - BOOST_CHECK( c.author == "foo1" ); - BOOST_CHECK( c.permlink == "bar1" ); - BOOST_CHECK( c.title == "" ); - BOOST_CHECK( c.body == "" ); - BOOST_CHECK( c.json_metadata == "" ); - - json_str = "{\"type\":\"not_a_type\",\"value\":{\"from\":\"foo\",\"to\":\"bar\",\"amount\":{\"amount\":\"1000\",\"precision\":3,\"nai\":\"@@000000021\"},\"memo\":\"\"}}"; - HIVE_REQUIRE_THROW( from_variant( fc::json::from_string( json_str ), op ), fc::assert_exception ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( legacy_operation_test ) -{ - try - { - auto v = fc::json::from_string( "{\"ref_block_num\": 41047, \"ref_block_prefix\": 4089157749, \"expiration\": \"2018-03-28T19:05:47\", \"operations\": [[\"witness_update\", {\"owner\": \"test\", \"url\": \"foo\", \"block_signing_key\": \"TST1111111111111111111111111111111114T1Anm\", \"props\": {\"account_creation_fee\": \"0.500 TESTS\", \"maximum_block_size\": 65536, \"hbd_interest_rate\": 0}, \"fee\": \"0.000 TESTS\"}]], \"extensions\": [], \"signatures\": [\"1f1b2d47427a46513777ae9ed032b761b504423b18350e673beb991a1b52d2381c26c36368f9cc4a72c9de3cc16bca83b269c2ea1960e28647caf151e17c35bf3f\"]}" ); - auto ls = v.as< hive::plugins::condenser_api::legacy_signed_transaction >(); - // not throwing an error here is success - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( asset_symbol_type_test ) -{ - try - { - uint32_t asset_num = 10000000 << HIVE_NAI_SHIFT; // Shift NAI value in to position - asset_num |= SMT_ASSET_NUM_CONTROL_MASK; // Flip the control bit - asset_num |= 3; // Add the precision - - auto symbol = asset_symbol_type::from_asset_num( asset_num ); - - BOOST_REQUIRE( symbol == asset_symbol_type::from_nai( 100000006, 3 ) ); - BOOST_REQUIRE( symbol == asset_symbol_type::from_nai_string( "@@100000006", 3 ) ); - BOOST_REQUIRE( asset_num == asset_symbol_type::asset_num_from_nai( 100000006, 3 ) ); - BOOST_REQUIRE( symbol.to_nai_string() == "@@100000006" ); - BOOST_REQUIRE( symbol.to_nai() == 100000006 ); - BOOST_REQUIRE( symbol.asset_num == asset_num ); - BOOST_REQUIRE( symbol.space() == asset_symbol_type::asset_symbol_space::smt_nai_space ); - BOOST_REQUIRE( symbol.get_paired_symbol() == asset_symbol_type::from_asset_num( asset_num ^ SMT_ASSET_NUM_VESTING_MASK ) ); - BOOST_REQUIRE( asset_symbol_type::from_nai( symbol.to_nai(), 3 ) == symbol ); - - asset_symbol_type hive = asset_symbol_type::from_asset_num( HIVE_ASSET_NUM_HIVE ); - asset_symbol_type hbd = asset_symbol_type::from_asset_num( HIVE_ASSET_NUM_HBD ); - asset_symbol_type vests = asset_symbol_type::from_asset_num( HIVE_ASSET_NUM_VESTS ); - - BOOST_REQUIRE( hive.space() == asset_symbol_type::asset_symbol_space::legacy_space ); - BOOST_REQUIRE( hbd.space() == asset_symbol_type::asset_symbol_space::legacy_space ); - BOOST_REQUIRE( vests.space() == asset_symbol_type::asset_symbol_space::legacy_space ); - - BOOST_REQUIRE( asset_symbol_type::from_nai( hive.to_nai(), HIVE_PRECISION_HIVE ) == hive ); - BOOST_REQUIRE( asset_symbol_type::from_nai( hbd.to_nai(), HIVE_PRECISION_HBD ) == hbd ); - BOOST_REQUIRE( asset_symbol_type::from_nai( vests.to_nai(), HIVE_PRECISION_VESTS ) == vests ); - - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( "@@100000006", HIVE_ASSET_MAX_DECIMALS + 1 ), fc::assert_exception ); // More than max decimals - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( "@0100000006", 3 ), fc::assert_exception ); // Invalid NAI prefix - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( "@@00000006", 3 ), fc::assert_exception ); // Length too short - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( "@@0100000006", 3 ), fc::assert_exception ); // Length too long - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( "@@invalid00", 3 ), fc::exception ); // Boost lexical bad cast - HIVE_REQUIRE_THROW( asset_symbol_type::from_nai_string( nullptr, 3 ), fc::exception ); // Null pointer - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( unpack_clear_test ) -{ - try - { - std::stringstream ss1; - std::stringstream ss2; - - signed_block b1; - - for ( int i = 0; i < 10; i++ ) - { - signed_transaction tx; - - vote_operation op; - op.voter = "alice"; - op.author = "bob"; - op.permlink = "permlink1"; - op.weight = HIVE_100_PERCENT; - tx.operations.push_back( op ); - - vote_operation op2; - op2.voter = "charlie"; - op2.author = "sam"; - op2.permlink = "permlink2"; - op2.weight = HIVE_100_PERCENT; - tx.operations.push_back( op2 ); - - tx.ref_block_num = 1000; - tx.ref_block_prefix = 1000000000; - tx.expiration = fc::time_point_sec( 1514764800 + i ); - - b1.transactions.push_back( tx ); - } - - signed_block b2; - - for ( int i = 0; i < 20; i++ ) - { - signed_transaction tx; - vote_operation op; - op.voter = "dave"; - op.author = "greg"; - op.permlink = "foobar"; - op.weight = HIVE_100_PERCENT/2; - tx.ref_block_num = 4000; - tx.ref_block_prefix = 4000000000; - tx.expiration = fc::time_point_sec( 1714764800 + i ); - tx.operations.push_back( op ); - - b2.transactions.push_back( tx ); - } - - fc::raw::pack( ss2, b2 ); - fc::raw::pack( ss1, b1 ); - - signed_block unpacked_block; - fc::raw::unpack( ss2, unpacked_block ); - - // This operation should completely overwrite signed block 'b2' - fc::raw::unpack( ss1, unpacked_block ); - - BOOST_REQUIRE( b1.transactions.size() == unpacked_block.transactions.size() ); - for ( size_t i = 0; i < unpacked_block.transactions.size(); i++ ) - { - signed_transaction tx = unpacked_block.transactions[ i ]; - BOOST_REQUIRE( unpacked_block.transactions[ i ].operations.size() == b1.transactions[ i ].operations.size() ); - - vote_operation op = tx.operations[ 0 ].get< vote_operation >(); - BOOST_REQUIRE( op.voter == "alice" ); - BOOST_REQUIRE( op.author == "bob" ); - BOOST_REQUIRE( op.permlink == "permlink1" ); - BOOST_REQUIRE( op.weight == HIVE_100_PERCENT ); - - vote_operation op2 = tx.operations[ 1 ].get< vote_operation >(); - BOOST_REQUIRE( op2.voter == "charlie" ); - BOOST_REQUIRE( op2.author == "sam" ); - BOOST_REQUIRE( op2.permlink == "permlink2" ); - BOOST_REQUIRE( op2.weight == HIVE_100_PERCENT ); - - BOOST_REQUIRE( tx.ref_block_num == 1000 ); - BOOST_REQUIRE( tx.ref_block_prefix == 1000000000 ); - BOOST_REQUIRE( tx.expiration == fc::time_point_sec( 1514764800 + i ) ); - } - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( unpack_recursion_test ) -{ - try - { - std::stringstream ss; - int recursion_level = 100000; - uint64_t allocation_per_level = 500000; - - for ( int i = 0; i < recursion_level; i++ ) - { - fc::raw::pack( ss, unsigned_int( allocation_per_level ) ); - fc::raw::pack( ss, static_cast< uint8_t >( variant::array_type ) ); - } - - std::vector< fc::variant > v; - HIVE_REQUIRE_THROW( fc::raw::unpack( ss, v ), fc::assert_exception ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/smt_operation_tests.cpp b/tests2/unit/tests/smt_operation_tests.cpp deleted file mode 100644 index 9beb1a9cd3eeb7016a4bba9beaf674a44d22b22e..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/smt_operation_tests.cpp +++ /dev/null @@ -1,3117 +0,0 @@ -#include <fc/macros.hpp> - -#if defined IS_TEST_NET && defined HIVE_ENABLE_SMT - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/smt_objects.hpp> - -#include <hive/chain/util/nai_generator.hpp> -#include <hive/chain/util/smt_token.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <fc/uint128.hpp> - -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; -using fc::uint128_t; -using boost::container::flat_set; - -BOOST_FIXTURE_TEST_SUITE( smt_operation_tests, smt_database_fixture ) - -BOOST_AUTO_TEST_CASE( smt_limit_order_create_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_limit_order_create_authorities" ); - - ACTORS( (alice)(bob) ) - - limit_order_create_operation op; - - //Create SMT and give some SMT to creator. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "alice"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = asset( 1000, alice_symbol ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_limit_order_create2_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_limit_order_create2_authorities" ); - - ACTORS( (alice)(bob) ) - - limit_order_create2_operation op; - - //Create SMT and give some SMT to creator. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 0 ); - - tx.operations.clear(); - tx.signatures.clear(); - - op.owner = "alice"; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), asset( 1000, alice_symbol ) ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_limit_order_create_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create_apply" ); - - ACTORS( (alice)(bob) ) - - //Create SMT and give some SMT to creators. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3); - - const account_object& alice_account = db->get_account( "alice" ); - const account_object& bob_account = db->get_account( "bob" ); - - asset alice_0 = asset( 0, alice_symbol ); - - FUND( "bob", 1000000 ); - convert( "bob", ASSET("1000.000 TESTS" ) ); - generate_block(); - - asset alice_smt_balance = asset( 1000000, alice_symbol ); - asset bob_smt_balance = asset( 1000000, alice_symbol ); - - asset alice_balance = alice_account.get_balance(); - - asset bob_balance = bob_account.get_balance(); - - FUND( "alice", alice_smt_balance ); - FUND( "bob", bob_smt_balance ); - - tx.operations.clear(); - tx.signatures.clear(); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have required funds" ); - limit_order_create_operation op; - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = asset( 10000, alice_symbol ); - op.fill_or_kill = false; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to receive is 0" ); - - op.owner = "alice"; - op.min_to_receive = alice_0; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to sell is 0" ); - - op.amount_to_sell = alice_0; - op.min_to_receive = ASSET( "10.000 TESTS" ) ; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when expiration is too long" ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = ASSET( "15.000 TBD" ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION + 1 ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test success creating limit order that will not be filled" ); - - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = asset( 15000, alice_symbol ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "10.000 TESTS" ); - - auto limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == op.amount_to_sell.amount ); - BOOST_REQUIRE( limit_order->sell_price == price( op.amount_to_sell / op.min_to_receive ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure creating limit order with duplicate id" ); - - op.amount_to_sell = ASSET( "20.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 10000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "10.000 TESTS" ), op.min_to_receive ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test sucess killing an order that will not be filled" ); - - op.orderid = 2; - op.fill_or_kill = true; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - // BOOST_TEST_MESSAGE( "--- Test having a partial match to limit order" ); - // // Alice has order for 15 SMT at a price of 2:3 - // // Fill 5 HIVE for 7.5 SMT - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = asset (7500, alice_symbol ); - op.min_to_receive = ASSET( "5.000 TESTS" ); - op.fill_or_kill = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - bob_smt_balance -= asset (7500, alice_symbol ); - alice_smt_balance += asset (7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - auto recent_ops = get_last_operations( 1 ); - auto fill_order_op = recent_ops[0].get< fill_order_operation >(); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 5000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "10.000 TESTS" ), asset( 15000, alice_symbol ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == ASSET( "5.000 TESTS").amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset(7500, alice_symbol ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order fully, but the new order partially" ); - - op.amount_to_sell = asset( 15000, alice_symbol ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - bob_smt_balance -= asset( 15000, alice_symbol ); - alice_smt_balance += asset( 7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 1 ); - BOOST_REQUIRE( limit_order->for_sale.value == 7500 ); - BOOST_REQUIRE( limit_order->sell_price == price( asset( 15000, alice_symbol ), ASSET( "10.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order and new order fully" ); - - op.owner = "alice"; - op.orderid = 3; - op.amount_to_sell = ASSET( "5.000 TESTS" ); - op.min_to_receive = asset( 7500, alice_symbol ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "5.000 TESTS" ); - alice_smt_balance += asset( 7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 3 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is better." ); - - op.owner = "alice"; - op.orderid = 4; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.min_to_receive = asset( 11000, alice_symbol ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = asset( 12000, alice_symbol ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "10.000 TESTS" ); - alice_smt_balance += asset( 11000, alice_symbol ); - bob_smt_balance -= asset( 12000, alice_symbol ); - bob_balance += ASSET( "10.000 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 4 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "alice", 4 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 4 ); - BOOST_REQUIRE( limit_order->for_sale.value == 1000 ); - BOOST_REQUIRE( limit_order->sell_price == price( asset( 12000, alice_symbol ), ASSET( "10.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - limit_order_cancel_operation can; - can.owner = "bob"; - can.orderid = 4; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( can ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is worse." ); - - //auto& gpo = db->get_dynamic_global_properties(); - //auto start_hbd = gpo.get_current_hbd_supply(); - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.min_to_receive = asset( 22000, alice_symbol ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 5; - op.amount_to_sell = asset( 12000, alice_symbol ); - op.min_to_receive = ASSET( "10.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "20.000 TESTS" ); - alice_smt_balance += asset( 12000, alice_symbol ); - - bob_smt_balance -= asset( 11000, alice_symbol ); - bob_balance += ASSET( "10.909 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 5 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "bob", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == 5 ); - BOOST_REQUIRE( limit_order->for_sale.value == 9091 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "20.000 TESTS" ), asset( 22000, alice_symbol ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_limit_order_cancel_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_limit_order_cancel_authorities" ); - - ACTORS( (alice)(bob) ) - - //Create SMT and give some SMT to creator. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - - FUND( "alice", asset( 100000, alice_symbol ) ); - - tx.operations.clear(); - tx.signatures.clear(); - - limit_order_create_operation c; - c.owner = "alice"; - c.orderid = 1; - c.amount_to_sell = ASSET( "1.000 TESTS" ); - c.min_to_receive = asset( 1000, alice_symbol ); - c.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - tx.operations.push_back( c ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - limit_order_cancel_operation op; - op.owner = "alice"; - op.orderid = 1; - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - - BOOST_TEST_MESSAGE( "--- Test failure when no signature." ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - BOOST_TEST_MESSAGE( "--- Test success with account signature" ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_TEST_MESSAGE( "--- Test failure with duplicate signature" ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_duplicate_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with additional incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_irrelevant_sig ); - - BOOST_TEST_MESSAGE( "--- Test failure with incorrect signature" ); - tx.signatures.clear(); - sign( tx, alice_post_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), tx_missing_active_auth ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_limit_order_cancel_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_limit_order_cancel_apply" ); - - ACTORS( (alice) ) - - //Create SMT and give some SMT to creator. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - - const account_object& alice_account = db->get_account( "alice" ); - - tx.operations.clear(); - tx.signatures.clear(); - - asset alice_smt_balance = asset( 1000000, alice_symbol ); - asset alice_balance = alice_account.get_balance(); - - FUND( "alice", alice_smt_balance ); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test cancel non-existent order" ); - - limit_order_cancel_operation op; - - op.owner = "alice"; - op.orderid = 5; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test cancel order" ); - - limit_order_create_operation create; - create.owner = "alice"; - create.orderid = 5; - create.amount_to_sell = ASSET( "5.000 TESTS" ); - create.min_to_receive = asset( 7500, alice_symbol ); - create.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( create ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 5 ) ) != limit_order_idx.end() ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_limit_order_create2_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: limit_order_create2_apply" ); - - ACTORS( (alice)(bob) ) - - //Create SMT and give some SMT to creators. - signed_transaction tx; - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3); - - const account_object& alice_account = db->get_account( "alice" ); - const account_object& bob_account = db->get_account( "bob" ); - - asset alice_0 = asset( 0, alice_symbol ); - - FUND( "bob", 1000000 ); - convert( "bob", ASSET("1000.000 TESTS" ) ); - generate_block(); - - asset alice_smt_balance = asset( 1000000, alice_symbol ); - asset bob_smt_balance = asset( 1000000, alice_symbol ); - - asset alice_balance = alice_account.get_balance(); - - asset bob_balance = bob_account.get_balance(); - - FUND( "alice", alice_smt_balance ); - FUND( "bob", bob_smt_balance ); - - tx.operations.clear(); - tx.signatures.clear(); - - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - BOOST_TEST_MESSAGE( "--- Test failure when account does not have required funds" ); - limit_order_create2_operation op; - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), asset( 1000, alice_symbol ) ); - op.fill_or_kill = false; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to receive is 0" ); - - op.owner = "alice"; - op.exchange_rate.base = ASSET( "0.000 TESTS" ); - op.exchange_rate.quote = alice_0; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when amount to sell is 0" ); - - op.amount_to_sell = alice_0; - op.exchange_rate = price( ASSET( "1.000 TESTS" ), asset( 1000, alice_symbol ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure when expiration is too long" ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "2.000 TESTS" ), ASSET( "3.000 TBD" ) ); - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION + 1 ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_TEST_MESSAGE( "--- Test success creating limit order that will not be filled" ); - - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "2.000 TESTS" ), asset( 3000, alice_symbol ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "10.000 TESTS" ); - - auto limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == op.amount_to_sell.amount ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test failure creating limit order with duplicate id" ); - - op.amount_to_sell = ASSET( "20.000 TESTS" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == op.owner ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 10000 ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test sucess killing an order that will not be filled" ); - - op.orderid = 2; - op.fill_or_kill = true; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - validate_database(); - - // BOOST_TEST_MESSAGE( "--- Test having a partial match to limit order" ); - // // Alice has order for 15 SMT at a price of 2:3 - // // Fill 5 HIVE for 7.5 SMT - - op.owner = "bob"; - op.orderid = 1; - op.amount_to_sell = asset( 7500, alice_symbol ); - op.exchange_rate = price( asset( 3000, alice_symbol ), ASSET( "2.000 TESTS" ) ); - op.fill_or_kill = false; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - bob_smt_balance -= asset (7500, alice_symbol ); - alice_smt_balance += asset (7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - auto recent_ops = get_last_operations( 1 ); - auto fill_order_op = recent_ops[0].get< fill_order_operation >(); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == op.orderid ); - BOOST_REQUIRE( limit_order->for_sale == 5000 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "2.000 TESTS" ), asset( 3000, alice_symbol ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", op.orderid ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == ASSET( "5.000 TESTS").amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset(7500, alice_symbol ).amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order fully, but the new order partially" ); - - op.amount_to_sell = asset( 15000, alice_symbol ); - op.exchange_rate = price( asset( 3000, alice_symbol ), ASSET( "2.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - bob_smt_balance -= asset( 15000, alice_symbol ); - alice_smt_balance += asset( 7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 1 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 1 ); - BOOST_REQUIRE( limit_order->for_sale.value == 7500 ); - BOOST_REQUIRE( limit_order->sell_price == price( asset( 3000, alice_symbol ), ASSET( "2.000 TESTS" ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling an existing order and new order fully" ); - - op.owner = "alice"; - op.orderid = 3; - op.amount_to_sell = ASSET( "5.000 TESTS" ); - op.exchange_rate = price( ASSET( "2.000 TESTS" ), asset( 3000, alice_symbol ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "5.000 TESTS" ); - alice_smt_balance += asset( 7500, alice_symbol ); - bob_balance += ASSET( "5.000 TESTS" ); - - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "alice", 3 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find( boost::make_tuple( "bob", 1 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is better." ); - - op.owner = "alice"; - op.orderid = 4; - op.amount_to_sell = ASSET( "10.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), asset( 1100, alice_symbol ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = asset( 12000, alice_symbol ); - op.exchange_rate = price( asset( 1200, alice_symbol ), ASSET( "1.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "10.000 TESTS" ); - alice_smt_balance += asset( 11000, alice_symbol ); - bob_smt_balance -= asset( 12000, alice_symbol ); - bob_balance += ASSET( "10.000 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "bob", 4 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "alice", 4 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "bob" ); - BOOST_REQUIRE( limit_order->orderid == 4 ); - BOOST_REQUIRE( limit_order->for_sale.value == 1000 ); - BOOST_REQUIRE( limit_order->sell_price == op.exchange_rate ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - - limit_order_cancel_operation can; - can.owner = "bob"; - can.orderid = 4; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( can ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Test filling limit order with better order when partial order is worse." ); - - //auto& gpo = db->get_dynamic_global_properties(); - //auto start_hbd = gpo.get_current_hbd_supply(); - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = ASSET( "20.000 TESTS" ); - op.exchange_rate = price( ASSET( "1.000 TESTS" ), asset( 1100, alice_symbol ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 5; - op.amount_to_sell = asset( 12000, alice_symbol ); - op.exchange_rate = price( asset( 1200, alice_symbol ), ASSET( "1.000 TESTS" ) ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_balance -= ASSET( "20.000 TESTS" ); - alice_smt_balance += asset( 12000, alice_symbol ); - - bob_smt_balance -= asset( 11000, alice_symbol ); - bob_balance += ASSET( "10.909 TESTS" ); - - limit_order = limit_order_idx.find( boost::make_tuple( "alice", 5 ) ); - BOOST_REQUIRE( limit_order != limit_order_idx.end() ); - BOOST_REQUIRE( limit_order_idx.find(boost::make_tuple( "bob", 5 ) ) == limit_order_idx.end() ); - BOOST_REQUIRE( limit_order->seller == "alice" ); - BOOST_REQUIRE( limit_order->orderid == 5 ); - BOOST_REQUIRE( limit_order->for_sale.value == 9091 ); - BOOST_REQUIRE( limit_order->sell_price == price( ASSET( "1.000 TESTS" ), asset( 1100, alice_symbol ) ) ); - BOOST_REQUIRE( limit_order->get_market() == std::make_pair( alice_symbol, HIVE_SYMBOL ) ); - BOOST_REQUIRE( db->get_balance( alice_account, alice_symbol ).amount.value == alice_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( alice_account, HIVE_SYMBOL ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, alice_symbol ).amount.value == bob_smt_balance.amount.value ); - BOOST_REQUIRE( db->get_balance( bob_account, HIVE_SYMBOL ).amount.value == bob_balance.amount.value ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance2_validate ) -{ - try - { - claim_reward_balance2_operation op; - op.account = "alice"; - - ACTORS( (alice) ) - - generate_block(); - - // Create SMT(s) and continue. - auto smts = create_smt_3("alice", alice_private_key); - const auto& smt1 = smts[0]; - const auto& smt2 = smts[1]; - const auto& smt3 = smts[2]; - - BOOST_TEST_MESSAGE( "Testing empty rewards" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "Testing ineffective rewards" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - // Manually inserted. - op.reward_tokens.push_back( ASSET( "0.000 TESTS" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( ASSET( "0.000 TBD" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( ASSET( "0.000000 VESTS" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( 0, smt1 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( 0, smt2 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( 0, smt3 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "Testing single reward claims" ); - op.reward_tokens.push_back( ASSET( "1.000 TESTS" ) ); - op.validate(); - op.reward_tokens.clear(); - - op.reward_tokens.push_back( ASSET( "1.000 TBD" ) ); - op.validate(); - op.reward_tokens.clear(); - - op.reward_tokens.push_back( ASSET( "1.000000 VESTS" ) ); - op.validate(); - op.reward_tokens.clear(); - - op.reward_tokens.push_back( asset( 1, smt1 ) ); - op.validate(); - op.reward_tokens.clear(); - - op.reward_tokens.push_back( asset( 1, smt2 ) ); - op.validate(); - op.reward_tokens.clear(); - - op.reward_tokens.push_back( asset( 1, smt3 ) ); - op.validate(); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "Testing multiple rewards" ); - op.reward_tokens.push_back( ASSET( "1.000 TBD" ) ); - op.reward_tokens.push_back( ASSET( "1.000 TESTS" ) ); - op.reward_tokens.push_back( ASSET( "1.000000 VESTS" ) ); - op.reward_tokens.push_back( asset( 1, smt1 ) ); - op.reward_tokens.push_back( asset( 1, smt2 ) ); - op.reward_tokens.push_back( asset( 1, smt3 ) ); - op.validate(); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "Testing invalid rewards" ); - op.reward_tokens.push_back( ASSET( "-1.000 TESTS" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( ASSET( "-1.000 TBD" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( ASSET( "-1.000000 VESTS" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( -1, smt1 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( -1, smt2 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( -1, smt3 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "Testing duplicated reward tokens." ); - op.reward_tokens.push_back( asset( 1, smt3 ) ); - op.reward_tokens.push_back( asset( 1, smt3 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "Testing inconsistencies of manually inserted reward tokens." ); - op.reward_tokens.push_back( ASSET( "1.000 TESTS" ) ); - op.reward_tokens.push_back( ASSET( "1.000 TBD" ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.push_back( asset( 1, smt3 ) ); - op.reward_tokens.push_back( asset( 1, smt1 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.reward_tokens.clear(); - op.reward_tokens.push_back( asset( 1, smt1 ) ); - op.reward_tokens.push_back( asset( -1, smt3 ) ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance2_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: decline_voting_rights_authorities" ); - - claim_reward_balance2_operation op; - op.account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( claim_reward_balance2_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: claim_reward_balance2_apply" ); - BOOST_TEST_MESSAGE( "--- Setting up test state" ); - - ACTORS( (alice) ) - generate_block(); - - auto smts = create_smt_3( "alice", alice_private_key ); - const auto& smt1 = smts[0]; - const auto& smt2 = smts[1]; - const auto& smt3 = smts[2]; - - FUND_SMT_REWARDS( "alice", asset( 10*std::pow(10, smt1.decimals()), smt1 ) ); - FUND_SMT_REWARDS( "alice", asset( 10*std::pow(10, smt2.decimals()), smt2 ) ); - FUND_SMT_REWARDS( "alice", asset( 10*std::pow(10, smt3.decimals()), smt3 ) ); - - db_plugin->debug_update( []( database& db ) - { - db.modify( db.get_account( "alice" ), []( account_object& a ) - { - a.reward_hbd_balance = ASSET( "10.000 TBD" ); - a.reward_hive_balance = ASSET( "10.000 TESTS" ); - a.reward_vesting_balance = ASSET( "10.000000 VESTS" ); - a.reward_vesting_hive = ASSET( "10.000 TESTS" ); - }); - - db.modify( db.get_dynamic_global_properties(), []( dynamic_global_property_object& gpo ) - { - gpo.current_hbd_supply += ASSET( "10.000 TBD" ); - gpo.current_supply += ASSET( "20.000 TESTS" ); - gpo.virtual_supply += ASSET( "20.000 TESTS" ); - gpo.pending_rewarded_vesting_shares += ASSET( "10.000000 VESTS" ); - gpo.pending_rewarded_vesting_hive += ASSET( "10.000 TESTS" ); - }); - }); - - generate_block(); - validate_database(); - - auto alice_hive = get_balance( "alice" ); - auto alice_hbd = get_hbd_balance( "alice" ); - auto alice_vests = get_vesting( "alice" ); - auto alice_smt1 = db->get_balance( "alice", smt1 ); - auto alice_smt2 = db->get_balance( "alice", smt2 ); - auto alice_smt3 = db->get_balance( "alice", smt3 ); - - claim_reward_balance2_operation op; - op.account = "alice"; - - BOOST_TEST_MESSAGE( "--- Attempting to claim more than exists in the reward balance." ); - // Legacy symbols - op.reward_tokens.push_back( ASSET( "0.000 TBD" ) ); - op.reward_tokens.push_back( ASSET( "20.000 TESTS" ) ); - op.reward_tokens.push_back( ASSET( "0.000000 VESTS" ) ); - FAIL_WITH_OP(op, alice_private_key, fc::assert_exception); - op.reward_tokens.clear(); - // SMTs - op.reward_tokens.push_back( asset( 0, smt1 ) ); - op.reward_tokens.push_back( asset( 0, smt2 ) ); - op.reward_tokens.push_back( asset( 20*std::pow(10, smt3.decimals()), smt3 ) ); - FAIL_WITH_OP(op, alice_private_key, fc::assert_exception); - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "--- Claiming a partial reward balance" ); - // Legacy symbols - asset partial_vests = ASSET( "5.000000 VESTS" ); - op.reward_tokens.push_back( ASSET( "0.000 TBD" ) ); - op.reward_tokens.push_back( ASSET( "0.000 TESTS" ) ); - op.reward_tokens.push_back( partial_vests ); - PUSH_OP(op, alice_private_key); - BOOST_REQUIRE( get_balance( "alice" ) == alice_hive + ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_rewards( "alice" ) == ASSET( "10.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == alice_hbd + ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ) == ASSET( "10.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( "alice" ) == alice_vests + partial_vests ); - BOOST_REQUIRE( get_vest_rewards( "alice" ) == ASSET( "5.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "alice" ) == ASSET( "5.000 TESTS" ) ); - validate_database(); - alice_vests += partial_vests; - op.reward_tokens.clear(); - // SMTs - asset partial_smt2 = asset( 5*std::pow(10, smt2.decimals()), smt2 ); - op.reward_tokens.push_back( asset( 0, smt1 ) ); - op.reward_tokens.push_back( partial_smt2 ); - op.reward_tokens.push_back( asset( 0, smt3 ) ); - PUSH_OP(op, alice_private_key); - BOOST_REQUIRE( db->get_balance( "alice", smt1 ) == alice_smt1 + asset( 0, smt1 ) ); - BOOST_REQUIRE( db->get_balance( "alice", smt2 ) == alice_smt2 + partial_smt2 ); - BOOST_REQUIRE( db->get_balance( "alice", smt3 ) == alice_smt3 + asset( 0, smt3 ) ); - validate_database(); - alice_smt2 += partial_smt2; - op.reward_tokens.clear(); - - BOOST_TEST_MESSAGE( "--- Claiming the full reward balance" ); - // Legacy symbols - asset full_hive = ASSET( "10.000 TESTS" ); - asset full_hbd = ASSET( "10.000 TBD" ); - op.reward_tokens.push_back( full_hbd ); - op.reward_tokens.push_back( full_hive ); - op.reward_tokens.push_back( partial_vests ); - PUSH_OP(op, alice_private_key); - BOOST_REQUIRE( get_balance( "alice" ) == alice_hive + full_hive ); - BOOST_REQUIRE( get_rewards( "alice" ) == ASSET( "0.000 TESTS" ) ); - BOOST_REQUIRE( get_hbd_balance( "alice" ) == alice_hbd + full_hbd ); - BOOST_REQUIRE( get_hbd_rewards( "alice" ) == ASSET( "0.000 TBD" ) ); - BOOST_REQUIRE( get_vesting( "alice" ) == alice_vests + partial_vests ); - BOOST_REQUIRE( get_vest_rewards( "alice" ) == ASSET( "0.000000 VESTS" ) ); - BOOST_REQUIRE( get_vest_rewards_as_hive( "alice" ) == ASSET( "0.000 TESTS" ) ); - validate_database(); - op.reward_tokens.clear(); - // SMTs - asset full_smt1 = asset( 10*std::pow(10, smt1.decimals()), smt1 ); - asset full_smt3 = asset( 10*std::pow(10, smt3.decimals()), smt3 ); - op.reward_tokens.push_back( full_smt1 ); - op.reward_tokens.push_back( partial_smt2 ); - op.reward_tokens.push_back( full_smt3 ); - PUSH_OP(op, alice_private_key); - BOOST_REQUIRE( db->get_balance( "alice", smt1 ) == alice_smt1 + full_smt1 ); - BOOST_REQUIRE( db->get_balance( "alice", smt2 ) == alice_smt2 + partial_smt2 ); - BOOST_REQUIRE( db->get_balance( "alice", smt3 ) == alice_smt3 + full_smt3 ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_transfer_to_vesting_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: transfer_to_vesting_validate with SMT" ); - - // Dramatis personae - ACTORS( (alice) ) - generate_block(); - // Create sample SMTs - auto smts = create_smt_3( "alice", alice_private_key ); - const auto& smt1 = smts[0]; - // Fund creator with SMTs - FUND( "alice", asset( 100, smt1 ) ); - - transfer_to_vesting_operation op; - op.from = "alice"; - op.amount = asset( 20, smt1 ); - op.validate(); - - // Fail on invalid 'from' account name - op.from = "@@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.from = "alice"; - - // Fail on invalid 'to' account name - op.to = "@@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.to = ""; - - // Fail on vesting symbol (instead of liquid) - op.amount = asset( 20, smt1.get_paired_symbol() ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = asset( 20, smt1 ); - - // Fail on 0 amount - op.amount = asset( 0, smt1 ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = asset( 20, smt1 ); - - // Fail on negative amount - op.amount = asset( -20, smt1 ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = asset( 20, smt1 ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -// Here would be smt_transfer_to_vesting_authorities if it differed from transfer_to_vesting_authorities -/* -BOOST_AUTO_TEST_CASE( smt_transfer_to_vesting_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_transfer_to_vesting_apply" ); - - auto test_single_smt = [this] (const asset_symbol_type& liquid_smt, const fc::ecc::private_key& key ) - { - asset_symbol_type vesting_smt = liquid_smt.get_paired_symbol(); - // Fund creator with SMTs - FUND( "alice", asset( 10000, liquid_smt ) ); - - const auto& smt_object = db->get< smt_token_object, by_symbol >( liquid_smt ); - - // Check pre-vesting balances - FC_ASSERT( db->get_balance( "alice", liquid_smt ).amount == 10000, "SMT balance adjusting error" ); - FC_ASSERT( db->get_balance( "alice", vesting_smt ).amount == 0, "SMT balance adjusting error" ); - - auto smt_shares = asset( smt_object.get_total_vesting_shares(), vesting_smt ); - auto smt_vests = asset( smt_object.total_vesting_fund_smt, liquid_smt ); - auto smt_share_price = smt_object.get_vesting_share_price(); - auto alice_smt_shares = db->get_balance( "alice", vesting_smt ); - auto bob_smt_shares = db->get_balance( "bob", vesting_smt );; - - // Self transfer Alice's liquid - transfer_to_vesting_operation op; - op.from = "alice"; - op.to = ""; - op.amount = asset( 7500, liquid_smt ); - PUSH_OP( op, key ); - - auto new_vest = op.amount * smt_share_price; - smt_shares += new_vest; - smt_vests += op.amount; - alice_smt_shares += new_vest; - - BOOST_REQUIRE( db->get_balance( "alice", liquid_smt ) == asset( 2500, liquid_smt ) ); - BOOST_REQUIRE( db->get_balance( "alice", vesting_smt ) == alice_smt_shares ); - BOOST_REQUIRE( smt_object.total_vesting_fund_smt.value == smt_vests.amount.value ); - BOOST_REQUIRE( smt_object.get_total_vesting_shares().value == smt_shares.amount.value ); - validate_database(); - smt_share_price = smt_object.get_vesting_share_price(); - - // Transfer Alice's liquid to Bob's vests - op.to = "bob"; - op.amount = asset( 2000, liquid_smt ); - PUSH_OP( op, key ); - - new_vest = op.amount * smt_share_price; - smt_shares += new_vest; - smt_vests += op.amount; - bob_smt_shares += new_vest; - - BOOST_REQUIRE( db->get_balance( "alice", liquid_smt ) == asset( 500, liquid_smt ) ); - BOOST_REQUIRE( db->get_balance( "alice", vesting_smt ) == alice_smt_shares ); - BOOST_REQUIRE( db->get_balance( "bob", liquid_smt ) == asset( 0, liquid_smt ) ); - BOOST_REQUIRE( db->get_balance( "bob", vesting_smt ) == bob_smt_shares ); - BOOST_REQUIRE( smt_object.total_vesting_fund_smt.value == smt_vests.amount.value ); - BOOST_REQUIRE( smt_object.get_total_vesting_shares().value == smt_shares.amount.value ); - validate_database(); - }; - - ACTORS( (alice)(bob) ) - generate_block(); - - // Create sample SMTs - auto smts = create_smt_3( "alice", alice_private_key ); - test_single_smt( smts[0], alice_private_key); - test_single_smt( smts[1], alice_private_key ); - test_single_smt( smts[2], alice_private_key ); - } - FC_LOG_AND_RETHROW() -} -*/ - -BOOST_AUTO_TEST_CASE( smt_create_validate ) -{ - try - { - ACTORS( (alice) ); - - BOOST_TEST_MESSAGE( " -- A valid smt_create_operation" ); - smt_create_operation op; - op.control_account = "alice"; - op.smt_creation_fee = db->get_dynamic_global_properties().smt_creation_fee; - op.symbol = get_new_smt_symbol( 3, db ); - op.precision = op.symbol.decimals(); - op.validate(); - - BOOST_TEST_MESSAGE( " -- Test invalid control account name" ); - op.control_account = "@@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.control_account = "alice"; - - // Test invalid creation fees. - BOOST_TEST_MESSAGE( " -- Invalid negative creation fee" ); - op.smt_creation_fee.amount = -op.smt_creation_fee.amount; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Valid maximum SMT creation fee (HIVE_MAX_SHARE_SUPPLY)" ); - op.smt_creation_fee.amount = HIVE_MAX_SHARE_SUPPLY; - op.validate(); - - BOOST_TEST_MESSAGE( " -- Invalid SMT creation fee (MAX_SHARE_SUPPLY + 1)" ); - op.smt_creation_fee.amount++; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Invalid currency for SMT creation fee (VESTS)" ); - op.smt_creation_fee = ASSET( "1.000000 VESTS" ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.smt_creation_fee = db->get_dynamic_global_properties().smt_creation_fee; - - BOOST_TEST_MESSAGE( " -- Invalid SMT creation fee: differing decimals" ); - op.precision = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.precision = op.symbol.decimals(); - - // Test symbol - BOOST_TEST_MESSAGE( " -- Invalid SMT creation symbol: vesting symbol used instead of liquid one" ); - op.symbol = op.symbol.get_paired_symbol(); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Invalid SMT creation symbol: HIVE cannot be an SMT" ); - op.symbol = HIVE_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Invalid SMT creation symbol: HBD cannot be an SMT" ); - op.symbol = HBD_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Invalid SMT creation symbol: VESTS cannot be an SMT" ); - op.symbol = VESTS_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - // If this fails, it could indicate a test above has failed for the wrong reasons - op.symbol = get_new_smt_symbol( 3, db ); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_create_authorities ) -{ - try - { - SMT_SYMBOL( alice, 3, db ); - - smt_create_operation op; - op.control_account = "alice"; - op.symbol = alice_symbol; - op.smt_creation_fee = db->get_dynamic_global_properties().smt_creation_fee; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_create_duplicate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_duplicate" ); - - ACTORS( (alice) ) - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 0 ); - - // We add the NAI back to the pool to ensure the test does not fail because the NAI is not in the pool - db->modify( db->get< nai_pool_object >(), [&] ( nai_pool_object& obj ) - { - obj.nais[ 0 ] = alice_symbol; - } ); - - // Fail on duplicate SMT lookup - HIVE_REQUIRE_THROW( create_smt_with_nai( "alice", alice_private_key, alice_symbol.to_nai(), alice_symbol.decimals() ), fc::assert_exception) - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_create_duplicate_differing_decimals ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_duplicate_differing_decimals" ); - - ACTORS( (alice) ) - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 /* Decimals */ ); - - // We add the NAI back to the pool to ensure the test does not fail because the NAI is not in the pool - db->modify( db->get< nai_pool_object >(), [&] ( nai_pool_object& obj ) - { - obj.nais[ 0 ] = asset_symbol_type::from_nai( alice_symbol.to_nai(), 0 ); - } ); - - // Fail on duplicate SMT lookup - HIVE_REQUIRE_THROW( create_smt_with_nai( "alice", alice_private_key, alice_symbol.to_nai(), 2 /* Decimals */ ), fc::assert_exception) - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_create_duplicate_different_users ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_duplicate_different_users" ); - - ACTORS( (alice)(bob) ) - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 0 ); - - // We add the NAI back to the pool to ensure the test does not fail because the NAI is not in the pool - db->modify( db->get< nai_pool_object >(), [&] ( nai_pool_object& obj ) - { - obj.nais[ 0 ] = alice_symbol; - } ); - - // Fail on duplicate SMT lookup - HIVE_REQUIRE_THROW( create_smt_with_nai( "bob", bob_private_key, alice_symbol.to_nai(), alice_symbol.decimals() ), fc::assert_exception) - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_create_with_hive_funds ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_with_hive_funds" ); - - // This test expects 1.000 TBD smt_creation_fee - db->modify( db->get_dynamic_global_properties(), [&] ( dynamic_global_property_object& dgpo ) - { - dgpo.smt_creation_fee = asset( 1000, HBD_SYMBOL ); - } ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - ACTORS( (alice) ) - - generate_block(); - - FUND( "alice", ASSET( "0.999 TESTS" ) ); - - smt_create_operation op; - op.control_account = "alice"; - op.smt_creation_fee = ASSET( "1.000 TESTS" ); - op.symbol = get_new_smt_symbol( 3, db ); - op.precision = op.symbol.decimals(); - op.validate(); - - // Fail insufficient funds - FAIL_WITH_OP( op, alice_private_key, fc::assert_exception ); - - BOOST_REQUIRE( util::smt::find_token( *db, op.symbol, true ) == nullptr ); - - FUND( "alice", ASSET( "0.001 TESTS" ) ); - - PUSH_OP( op, alice_private_key ); - - BOOST_REQUIRE( util::smt::find_token( *db, op.symbol, true ) != nullptr ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_create_with_hbd_funds ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_with_hbd_funds" ); - - // This test expects 1.000 TBD smt_creation_fee - db->modify( db->get_dynamic_global_properties(), [&] ( dynamic_global_property_object& dgpo ) - { - dgpo.smt_creation_fee = asset( 1000, HBD_SYMBOL ); - } ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - ACTORS( (alice) ) - - generate_block(); - - FUND( "alice", ASSET( "0.999 TBD" ) ); - - smt_create_operation op; - op.control_account = "alice"; - op.smt_creation_fee = ASSET( "1.000 TBD" ); - op.symbol = get_new_smt_symbol( 3, db ); - op.precision = op.symbol.decimals(); - op.validate(); - - // Fail insufficient funds - FAIL_WITH_OP( op, alice_private_key, fc::assert_exception ); - - BOOST_REQUIRE( util::smt::find_token( *db, op.symbol, true ) == nullptr ); - - FUND( "alice", ASSET( "0.001 TBD" ) ); - - PUSH_OP( op, alice_private_key ); - - BOOST_REQUIRE( util::smt::find_token( *db, op.symbol, true ) != nullptr ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_create_with_invalid_nai ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_create_with_invalid_nai" ); - - ACTORS( (alice) ) - - uint32_t seed = 0; - asset_symbol_type ast; - uint32_t collisions = 0; - do - { - BOOST_REQUIRE( collisions < SMT_MAX_NAI_GENERATION_TRIES ); - collisions++; - - ast = util::nai_generator::generate( seed++ ); - } - while ( db->get< nai_pool_object >().contains( ast ) || util::smt::find_token( *db, ast, true ) != nullptr ); - - // Fail on NAI pool not containing this NAI - HIVE_REQUIRE_THROW( create_smt_with_nai( "alice", alice_private_key, ast.to_nai(), ast.decimals() ), fc::assert_exception) - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_creation_fee_test ) -{ - try - { - ACTORS( (alice) ); - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "2.000 TESTS" ) ) ); - - // This ensures that our actual smt_creation_fee is sane in production (either HIVE or HBD) - const dynamic_global_property_object& dgpo = db->get_dynamic_global_properties(); - FC_ASSERT( dgpo.smt_creation_fee.symbol == HIVE_SYMBOL || dgpo.smt_creation_fee.symbol == HBD_SYMBOL, - "Unexpected symbol for the SMT creation fee on the dynamic global properties object: ${s}", ("s", dgpo.smt_creation_fee.symbol) ); - - FC_ASSERT( dgpo.smt_creation_fee.amount > 0, "Expected positive smt_creation_fee." ); - - for ( int i = 0; i < 2; i++ ) - { - FUND( "alice", ASSET( "2.000 TESTS" ) ); - FUND( "alice", ASSET( "1.000 TBD" ) ); - - // These values should be equivilant as per our price feed and all tests here should work either way - if ( !i ) // First pass - db->modify( dgpo, [&] ( dynamic_global_property_object& dgpo ) - { - dgpo.smt_creation_fee = asset( 2000, HIVE_SYMBOL ); - } ); - else // Second pass - db->modify( dgpo, [&] ( dynamic_global_property_object& dgpo ) - { - dgpo.smt_creation_fee = asset( 1000, HBD_SYMBOL ); - } ); - - BOOST_TEST_MESSAGE( " -- Invalid creation fee, 0.001 TESTS short" ); - smt_create_operation fail_op; - fail_op.control_account = "alice"; - fail_op.smt_creation_fee = ASSET( "1.999 TESTS" ); - fail_op.symbol = get_new_smt_symbol( 3, db ); - fail_op.precision = fail_op.symbol.decimals(); - fail_op.validate(); - - // Fail because we are 0.001 TESTS short of the fee - FAIL_WITH_OP( fail_op, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Invalid creation fee, 0.001 TBD short" ); - smt_create_operation fail_op2; - fail_op2.control_account = "alice"; - fail_op2.smt_creation_fee = ASSET( "0.999 TBD" ); - fail_op2.symbol = get_new_smt_symbol( 3, db ); - fail_op2.precision = fail_op2.symbol.decimals(); - fail_op2.validate(); - - // Fail because we are 0.001 TBD short of the fee - FAIL_WITH_OP( fail_op2, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Valid creation fee, using HIVE" ); - // We should be able to pay with HIVE - smt_create_operation op; - op.control_account = "alice"; - op.smt_creation_fee = ASSET( "2.000 TESTS" ); - op.symbol = get_new_smt_symbol( 3, db ); - op.precision = op.symbol.decimals(); - op.validate(); - - // Succeed because we have paid the equivilant of 1 TBD or 2 TESTS - PUSH_OP( op, alice_private_key ); - - BOOST_TEST_MESSAGE( " -- Valid creation fee, using HBD" ); - // We should be able to pay with HBD - smt_create_operation op2; - op2.control_account = "alice"; - op2.smt_creation_fee = ASSET( "1.000 TBD" ); - op2.symbol = get_new_smt_symbol( 3, db ); - op2.precision = op.symbol.decimals(); - op2.validate(); - - // Succeed because we have paid the equivilant of 1 TBD or 2 TESTS - PUSH_OP( op2, alice_private_key ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_create_reset ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing smt_create_operation reset" ); - - ACTORS( (alice) ) - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - fund( "alice", ASSET( "100.000 TESTS" ) ); - - SMT_SYMBOL( alice, 3, db ) - - db_plugin->debug_update( [=]( database& db ) - { - db.create< smt_token_object >( alice_symbol, "alice" ); - }); - - generate_block(); - - signed_transaction tx; - smt_setup_emissions_operation op1; - op1.control_account = "alice"; - op1.symbol = alice_symbol; - op1.emissions_unit.token_unit[ "alice" ] = 10; - op1.schedule_time = db->head_block_time() + fc::days(30); - op1.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op1.interval_count = 1; - op1.lep_abs_amount = asset( 0, alice_symbol ); - op1.rep_abs_amount = asset( 0, alice_symbol ); - op1.lep_rel_amount_numerator = 1; - op1.rep_rel_amount_numerator = 0; - - smt_setup_emissions_operation op2; - op2.control_account = "alice"; - op2.symbol = alice_symbol; - op2.emissions_unit.token_unit[ "alice" ] = 10; - op2.schedule_time = op1.schedule_time + fc::days( 365 ); - op2.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op2.interval_count = 10; - op2.lep_abs_amount = asset( 0, alice_symbol ); - op2.rep_abs_amount = asset( 0, alice_symbol ); - op2.lep_rel_amount_numerator = 1; - op2.rep_rel_amount_numerator = 0; - - smt_set_runtime_parameters_operation op3; - smt_param_windows_v1 windows; - windows.cashout_window_seconds = 86400 * 4; - windows.reverse_auction_window_seconds = 60 * 5; - smt_param_vote_regeneration_period_seconds_v1 vote_regen; - vote_regen.vote_regeneration_period_seconds = 86400 * 6; - vote_regen.votes_per_regeneration_period = 600; - smt_param_rewards_v1 rewards; - rewards.content_constant = uint128_t( uint64_t( 1000000000000ull ) ); - rewards.percent_curation_rewards = 15 * HIVE_1_PERCENT; - rewards.author_reward_curve = curve_id::quadratic; - rewards.curation_reward_curve = curve_id::linear; - smt_param_allow_downvotes downvotes; - downvotes.value = false; - op3.runtime_parameters.insert( windows ); - op3.runtime_parameters.insert( vote_regen ); - op3.runtime_parameters.insert( rewards ); - op3.runtime_parameters.insert( downvotes ); - op3.control_account = "alice"; - op3.symbol = alice_symbol; - - smt_set_setup_parameters_operation op4; - smt_param_allow_voting voting; - voting.value = false; - op4.setup_parameters.insert( voting ); - op4.control_account = "alice"; - op4.symbol = alice_symbol; - - tx.operations.push_back( op1 ); - tx.operations.push_back( op2 ); - tx.operations.push_back( op3 ); - tx.operations.push_back( op4 ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Failure when specifying fee" ); - auto alice_prec_4 = asset_symbol_type::from_nai( alice_symbol.to_nai(), 4 ); - smt_create_operation op; - op.control_account = "alice"; - op.symbol = alice_prec_4; - op.smt_creation_fee = ASSET( "1.000 TESTS" ); - op.precision = 4; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure resetting SMT with token emissions" ); - op.smt_creation_fee = ASSET( "0.000 TBD" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure deleting token emissions in wrong order" ); - op1.remove = true; - op2.remove = true; - tx.clear(); - tx.operations.push_back( op1 ); - tx.operations.push_back( op2 ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success deleting token emissions" ); - tx.clear(); - tx.operations.push_back( op2 ); - tx.operations.push_back( op1 ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "--- Success resetting SMT" ); - op.smt_creation_fee = ASSET( "0.000 TBD" ); - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - { - auto& token = db->get< smt_token_object, by_symbol >( alice_prec_4 ); - - BOOST_REQUIRE( token.liquid_symbol == op.symbol ); - BOOST_REQUIRE( token.control_account == "alice" ); - BOOST_REQUIRE( token.allow_voting == true ); - BOOST_REQUIRE( token.cashout_window_seconds == HIVE_CASHOUT_WINDOW_SECONDS ); - BOOST_REQUIRE( token.reverse_auction_window_seconds == HIVE_REVERSE_AUCTION_WINDOW_SECONDS_HF20 ); - BOOST_REQUIRE( token.vote_regeneration_period_seconds == HIVE_VOTING_MANA_REGENERATION_SECONDS ); - BOOST_REQUIRE( token.votes_per_regeneration_period == SMT_DEFAULT_VOTES_PER_REGEN_PERIOD ); - BOOST_REQUIRE( token.content_constant == HIVE_CONTENT_CONSTANT_HF0 ); - BOOST_REQUIRE( token.percent_curation_rewards == SMT_DEFAULT_PERCENT_CURATION_REWARDS ); - BOOST_REQUIRE( token.author_reward_curve == curve_id::linear ); - BOOST_REQUIRE( token.curation_reward_curve == curve_id::square_root ); - BOOST_REQUIRE( token.allow_downvotes == true ); - } - - const auto& emissions_idx = db->get_index< smt_token_emissions_index, by_id >(); - BOOST_REQUIRE( emissions_idx.begin() == emissions_idx.end() ); - - generate_block(); - - BOOST_TEST_MESSAGE( "--- Failure resetting a token that has completed setup" ); - - db_plugin->debug_update( [=]( database& db ) - { - db.modify( db.get< smt_token_object, by_symbol >( alice_prec_4 ), [&]( smt_token_object& o ) - { - o.phase = smt_phase::setup_completed; - }); - }); - - tx.set_expiration( db->head_block_time() + HIVE_BLOCK_INTERVAL * 10 ); - tx.signatures.clear(); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_nai_pool_removal ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_nai_pool_removal" ); - - ACTORS( (alice) ) - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 0 ); - - // Ensure the NAI does not exist in the pool after being registered - BOOST_REQUIRE( !db->get< nai_pool_object >().contains( alice_symbol ) ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_nai_pool_count ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_nai_pool_count" ); - const auto &npo = db->get< nai_pool_object >(); - - // We should begin with a full NAI pool - BOOST_REQUIRE( npo.num_available_nais == SMT_MAX_NAI_POOL_COUNT ); - - ACTORS( (alice) ) - - fund( "alice", 10 * 1000 * 1000 ); - this->generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - convert( "alice", ASSET( "10000.000 TESTS" ) ); - - // Drain the NAI pool one at a time - for ( unsigned int i = 1; i <= SMT_MAX_NAI_POOL_COUNT; i++ ) - { - smt_create_operation op; - signed_transaction tx; - - op.symbol = get_new_smt_symbol( 0, this->db ); - op.precision = op.symbol.decimals(); - op.smt_creation_fee = db->get_dynamic_global_properties().smt_creation_fee; - op.control_account = "alice"; - - tx.operations.push_back( op ); - tx.set_expiration( this->db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.sign( alice_private_key, this->db->get_chain_id(), fc::ecc::bip_0062 ); - - this->db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( npo.num_available_nais == SMT_MAX_NAI_POOL_COUNT - i ); - BOOST_REQUIRE( npo.nais[ npo.num_available_nais ] == asset_symbol_type() ); - } - - // At this point, there should be no available NAIs - HIVE_REQUIRE_THROW( get_new_smt_symbol( 0, this->db ), fc::assert_exception ); - - this->generate_block(); - - // We should end with a full NAI pool after block generation - BOOST_REQUIRE( npo.num_available_nais == SMT_MAX_NAI_POOL_COUNT ); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_CASE( smt_setup_emissions_validate ) -{ - try - { - ACTORS( (alice)(bob) ); - generate_block(); - - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - - smt_setup_emissions_operation op; - op.control_account = "alice"; - op.symbol = alice_symbol; - op.emissions_unit.token_unit[ "alice" ] = 10; - op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op.interval_count = 1; - - fc::time_point_sec schedule_time = fc::time_point::now(); - fc::time_point_sec schedule_end_time = schedule_time + fc::seconds( op.interval_seconds * op.interval_count ); - - op.schedule_time = schedule_time; - op.lep_abs_amount = asset( 0, alice_symbol ); - op.rep_abs_amount = asset( 0, alice_symbol ); - op.lep_rel_amount_numerator = 1; - op.rep_rel_amount_numerator = 0; - op.lep_time = schedule_time; - op.rep_time = schedule_end_time; - op.validate(); - - BOOST_TEST_MESSAGE( " -- Invalid token symbol" ); - op.symbol = HIVE_SYMBOL; - op.lep_abs_amount = asset( 0, HIVE_SYMBOL ); - op.rep_abs_amount = asset( 0, HIVE_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.symbol = alice_symbol; - op.lep_abs_amount = asset( 0, alice_symbol ); - op.rep_abs_amount = asset( 0, alice_symbol ); - - BOOST_TEST_MESSAGE( " -- Mismatching right endpoint token" ); - op.rep_abs_amount = asset( 0, HIVE_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.rep_abs_amount = asset( 0, alice_symbol ); - - BOOST_TEST_MESSAGE( " -- Mismatching left endpoint token" ); - op.lep_abs_amount = asset( 0, HIVE_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.lep_abs_amount = asset( 0, alice_symbol ); - - BOOST_TEST_MESSAGE( " -- No emissions" ); - op.lep_rel_amount_numerator = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.lep_rel_amount_numerator = 1; - - BOOST_TEST_MESSAGE( " -- Invalid control account name" ); - op.control_account = "@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.control_account = "alice"; - - BOOST_TEST_MESSAGE(" -- Empty emission unit" ); - op.emissions_unit.token_unit.clear(); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - BOOST_TEST_MESSAGE( " -- Invalid emission unit token unit account" ); - op.emissions_unit.token_unit[ "@@@@" ] = 10; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.emissions_unit.token_unit.clear(); - op.emissions_unit.token_unit[ "alice" ] = 1; - op.emissions_unit.token_unit[ "$rewards" ] = 1; - op.emissions_unit.token_unit[ "$market_maker" ] = 1; - op.emissions_unit.token_unit[ "$vesting" ] = 1; - - BOOST_TEST_MESSAGE( " -- Invalid schedule time" ); - op.schedule_time = HIVE_GENESIS_TIME; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.schedule_time = fc::time_point::now(); - - BOOST_TEST_MESSAGE( " -- 0 interval count" ); - op.interval_count = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.interval_count = 1; - - BOOST_TEST_MESSAGE( " -- Interval seconds too low" ); - op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS - 1; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - - BOOST_TEST_MESSAGE( " -- Negative asset left endpoint" ); - op.lep_abs_amount = asset( -1, alice_symbol ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.lep_abs_amount = asset( 0 , alice_symbol ); - - BOOST_TEST_MESSAGE( " -- Negative asset right endpoint" ); - op.rep_abs_amount = asset( -1 , alice_symbol ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.rep_abs_amount = asset( 0 , alice_symbol ); - - BOOST_TEST_MESSAGE( " -- Left endpoint time cannot be before schedule time" ); - op.lep_time -= fc::seconds( 1 ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.lep_time += fc::seconds( 1 ); - - BOOST_TEST_MESSAGE( " -- Right endpoint time cannot be after schedule end time" ); - op.rep_time += fc::seconds( 1 ); - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - op.rep_time -= fc::seconds( 1 ); - - BOOST_TEST_MESSAGE( " -- Left endpoint time and right endpoint time can be anything if they're equal" ); - fc::time_point_sec tp = fc::time_point_sec( 0 ); - op.lep_time = tp; - op.rep_time = tp; - - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_setup_emissions_authorities ) -{ - try - { - SMT_SYMBOL( alice, 3, db ); - - smt_setup_emissions_operation op; - op.control_account = "alice"; - fc::time_point now = fc::time_point::now(); - op.schedule_time = now; - op.emissions_unit.token_unit[ "alice" ] = 10; - op.lep_abs_amount = op.rep_abs_amount = asset( 1000, alice_symbol ); - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_setup_emissions_apply ) -{ - try - { - ACTORS( (alice)(bob) ) - - generate_block(); - - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - - fc::time_point_sec emissions1_schedule_time = fc::time_point::now(); - - smt_setup_emissions_operation op; - op.control_account = "alice"; - op.symbol = alice_symbol; - op.emissions_unit.token_unit[ "alice" ] = 10; - op.schedule_time = emissions1_schedule_time; - op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op.interval_count = 1; - op.lep_abs_amount = asset( 0, alice_symbol ); - op.rep_abs_amount = asset( 0, alice_symbol ); - op.lep_rel_amount_numerator = 1; - op.rep_rel_amount_numerator = 0;; - op.validate(); - - BOOST_TEST_MESSAGE( " -- Control account does not own SMT" ); - op.control_account = "bob"; - FAIL_WITH_OP( op, bob_private_key, fc::assert_exception ); - op.control_account = "alice"; - - BOOST_TEST_MESSAGE( " -- SMT setup phase has already completed" ); - auto smt_token = util::smt::find_token( *db, alice_symbol ); - db->modify( *smt_token, [&] ( smt_token_object& obj ) - { - obj.phase = smt_phase::setup_completed; - } ); - FAIL_WITH_OP( op, alice_private_key, fc::assert_exception ); - db->modify( *smt_token, [&] ( smt_token_object& obj ) - { - obj.phase = smt_phase::account_elevated; - } ); - PUSH_OP( op, alice_private_key ); - - BOOST_TEST_MESSAGE( " -- Emissions range is overlapping" ); - smt_setup_emissions_operation op2; - op2.control_account = "alice"; - op2.symbol = alice_symbol; - op2.emissions_unit.token_unit[ "alice" ] = 10; - op2.schedule_time = emissions1_schedule_time + fc::seconds( SMT_EMISSION_MIN_INTERVAL_SECONDS ); - op2.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op2.interval_count = 5; - op2.lep_abs_amount = asset( 1200, alice_symbol ); - op2.rep_abs_amount = asset( 1000, alice_symbol ); - op2.lep_rel_amount_numerator = 1; - op2.rep_rel_amount_numerator = 2;; - op2.validate(); - - FAIL_WITH_OP( op2, alice_private_key, fc::assert_exception ); - - op2.schedule_time += fc::seconds( 1 ); - PUSH_OP( op2, alice_private_key ); - - BOOST_TEST_MESSAGE( " -- Emissions must be created in chronological order" ); - smt_setup_emissions_operation op3; - op3.control_account = "alice"; - op3.symbol = alice_symbol; - op3.emissions_unit.token_unit[ "alice" ] = 10; - op3.schedule_time = emissions1_schedule_time - fc::seconds( SMT_EMISSION_MIN_INTERVAL_SECONDS + 1 ); - op3.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op3.interval_count = SMT_EMIT_INDEFINITELY; - op3.lep_abs_amount = asset( 0, alice_symbol ); - op3.rep_abs_amount = asset( 1000, alice_symbol ); - op3.lep_rel_amount_numerator = 0; - op3.rep_rel_amount_numerator = 0;; - op3.validate(); - FAIL_WITH_OP( op3, alice_private_key, fc::assert_exception ); - - op3.schedule_time = op2.schedule_time + fc::seconds( uint64_t( op2.interval_seconds ) * uint64_t( op2.interval_count ) ); - FAIL_WITH_OP( op3, alice_private_key, fc::assert_exception ); - - op3.schedule_time += fc::seconds( 1 ); - PUSH_OP( op3, alice_private_key ); - - BOOST_TEST_MESSAGE( " -- No more emissions permitted" ); - smt_setup_emissions_operation op4; - op4.control_account = "alice"; - op4.symbol = alice_symbol; - op4.emissions_unit.token_unit[ "alice" ] = 10; - op4.schedule_time = op3.schedule_time + fc::days( 365 ); - op4.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; - op4.interval_count = 10; - op4.lep_abs_amount = asset( 0, alice_symbol ); - op4.rep_abs_amount = asset( 0, alice_symbol ); - op4.lep_rel_amount_numerator = 1; - op4.rep_rel_amount_numerator = 0;; - op4.validate(); - - FAIL_WITH_OP( op4, alice_private_key, fc::assert_exception ); - - op4.schedule_time = fc::time_point_sec::maximum(); - FAIL_WITH_OP( op4, alice_private_key, fc::assert_exception ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( set_setup_parameters_validate ) -{ - try - { - ACTORS( (alice) ) - generate_block(); - - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - - smt_set_setup_parameters_operation op; - op.control_account = "alice"; - op.symbol = alice_symbol; - op.setup_parameters.emplace( smt_param_allow_voting { .value = true } ); - - op.validate(); - - op.symbol = HIVE_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); // Invalid symbol - op.symbol = VESTS_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); // Invalid symbol - op.symbol = HBD_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); // Invalid symbol - op.symbol = alice_symbol; - - op.control_account = "####"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); // Invalid account name - op.control_account = "alice"; - - op.setup_parameters.clear(); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); // Empty setup parameters - op.setup_parameters.emplace( smt_param_allow_voting { .value = true } ); - - op.validate(); - - op.setup_parameters.clear(); - op.setup_parameters.emplace( smt_param_allow_voting { .value = false } ); - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( set_setup_parameters_authorities ) -{ - try - { - smt_set_setup_parameters_operation op; - op.control_account = "alice"; - - flat_set<account_name_type> auths; - flat_set<account_name_type> expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( set_setup_parameters_apply ) -{ - try - { - ACTORS( (alice)(bob) ) - - generate_block(); - - FUND( "alice", 5000000 ); - FUND( "bob", 5000000 ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - convert( "alice", ASSET( "5000.000 TESTS" ) ); - convert( "bob", ASSET( "5000.000 TESTS" ) ); - - auto alice_symbol = create_smt( "alice", alice_private_key, 3 ); - auto bob_symbol = create_smt( "bob", bob_private_key, 3 ); - - auto alice_token = util::smt::find_token( *db, alice_symbol ); - auto bob_token = util::smt::find_token( *db, bob_symbol ); - - BOOST_REQUIRE( alice_token->allow_voting == true ); - - smt_set_setup_parameters_operation op; - op.control_account = "alice"; - op.symbol = alice_symbol; - - BOOST_TEST_MESSAGE( " -- Succeed set voting to false" ); - op.setup_parameters.emplace( smt_param_allow_voting { .value = false } ); - PUSH_OP( op, alice_private_key ); - - BOOST_REQUIRE( alice_token->allow_voting == false ); - - BOOST_TEST_MESSAGE( " -- Succeed set voting to true" ); - op.setup_parameters.clear(); - op.setup_parameters.emplace( smt_param_allow_voting { .value = true } ); - PUSH_OP( op, alice_private_key ); - - BOOST_REQUIRE( alice_token->allow_voting == true ); - - BOOST_TEST_MESSAGE( "--- Failure with wrong control account" ); - op.symbol = bob_symbol; - - FAIL_WITH_OP( op, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Succeed set voting to true" ); - op.control_account = "bob"; - op.setup_parameters.clear(); - op.setup_parameters.emplace( smt_param_allow_voting { .value = true } ); - - PUSH_OP( op, bob_private_key ); - BOOST_REQUIRE( bob_token->allow_voting == true ); - - - BOOST_TEST_MESSAGE( " -- Failure with mismatching precision" ); - op.symbol.asset_num++; - FAIL_WITH_OP( op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure with non-existent asset symbol" ); - op.symbol = this->get_new_smt_symbol( 1, db ); - FAIL_WITH_OP( op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Succeed set voting to false" ); - op.symbol = bob_symbol; - op.setup_parameters.clear(); - op.setup_parameters.emplace( smt_param_allow_voting { .value = false } ); - PUSH_OP( op, bob_private_key ); - BOOST_REQUIRE( bob_token->allow_voting == false ); - - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_set_runtime_parameters_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_set_runtime_parameters_validate" ); - - smt_set_runtime_parameters_operation op; - - auto new_symbol = get_new_smt_symbol( 3, db ); - - op.symbol = new_symbol; - op.control_account = "alice"; - op.runtime_parameters.insert( smt_param_allow_downvotes() ); - - // If this fails, it could indicate a test above has failed for the wrong reasons - op.validate(); - - BOOST_TEST_MESSAGE( "--- Test invalid control account name" ); - op.control_account = "@@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.control_account = "alice"; - - // Test symbol - BOOST_TEST_MESSAGE( "--- Invalid SMT creation symbol: vesting symbol used instead of liquid one" ); - op.symbol = op.symbol.get_paired_symbol(); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Invalid SMT creation symbol: HIVE cannot be an SMT" ); - op.symbol = HIVE_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Invalid SMT creation symbol: HBD cannot be an SMT" ); - op.symbol = HBD_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Invalid SMT creation symbol: VESTS cannot be an SMT" ); - op.symbol = VESTS_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.symbol = new_symbol; - - BOOST_TEST_MESSAGE( "--- Failure when no parameters are set" ); - op.runtime_parameters.clear(); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - /* - * Inequality to test: - * - * 0 <= reverse_auction_window_seconds + SMT_UPVOTE_LOCKOUT < cashout_window_seconds - * <= SMT_VESTING_WITHDRAW_INTERVAL_SECONDS - */ - - BOOST_TEST_MESSAGE( "--- Failure when cashout_window_second is equal to SMT_UPVOTE_LOCKOUT" ); - smt_param_windows_v1 windows; - windows.reverse_auction_window_seconds = 0; - windows.cashout_window_seconds = SMT_UPVOTE_LOCKOUT; - op.runtime_parameters.insert( windows ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when cashout_window_seconds is above SMT_UPVOTE_LOCKOUT" ); - windows.cashout_window_seconds++; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Failure when cashout_window_seconds is equal to reverse_auction_window_seconds + SMT_UPVOTE_LOCKOUT" ); - windows.reverse_auction_window_seconds++; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure when cashout_window_seconds is greater than SMT_VESTING_WITHDRAW_INTERVAL_SECONDS" ); - windows.cashout_window_seconds = SMT_VESTING_WITHDRAW_INTERVAL_SECONDS + 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when cashout_window_seconds is equal to SMT_VESTING_WITHDRAW_INTERVAL_SECONDS" ); - windows.cashout_window_seconds--; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Success when reverse_auction_window_seconds + SMT_UPVOTE_LOCKOUT is one less than cashout_window_seconds" ); - windows.reverse_auction_window_seconds = windows.cashout_window_seconds - SMT_UPVOTE_LOCKOUT - 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Failure when reverse_auction_window_seconds + SMT_UPVOTE_LOCKOUT is equal to cashout_window_seconds" ); - windows.cashout_window_seconds--; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( windows ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - /* - * Conditions to test: - * - * 0 < vote_regeneration_seconds < SMT_VESTING_WITHDRAW_INTERVAL_SECONDS - * - * votes_per_regeneration_period * 86400 / vote_regeneration_period - * <= SMT_MAX_NOMINAL_VOTES_PER_DAY - * - * 0 < votes_per_regeneration_period <= SMT_MAX_VOTES_PER_REGENERATION - */ - uint32_t practical_regen_seconds_lower_bound = 86400 / SMT_MAX_NOMINAL_VOTES_PER_DAY; - - BOOST_TEST_MESSAGE( "--- Failure when vote_regeneration_period_seconds is 0" ); - smt_param_vote_regeneration_period_seconds_v1 vote_regen; - vote_regen.vote_regeneration_period_seconds = 0; - vote_regen.votes_per_regeneration_period = 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when vote_regeneration_period_seconds is greater than 0" ); - // Any value less than 86 will violate the nominal votes per day check. 86 is a practical minimum as a consequence. - vote_regen.vote_regeneration_period_seconds = practical_regen_seconds_lower_bound + 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Failure when vote_regeneration_period_seconds is greater SMT_VESTING_WITHDRAW_INTERVAL_SECONDS" ); - vote_regen.vote_regeneration_period_seconds = SMT_VESTING_WITHDRAW_INTERVAL_SECONDS + 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when vote_regeneration_period_seconds is equal to SMT_VESTING_WITHDRAW_INTERVAL_SECONDS" ); - vote_regen.vote_regeneration_period_seconds--; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Test various \"nominal votes per day\" scenarios" ); - BOOST_TEST_MESSAGE( "--- Mid Point Checks" ); - vote_regen.vote_regeneration_period_seconds = 86400; - vote_regen.votes_per_regeneration_period = SMT_MAX_NOMINAL_VOTES_PER_DAY; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - vote_regen.vote_regeneration_period_seconds = 86399; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = 86400; - vote_regen.votes_per_regeneration_period = SMT_MAX_NOMINAL_VOTES_PER_DAY + 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = 86401; - vote_regen.votes_per_regeneration_period = SMT_MAX_NOMINAL_VOTES_PER_DAY; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - vote_regen.vote_regeneration_period_seconds = 86400; - vote_regen.votes_per_regeneration_period = SMT_MAX_NOMINAL_VOTES_PER_DAY - 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Lower Bound Checks" ); - vote_regen.vote_regeneration_period_seconds = practical_regen_seconds_lower_bound; - vote_regen.votes_per_regeneration_period = 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = practical_regen_seconds_lower_bound + 1; - vote_regen.votes_per_regeneration_period = 2; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = practical_regen_seconds_lower_bound + 2; - vote_regen.votes_per_regeneration_period = 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Upper Bound Checks" ); - vote_regen.vote_regeneration_period_seconds = SMT_VESTING_WITHDRAW_INTERVAL_SECONDS; - vote_regen.votes_per_regeneration_period = SMT_MAX_VOTES_PER_REGENERATION; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - vote_regen.votes_per_regeneration_period = SMT_MAX_VOTES_PER_REGENERATION + 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = SMT_VESTING_WITHDRAW_INTERVAL_SECONDS - 1; - vote_regen.votes_per_regeneration_period = SMT_MAX_VOTES_PER_REGENERATION; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - vote_regen.vote_regeneration_period_seconds = SMT_VESTING_WITHDRAW_INTERVAL_SECONDS; - vote_regen.votes_per_regeneration_period = SMT_MAX_VOTES_PER_REGENERATION - 1; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( vote_regen ); - op.validate(); - - /* - * Conditions to test: - * - * percent_curation_rewards <= 10000 - * - * percent_content_rewards + percent_curation_rewards == 10000 - * - * author_reward_curve must be quadratic or linear - * - * curation_reward_curve must be bounded_curation, linear, or square_root - */ - BOOST_TEST_MESSAGE( "--- Failure when percent_curation_rewards greater than 10000" ); - smt_param_rewards_v1 rewards; - rewards.content_constant = HIVE_CONTENT_CONSTANT_HF0; - rewards.percent_curation_rewards = HIVE_100_PERCENT + 1; - rewards.author_reward_curve = curve_id::linear; - rewards.curation_reward_curve = curve_id::square_root; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when percent_curation_rewards is 10000" ); - rewards.percent_curation_rewards = HIVE_100_PERCENT; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Success when author curve is quadratic" ); - rewards.author_reward_curve = curve_id::quadratic; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Failure when author curve is bounded_curation" ); - rewards.author_reward_curve = curve_id::bounded_curation; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure when author curve is square_root" ); - rewards.author_reward_curve = curve_id::square_root; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success when curation curve is bounded_curation" ); - rewards.author_reward_curve = curve_id::linear; - rewards.curation_reward_curve = curve_id::bounded_curation; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Success when curation curve is linear" ); - rewards.curation_reward_curve = curve_id::linear; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - op.validate(); - - BOOST_TEST_MESSAGE( "--- Failure when curation curve is quadratic" ); - rewards.curation_reward_curve = curve_id::quadratic; - op.runtime_parameters.clear(); - op.runtime_parameters.insert( rewards ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - - // Literally nothing to test for smt_param_allow_downvotes because it can only be true or false. - // Inclusion success was tested in initial positive validation at the beginning of the test. - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_set_runtime_parameters_authorities ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_set_runtime_parameters_authorities" ); - smt_set_runtime_parameters_operation op; - op.control_account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_set_runtime_parameters_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_set_runtime_parameters_evaluate" ); - - ACTORS( (alice)(bob) ) - SMT_SYMBOL( alice, 3, db ); - SMT_SYMBOL( bob, 3, db ); - - generate_block(); - - db_plugin->debug_update( [=](database& db) - { - db.create< smt_token_object >( alice_symbol, "alice" ); - }); - - smt_set_runtime_parameters_operation op; - signed_transaction tx; - - BOOST_TEST_MESSAGE( "--- Failure with wrong control account" ); - op.control_account = "bob"; - op.symbol = alice_symbol; - op.runtime_parameters.insert( smt_param_allow_downvotes() ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure with a non-existent asset symbol" ); - op.control_account = "alice"; - op.symbol = bob_symbol; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Failure with wrong precision in asset symbol" ); - op.symbol = alice_symbol; - op.symbol.asset_num++; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::assert_exception ); - - BOOST_TEST_MESSAGE( "--- Success updating runtime parameters" ); - op.runtime_parameters.clear(); - // These are params different than the default - smt_param_windows_v1 windows; - windows.cashout_window_seconds = 86400 * 4; - windows.reverse_auction_window_seconds = 60 * 5; - smt_param_vote_regeneration_period_seconds_v1 vote_regen; - vote_regen.vote_regeneration_period_seconds = 86400 * 6; - vote_regen.votes_per_regeneration_period = 600; - smt_param_rewards_v1 rewards; - rewards.content_constant = uint128_t( uint64_t( 1000000000000ull ) ); - rewards.percent_curation_rewards = 15 * HIVE_1_PERCENT; - rewards.author_reward_curve = curve_id::quadratic; - rewards.curation_reward_curve = curve_id::linear; - smt_param_allow_downvotes downvotes; - downvotes.value = false; - op.runtime_parameters.insert( windows ); - op.runtime_parameters.insert( vote_regen ); - op.runtime_parameters.insert( rewards ); - op.runtime_parameters.insert( downvotes ); - op.symbol = alice_symbol; - tx.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - const auto& token = db->get< smt_token_object, by_symbol >( alice_symbol ); - - BOOST_REQUIRE( token.cashout_window_seconds == windows.cashout_window_seconds ); - BOOST_REQUIRE( token.reverse_auction_window_seconds == windows.reverse_auction_window_seconds ); - BOOST_REQUIRE( token.vote_regeneration_period_seconds == vote_regen.vote_regeneration_period_seconds ); - BOOST_REQUIRE( token.votes_per_regeneration_period == vote_regen.votes_per_regeneration_period ); - BOOST_REQUIRE( token.content_constant == rewards.content_constant ); - BOOST_REQUIRE( token.percent_curation_rewards == rewards.percent_curation_rewards ); - BOOST_REQUIRE( token.author_reward_curve == rewards.author_reward_curve ); - BOOST_REQUIRE( token.curation_reward_curve == rewards.curation_reward_curve ); - BOOST_REQUIRE( token.allow_downvotes == downvotes.value ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_contribute_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_contribute_validate" ); - - auto new_symbol = get_new_smt_symbol( 3, db ); - - smt_contribute_operation op; - op.contributor = "alice"; - op.contribution = asset( 1000, HIVE_SYMBOL ); - op.contribution_id = 1; - op.symbol = new_symbol; - op.validate(); - - BOOST_TEST_MESSAGE( " -- Failure on invalid account name" ); - op.contributor = "@@@@@"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contributor = "alice"; - - BOOST_TEST_MESSAGE( " -- Failure on negative contribution" ); - op.contribution = asset( -1, HIVE_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contribution = asset( 1000, HIVE_SYMBOL ); - - BOOST_TEST_MESSAGE( " -- Failure on no contribution" ); - op.contribution = asset( 0, HIVE_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contribution = asset( 1000, HIVE_SYMBOL ); - - BOOST_TEST_MESSAGE( " -- Failure on VESTS contribution" ); - op.contribution = asset( 1000, VESTS_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contribution = asset( 1000, HIVE_SYMBOL ); - - BOOST_TEST_MESSAGE( " -- Failure on HBD contribution" ); - op.contribution = asset( 1000, HBD_SYMBOL ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contribution = asset( 1000, HIVE_SYMBOL ); - - BOOST_TEST_MESSAGE( " -- Failure on SMT contribution" ); - op.contribution = asset( 1000, new_symbol ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.contribution = asset( 1000, HIVE_SYMBOL ); - - BOOST_TEST_MESSAGE( " -- Failure on contribution to HIVE" ); - op.symbol = HIVE_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.symbol = new_symbol; - - BOOST_TEST_MESSAGE( " -- Failure on contribution to VESTS" ); - op.symbol = VESTS_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.symbol = new_symbol; - - BOOST_TEST_MESSAGE( " -- Failure on contribution to HBD" ); - op.symbol = HBD_SYMBOL; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.symbol = new_symbol; - - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_contribute_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_contribute_evaluate" ); - - ACTORS( (alice)(bob)(sam) ); - SMT_SYMBOL( alice, 3, db ); - - generate_block(); - - auto alice_asset_accumulator = asset( 0, HIVE_SYMBOL ); - auto bob_asset_accumulator = asset( 0, HIVE_SYMBOL ); - auto sam_asset_accumulator = asset( 0, HIVE_SYMBOL ); - - auto alice_contribution_counter = 0; - auto bob_contribution_counter = 0; - auto sam_contribution_counter = 0; - - FUND( "sam", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - db_plugin->debug_update( [=] ( database& db ) - { - db.create< smt_token_object >( alice_symbol, "alice" ); - - db.create< smt_ico_object >( [&]( smt_ico_object& o ) - { - o.symbol = alice_symbol; - o.hive_units_soft_cap = SMT_MIN_SOFT_CAP_HIVE_UNITS; - o.hive_units_hard_cap = 99000; - } ); - } ); - - smt_contribute_operation bob_op; - bob_op.contributor = "bob"; - bob_op.contribution = asset( 1000, HIVE_SYMBOL ); - bob_op.contribution_id = bob_contribution_counter; - bob_op.symbol = alice_symbol; - - smt_contribute_operation alice_op; - alice_op.contributor = "alice"; - alice_op.contribution = asset( 2000, HIVE_SYMBOL ); - alice_op.contribution_id = alice_contribution_counter; - alice_op.symbol = alice_symbol; - - smt_contribute_operation sam_op; - sam_op.contributor = "sam"; - sam_op.contribution = asset( 3000, HIVE_SYMBOL ); - sam_op.contribution_id = sam_contribution_counter; - sam_op.symbol = alice_symbol; - - BOOST_TEST_MESSAGE( " -- Failure on SMT not in contribution phase" ); - FAIL_WITH_OP( bob_op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure on SMT not in contribution phase" ); - FAIL_WITH_OP( alice_op, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure on SMT not in contribution phase" ); - FAIL_WITH_OP( sam_op, sam_private_key, fc::assert_exception ); - - db_plugin->debug_update( [=] ( database& db ) - { - const smt_token_object *token = util::smt::find_token( db, alice_symbol ); - db.modify( *token, [&]( smt_token_object& o ) - { - o.phase = smt_phase::contribution_begin_time_completed; - } ); - } ); - - BOOST_TEST_MESSAGE( " -- Failure on insufficient funds" ); - FAIL_WITH_OP( bob_op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure on insufficient funds" ); - FAIL_WITH_OP( alice_op, alice_private_key, fc::assert_exception ); - - FUND( "alice", ASSET( "1000.000 TESTS" ) ); - FUND( "bob", ASSET( "1000.000 TESTS" ) ); - - generate_block(); - - BOOST_TEST_MESSAGE( " -- Succeed on sufficient funds" ); - bob_op.contribution_id = bob_contribution_counter++; - PUSH_OP( bob_op, bob_private_key ); - bob_asset_accumulator += bob_op.contribution; - - BOOST_TEST_MESSAGE( " -- Failure on duplicate contribution ID" ); - FAIL_WITH_OP( bob_op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Succeed with new contribution ID" ); - bob_op.contribution_id = bob_contribution_counter++; - PUSH_OP( bob_op, bob_private_key ); - bob_asset_accumulator += bob_op.contribution; - - BOOST_TEST_MESSAGE( " -- Succeed on sufficient funds" ); - alice_op.contribution_id = alice_contribution_counter++; - PUSH_OP( alice_op, alice_private_key ); - alice_asset_accumulator += alice_op.contribution; - - BOOST_TEST_MESSAGE( " -- Failure on duplicate contribution ID" ); - FAIL_WITH_OP( alice_op, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Succeed with new contribution ID" ); - alice_op.contribution_id = alice_contribution_counter++; - PUSH_OP( alice_op, alice_private_key ); - alice_asset_accumulator += alice_op.contribution; - - BOOST_TEST_MESSAGE( " -- Succeed with sufficient funds" ); - sam_op.contribution_id = sam_contribution_counter++; - PUSH_OP( sam_op, sam_private_key ); - sam_asset_accumulator += sam_op.contribution; - - validate_database(); - - for ( int i = 0; i < 15; i++ ) - { - BOOST_TEST_MESSAGE( " -- Successful contribution (alice)" ); - alice_op.contribution_id = alice_contribution_counter++; - PUSH_OP( alice_op, alice_private_key ); - alice_asset_accumulator += alice_op.contribution; - - BOOST_TEST_MESSAGE( " -- Successful contribution (bob)" ); - bob_op.contribution_id = bob_contribution_counter++; - PUSH_OP( bob_op, bob_private_key ); - bob_asset_accumulator += bob_op.contribution; - - BOOST_TEST_MESSAGE( " -- Successful contribution (sam)" ); - sam_op.contribution_id = sam_contribution_counter++; - PUSH_OP( sam_op, sam_private_key ); - sam_asset_accumulator += sam_op.contribution; - } - - BOOST_TEST_MESSAGE( " -- Fail to contribute after hard cap (alice)" ); - alice_op.contribution_id = alice_contribution_counter + 1; - FAIL_WITH_OP( alice_op, alice_private_key, fc::exception ); - - BOOST_TEST_MESSAGE( " -- Fail to contribute after hard cap (bob)" ); - bob_op.contribution_id = bob_contribution_counter + 1; - FAIL_WITH_OP( bob_op, bob_private_key, fc::exception ); - - BOOST_TEST_MESSAGE( " -- Fail to contribute after hard cap (sam)" ); - sam_op.contribution_id = sam_contribution_counter + 1; - FAIL_WITH_OP( sam_op, sam_private_key, fc::exception ); - - validate_database(); - - generate_block(); - - db_plugin->debug_update( [=] ( database& db ) - { - const smt_token_object *token = util::smt::find_token( db, alice_symbol ); - db.modify( *token, [&]( smt_token_object& o ) - { - o.phase = smt_phase::contribution_end_time_completed; - } ); - } ); - - BOOST_TEST_MESSAGE( " -- Failure SMT contribution phase has ended" ); - alice_op.contribution_id = alice_contribution_counter; - FAIL_WITH_OP( alice_op, alice_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure SMT contribution phase has ended" ); - bob_op.contribution_id = bob_contribution_counter; - FAIL_WITH_OP( bob_op, bob_private_key, fc::assert_exception ); - - BOOST_TEST_MESSAGE( " -- Failure SMT contribution phase has ended" ); - sam_op.contribution_id = sam_contribution_counter; - FAIL_WITH_OP( sam_op, sam_private_key, fc::assert_exception ); - - auto alices_contributions = asset( 0, HIVE_SYMBOL ); - auto bobs_contributions = asset( 0, HIVE_SYMBOL ); - auto sams_contributions = asset( 0, HIVE_SYMBOL ); - - auto alices_num_contributions = 0; - auto bobs_num_contributions = 0; - auto sams_num_contributions = 0; - - const auto& idx = db->get_index< smt_contribution_index, by_symbol_contributor >(); - - auto itr = idx.lower_bound( boost::make_tuple( alice_symbol, account_name_type( "alice" ), 0 ) ); - while( itr != idx.end() && itr->contributor == account_name_type( "alice" ) ) - { - alices_contributions += itr->contribution; - alices_num_contributions++; - ++itr; - } - - itr = idx.lower_bound( boost::make_tuple( alice_symbol, account_name_type( "bob" ), 0 ) ); - while( itr != idx.end() && itr->contributor == account_name_type( "bob" ) ) - { - bobs_contributions += itr->contribution; - bobs_num_contributions++; - ++itr; - } - - itr = idx.lower_bound( boost::make_tuple( alice_symbol, account_name_type( "sam" ), 0 ) ); - while( itr != idx.end() && itr->contributor == account_name_type( "sam" ) ) - { - sams_contributions += itr->contribution; - sams_num_contributions++; - ++itr; - } - - BOOST_TEST_MESSAGE( " -- Checking account contributions" ); - BOOST_REQUIRE( alices_contributions == alice_asset_accumulator ); - BOOST_REQUIRE( bobs_contributions == bob_asset_accumulator ); - BOOST_REQUIRE( sams_contributions == sam_asset_accumulator ); - - BOOST_TEST_MESSAGE( " -- Checking contribution counts" ); - BOOST_REQUIRE( alices_num_contributions == alice_contribution_counter ); - BOOST_REQUIRE( bobs_num_contributions == bob_contribution_counter ); - BOOST_REQUIRE( sams_num_contributions == sam_contribution_counter ); - - BOOST_TEST_MESSAGE( " -- Checking account balances" ); - BOOST_REQUIRE( db->get_balance( "alice", HIVE_SYMBOL ) == ASSET( "1000.000 TESTS" ) - alice_asset_accumulator ); - BOOST_REQUIRE( db->get_balance( "bob", HIVE_SYMBOL ) == ASSET( "1000.000 TESTS" ) - bob_asset_accumulator ); - BOOST_REQUIRE( db->get_balance( "sam", HIVE_SYMBOL ) == ASSET( "1000.000 TESTS" ) - sam_asset_accumulator ); - - BOOST_TEST_MESSAGE( " -- Checking ICO total contributions" ); - const auto* ico_obj = db->find< smt_ico_object, by_symbol >( alice_symbol ); - BOOST_REQUIRE( ico_obj->contributed == alice_asset_accumulator + bob_asset_accumulator + sam_asset_accumulator ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_transfer_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_transfer_validate" ); - ACTORS( (alice) ) - auto symbol = create_smt( "alice", alice_private_key, 3 ); - - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.memo = "Memo"; - op.amount = asset( 100, symbol ); - op.validate(); - - BOOST_TEST_MESSAGE( " --- Invalid from account" ); - op.from = "alice-"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.from = "alice"; - - BOOST_TEST_MESSAGE( " --- Invalid to account" ); - op.to = "bob-"; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.to = "bob"; - - BOOST_TEST_MESSAGE( " --- Memo too long" ); - std::string memo; - for ( int i = 0; i < HIVE_MAX_MEMO_SIZE + 1; i++ ) - memo += "x"; - op.memo = memo; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.memo = "Memo"; - - BOOST_TEST_MESSAGE( " --- Negative amount" ); - op.amount = -op.amount; - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = -op.amount; - - BOOST_TEST_MESSAGE( " --- Transferring vests" ); - op.amount = asset( 100, symbol.get_paired_symbol() ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - op.amount = asset( 100, symbol ); - - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_transfer_apply ) -{ - try - { - BOOST_TEST_MESSAGE( "Testing: smt_transfer_apply" ); - - ACTORS( (alice)(bob) ) - generate_block(); - - auto symbol = create_smt( "alice", alice_private_key, 3 ); - - fund( "alice", asset( 10000, symbol ) ); - - BOOST_REQUIRE( db->get_balance( "alice", symbol ) == asset( 10000, symbol ) ); - BOOST_REQUIRE( db->get_balance( "bob", symbol ) == asset( 0, symbol ) ); - - signed_transaction tx; - transfer_operation op; - - op.from = "alice"; - op.to = "bob"; - op.amount = asset( 5000, symbol ); - - BOOST_TEST_MESSAGE( "--- Test normal transaction" ); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_REQUIRE( db->get_balance( "alice", symbol ) == asset( 5000, symbol ) ); - BOOST_REQUIRE( db->get_balance( "bob", symbol ) == asset( 5000, symbol ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Generating a block" ); - generate_block(); - - BOOST_REQUIRE( db->get_balance( "alice", symbol ) == asset( 5000, symbol ) ); - BOOST_REQUIRE( db->get_balance( "bob", symbol ) == asset( 5000, symbol ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test emptying an account" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, database::skip_transaction_dupe_check ); - - BOOST_REQUIRE( db->get_balance( "alice", symbol ) == asset( 0, symbol ) ); - BOOST_REQUIRE( db->get_balance( "bob", symbol ) == asset( 10000, symbol ) ); - validate_database(); - - BOOST_TEST_MESSAGE( "--- Test transferring non-existent funds" ); - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, database::skip_transaction_dupe_check ), fc::exception ); - - BOOST_REQUIRE( db->get_balance( "alice", symbol ) == asset( 0, symbol ) ); - BOOST_REQUIRE( db->get_balance( "bob", symbol ) == asset( 10000, symbol ) ); - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/smt_operation_time_tests.cpp b/tests2/unit/tests/smt_operation_time_tests.cpp deleted file mode 100644 index c576c6a1a52f67d8259c1f7cc451c6d626b7a366..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/smt_operation_time_tests.cpp +++ /dev/null @@ -1,664 +0,0 @@ - -#if defined IS_TEST_NET && defined HIVE_ENABLE_SMT - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/block_summary_object.hpp> -#include <hive/chain/database.hpp> -#include <hive/chain/history_object.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <hive/plugins/debug_node/debug_node_plugin.hpp> - -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" - -#include <cmath> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; - -BOOST_FIXTURE_TEST_SUITE( smt_operation_time_tests, smt_database_fixture ) - -BOOST_AUTO_TEST_CASE( smt_liquidity_rewards ) -{ - using std::abs; - - try - { - db->liquidity_rewards_enabled = false; - - ACTORS( (alice)(bob)(sam)(dave)(smtcreator) ) - - //Create SMT and give some SMT to creators. - signed_transaction tx; - asset_symbol_type any_smt_symbol = create_smt( "smtcreator", smtcreator_private_key, 3); - - generate_block(); - vest( HIVE_INIT_MINER_NAME, "alice", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "bob", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "sam", ASSET( "10.000 TESTS" ) ); - vest( HIVE_INIT_MINER_NAME, "dave", ASSET( "10.000 TESTS" ) ); - - tx.operations.clear(); - tx.signatures.clear(); - - BOOST_TEST_MESSAGE( "Rewarding Bob with TESTS" ); - - auto exchange_rate = price( ASSET( "1.250 TESTS" ), asset( 1000, any_smt_symbol ) ); - - const account_object& alice_account = db->get_account( "alice" ); - FUND( "alice", asset( 25522, any_smt_symbol ) ); - asset alice_smt = db->get_balance( alice_account, any_smt_symbol ); - - FUND( "alice", alice_smt.amount ); - FUND( "bob", alice_smt.amount ); - FUND( "sam", alice_smt.amount ); - FUND( "dave", alice_smt.amount ); - - int64_t alice_smt_volume = 0; - int64_t alice_hive_volume = 0; - time_point_sec alice_reward_last_update = fc::time_point_sec::min(); - int64_t bob_smt_volume = 0; - int64_t bob_hive_volume = 0; - time_point_sec bob_reward_last_update = fc::time_point_sec::min(); - int64_t sam_smt_volume = 0; - int64_t sam_hive_volume = 0; - time_point_sec sam_reward_last_update = fc::time_point_sec::min(); - int64_t dave_smt_volume = 0; - int64_t dave_hive_volume = 0; - time_point_sec dave_reward_last_update = fc::time_point_sec::min(); - - BOOST_TEST_MESSAGE( "Creating Limit Order for HIVE that will stay on the books for 30 minutes exactly." ); - - limit_order_create_operation op; - op.owner = "alice"; - op.amount_to_sell = asset( alice_smt.amount.value / 20, any_smt_symbol ) ; - op.min_to_receive = op.amount_to_sell * exchange_rate; - op.orderid = 1; - op.expiration = db->head_block_time() + fc::seconds( HIVE_MAX_LIMIT_ORDER_EXPIRATION ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 10 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for SMT that will be filled immediately." ); - - op.owner = "bob"; - op.min_to_receive = op.amount_to_sell; - op.amount_to_sell = op.min_to_receive * exchange_rate; - op.fill_or_kill = false; - op.orderid = 2; - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_hive_volume += ( asset( alice_smt.amount / 20, any_smt_symbol ) * exchange_rate ).amount.value; - alice_reward_last_update = db->head_block_time(); - bob_hive_volume -= ( asset( alice_smt.amount / 20, any_smt_symbol ) * exchange_rate ).amount.value; - bob_reward_last_update = db->head_block_time(); - - auto ops = get_last_operations( 1 ); - const auto& liquidity_idx = db->get_index< liquidity_reward_balance_index >().indices().get< by_owner >(); - const auto& limit_order_idx = db->get_index< limit_order_index >().indices().get< by_account >(); - - auto reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - auto fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 1 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_smt.amount.value / 20, any_smt_symbol ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 2 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == ( asset( alice_smt.amount.value / 20, any_smt_symbol ) * exchange_rate ).amount.value ); - - BOOST_CHECK( limit_order_idx.find( boost::make_tuple( "alice", 1 ) ) == limit_order_idx.end() ); - BOOST_CHECK( limit_order_idx.find( boost::make_tuple( "bob", 2 ) ) == limit_order_idx.end() ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for SMT that will stay on the books for 60 minutes." ); - - op.owner = "sam"; - op.amount_to_sell = asset( ( alice_smt.amount.value / 20 ), HIVE_SYMBOL ); - op.min_to_receive = asset( ( alice_smt.amount.value / 20 ), any_smt_symbol ); - op.orderid = 3; - - tx.signatures.clear(); - tx.operations.clear(); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 10 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Creating Limit Order for SMT that will stay on the books for 30 minutes." ); - - op.owner = "bob"; - op.orderid = 4; - op.amount_to_sell = asset( ( alice_smt.amount.value / 10 ) * 3 - alice_smt.amount.value / 20, HIVE_SYMBOL ); - op.min_to_receive = asset( ( alice_smt.amount.value / 10 ) * 3 - alice_smt.amount.value / 20, any_smt_symbol ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - BOOST_TEST_MESSAGE( "Waiting 30 minutes" ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - BOOST_TEST_MESSAGE( "Filling both limit orders." ); - - op.owner = "alice"; - op.orderid = 5; - op.amount_to_sell = asset( ( alice_smt.amount.value / 10 ) * 3, any_smt_symbol ); - op.min_to_receive = asset( ( alice_smt.amount.value / 10 ) * 3, HIVE_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - alice_smt_volume -= ( alice_smt.amount.value / 10 ) * 3; - alice_reward_last_update = db->head_block_time(); - sam_smt_volume += alice_smt.amount.value / 20; - sam_reward_last_update = db->head_block_time(); - bob_smt_volume += ( alice_smt.amount.value / 10 ) * 3 - ( alice_smt.amount.value / 20 ); - bob_reward_last_update = db->head_block_time(); - ops = get_last_operations( 4 ); - - fill_order_op = ops[1].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 4 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( ( alice_smt.amount.value / 10 ) * 3 - alice_smt.amount.value / 20, HIVE_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 5 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( ( alice_smt.amount.value / 10 ) * 3 - alice_smt.amount.value / 20, any_smt_symbol ).amount.value ); - - fill_order_op = ops[3].get< fill_order_operation >(); - BOOST_REQUIRE( fill_order_op.open_owner == "sam" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 3 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_smt.amount.value / 20, HIVE_SYMBOL ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 5 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_smt.amount.value / 20, any_smt_symbol ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - BOOST_TEST_MESSAGE( "Testing a partial fill before minimum time and full fill after minimum time" ); - - op.orderid = 6; - op.amount_to_sell = asset( alice_smt.amount.value / 20 * 2, any_smt_symbol ); - op.min_to_receive = asset( alice_smt.amount.value / 20 * 2, HIVE_SYMBOL ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10.to_seconds() / 2 ), true ); - - op.owner = "bob"; - op.orderid = 7; - op.amount_to_sell = asset( alice_smt.amount.value / 20, HIVE_SYMBOL ); - op.min_to_receive = asset( alice_smt.amount.value / 20, any_smt_symbol ); - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + fc::seconds( HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10.to_seconds() / 2 ), true ); - - ops = get_last_operations( 4 ); - fill_order_op = ops[3].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 6 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_smt.amount.value / 20, any_smt_symbol ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 7 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_smt.amount.value / 20, HIVE_SYMBOL ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "sam"; - op.orderid = 8; - - tx.signatures.clear(); - tx.operations.clear(); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - tx.operations.push_back( op ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - alice_hive_volume += alice_smt.amount.value / 20; - alice_reward_last_update = db->head_block_time(); - sam_hive_volume -= alice_smt.amount.value / 20; - sam_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 2 ); - fill_order_op = ops[1].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 6 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == asset( alice_smt.amount.value / 20, any_smt_symbol ).amount.value ); - BOOST_REQUIRE( fill_order_op.current_owner == "sam" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 8 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == asset( alice_smt.amount.value / 20, HIVE_SYMBOL ).amount.value ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - BOOST_TEST_MESSAGE( "Trading to give Alice and Bob positive volumes to receive rewards" ); - - transfer_operation transfer; - transfer.to = "dave"; - transfer.from = "alice"; - transfer.amount = asset( alice_smt.amount / 2, any_smt_symbol ); - - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "alice"; - op.amount_to_sell = asset( 8 * ( alice_smt.amount.value / 20 ), HIVE_SYMBOL ); - op.min_to_receive = asset( op.amount_to_sell.amount, any_smt_symbol ); - op.orderid = 9; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "dave"; - op.amount_to_sell = asset( 7 * ( alice_smt.amount.value / 20 ), any_smt_symbol );; - op.min_to_receive = asset( op.amount_to_sell.amount, HIVE_SYMBOL ); - op.orderid = 10; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - alice_smt_volume += op.amount_to_sell.amount.value; - alice_reward_last_update = db->head_block_time(); - dave_smt_volume -= op.amount_to_sell.amount.value; - dave_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 9 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == 7 * ( alice_smt.amount.value / 20 ) ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 10 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == 7 * ( alice_smt.amount.value / 20 ) ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - op.owner = "bob"; - op.amount_to_sell.amount = alice_smt.amount / 20; - op.min_to_receive.amount = op.amount_to_sell.amount; - op.orderid = 11; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - alice_smt_volume += op.amount_to_sell.amount.value; - alice_reward_last_update = db->head_block_time(); - bob_smt_volume -= op.amount_to_sell.amount.value; - bob_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "alice" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 9 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == alice_smt.amount.value / 20 ); - BOOST_REQUIRE( fill_order_op.current_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 11 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == alice_smt.amount.value / 20 ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - transfer.to = "bob"; - transfer.from = "alice"; - transfer.amount = asset( alice_smt.amount / 5, any_smt_symbol ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( transfer ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - op.owner = "bob"; - op.orderid = 12; - op.amount_to_sell = asset( 3 * ( alice_smt.amount / 40 ), any_smt_symbol ); - op.min_to_receive = asset( op.amount_to_sell.amount, HIVE_SYMBOL ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC_HF10, true ); - - op.owner = "dave"; - op.orderid = 13; - op.amount_to_sell = op.min_to_receive; - op.min_to_receive.symbol = any_smt_symbol; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - sign( tx, dave_private_key ); - db->push_transaction( tx, 0 ); - - bob_hive_volume += op.amount_to_sell.amount.value; - bob_reward_last_update = db->head_block_time(); - dave_hive_volume -= op.amount_to_sell.amount.value; - dave_reward_last_update = db->head_block_time(); - - ops = get_last_operations( 1 ); - fill_order_op = ops[0].get< fill_order_operation >(); - - BOOST_REQUIRE( fill_order_op.open_owner == "bob" ); - BOOST_REQUIRE( fill_order_op.open_orderid == 12 ); - BOOST_REQUIRE( fill_order_op.open_pays.amount.value == 3 * ( alice_smt.amount.value / 40 ) ); - BOOST_REQUIRE( fill_order_op.current_owner == "dave" ); - BOOST_REQUIRE( fill_order_op.current_orderid == 13 ); - BOOST_REQUIRE( fill_order_op.current_pays.amount.value == 3 * ( alice_smt.amount.value / 40 ) ); - - reward = liquidity_idx.find( get_account_id( "alice" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "alice" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == alice_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == alice_hive_volume ); - BOOST_CHECK( reward->last_update == alice_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "bob" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "bob" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == bob_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == bob_hive_volume ); - BOOST_CHECK( reward->last_update == bob_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - reward = liquidity_idx.find( get_account_id( "dave" ) ); - BOOST_REQUIRE( reward == liquidity_idx.end() ); - /*BOOST_REQUIRE( reward->owner == get_account_id( "dave" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == dave_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == dave_hive_volume ); - BOOST_CHECK( reward->last_update == dave_reward_last_update );*/ - - auto alice_balance = get_balance( "alice" ); - auto bob_balance = get_balance( "bob" ); - auto sam_balance = get_balance( "sam" ); - auto dave_balance = get_balance( "dave" ); - - BOOST_TEST_MESSAGE( "Generating Blocks to trigger liquidity rewards" ); - - db->liquidity_rewards_enabled = true; - generate_blocks( HIVE_LIQUIDITY_REWARD_BLOCKS - ( db->head_block_num() % HIVE_LIQUIDITY_REWARD_BLOCKS ) - 1 ); - - BOOST_REQUIRE( db->head_block_num() % HIVE_LIQUIDITY_REWARD_BLOCKS == HIVE_LIQUIDITY_REWARD_BLOCKS - 1 ); - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - generate_block(); - - //alice_balance += HIVE_MIN_LIQUIDITY_REWARD; - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - ops = get_last_operations( 1 ); - - HIVE_REQUIRE_THROW( ops[0].get< liquidity_reward_operation>(), fc::exception ); - //BOOST_REQUIRE( ops[0].get< liquidity_reward_operation>().payout.amount.value == HIVE_MIN_LIQUIDITY_REWARD.amount.value ); - - generate_blocks( HIVE_LIQUIDITY_REWARD_BLOCKS ); - - //bob_balance += HIVE_MIN_LIQUIDITY_REWARD; - - BOOST_REQUIRE( get_balance( "alice" ).amount.value == alice_balance.amount.value ); - BOOST_REQUIRE( get_balance( "bob" ).amount.value == bob_balance.amount.value ); - BOOST_REQUIRE( get_balance( "sam" ).amount.value == sam_balance.amount.value ); - BOOST_REQUIRE( get_balance( "dave" ).amount.value == dave_balance.amount.value ); - - ops = get_last_operations( 1 ); - - HIVE_REQUIRE_THROW( ops[0].get< liquidity_reward_operation>(), fc::exception ); - //BOOST_REQUIRE( ops[0].get< liquidity_reward_operation>().payout.amount.value == HIVE_MIN_LIQUIDITY_REWARD.amount.value ); - - alice_hive_volume = 0; - alice_smt_volume = 0; - bob_hive_volume = 0; - bob_smt_volume = 0; - - BOOST_TEST_MESSAGE( "Testing liquidity timeout" ); - - generate_blocks( sam_reward_last_update + HIVE_LIQUIDITY_TIMEOUT_SEC - fc::seconds( HIVE_BLOCK_INTERVAL / 2 ) - HIVE_MIN_LIQUIDITY_REWARD_PERIOD_SEC, true ); - - op.owner = "sam"; - op.orderid = 14; - op.amount_to_sell = ASSET( "1.000 TESTS" ); - op.min_to_receive = ASSET( "1.000 TBD" ); - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, sam_private_key ); - db->push_transaction( tx, 0 ); - - generate_blocks( db->head_block_time() + ( HIVE_BLOCK_INTERVAL / 2 ) + HIVE_LIQUIDITY_TIMEOUT_SEC, true ); - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - /*BOOST_REQUIRE( reward == liquidity_idx.end() ); - BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - generate_block(); - - op.owner = "alice"; - op.orderid = 15; - op.amount_to_sell.symbol = any_smt_symbol; - op.min_to_receive.symbol = HIVE_SYMBOL; - tx.operations.clear(); - tx.signatures.clear(); - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - - sam_smt_volume = ASSET( "1.000 TBD" ).amount.value; - sam_hive_volume = 0; - sam_reward_last_update = db->head_block_time(); - - reward = liquidity_idx.find( get_account_id( "sam" ) ); - /*BOOST_REQUIRE( reward == liquidity_idx.end() ); - BOOST_REQUIRE( reward->owner == get_account_id( "sam" ) ); - BOOST_REQUIRE( reward->get_hbd_volume() == sam_smt_volume ); - BOOST_REQUIRE( reward->get_hive_volume() == sam_hive_volume ); - BOOST_CHECK( reward->last_update == sam_reward_last_update );*/ - - validate_database(); - } - FC_LOG_AND_RETHROW(); -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/smt_tests.cpp b/tests2/unit/tests/smt_tests.cpp deleted file mode 100644 index 64765eafa201ecbff8a762c40e29f918dc774cab..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/smt_tests.cpp +++ /dev/null @@ -1,640 +0,0 @@ -#include <fc/macros.hpp> - -#if defined IS_TEST_NET && defined HIVE_ENABLE_SMT - -FC_TODO(Extend testing scenarios to support multiple NAIs per account) - -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> -#include <hive/chain/smt_objects.hpp> - -#include <hive/chain/util/smt_token.hpp> - -#include "../db_fixture/database_fixture.hpp" - -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; -using boost::container::flat_set; -using boost::container::flat_map; - -BOOST_FIXTURE_TEST_SUITE( smt_tests, smt_database_fixture ) - -BOOST_AUTO_TEST_CASE( smt_transfer_validate ) -{ - try - { - ACTORS( (alice) ) - - generate_block(); - - asset_symbol_type alice_symbol = create_smt("alice", alice_private_key, 0); - - transfer_operation op; - op.from = "alice"; - op.to = "bob"; - op.amount = asset(100, alice_symbol); - op.validate(); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( smt_transfer_apply ) -{ - // This simple test touches SMT account balance objects, related functions (get/adjust) - // and transfer operation that builds on them. - try - { - ACTORS( (alice)(bob) ) - - generate_block(); - - // Create SMT. - asset_symbol_type alice_symbol = create_smt("alice", alice_private_key, 0); - asset_symbol_type bob_symbol = create_smt("bob", bob_private_key, 1); - - // Give some SMT to creators. - FUND( "alice", asset( 100, alice_symbol ) ); - FUND( "bob", asset( 110, bob_symbol ) ); - - // Check pre-tranfer amounts. - FC_ASSERT( db->get_balance( "alice", alice_symbol ).amount == 100, "SMT balance adjusting error" ); - FC_ASSERT( db->get_balance( "alice", bob_symbol ).amount == 0, "SMT balance adjusting error" ); - FC_ASSERT( db->get_balance( "bob", alice_symbol ).amount == 0, "SMT balance adjusting error" ); - FC_ASSERT( db->get_balance( "bob", bob_symbol ).amount == 110, "SMT balance adjusting error" ); - - // Transfer SMT. - transfer( "alice", "bob", asset(20, alice_symbol) ); - transfer( "bob", "alice", asset(50, bob_symbol) ); - - // Check transfer outcome. - FC_ASSERT( db->get_balance( "alice", alice_symbol ).amount == 80, "SMT transfer error" ); - FC_ASSERT( db->get_balance( "alice", bob_symbol ).amount == 50, "SMT transfer error" ); - FC_ASSERT( db->get_balance( "bob", alice_symbol ).amount == 20, "SMT transfer error" ); - FC_ASSERT( db->get_balance( "bob", bob_symbol ).amount == 60, "SMT transfer error" ); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( comment_votable_assers_validate ) -{ - try - { - BOOST_TEST_MESSAGE( "Test Comment Votable Assets Validate" ); - ACTORS((alice)); - - generate_block(); - - std::array<asset_symbol_type, SMT_MAX_VOTABLE_ASSETS + 1> smts; - /// Create one more than limit to test negative cases - for(size_t i = 0; i < SMT_MAX_VOTABLE_ASSETS + 1; ++i) - { - asset_symbol_type smt = create_smt("alice", alice_private_key, 0); - smts[i] = std::move(smt); - } - - { - comment_options_operation op; - - op.author = "alice"; - op.permlink = "test"; - - BOOST_TEST_MESSAGE( "--- Testing valid configuration: no votable_assets" ); - allowed_vote_assets ava; - op.extensions.insert( ava ); - op.validate(); - } - - { - comment_options_operation op; - - op.author = "alice"; - op.permlink = "test"; - - BOOST_TEST_MESSAGE( "--- Testing valid configuration of votable_assets" ); - allowed_vote_assets ava; - for(size_t i = 0; i < SMT_MAX_VOTABLE_ASSETS; ++i) - { - const auto& smt = smts[i]; - ava.add_votable_asset(smt, share_type(10 + i), (i & 2) != 0); - } - - op.extensions.insert( ava ); - op.validate(); - } - - { - comment_options_operation op; - - op.author = "alice"; - op.permlink = "test"; - - BOOST_TEST_MESSAGE( "--- Testing invalid configuration of votable_assets - too much assets specified" ); - allowed_vote_assets ava; - for(size_t i = 0; i < smts.size(); ++i) - { - const auto& smt = smts[i]; - ava.add_votable_asset(smt, share_type(20 + i), (i & 2) != 0); - } - - op.extensions.insert( ava ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - } - - { - comment_options_operation op; - - op.author = "alice"; - op.permlink = "test"; - - BOOST_TEST_MESSAGE( "--- Testing invalid configuration of votable_assets - HIVE added to container" ); - allowed_vote_assets ava; - const auto& smt = smts.front(); - ava.add_votable_asset(smt, share_type(20), false); - ava.add_votable_asset(HIVE_SYMBOL, share_type(20), true); - op.extensions.insert( ava ); - HIVE_REQUIRE_THROW( op.validate(), fc::assert_exception ); - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( asset_symbol_vesting_methods ) -{ - try - { - BOOST_TEST_MESSAGE( "Test asset_symbol vesting methods" ); - - asset_symbol_type Hive = HIVE_SYMBOL; - FC_ASSERT( Hive.is_vesting() == false ); - FC_ASSERT( Hive.get_paired_symbol() == VESTS_SYMBOL ); - - asset_symbol_type Vests = VESTS_SYMBOL; - FC_ASSERT( Vests.is_vesting() ); - FC_ASSERT( Vests.get_paired_symbol() == HIVE_SYMBOL ); - - asset_symbol_type Hbd = HBD_SYMBOL; - FC_ASSERT( Hbd.is_vesting() == false ); - FC_ASSERT( Hbd.get_paired_symbol() == HBD_SYMBOL ); - - ACTORS( (alice) ) - generate_block(); - auto smts = create_smt_3("alice", alice_private_key); - { - for( const asset_symbol_type& liquid_smt : smts ) - { - FC_ASSERT( liquid_smt.is_vesting() == false ); - auto vesting_smt = liquid_smt.get_paired_symbol(); - FC_ASSERT( vesting_smt != liquid_smt ); - FC_ASSERT( vesting_smt.is_vesting() ); - FC_ASSERT( vesting_smt.get_paired_symbol() == liquid_smt ); - } - } - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( vesting_smt_creation ) -{ - try - { - BOOST_TEST_MESSAGE( "Test Creation of vesting SMT" ); - - ACTORS((alice)); - generate_block(); - - asset_symbol_type liquid_symbol = create_smt("alice", alice_private_key, 6); - // Use liquid symbol/NAI to confirm smt object was created. - auto liquid_object_by_symbol = util::smt::find_token( *db, liquid_symbol ); - FC_ASSERT( liquid_object_by_symbol != nullptr ); - - asset_symbol_type vesting_symbol = liquid_symbol.get_paired_symbol(); - // Use vesting symbol/NAI to confirm smt object was created. - auto vesting_object_by_symbol = util::smt::find_token( *db, vesting_symbol ); - FC_ASSERT( vesting_object_by_symbol != nullptr ); - - // Check that liquid and vesting objects are the same one. - FC_ASSERT( liquid_object_by_symbol == vesting_object_by_symbol ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( setup_validate ) -{ - try - { - smt_setup_operation op; - - ACTORS( (alice) ) - generate_block(); - asset_symbol_type alice_symbol = create_smt("alice", alice_private_key, 4); - - op.control_account = ""; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //Invalid account - op.control_account = "&&&&&&"; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( max_supply > 0 ) - op.control_account = "abcd"; - op.max_supply = -1; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.symbol = alice_symbol; - - //FC_ASSERT( max_supply > 0 ) - op.max_supply = 0; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( max_supply <= HIVE_MAX_SHARE_SUPPLY ) - op.max_supply = HIVE_MAX_SHARE_SUPPLY + 1; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( generation_begin_time > HIVE_GENESIS_TIME ) - op.max_supply = HIVE_MAX_SHARE_SUPPLY / 1000; - op.contribution_begin_time = HIVE_GENESIS_TIME; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - fc::time_point_sec start_time = fc::variant( "2018-03-07T00:00:00" ).as< fc::time_point_sec >(); - fc::time_point_sec t50 = start_time + fc::seconds( 50 ); - fc::time_point_sec t100 = start_time + fc::seconds( 100 ); - fc::time_point_sec t200 = start_time + fc::seconds( 200 ); - fc::time_point_sec t300 = start_time + fc::seconds( 300 ); - - op.contribution_begin_time = t100; - op.contribution_end_time = t50; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.contribution_begin_time = t100; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.launch_time = t200; - op.contribution_end_time = t300; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.contribution_begin_time = t50; - op.contribution_end_time = t100; - op.launch_time = t300; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.launch_time = t200; - smt_capped_generation_policy gp = get_capped_generation_policy - ( - get_generation_unit( { { "xyz", 1 } }, { { "xyz2", 2 } } )/*pre_soft_cap_unit*/, - get_generation_unit()/*post_soft_cap_unit*/, - HIVE_100_PERCENT/*soft_cap_percent*/, - 1/*min_unit_ratio*/, - 2/*max_unit_ratio*/ - ); - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - units to_many_units; - for( uint32_t i = 0; i < SMT_MAX_UNIT_ROUTES + 1; ++i ) - to_many_units.emplace( "alice" + std::to_string( i ), 1 ); - - //FC_ASSERT( hive_unit.size() <= SMT_MAX_UNIT_ROUTES ) - gp.pre_soft_cap_unit.hive_unit = to_many_units; - gp.pre_soft_cap_unit.token_unit = { { "bob",3 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "bob2", 33 } }; - gp.pre_soft_cap_unit.token_unit = to_many_units; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //Invalid account - gp.pre_soft_cap_unit.hive_unit = { { "{}{}", 12 } }; - gp.pre_soft_cap_unit.token_unit = { { "xyz", 13 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "xyz2", 14 } }; - gp.pre_soft_cap_unit.token_unit = { { "{}", 15 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //Invalid account -> valid is '$from' - gp.pre_soft_cap_unit.hive_unit = { { "$fromx", 1 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from", 2 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "$from", 3 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from_", 4 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //Invalid account -> valid is '$from.vesting' - gp.pre_soft_cap_unit.hive_unit = { { "$from.vestingx", 2 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from.vesting", 222 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "$from.vesting", 13 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from.vesting.vesting", 3 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( hive_unit.value > 0 ); - gp.pre_soft_cap_unit.hive_unit = { { "$from.vesting", 0 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from.vesting", 2 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "$from.vesting", 10 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from.vesting", 0 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( hive_unit.value > 0 ); - gp.pre_soft_cap_unit.hive_unit = { { "$from", 0 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from", 100 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "$from", 33 } }; - gp.pre_soft_cap_unit.token_unit = { { "$from", 0 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - //FC_ASSERT( hive_unit.value > 0 ); - gp.pre_soft_cap_unit.hive_unit = { { "qprst", 0 } }; - gp.pre_soft_cap_unit.token_unit = { { "qprst", 67 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "my_account2", 55 } }; - gp.pre_soft_cap_unit.token_unit = { { "my_account", 0 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.pre_soft_cap_unit.hive_unit = { { "bob", 2 }, { "$from.vesting", 3 }, { "$from", 4 } }; - gp.pre_soft_cap_unit.token_unit = { { "alice", 5 }, { "$from", 3 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = 0; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = HIVE_100_PERCENT + 1; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = HIVE_100_PERCENT; - gp.post_soft_cap_unit.hive_unit = { { "bob", 2 } }; - gp.post_soft_cap_unit.token_unit = {}; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = HIVE_100_PERCENT; - gp.post_soft_cap_unit.hive_unit = {}; - gp.post_soft_cap_unit.token_unit = { { "alice", 3 } }; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = HIVE_100_PERCENT / 2; - gp.post_soft_cap_unit.hive_unit = {}; - gp.post_soft_cap_unit.token_unit = {}; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - gp.soft_cap_percent = HIVE_100_PERCENT; - gp.post_soft_cap_unit.hive_unit = {}; - gp.post_soft_cap_unit.token_unit = {}; - op.initial_generation_policy = gp; - HIVE_REQUIRE_THROW( op.validate(), fc::exception ); - - op.hive_units_soft_cap = SMT_MIN_SOFT_CAP_HIVE_UNITS; - op.hive_units_hard_cap = SMT_MIN_HARD_CAP_HIVE_UNITS; - op.validate(); - - gp.max_unit_ratio = ( ( 11 * SMT_MIN_HARD_CAP_HIVE_UNITS ) / SMT_MIN_SATURATION_HIVE_UNITS ) * 2; - op.initial_generation_policy = gp; - op.validate(); - - gp.max_unit_ratio = 2; - op.initial_generation_policy = gp; - op.validate(); - - smt_capped_generation_policy gp_valid = gp; - - gp.soft_cap_percent = 1; - gp.post_soft_cap_unit.hive_unit = { { "bob", 2 } }; - op.initial_generation_policy = gp; - op.validate(); - - gp = gp_valid; - op.initial_generation_policy = gp; - op.validate(); - - uint16_t max_val_16 = std::numeric_limits<uint16_t>::max(); - uint32_t max_val_32 = std::numeric_limits<uint32_t>::max(); - - gp.soft_cap_percent = HIVE_100_PERCENT - 1; - gp.min_unit_ratio = max_val_32; - gp.post_soft_cap_unit.hive_unit = { { "abc", 1 } }; - gp.post_soft_cap_unit.token_unit = { { "abc1", max_val_16 } }; - gp.pre_soft_cap_unit.token_unit = { { "abc2", max_val_16 } }; - op.initial_generation_policy = gp; - op.validate(); - - gp.min_unit_ratio = 1; - gp.post_soft_cap_unit.token_unit = { { "abc1", 1 } }; - gp.pre_soft_cap_unit.token_unit = { { "abc2", 1 } }; - gp.post_soft_cap_unit.hive_unit = { { "abc3", max_val_16 } }; - gp.pre_soft_cap_unit.hive_unit = { { "abc34", max_val_16 } }; - op.initial_generation_policy = gp; - op.validate(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( setup_authorities ) -{ - try - { - smt_setup_operation op; - op.control_account = "alice"; - - flat_set< account_name_type > auths; - flat_set< account_name_type > expected; - - op.get_required_owner_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - op.get_required_posting_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - - expected.insert( "alice" ); - op.get_required_active_authorities( auths ); - BOOST_REQUIRE( auths == expected ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( setup_apply ) -{ - try - { - ACTORS( (alice)(bob) ) - - generate_block(); - - FUND( "alice", 10 * 1000 * 1000 ); - FUND( "bob", 10 * 1000 * 1000 ); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - smt_setup_operation op; - op.control_account = "alice"; - op.hive_units_soft_cap = SMT_MIN_SOFT_CAP_HIVE_UNITS; - op.hive_units_hard_cap = SMT_MIN_HARD_CAP_HIVE_UNITS; - - smt_capped_generation_policy gp = get_capped_generation_policy - ( - get_generation_unit( { { "xyz", 1 } }, { { "xyz2", 2 } } )/*pre_soft_cap_unit*/, - get_generation_unit()/*post_soft_cap_unit*/, - HIVE_100_PERCENT/*soft_cap_percent*/, - 1/*min_unit_ratio*/, - 2/*max_unit_ratio*/ - ); - - fc::time_point_sec start_time = fc::variant( "2021-01-01T00:00:00" ).as< fc::time_point_sec >(); - fc::time_point_sec start_time_plus_1 = start_time + fc::seconds(1); - - op.initial_generation_policy = gp; - op.contribution_begin_time = start_time; - op.contribution_end_time = op.launch_time = start_time_plus_1; - - signed_transaction tx; - - //SMT doesn't exist - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - HIVE_REQUIRE_THROW( db->push_transaction( tx, 0 ), fc::exception ); - tx.operations.clear(); - tx.signatures.clear(); - - //Try to elevate account - asset_symbol_type alice_symbol = create_smt( "alice", alice_private_key, 3 ); - tx.operations.clear(); - tx.signatures.clear(); - - //Make transaction again. Everything is correct. - op.symbol = alice_symbol; - tx.operations.push_back( op ); - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - db->push_transaction( tx, 0 ); - tx.operations.clear(); - tx.signatures.clear(); - } - FC_LOG_AND_RETHROW() -} - -/* - * SMT legacy tests - * - * The logic tests in legacy tests *should* be entirely duplicated in smt_operation_tests.cpp - * We are keeping these tests around to provide an additional layer re-assurance for the time being - */ -FC_TODO( "Remove SMT legacy tests and ensure code coverage is not reduced" ); - -BOOST_AUTO_TEST_CASE( smt_create_apply ) -{ - try - { - ACTORS( (alice)(bob) ) - - generate_block(); - - set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); - - const dynamic_global_property_object& dgpo = db->get_dynamic_global_properties(); - asset required_creation_fee = dgpo.smt_creation_fee; - unsigned int test_amount = required_creation_fee.amount.value; - - smt_create_operation op; - op.control_account = "alice"; - op.symbol = get_new_smt_symbol( 3, db ); - op.precision = op.symbol.decimals(); - - BOOST_TEST_MESSAGE( " -- SMT create with insufficient HBD balance" ); - // Fund with HIVE, and set fee with HBD. - FUND( "alice", test_amount ); - // Declare fee in HBD/TBD though alice has none. - op.smt_creation_fee = asset( test_amount, HBD_SYMBOL ); - // Throw due to insufficient balance of HBD/TBD. - FAIL_WITH_OP(op, alice_private_key, fc::assert_exception); - - BOOST_TEST_MESSAGE( " -- SMT create with insufficient HIVE balance" ); - // Now fund with HBD, and set fee with HIVE. - convert( "alice", asset( test_amount, HIVE_SYMBOL ) ); - // Declare fee in HIVE though alice has none. - op.smt_creation_fee = asset( test_amount, HIVE_SYMBOL ); - // Throw due to insufficient balance of HIVE. - FAIL_WITH_OP(op, alice_private_key, fc::assert_exception); - - BOOST_TEST_MESSAGE( " -- SMT create with available funds" ); - // Push valid operation. - op.smt_creation_fee = asset( test_amount, HBD_SYMBOL ); - PUSH_OP( op, alice_private_key ); - - BOOST_TEST_MESSAGE( " -- SMT cannot be created twice even with different precision" ); - create_conflicting_smt(op.symbol, "alice", alice_private_key); - - BOOST_TEST_MESSAGE( " -- Another user cannot create an SMT twice even with different precision" ); - // Check that another user/account can't be used to create duplicating SMT even with different precision. - create_conflicting_smt(op.symbol, "bob", bob_private_key); - - BOOST_TEST_MESSAGE( " -- Check that an SMT cannot be created with decimals greater than HIVE_MAX_DECIMALS" ); - // Check that invalid SMT can't be created - create_invalid_smt("alice", alice_private_key); - - BOOST_TEST_MESSAGE( " -- Check that an SMT cannot be created with a creation fee lower than required" ); - // Check fee set too low. - asset fee_too_low = required_creation_fee; - unsigned int too_low_fee_amount = required_creation_fee.amount.value-1; - fee_too_low.amount -= 1; - - SMT_SYMBOL( bob, 0, db ); - op.control_account = "bob"; - op.symbol = bob_symbol; - op.precision = op.symbol.decimals(); - - BOOST_TEST_MESSAGE( " -- Check that we cannot create an SMT with an insufficent HIVE creation fee" ); - // Check too low fee in HIVE. - FUND( "bob", too_low_fee_amount ); - op.smt_creation_fee = asset( too_low_fee_amount, HIVE_SYMBOL ); - FAIL_WITH_OP(op, bob_private_key, fc::assert_exception); - - BOOST_TEST_MESSAGE( " -- Check that we cannot create an SMT with an insufficent HBD creation fee" ); - // Check too low fee in HBD. - convert( "bob", asset( too_low_fee_amount, HIVE_SYMBOL ) ); - op.smt_creation_fee = asset( too_low_fee_amount, HBD_SYMBOL ); - FAIL_WITH_OP(op, bob_private_key, fc::assert_exception); - - validate_database(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/tests/undo_tests.cpp b/tests2/unit/tests/undo_tests.cpp deleted file mode 100644 index e56f73e238a90dd5115e37d6e0cb2f8669f92213..0000000000000000000000000000000000000000 --- a/tests2/unit/tests/undo_tests.cpp +++ /dev/null @@ -1,529 +0,0 @@ -#ifdef IS_TEST_NET -#include <boost/test/unit_test.hpp> - -#include <hive/chain/hive_fwd.hpp> - -#include <hive/protocol/exceptions.hpp> -#include <hive/protocol/hardfork.hpp> - -#include <hive/chain/database.hpp> -#include <hive/chain/database_exceptions.hpp> -#include <hive/chain/hive_objects.hpp> - -#include <hive/chain/util/reward.hpp> - -#include <fc/macros.hpp> -#include <fc/crypto/digest.hpp> - -#include "../db_fixture/database_fixture.hpp" -#include "../undo_data/undo.hpp" - -#include <cmath> -#include <iostream> -#include <stdexcept> - -using namespace hive; -using namespace hive::chain; -using namespace hive::protocol; -using fc::string; - -BOOST_FIXTURE_TEST_SUITE( undo_tests, clean_database_fixture ) - -BOOST_AUTO_TEST_CASE( undo_basic ) -{ - try - { - BOOST_TEST_MESSAGE( "--- Testing: undo_basic" ); - - undo_db udb( *db ); - undo_scenario< account_object > ao( *db ); - - BOOST_TEST_MESSAGE( "--- No object added" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj0 = ao.create( "name00" ); - BOOST_REQUIRE( std::string( obj0.name ) == "name00" ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create, modify )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj1 = ao.create( "name00" ); - BOOST_REQUIRE( std::string( obj1.name ) == "name00" ); - const account_object& obj2 = ao.modify( obj1, [&]( account_object& obj ){ obj.name = "name01"; } ); - BOOST_REQUIRE( std::string( obj2.name ) == "name01" ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create, remove )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj3 = ao.create( "name00" ); - ao.remove( obj3 ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create, modify, remove )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj4 = ao.create( "name00" ); - ao.modify( obj4, [&]( account_object& obj ){ obj.proxy = "proxy00"; } ); - ao.remove( obj4 ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create, remove, create )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj5 = ao.create( "name00" ); - ao.remove( obj5 ); - ao.create( "name00" ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 1 object( create, modify, remove, create )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj6 = ao.create( "name00" ); - ao.modify( obj6, [&]( account_object& obj ){ obj.proxy = "proxy00"; } ); - ao.remove( obj6 ); - ao.create( "name00" ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "--- 3 objects( create, create/modify, create/remove )" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - const account_object& obj_c = ao.create( "name00" ); - BOOST_REQUIRE( std::string( obj_c.name ) == "name00" ); - - const account_object& obj_cm = ao.create( "name01" ); - BOOST_REQUIRE( std::string( obj_cm.name ) == "name01" ); - ao.modify( obj_cm, [&]( account_object& obj ){ obj.name = "name02"; } ); - BOOST_REQUIRE( std::string( obj_cm.name ) == "name02" ); - - const account_object& obj_cr = ao.create( "name03" ); - BOOST_REQUIRE( std::string( obj_cr.name ) == "name03" ); - ao.remove( obj_cr ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( undo_object_disappear ) -{ - try - { - BOOST_TEST_MESSAGE( "--- 2 objects. Modifying 1 object - uniqueness of complex index is violated" ); - - undo_db udb( *db ); - undo_scenario< account_object > ao( *db ); - - uint32_t old_size = ao.size< account_index >(); - - const account_object& obj0 = ao.create( "name00" ); ao.modify( obj0, [&]( account_object& obj ){ obj.proxy = "proxy00"; } ); - BOOST_REQUIRE( old_size + 1 == ao.size< account_index >() ); - - const account_object& obj1 = ao.create( "name01" ); ao.modify( obj1, [&]( account_object& obj ){ obj.proxy = "proxy01"; } ); - BOOST_REQUIRE( old_size + 2 == ao.size< account_index >() ); - - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - /* - Important!!! - Method 'generic_index::modify' works incorrectly - after 'contraint violation', element is removed. - Solution: - It's necessary to write fix, according to issue #2154. - */ - //Temporary. After fix, this line should be enabled. - HIVE_REQUIRE_THROW( ao.modify( obj1, [&]( account_object& obj ){ obj.name = "name00"; obj.proxy = "proxy00"; } ), boost::exception ); - - //Temporary. After fix, this line should be removed. - //ao.modify( obj1, [&]( account_object& obj ){ obj.name = "nameXYZ"; obj.proxy = "proxyXYZ"; } ); - - udb.undo_end(); - BOOST_REQUIRE( old_size + 2 == ao.size< account_index >() ); - - BOOST_REQUIRE( ao.check< account_index >() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( undo_key_collision ) -{ - try - { - BOOST_TEST_MESSAGE( "--- Testing: undo_key_collision" ); - - const auto& fake_account_object = db->create< account_object >( "fake" ); - fc::optional< std::reference_wrapper< const comment_object > > fake_parent_comment; - - undo_db udb( *db ); - undo_scenario< account_object > ao( *db ); - - BOOST_TEST_MESSAGE( "--- 1 object - twice with the same key" ); - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - ao.create( "name00" ); - HIVE_REQUIRE_THROW( ao.create( "name00" ), boost::exception ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "Version A - doesn't work without fix" ); - BOOST_TEST_MESSAGE( "--- 2 objects. Object 'obj0' is created before 'undo' and has modified key in next step." ); - BOOST_TEST_MESSAGE( "--- Object 'obj1' retrieves old key from object 'obj0'." ); - - const account_object& obj0 = ao.create( "name00" ); - - ao.remember_old_values< account_index >(); - udb.undo_begin(); - - uint32_t old_size = ao.size< account_index >(); - - ao.modify( obj0, [&]( account_object& obj ){ obj.post_count = 1; } ); - ao.modify( obj0, [&]( account_object& obj ){ obj.name = "name01"; } ); - - /* - Important!!! - The mechanism 'undo' works incorrectly, when a unique key is changed in object, but such object is saved in 'undo' earlier. - In next step another object gets identical key what first object had before. - In such situation, attempt of modification by 'undo', raises 'uniqueness constraint' violation. - Currently, simple solution used in whole project is adding unique key 'id' to save uniqueness. - Solution: - Is necessary to write another version of 'undo'? - */ - //Temporary. After fix, this line should be enabled. - //ao.create( "name00" ); - - //Temporary. After fix, this line should be removed. - ao.create( "nameXYZ" ); - - BOOST_REQUIRE( old_size + 1 == ao.size< account_index >() ); - - udb.undo_end(); //ABW: when above lines are commented/uncommented as instructed undo fails because uniqueness constraints are checked - //with every [un]modified object meaning original obj0 tries to regain its name00 which is in conflict with still not undone new name00 object; - //in this particular case changing order of undoing to first remove new objects prior to restoring modified ones would help, but it would - //still be easy to make two objects modified in such a way that undoing changes one by one would still run into uniqueness constraint fail - //(f.e. they could swap names) - BOOST_REQUIRE( ao.check< account_index >() ); - - BOOST_TEST_MESSAGE( "Version B - work without fix, because key 'cashout_time' is combined with 'id' key." ); - BOOST_TEST_MESSAGE( "--- 2 objects. Object 'obj0' is created before 'undo' and has modified key in next step." ); - BOOST_TEST_MESSAGE( "--- Object 'obj1' retrieves old key from object 'obj0'." ); - - undo_scenario< comment_object > co( *db ); - undo_scenario< comment_cashout_object > co_cashout( *db ); - const comment_object& objc0 = co.create( fake_account_object, "permlink", fake_parent_comment ); - const comment_cashout_object& objc0_cashout = co_cashout.create( objc0, fake_account_object, "permlink", time_point_sec( 10 ), time_point_sec( 20 ) ); - - BOOST_REQUIRE( objc0_cashout.get_comment_id() == objc0.get_id() ); - - co.remember_old_values< comment_index >(); - co_cashout.remember_old_values< comment_cashout_index >(); - - udb.undo_begin(); - - old_size = co.size< comment_index >(); - uint32_t old_size_cashout = co_cashout.size< comment_cashout_index >(); - - co_cashout.modify( objc0_cashout, [&]( comment_cashout_object& obj ){ obj.cashout_time = time_point_sec( 21 ); } ); - - const comment_object& objc1 = co.create( fake_account_object, "permlink2", fake_parent_comment ); - const comment_cashout_object& objc1_cashout = co_cashout.create( objc1, fake_account_object, "permlink2", time_point_sec( 10 ), time_point_sec( 20 ) ); - - BOOST_REQUIRE( objc1_cashout.get_comment_id() == objc1.get_id() ); - - BOOST_REQUIRE( old_size + 1 == co.size< comment_index >() ); - BOOST_REQUIRE( old_size_cashout + 1 == co_cashout.size< comment_cashout_index >() ); - - udb.undo_end(); - BOOST_REQUIRE( co.check< comment_index >() ); - BOOST_REQUIRE( co_cashout.check< comment_cashout_index >() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( undo_different_indexes ) -{ - try - { - const auto& fake_account_object = db->create< account_object >( "fake" ); - fc::optional< std::reference_wrapper< const comment_object > > fake_parent_comment; - - BOOST_TEST_MESSAGE( "--- Testing: undo_different_indexes" ); - - undo_db udb( *db ); - undo_scenario< account_object > ao( *db ); - undo_scenario< comment_object > co( *db ); - undo_scenario< comment_cashout_object > co_cashout( *db ); - undo_scenario< comment_content_object > cc( *db ); - - uint32_t old_size_ao; - uint32_t old_size_co; - uint32_t old_size_co_cashout; - uint32_t old_size_cc; - - BOOST_TEST_MESSAGE( "--- 2 objects( different types )" ); - ao.remember_old_values< account_index >(); - co.remember_old_values< comment_index >(); - old_size_ao = ao.size< account_index >(); - old_size_co = co.size< comment_index >(); - udb.undo_begin(); - - const account_object& obja0 = ao.create( "name00" ); - BOOST_REQUIRE( std::string( obja0.name ) == "name00" ); - BOOST_REQUIRE( old_size_ao + 1 == ao.size< account_index >() ); - - const comment_object& objc0 = co.create( fake_account_object, "11", fake_parent_comment ); - BOOST_CHECK_EQUAL( objc0.get_author_and_permlink_hash(), comment_object::compute_author_and_permlink_hash( fake_account_object.get_id(), "11" ) ); - BOOST_REQUIRE( old_size_co + 1 == co.size< comment_index >() ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - - BOOST_TEST_MESSAGE( "--- 3 objects 'account_objects' + 2 objects 'comment_objects'." ); - BOOST_TEST_MESSAGE( "--- 'account_objects' - ( obj A )create, ( obj B )create/modify, ( obj C )create/remove." ); - BOOST_TEST_MESSAGE( "--- 'comment_objects' - ( obj A )create, ( obj B )create/remove." ); - ao.remember_old_values< account_index >(); - co.remember_old_values< comment_index >(); - co_cashout.remember_old_values< comment_cashout_index >(); - old_size_ao = ao.size< account_index >(); - old_size_co = co.size< comment_index >(); - old_size_co_cashout = co.size< comment_cashout_index >(); - udb.undo_begin(); - - ao.create( "name00" ); - const account_object& obja1 = ao.create( "name01" ); - const account_object& obja2 = ao.create( "name02" ); - BOOST_REQUIRE( old_size_ao + 3 == ao.size< account_index >() ); - ao.modify( obja1, [&]( account_object& obj ){ obj.proxy = "proxy01"; } ); - ao.remove( obja2 ); - BOOST_REQUIRE( old_size_ao + 2 == ao.size< account_index >() ); - - co.create( fake_account_object, "11", fake_parent_comment ); - const comment_object& objc1 = co.create( fake_account_object, "12", fake_parent_comment ); - const comment_cashout_object& objc1_cashout = co_cashout.create( objc1, fake_account_object, "12", time_point_sec( 10 ), time_point_sec( 20 ) ); - co_cashout.modify( objc1_cashout, [&]( comment_cashout_object& obj ){ obj.active = time_point_sec( 21 ); } ); - BOOST_REQUIRE( old_size_co + 2 == co.size< comment_index >() ); - BOOST_REQUIRE( old_size_co_cashout + 1 == co_cashout.size< comment_cashout_index >() ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - BOOST_REQUIRE( co_cashout.check< comment_cashout_index >() ); - - BOOST_TEST_MESSAGE( "--- 4 objects: 'account_object' + 'comment_object' + 'comment_cashout_object' + 'comment_content_object'" ); - BOOST_TEST_MESSAGE( "--- 'account_object' - ( obj A )create" ); - BOOST_TEST_MESSAGE( "--- 'comment_object' - ( obj A )create/remove." ); - BOOST_TEST_MESSAGE( "--- 'comment_cashout_object' - ( obj A )create/remove." ); - BOOST_TEST_MESSAGE( "--- 'comment_content_object' - ( obj A )create/remove." ); - ao.remember_old_values< account_index >(); - co.remember_old_values< comment_index >(); - co_cashout.remember_old_values< comment_cashout_index >(); - cc.remember_old_values< comment_content_index >(); - old_size_ao = ao.size< account_index >(); - old_size_co = co.size< comment_index >(); - old_size_co_cashout = co_cashout.size< comment_cashout_index >(); - old_size_cc = cc.size< comment_content_index >(); - udb.undo_begin(); - - ao.create( "name01" ); - const comment_object& objc2 = co.create( fake_account_object, "12", fake_parent_comment ); - const comment_cashout_object& objc2_cashout = co_cashout.create( objc2, fake_account_object, "12", time_point_sec( 10 ), time_point_sec( 20 ) ); - const comment_content_object& objcc1 = cc.create( [&]( comment_content_object& obj ){ obj.comment = comment_object::id_type( 13 ); } ); - BOOST_REQUIRE( old_size_ao + 1 == ao.size< account_index >() ); - BOOST_REQUIRE( old_size_co + 1 == co.size< comment_index >() ); - BOOST_REQUIRE( old_size_co_cashout + 1 == co_cashout.size< comment_cashout_index >() ); - BOOST_REQUIRE( old_size_cc + 1 == cc.size< comment_content_index >() ); - - co_cashout.modify( objc2_cashout, [&]( comment_cashout_object& obj ){ obj.active = time_point_sec( 21 ); } ); - cc.remove( objcc1 ); - BOOST_REQUIRE( old_size_ao + 1 == ao.size< account_index >() ); - BOOST_REQUIRE( old_size_co + 1 == co.size< comment_index >() ); - BOOST_REQUIRE( old_size_co_cashout + 1 == co_cashout.size< comment_cashout_index >() ); - BOOST_REQUIRE( old_size_cc == cc.size< comment_content_index >() ); - - udb.undo_end(); - BOOST_REQUIRE( ao.check< account_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - BOOST_REQUIRE( cc.check< comment_content_index >() ); - - BOOST_TEST_MESSAGE( "--- 4 objects: 'account_object' + 'comment_object' + 'comment_cashout_object' + 'comment_content_object'" ); - BOOST_TEST_MESSAGE( "--- Creating is before 'undo_start'." ); - BOOST_TEST_MESSAGE( "--- 'account_object' - create/5*modify" ); - BOOST_TEST_MESSAGE( "--- 'comment_object' - create/remove" ); - BOOST_TEST_MESSAGE( "--- 'comment_cashout_object' - create/5*modify/remove" ); - BOOST_TEST_MESSAGE( "--- 'comment_content_object' - create/remove" ); - - const comment_content_object& cc1 = cc.create( [&]( comment_content_object& obj ){ obj.comment = comment_object::id_type( 0 ); } ); - const comment_object& co1 = co.create( fake_account_object, "12", fake_parent_comment ); - const comment_cashout_object& co1_cashout = co_cashout.create( co1, fake_account_object, "12", time_point_sec( 10 ), time_point_sec( 20 ) ); - const account_object& ao1 = ao.create( std::to_string(0) ); - - ao.remember_old_values< account_index >(); - co.remember_old_values< comment_index >(); - co_cashout.remember_old_values< comment_cashout_index >(); - cc.remember_old_values< comment_content_index >(); - old_size_ao = ao.size< account_index >(); - old_size_co = co.size< comment_index >(); - old_size_co_cashout = co_cashout.size< comment_cashout_index >(); - old_size_cc = cc.size< comment_content_index >(); - udb.undo_begin(); - - for( int32_t i=1; i<=5; ++i ) - { - co_cashout.modify( co1_cashout, [&]( comment_cashout_object& obj ){ obj.active = time_point_sec( 21 ); } ); - ao.modify( ao1, [&]( account_object& obj ){ obj.name = std::to_string(0); } ); - - BOOST_REQUIRE( old_size_ao == ao.size< account_index >() ); - BOOST_REQUIRE( old_size_co_cashout = co_cashout.size< comment_cashout_index >() ); - } - - cc.remove( cc1 ); - BOOST_REQUIRE( old_size_cc - 1 == cc.size< comment_content_index >() ); - - udb.undo_end(); - BOOST_REQUIRE( old_size_ao == ao.size< account_index >() ); - BOOST_REQUIRE( old_size_co == co.size< comment_index >() ); - BOOST_REQUIRE( old_size_co_cashout == co_cashout.size< comment_cashout_index >() ); - BOOST_REQUIRE( old_size_cc == cc.size< comment_content_index >() ); - BOOST_REQUIRE( ao.check< account_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - BOOST_REQUIRE( co_cashout.check< comment_cashout_index >() ); - BOOST_REQUIRE( cc.check< comment_content_index >() ); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_CASE( undo_generate_blocks ) -{ - try - { - BOOST_TEST_MESSAGE( "--- Testing: undo_generate_blocks" ); - - ACTORS( (alice)(bob)(chuck)(dan) ) - - struct _data - { - std::string author; - std::string permlink; - std::string parent_author; - std::string parent_permlink; - std::string title; - std::string body;; - - _data( std::string a, std::string pl, std::string pa, std::string ppl, std::string t, std::string b ) - : author( a ), permlink( pl ), parent_author( pa ), parent_permlink( ppl ), title( t ), body( b ){} - - void fill( comment_operation& com ) - { - com.author = author; - com.permlink = permlink; - com.parent_author = parent_author; - com.parent_permlink = parent_permlink; - com.title = title; - com.body = body; - } - }; - _data data[4]= - { - _data( "bob", "post4", std::string( HIVE_ROOT_POST_PARENT ), "pl4", "t4", "b4" ), - _data( "alice", "post", std::string( HIVE_ROOT_POST_PARENT ), "pl", "t", "b" ), - _data( "dan", "post2", "bob", "post4", "t2", "b2" ), - _data( "chuck", "post3", "bob", "post4", "t3", "b3" ) - }; - - generate_blocks( 1 ); - - comment_operation op; - - undo_db udb( *db ); - undo_scenario< comment_object > co( *db ); - - signed_transaction tx; - - BOOST_TEST_MESSAGE( "--- 1 objects: 'comment_object' without undo" ); - data[0].fill( op ); - tx.operations.push_back( op ); - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, bob_private_key ); - db->push_transaction( tx, 0 ); - generate_blocks( 1 ); - tx.operations.clear(); - tx.signatures.clear(); - - generate_blocks( 1 ); - - co.remember_old_values< comment_index >(); - - uint32_t old_size_co = co.size< comment_index >(); - - BOOST_TEST_MESSAGE( "--- 1 objects: 'comment_object' + undo" ); - data[1].fill( op ); - tx.operations.push_back( op ); - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, alice_private_key ); - - db->push_transaction( tx, 0 ); - generate_blocks( 1 ); - db->pop_block(); - - BOOST_REQUIRE( old_size_co == co.size< comment_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - tx.operations.clear(); - tx.signatures.clear(); - - generate_blocks( 1 ); - - BOOST_TEST_MESSAGE( "--- 2 objects: 'comment_object' + undo" ); - data[2].fill( op ); - tx.operations.push_back( op ); - data[3].fill( op ); - tx.operations.push_back( op ); - - tx.set_expiration( db->head_block_time() + HIVE_MAX_TIME_UNTIL_EXPIRATION ); - sign( tx, dan_private_key ); - sign( tx, chuck_private_key ); - - db->push_transaction( tx, 0 ); - generate_blocks( 1 ); - db->pop_block(); - - BOOST_REQUIRE( old_size_co == co.size< comment_index >() ); - BOOST_REQUIRE( co.check< comment_index >() ); - tx.operations.clear(); - tx.signatures.clear(); - } - FC_LOG_AND_RETHROW() -} - -BOOST_AUTO_TEST_SUITE_END() -#endif diff --git a/tests2/unit/undo_data/undo.hpp b/tests2/unit/undo_data/undo.hpp deleted file mode 100644 index 44fa5e28cbfd0c3ca0b74ac59a7a4fa874719b2e..0000000000000000000000000000000000000000 --- a/tests2/unit/undo_data/undo.hpp +++ /dev/null @@ -1,149 +0,0 @@ -#pragma once - -#include <hive/chain/database.hpp> -#include <fstream> - -namespace hive { namespace chain { - - /* - The class 'undo_scenario' simplifies writing tests from 'undo_tests' group. - a) There are implemented wrappers for 3 methods: database::create, database::modify, database::remove. - b) Methods 'remember_old_values' and 'check' help to compare state before and after running 'undo' mechanism. - */ - template< typename Object > - class undo_scenario - { - private: - - chain::database& db; - - std::list< Object > old_values; - - public: - - undo_scenario( chain::database& _db ): db( _db ) - { - } - - virtual ~undo_scenario(){} - - //Proxy method for `database::create`. - template< typename ... CALL_ARGS > - const Object& create( CALL_ARGS&&... call_args ) - { - return db.create< Object >( std::forward<CALL_ARGS>( call_args )... ); - } - - //Proxy method for `database::modify`. - template< typename CALL > - const Object& modify( const Object& old_obj, CALL&& call ) - { - db.modify( old_obj, std::forward<CALL>( call ) ); - return old_obj; - } - - //Proxy method for `database::remove`. - const void remove( const Object& old_obj ) - { - db.remove( old_obj ); - } - - //Save old objects before launching 'undo' mechanism. - //The objects are always sorted using 'by_id' index. - template< typename Index > - void remember_old_values() - { - old_values.clear(); - - const auto& idx = db.get_index< Index, by_id >(); - auto it = idx.begin(); - - while( it != idx.end() ) - old_values.emplace_back( ( it++ )->copy_chain_object() ); - } - - //Get size of given index. - template< typename Index > - uint32_t size() - { - const auto& idx = db.get_index< Index, by_id >(); - return idx.size(); - } - - //Reads current objects( for given index ) and compares with objects which have been saved before. - //The comparision is according to 'id' field. - template< typename Index > - bool check() - { - try - { - const auto& idx = db.get_index< Index, by_id >(); - - uint32_t idx_size = idx.size(); - uint32_t old_size = old_values.size(); - if( idx_size != old_size ) - return false; - - auto it = idx.begin(); - auto it_end = idx.end(); - - auto it_old = old_values.begin(); - - while( it != it_end ) - { - const Object& actual = *it; - const Object& old = *it_old; - if( actual.get_id() != old.get_id() ) - return false; - - ++it; - ++it_old; - } - } - FC_LOG_AND_RETHROW() - - return true; - } - - }; - - /* - The class 'undo_scenario' simplifies writing tests from 'undo_tests' group. - A method 'undo_begin' allows to enable 'undo' mechanism artificially. - A method 'undo_end' allows to revert all changes. - */ - class undo_db - { - private: - - database::session* session = nullptr; - chain::database& db; - - protected: - public: - - undo_db( chain::database& _db ): db( _db ) - { - } - - //Enable 'undo' mechanism. - void undo_begin() - { - if( session ) - { - delete session; - session = nullptr; - } - - session = new database::session( db.start_undo_session() ); - } - - //Revert all changes. - void undo_end() - { - if( session ) - session->undo(); - } - }; - -} }