text:
/*
 * 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 <graphene/chain/database.hpp>
#include <graphene/chain/fba_accumulator_id.hpp>

#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/balance_object.hpp>
#include <graphene/chain/block_summary_object.hpp>
#include <graphene/chain/budget_record_object.hpp>
#include <graphene/chain/buyback_object.hpp>
#include <graphene/chain/chain_property_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/confidential_object.hpp>
#include <graphene/chain/fba_object.hpp>
#include <graphene/chain/frequency_history_record_object.hpp>
#include <graphene/chain/global_property_object.hpp>
#include <graphene/chain/issued_asset_record_object.hpp>
#include <graphene/chain/license_objects.hpp>
#include <graphene/chain/market_object.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/queue_objects.hpp>
#include <graphene/chain/special_authority_object.hpp>
#include <graphene/chain/transaction_object.hpp>
#include <graphene/chain/vesting_balance_object.hpp>
#include <graphene/chain/upgrade_event_object.hpp>
#include <graphene/chain/wire_object.hpp>
#include <graphene/chain/wire_out_with_fee_object.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
#include <graphene/chain/withdrawal_limit_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/witness_schedule_object.hpp>
#include <graphene/chain/worker_object.hpp>
#include <graphene/chain/daspay_object.hpp>
#include <graphene/chain/das33_object.hpp>

#include <graphene/chain/account_evaluator.hpp>
#include <graphene/chain/asset_evaluator.hpp>
#include <graphene/chain/assert_evaluator.hpp>
#include <graphene/chain/balance_evaluator.hpp>
#include <graphene/chain/change_fee_evaluator.hpp>
#include <graphene/chain/committee_member_evaluator.hpp>
#include <graphene/chain/confidential_evaluator.hpp>
#include <graphene/chain/custom_evaluator.hpp>
#include <graphene/chain/cycle_evaluator.hpp>
#include <graphene/chain/das33_evaluator.hpp>
#include <graphene/chain/daspay_evaluator.hpp>
#include <graphene/chain/license_evaluator.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/proposal_evaluator.hpp>
#include <graphene/chain/transfer_evaluator.hpp>
#include <graphene/chain/vesting_balance_evaluator.hpp>
#include <graphene/chain/update_global_parameters_evaluator.hpp>
#include <graphene/chain/upgrade_event_evaluator.hpp>
#include <graphene/chain/wire_evaluator.hpp>
#include <graphene/chain/wire_out_with_fee_evaluator.hpp>
#include <graphene/chain/withdraw_permission_evaluator.hpp>
#include <graphene/chain/witness_evaluator.hpp>
#include <graphene/chain/worker_evaluator.hpp>

#include <graphene/chain/protocol/fee_schedule.hpp>

#include <fc/uint128.hpp>
#include <fc/crypto/digest.hpp>

#include <boost/algorithm/string.hpp>

#include <cmath>

namespace graphene { namespace chain {

// C++ requires that static class variables declared and initialized
// in headers must also have a definition in a single source file,
// else linker errors will occur [1].
//
// The purpose of this source file is to collect such definitions in
// a single place.
//
// [1] http://stackoverflow.com/questions/8016780/undefined-reference-to-static-constexpr-char

const uint8_t account_object::space_id;
const uint8_t account_object::type_id;

const uint8_t asset_object::space_id;
const uint8_t asset_object::type_id;

const uint8_t block_summary_object::space_id;
const uint8_t block_summary_object::type_id;

const uint8_t call_order_object::space_id;
const uint8_t call_order_object::type_id;

const uint8_t committee_member_object::space_id;
const uint8_t committee_member_object::type_id;

const uint8_t force_settlement_object::space_id;
const uint8_t force_settlement_object::type_id;

const uint8_t global_property_object::space_id;
const uint8_t global_property_object::type_id;

const uint8_t limit_order_object::space_id;
const uint8_t limit_order_object::type_id;

const uint8_t operation_history_object::space_id;
const uint8_t operation_history_object::type_id;

const uint8_t proposal_object::space_id;
const uint8_t proposal_object::type_id;

const uint8_t transaction_object::space_id;
const uint8_t transaction_object::type_id;

const uint8_t vesting_balance_object::space_id;
const uint8_t vesting_balance_object::type_id;

const uint8_t withdraw_permission_object::space_id;
const uint8_t withdraw_permission_object::type_id;

const uint8_t witness_object::space_id;
const uint8_t witness_object::type_id;

const uint8_t worker_object::space_id;
const uint8_t worker_object::type_id;

const uint8_t license_type_object::space_id;
const uint8_t license_type_object::type_id;

const uint8_t account_cycle_balance_object::space_id;
const uint8_t account_cycle_balance_object::type_id;

const uint8_t issue_asset_request_object::space_id;
const uint8_t issue_asset_request_object::type_id;

const uint8_t wire_out_holder_object::space_id;
const uint8_t wire_out_holder_object::type_id;

const uint8_t wire_out_with_fee_holder_object::space_id;
const uint8_t wire_out_with_fee_holder_object::type_id;

const uint8_t payment_service_provider_object::space_id;
const uint8_t payment_service_provider_object::type_id;

const uint8_t reward_queue_object::space_id;
const uint8_t reward_queue_object::type_id;

const uint8_t license_information_object::space_id;
const uint8_t license_information_object::type_id;

const uint8_t issued_asset_record_object::space_id;
const uint8_t issued_asset_record_object::type_id;

const uint8_t frequency_history_record_object::space_id;
const uint8_t frequency_history_record_object::type_id;

const uint8_t upgrade_event_object::space_id;
const uint8_t upgrade_event_object::type_id;

const uint8_t withdrawal_limit_object::space_id;
const uint8_t withdrawal_limit_object::type_id;

void database::initialize_genesis_transaction_state()
{
  // Since this is the database initialization, skip checking signatures:
  _genesis_eval_state = transaction_evaluation_state(this);
  _genesis_eval_state.skip_chain_authority_check = true;
}

void database::initialize_evaluators()
{
   _operation_evaluators.resize(255);
   register_evaluator<account_create_evaluator>();
   register_evaluator<account_update_evaluator>();
   register_evaluator<account_upgrade_evaluator>();
   register_evaluator<account_whitelist_evaluator>();
   register_evaluator<committee_member_create_evaluator>();
   register_evaluator<committee_member_update_evaluator>();
   register_evaluator<committee_member_update_global_parameters_evaluator>();
   register_evaluator<custom_evaluator>();
   register_evaluator<asset_create_evaluator>();
   register_evaluator<asset_issue_evaluator>();
   register_evaluator<asset_reserve_evaluator>();
   register_evaluator<asset_update_evaluator>();
   register_evaluator<asset_update_bitasset_evaluator>();
   register_evaluator<asset_update_feed_producers_evaluator>();
   register_evaluator<asset_settle_evaluator>();
   register_evaluator<asset_global_settle_evaluator>();
   register_evaluator<assert_evaluator>();
   register_evaluator<limit_order_create_evaluator>();
   register_evaluator<limit_order_cancel_evaluator>();
   register_evaluator<call_order_update_evaluator>();
   register_evaluator<transfer_evaluator>();
   register_evaluator<override_transfer_evaluator>();
   register_evaluator<asset_fund_fee_pool_evaluator>();
   register_evaluator<asset_publish_feeds_evaluator>();
   register_evaluator<proposal_create_evaluator>();
   register_evaluator<proposal_update_evaluator>();
   register_evaluator<proposal_delete_evaluator>();
   register_evaluator<vesting_balance_create_evaluator>();
   register_evaluator<vesting_balance_withdraw_evaluator>();
   register_evaluator<remove_root_authority_evaluator>();
   register_evaluator<create_witness_evaluator>();
   register_evaluator<update_witness_evaluator>();
   register_evaluator<remove_witness_evaluator>();
   register_evaluator<activate_witness_evaluator>();
   register_evaluator<deactivate_witness_evaluator>();
   register_evaluator<witness_create_evaluator>();
   register_evaluator<witness_update_evaluator>();
   register_evaluator<withdraw_permission_create_evaluator>();
   register_evaluator<withdraw_permission_claim_evaluator>();
   register_evaluator<withdraw_permission_update_evaluator>();
   register_evaluator<withdraw_permission_delete_evaluator>();
   register_evaluator<worker_create_evaluator>();
   register_evaluator<balance_claim_evaluator>();
   register_evaluator<transfer_to_blind_evaluator>();
   register_evaluator<transfer_from_blind_evaluator>();
   register_evaluator<blind_transfer_evaluator>();
   register_evaluator<asset_claim_fees_evaluator>();
   register_evaluator<board_update_chain_authority_evaluator>();
   register_evaluator<create_license_type_evaluator>();
   register_evaluator<issue_license_evaluator>();
   register_evaluator<tether_accounts_evaluator>();
   // register_evaluator<update_pi_limits_evaluator>();
   register_evaluator<asset_create_issue_request_evaluator>();
   register_evaluator<asset_deny_issue_request_evaluator>();
   register_evaluator<wire_out_evaluator>();
   register_evaluator<wire_out_complete_evaluator>();
   register_evaluator<wire_out_reject_evaluator>();
   register_evaluator<transfer_vault_to_wallet_evaluator>();
   register_evaluator<transfer_wallet_to_vault_evaluator>();
   register_evaluator<submit_reserve_cycles_to_queue_evaluator>();
   register_evaluator<submit_cycles_to_queue_evaluator>();
   register_evaluator<update_queue_parameters_evaluator>();
   register_evaluator<change_public_keys_evaluator>();
   register_evaluator<update_global_frequency_evaluator>();
   register_evaluator<issue_free_cycles_evaluator>();
   register_evaluator<edit_license_type_evaluator>();
   register_evaluator<update_euro_limit_evaluator>();
   register_evaluator<remove_vault_limit_evaluator>();
   register_evaluator<submit_cycles_to_queue_by_license_evaluator>();
   register_evaluator<create_upgrade_event_evaluator>();
   register_evaluator<update_upgrade_event_evaluator>();
   register_evaluator<delete_upgrade_event_evaluator>();
   register_evaluator<update_license_evaluator>();
   register_evaluator<issue_cycles_to_license_evaluator>();
   register_evaluator<change_fee_evaluator>();
   register_evaluator<change_fee_pool_account_evaluator>();
   register_evaluator<purchase_cycles_evaluator>();
   register_evaluator<transfer_cycles_from_licence_to_wallet_evaluator>();
   register_evaluator<wire_out_with_fee_evaluator>();
   register_evaluator<wire_out_with_fee_complete_evaluator>();
   register_evaluator<wire_out_with_fee_reject_evaluator>();
   register_evaluator<set_starting_cycle_asset_amount_evaluator>();
   register_evaluator<set_roll_back_enabled_evaluator>();
   register_evaluator<roll_back_public_keys_evaluator>();
   register_evaluator<fee_pool_cycles_submit_evaluator>();
   register_evaluator<set_chain_authority_evaluator>();
   register_evaluator<register_daspay_authority_evaluator>();
   register_evaluator<unregister_daspay_authority_evaluator>();
   register_evaluator<set_daspay_transaction_ratio_evaluator>();
   register_evaluator<create_payment_service_provider_evaluator>();
   register_evaluator<update_payment_service_provider_evaluator>();
   register_evaluator<delete_payment_service_provider_evaluator>();
   register_evaluator<reserve_asset_on_account_evaluator>();
   register_evaluator<unreserve_asset_on_account_evaluator>();
   register_evaluator<daspay_debit_account_evaluator>();
   register_evaluator<daspay_credit_account_evaluator>();
   register_evaluator<update_daspay_clearing_parameters_evaluator>();
   register_evaluator<das33_project_create_evaluator>();
   register_evaluator<das33_project_update_evaluator>();
   register_evaluator<das33_project_delete_evaluator>();
   register_evaluator<das33_pledge_asset_evaluator>();
   register_evaluator<das33_distribute_project_pledges_evaluator>();
   register_evaluator<das33_project_reject_evaluator>();
   register_evaluator<das33_distribute_pledge_evaluator>();
   register_evaluator<das33_pledge_reject_evaluator>();
   register_evaluator<update_delayed_operations_resolver_parameters_evaluator>();
   register_evaluator<update_global_parameters_evaluator>();
   register_evaluator<update_external_btc_price_evaluator>();
   register_evaluator<das33_set_use_external_btc_price_evaluator>();
   register_evaluator<update_external_token_price_evaluator>();
   register_evaluator<das33_set_use_market_price_for_token_evaluator>();
   register_evaluator<daspay_set_use_external_token_price_evaluator>();
}

void database::initialize_indexes()
{
   reset_indexes();
   _undo_db.set_max_size( GRAPHENE_MIN_UNDO_HISTORY );

   //Protocol object indexes
   add_index< primary_index<asset_index> >();
   add_index< primary_index<force_settlement_index> >();

   auto acnt_index = add_index< primary_index<account_index> >();
   acnt_index->add_secondary_index<account_member_index>();
   acnt_index->add_secondary_index<account_referrer_index>();

   add_index< primary_index<committee_member_index> >();
   add_index< primary_index<witness_index> >();
   add_index< primary_index<limit_order_index > >();
   add_index< primary_index<last_price_index > >();
   add_index< primary_index<external_price_index > >();
   add_index< primary_index<call_order_index > >();

   auto prop_index = add_index< primary_index<proposal_index > >();
   prop_index->add_secondary_index<required_approval_index>();

   add_index< primary_index<withdraw_permission_index > >();
   add_index< primary_index<vesting_balance_index> >();
   add_index< primary_index<worker_index> >();
   add_index< primary_index<balance_index> >();
   add_index< primary_index<blinded_balance_index> >();

   //Implementation object indexes
   add_index< primary_index<transaction_index                             > >();
   add_index< primary_index<account_balance_index                         > >();
   add_index< primary_index<asset_bitasset_data_index                     > >();
   add_index< primary_index<simple_index<global_property_object          >> >();
   add_index< primary_index<simple_index<dynamic_global_property_object  >> >();
   add_index< primary_index<account_stats_index                           > >();
   add_index< primary_index<simple_index<asset_dynamic_data_object       >> >();
   add_index< primary_index<simple_index<block_summary_object            >> >();
   add_index< primary_index<simple_index<chain_property_object          > > >();
   add_index< primary_index<simple_index<witness_schedule_object        > > >();
   add_index< primary_index<simple_index<budget_record_object           > > >();
   add_index< primary_index< special_authority_index                      > >();
   add_index< primary_index< buyback_index                                > >();

   add_index< primary_index< simple_index< fba_accumulator_object       > > >();

   add_index<primary_index<license_type_index>>();
   add_index<primary_index<upgrade_event_index>>();
   add_index<primary_index<account_cycle_balance_index>>();
   add_index<primary_index<issue_asset_request_index>>();
   add_index<primary_index<wire_out_holder_index>>();
   add_index<primary_index<reward_queue_index>>();
   add_index<primary_index<license_information_index>>();
   add_index<primary_index<issued_asset_record_index>>();
   add_index<primary_index<frequency_history_record_index>>();
   add_index<primary_index<witness_delegate_data_index > >();
   add_index<primary_index<wire_out_with_fee_holder_index>>();
   add_index<primary_index<daspay_authority_index>>();
   add_index<primary_index<payment_service_provider_index>>();
   add_index<primary_index<das33_project_index>>();
   add_index<primary_index<das33_pledge_holder_index>>();
   add_index<primary_index<delayed_operations_index>>();
   add_index<primary_index<withdrawal_limit_index>>();
}

account_id_type database::initialize_chain_authority(const string& kind_name, const string& acc_name)
{ try {
   using namespace graphene::chain::util;
   account_id_type account_id = get_account_id(acc_name);

   board_update_chain_authority_operation op;
   op.kind = kind_name;
   op.account = account_id;
   op.committee_member_account = GRAPHENE_COMMITTEE_ACCOUNT;
   apply_operation(_genesis_eval_state, std::move(op));
   return account_id;

} FC_CAPTURE_AND_RETHROW((kind_name)(acc_name)) }

void database::init_genesis(const genesis_state_type& genesis_state)
{ try {

   const auto DASCOIN_DEFAULT_START_PRICE =
      asset{genesis_state.initial_dascoin_price.base_amount, get_dascoin_asset_id()}
      / asset {genesis_state.initial_dascoin_price.quote_amount, get_web_asset_id()};

   const auto BTC_DEFAULT_START_PRICE = price();

   FC_ASSERT( genesis_state.initial_timestamp != time_point_sec(), "Must initialize genesis timestamp." );
   FC_ASSERT( genesis_state.initial_timestamp.sec_since_epoch() % GRAPHENE_DEFAULT_BLOCK_INTERVAL == 0,
              "Genesis timestamp must be divisible by GRAPHENE_DEFAULT_BLOCK_INTERVAL." );
   FC_ASSERT(genesis_state.initial_witness_candidates.size() > 0,
             "Cannot start a chain with zero witnesses.");
   FC_ASSERT(genesis_state.initial_active_witnesses <= genesis_state.initial_witness_candidates.size(),
             "initial_active_witnesses is larger than the number of candidate witnesses.");

   _undo_db.disable();
   struct auth_inhibitor {
      auth_inhibitor(database& db) : db(db), old_flags(db.node_properties().skip_flags)
      { db.node_properties().skip_flags |= skip_authority_check; }
      ~auth_inhibitor()
      { db.node_properties().skip_flags = old_flags; }
   private:
      database& db;
      uint32_t old_flags;
   } inhibitor(*this);

   for (uint32_t i = 0; i <= 0x10000; i++)
     create<block_summary_object>( [&]( block_summary_object&) {});

   // Create blockchain accounts
   fc::ecc::private_key null_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
   create<account_balance_object>([](account_balance_object& b) {
      b.balance = GRAPHENE_MAX_SHARE_SUPPLY;
   });
   const account_object& committee_account =
      create<account_object>( [&](account_object& n) {
         n.kind = account_kind::special;
         n.membership_expiration_date = time_point_sec::maximum();
         n.network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
         n.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT - GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
         n.owner.weight_threshold = 1;
         n.active.weight_threshold = 1;
         n.name = "committee-account";
          n.statistics = create<account_statistics_object>( [&n](account_statistics_object& s){
                           s.owner = n.id;
                           s.name = n.name;
                           s.core_in_balance = GRAPHENE_MAX_SHARE_SUPPLY;
                        }).id;
      });
   FC_ASSERT(committee_account.get_id() == GRAPHENE_COMMITTEE_ACCOUNT);
   FC_ASSERT(create<account_object>([this](account_object& a) {
       a.kind = account_kind::special;
       a.name = "witness-account";
       a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                         s.owner = a.id;
                         s.name = a.name;
                      }).id;
       a.owner.weight_threshold = 1;
       a.active.weight_threshold = 1;
       a.registrar = a.lifetime_referrer = a.referrer = GRAPHENE_WITNESS_ACCOUNT;
       a.membership_expiration_date = time_point_sec::maximum();
       a.network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
       a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT - GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
   }).get_id() == GRAPHENE_WITNESS_ACCOUNT);
   FC_ASSERT(create<account_object>([this](account_object& a) {
       a.kind = account_kind::special;
       a.name = "relaxed-committee-account";
       a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                         s.owner = a.id;
                         s.name = a.name;
                      }).id;
       a.owner.weight_threshold = 1;
       a.active.weight_threshold = 1;
       a.registrar = a.lifetime_referrer = a.referrer = GRAPHENE_RELAXED_COMMITTEE_ACCOUNT;
       a.membership_expiration_date = time_point_sec::maximum();
       a.network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
       a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT - GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
   }).get_id() == GRAPHENE_RELAXED_COMMITTEE_ACCOUNT);
   FC_ASSERT(create<account_object>([this](account_object& a) {
       a.kind = account_kind::special;
       a.name = "null-account";
       a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                         s.owner = a.id;
                         s.name = a.name;
                      }).id;
       a.owner.weight_threshold = 1;
       a.active.weight_threshold = 1;
       a.registrar = a.lifetime_referrer = a.referrer = GRAPHENE_NULL_ACCOUNT;
       a.membership_expiration_date = time_point_sec::maximum();
       a.network_fee_percentage = 0;
       a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT;
   }).get_id() == GRAPHENE_NULL_ACCOUNT);
   FC_ASSERT(create<account_object>([this](account_object& a) {
       a.kind = account_kind::special;
       a.name = "temp-account";
       a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                         s.owner = a.id;
                         s.name = a.name;
                      }).id;
       a.owner.weight_threshold = 0;
       a.active.weight_threshold = 0;
       a.registrar = a.lifetime_referrer = a.referrer = GRAPHENE_TEMP_ACCOUNT;
       a.membership_expiration_date = time_point_sec::maximum();
       a.network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
       a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT - GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
       create_empty_balance(a.id, get_cycle_asset_id());
   }).get_id() == GRAPHENE_TEMP_ACCOUNT);
   FC_ASSERT(create<account_object>([this](account_object& a) {
       a.kind = account_kind::special;
       a.name = "proxy-to-self";
       a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                         s.owner = a.id;
                         s.name = a.name;
                      }).id;
       a.owner.weight_threshold = 1;
       a.active.weight_threshold = 1;
       a.registrar = a.lifetime_referrer = a.referrer = GRAPHENE_NULL_ACCOUNT;
       a.membership_expiration_date = time_point_sec::maximum();
       a.network_fee_percentage = 0;
       a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT;
   }).get_id() == GRAPHENE_PROXY_TO_SELF_ACCOUNT);

   // Create more special accounts
   while( true )
   {
      uint64_t id = get_index<account_object>().get_next_id().instance();
      if( id >= genesis_state.immutable_parameters.num_special_accounts )
         break;
      const account_object& acct = create<account_object>([this,id](account_object& a) {
          a.kind = account_kind::special;
          a.name = "special-account-" + std::to_string(id);
          a.statistics = create<account_statistics_object>([&a](account_statistics_object& s){
                            s.owner = a.id;
                            s.name = a.name;
                         }).id;
          a.owner.weight_threshold = 1;
          a.active.weight_threshold = 1;
          a.registrar = a.lifetime_referrer = a.referrer = account_id_type(id);
          a.membership_expiration_date = time_point_sec::maximum();
          a.network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
          a.lifetime_referrer_fee_percentage = GRAPHENE_100_PERCENT - GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
      });
      FC_ASSERT( acct.get_id() == account_id_type(id) );
      remove( acct );
   }

   // TODO: use contexpr, do not perform asserts.
   FC_ASSERT(DASCOIN_DEFAULT_ASSET_PRECISION == pow(10, DASCOIN_DEFAULT_ASSET_PRECISION_DIGITS),
             "Dascoin default asset precision is invalid, check config");

   FC_ASSERT(DASCOIN_FIAT_ASSET_PRECISION == pow(10, DASCOIN_FIAT_ASSET_PRECISION_DIGITS),
             "Fiat default asset precision is invalid, check config");

   // Create core asset;
   const asset_dynamic_data_object& core_dyn_asset =
      create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a) {
         a.current_supply = GRAPHENE_MAX_SHARE_SUPPLY;
      });
   const asset_object& core_asset =
     create<asset_object>( [&]( asset_object& a ) {
         a.symbol = GRAPHENE_SYMBOL;
         a.options.max_supply = genesis_state.max_core_supply;
         a.precision = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS;
         a.options.flags = 0;
         a.options.issuer_permissions = 0;
         a.issuer = GRAPHENE_NULL_ACCOUNT;
         a.options.core_exchange_rate.base.amount = 1;
         a.options.core_exchange_rate.base.asset_id = asset_id_type(0);
         a.options.core_exchange_rate.quote.amount = 1;
         a.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
         a.dynamic_asset_data_id = core_dyn_asset.id;
      });
   assert( asset_id_type(core_asset.id) == asset().asset_id );
   assert( get_balance(account_id_type(), asset_id_type()) == asset(core_dyn_asset.current_supply) );

   // Create web assets:
   const auto& web_dyn_asset = create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a){
         a.current_supply = 0;  // Web starts with 0 initial supply.
      });
   const asset_object& web_asset =
     create<asset_object>( [&]( asset_object& a ) {
         a.symbol = DASCOIN_WEBASSET_SYMBOL;
         a.options.max_supply = genesis_state.max_core_supply;  // TODO: this should remain 10 trillion?
         a.precision = DASCOIN_FIAT_ASSET_PRECISION_DIGITS;
         a.options.flags = WEB_ASSET_INITIAL_FLAGS;
         a.options.issuer_permissions = WEB_ASSET_ISSUER_PERMISSION_MASK;  // TODO: set the appropriate issuer permissions.
         a.issuer = GRAPHENE_NULL_ACCOUNT;
         a.authenticator = GRAPHENE_NULL_ACCOUNT;
         // TODO: figure out the base conversion rates.
         a.options.core_exchange_rate.base.amount = 1;
         a.options.core_exchange_rate.base.asset_id = asset_id_type(0);
         a.options.core_exchange_rate.quote.amount = 1;
         a.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
         a.dynamic_asset_data_id = web_dyn_asset.id;
      });
   FC_ASSERT( asset_id_type(web_asset.id) == get_web_asset_id() );

   // Create dascoin asset:
   const auto& dascoin_dyn_asset = create<asset_dynamic_data_object>([&](asset_dynamic_data_object& adao){
      adao.current_supply = 0;
   });

   const asset_object& dasc_asset = create<asset_object>([&](asset_object& ao){
      ao.symbol = DASCOIN_DASCOIN_SYMBOL;
      ao.options.max_supply = DASCOIN_MAX_DASCOIN_SUPPLY * DASCOIN_DEFAULT_ASSET_PRECISION + DASCOIN_MAX_DASCOIN_SUPPLY_DECIMALS;
      ao.precision = DASCOIN_DEFAULT_ASSET_PRECISION_DIGITS;
      ao.options.flags = DASCOIN_ASSET_INITIAL_FLAGS;
      ao.options.issuer_permissions = WEB_ASSET_ISSUER_PERMISSION_MASK;
      ao.issuer = GRAPHENE_NULL_ACCOUNT;
      ao.authenticator = GRAPHENE_NULL_ACCOUNT;
      // TODO: the base conversion rates are ignored.
      ao.options.core_exchange_rate.base.amount = 1;
      ao.options.core_exchange_rate.base.asset_id = asset_id_type(0);
      ao.options.core_exchange_rate.quote.amount = 1;
      ao.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
      ao.dynamic_asset_data_id = dascoin_dyn_asset.id;
   });

   // Create cycle assets:
   const auto& cycle_dyn_asset = create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a){
         a.current_supply = 0;  // Cycle starts with 0 initial supply.
      });
   create<asset_object>( [&]( asset_object& a ) {
      a.symbol = DASCOIN_CYCLE_ASSET_SYMBOL;
      a.options.max_supply = genesis_state.max_core_supply;  // TODO: this should remain 10 trillion?
      a.precision = DASCOIN_CYCLE_ASSET_PRECISION_DIGITS;
      a.options.flags = WEB_ASSET_INITIAL_FLAGS;
      a.options.issuer_permissions = WEB_ASSET_ISSUER_PERMISSION_MASK;  // TODO: set the appropriate issuer permissions.
      a.issuer = GRAPHENE_NULL_ACCOUNT;
      a.authenticator = GRAPHENE_NULL_ACCOUNT;
      // TODO: figure out the base conversion rates.
      a.options.core_exchange_rate.base.amount = 1;
      a.options.core_exchange_rate.base.asset_id = asset_id_type(3);
      a.options.core_exchange_rate.quote.amount = 1;
      a.options.core_exchange_rate.quote.asset_id = asset_id_type(3);
      a.dynamic_asset_data_id = cycle_dyn_asset.id;
   });

   // Create bitcoin assets:
   const auto& bitcoin_dyn_asset = create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a){
         a.current_supply = 0;  // Cycle starts with 0 initial supply.
      });
   const asset_object& btc_asset = create<asset_object>( [&]( asset_object& a ) {
      a.symbol = DASCOIN_BITCOIN_SYMBOL;
      a.options.max_supply = genesis_state.max_bitcoin_supply * DASCOIN_BITCOIN_PRECISION;
      a.precision = DASCOIN_BITCOIN_PRECISION_DIGITS;
      a.options.flags = BITCOIN_ASSET_INITIAL_FLAGS; //
      a.options.issuer_permissions = WEB_ASSET_ISSUER_PERMISSION_MASK;  // TODO: set the appropriate issuer permissions.
      a.issuer = GRAPHENE_NULL_ACCOUNT;
      a.authenticator = GRAPHENE_NULL_ACCOUNT;
      // TODO: figure out the base conversion rates.
      a.options.core_exchange_rate.base.amount = 1;
      a.options.core_exchange_rate.base.asset_id = asset_id_type(0);
      a.options.core_exchange_rate.quote.amount = 1;
      a.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
      a.dynamic_asset_data_id = bitcoin_dyn_asset.id;
   });

   // Create one placeholder asset for id 1.3.5
   const asset_dynamic_data_object& placholder_dyn_asset =
     create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a) {
       a.current_supply = 0;
     });
   const asset_object& placeholder_asset_obj = create<asset_object>( [&]( asset_object& a ) {
     a.symbol = "PLCHLD";
     a.options.max_supply = GRAPHENE_MAX_SHARE_SUPPLY;
     a.precision = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS;
     a.options.flags = 0;
     a.options.issuer_permissions = 0;
     a.issuer = GRAPHENE_NULL_ACCOUNT;
     a.options.core_exchange_rate.base.amount = 1;
     a.options.core_exchange_rate.base.asset_id = asset_id_type(0);
     a.options.core_exchange_rate.quote.amount = 1;
     a.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
     a.dynamic_asset_data_id = placholder_dyn_asset.id;
   });

   // Create more special assets
   while( true )
   {
      uint64_t id = get_index<asset_object>().get_next_id().instance();
      //Note: this is a workaround so we do not change genesis.json
      //if( id >= genesis_state.immutable_parameters.num_special_assets )
      if ( id >= DASCOIN_PLACEHOLDER_ASSET_COUNT)
         break;
      const asset_dynamic_data_object& dyn_asset =
         create<asset_dynamic_data_object>([&](asset_dynamic_data_object& a) {
            a.current_supply = 0;
         });
      const asset_object& asset_obj = create<asset_object>( [&]( asset_object& a ) {
         a.symbol = "SPECIAL" + std::to_string( id );
         a.options.max_supply = 0;
         a.precision = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS;
         a.options.flags = 0;
         a.options.issuer_permissions = 0;
         a.issuer = GRAPHENE_NULL_ACCOUNT;
         a.options.core_exchange_rate.base.amount = 1;
         a.options.core_exchange_rate.base.asset_id = asset_id_type(0);
         a.options.core_exchange_rate.quote.amount = 1;
         a.options.core_exchange_rate.quote.asset_id = asset_id_type(0);
         a.dynamic_asset_data_id = dyn_asset.id;
      });
      FC_ASSERT( asset_obj.get_id() == asset_id_type(id) );
      remove( asset_obj );
   }

   // Create null das33 project and pledge
   create<das33_project_object>( [&](das33_project_object& a){});
   create<das33_pledge_holder_object>( [&](das33_pledge_holder_object& a){});

   chain_id_type chain_id = genesis_state.compute_chain_id();

   // Create global properties
   create<global_property_object>([&](global_property_object& p) {
       auto fee_schedule_temp = fee_schedule::get_default();
       p.parameters = genesis_state.initial_parameters;
       for(auto param : fee_schedule_temp.parameters)
       {
          if( p.parameters.current_fees->parameters.find(param) == p.parameters.current_fees->parameters.end() )
          {
             p.parameters.current_fees->parameters.insert(param);
          }
       }

       // Set fees to zero initially, so that genesis initialization needs not pay them
       // We'll fix it at the end of the function
       p.parameters.current_fees->zero_all_fees();

   });
   create<dynamic_global_property_object>([&](dynamic_global_property_object& p) {
      p.time = genesis_state.initial_timestamp;
      p.dynamic_flags = 0;
      p.witness_budget = 0;
      p.recent_slots_filled = fc::uint128::max_value();
      p.frequency = genesis_state.initial_frequency;
      p.last_dascoin_price = DASCOIN_DEFAULT_START_PRICE;
      p.last_btc_price = BTC_DEFAULT_START_PRICE;
      p.external_btc_price = BTC_DEFAULT_START_PRICE;
      p.last_daily_dascoin_price = DASCOIN_DEFAULT_START_PRICE;
   });

   FC_ASSERT( (genesis_state.immutable_parameters.min_witness_count & 1) == 1, "min_witness_count must be odd" );
   FC_ASSERT( (genesis_state.immutable_parameters.min_committee_member_count & 1) == 1, "min_committee_member_count must be odd" );

   create<chain_property_object>([&](chain_property_object& p)
   {
      p.chain_id = chain_id;
      p.immutable_parameters = genesis_state.immutable_parameters;
   } );
   create<block_summary_object>([&](block_summary_object&) {});

   // Create initial accounts
   for( const auto& account : genesis_state.initial_accounts )
   {
      account_create_operation cop;
      cop.name = account.name;
      cop.registrar = GRAPHENE_TEMP_ACCOUNT;
      cop.owner = authority(1, account.owner_key, 1);
      cop.kind = static_cast<uint8_t>(account_kind::special);
      if( account.active_key == public_key_type() )
      {
         cop.active = cop.owner;
         cop.options.memo_key = account.owner_key;
      }
      else
      {
         cop.active = authority(1, account.active_key, 1);
         cop.options.memo_key = account.active_key;
      }
      account_id_type account_id(apply_operation(_genesis_eval_state, cop).get<object_id_type>());

      if( account.is_lifetime_member )
      {
          account_upgrade_operation op;
          op.account_to_upgrade = account_id;
          op.upgrade_to_lifetime_member = true;
          apply_operation(_genesis_eval_state, op);
      }
   }

   map<asset_id_type, share_type> total_supplies;
   map<asset_id_type, share_type> total_debts;

   // Create initial assets
   for( const genesis_state_type::initial_asset_type& asset : genesis_state.initial_assets )
   {
      asset_id_type new_asset_id = get_index_type<asset_index>().get_next_id();
      total_supplies[ new_asset_id ] = 0;

      asset_dynamic_data_id_type dynamic_data_id;
      optional<asset_bitasset_data_id_type> bitasset_data_id;
      if( asset.is_bitasset )
      {
         int collateral_holder_number = 0;
         total_debts[ new_asset_id ] = 0;
         for( const auto& collateral_rec : asset.collateral_records )
         {
            account_create_operation cop;
            cop.name = asset.symbol + "-collateral-holder-" + std::to_string(collateral_holder_number);
            boost::algorithm::to_lower(cop.name);
            cop.registrar = GRAPHENE_TEMP_ACCOUNT;
            cop.owner = authority(1, collateral_rec.owner, 1);
            cop.active = cop.owner;
            account_id_type owner_account_id = apply_operation(_genesis_eval_state, cop).get<object_id_type>();

            modify( owner_account_id(*this).statistics(*this), [&]( account_statistics_object& o ) {
                    o.total_core_in_orders = collateral_rec.collateral;
                    });

            create<call_order_object>([&](call_order_object& c) {
               c.borrower = owner_account_id;
               c.collateral = collateral_rec.collateral;
               c.debt = collateral_rec.debt;
               c.call_price = price::call_price(chain::asset(c.debt, new_asset_id),
                                                chain::asset(c.collateral, core_asset.id),
                                                GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO);
            });

            total_supplies[ asset_id_type(0) ] += collateral_rec.collateral;
            total_debts[ new_asset_id ] += collateral_rec.debt;
            ++collateral_holder_number;
         }

         bitasset_data_id = create<asset_bitasset_data_object>([&](asset_bitasset_data_object& b) {
            b.options.short_backing_asset = core_asset.id;
            b.options.minimum_feeds = GRAPHENE_DEFAULT_MINIMUM_FEEDS;
         }).id;
      }

      dynamic_data_id = create<asset_dynamic_data_object>([&](asset_dynamic_data_object& d) {
         d.accumulated_fees = asset.accumulated_fees;
      }).id;

      total_supplies[ new_asset_id ] += asset.accumulated_fees;

      create<asset_object>([&](asset_object& a) {
         a.symbol = asset.symbol;
         a.options.description = asset.description;
         a.precision = asset.precision;
         string issuer_name = asset.issuer_name;
         a.issuer = get_account_id(issuer_name);
         a.options.max_supply = asset.max_supply;
         a.options.flags = witness_fed_asset;
         a.options.issuer_permissions = charge_market_fee | global_settle | witness_fed_asset | committee_fed_asset;
         a.dynamic_asset_data_id = dynamic_data_id;
         a.bitasset_data_id = bitasset_data_id;
      });
   }

   // Create initial balances
   share_type total_allocation;
   for( const auto& handout : genesis_state.initial_balances )
   {
      const auto asset_id = get_asset_id(handout.asset_symbol);
      create<balance_object>([&handout,total_allocation,asset_id](balance_object& b) {
         b.balance = asset(handout.amount, asset_id);
         b.owner = handout.owner;
      });

      total_supplies[ asset_id ] += handout.amount;
   }

   // Create initial vesting balances
   for( const genesis_state_type::initial_vesting_balance_type& vest : genesis_state.initial_vesting_balances )
   {
      const auto asset_id = get_asset_id(vest.asset_symbol);
      create<balance_object>([&](balance_object& b) {
         b.owner = vest.owner;
         b.balance = asset(vest.amount, asset_id);

         linear_vesting_policy policy;
         policy.begin_timestamp = vest.begin_timestamp;
         policy.vesting_cliff_seconds = 0;
         policy.vesting_duration_seconds = vest.vesting_duration_seconds;
         policy.begin_balance = vest.begin_balance;

         b.vesting_policy = std::move(policy);
      });

      total_supplies[ asset_id ] += vest.amount;
   }

   if( total_supplies[ asset_id_type(0) ] > 0 )
   {
       adjust_balance(GRAPHENE_COMMITTEE_ACCOUNT, -get_balance(GRAPHENE_COMMITTEE_ACCOUNT,{}));
   }
   else
   {
       total_supplies[ asset_id_type(0) ] = GRAPHENE_MAX_SHARE_SUPPLY;
   }

   const auto& idx = get_index_type<asset_index>().indices().get<by_symbol>();
   auto it = idx.begin();
   bool has_imbalanced_assets = false;

   while( it != idx.end() )
   {
      if( it->bitasset_data_id.valid() )
      {
         auto supply_itr = total_supplies.find( it->id );
         auto debt_itr = total_debts.find( it->id );
         FC_ASSERT( supply_itr != total_supplies.end() );
         FC_ASSERT( debt_itr != total_debts.end() );
         if( supply_itr->second != debt_itr->second )
         {
            has_imbalanced_assets = true;
            elog( "Genesis for asset ${aname} is not balanced\n"
                  "   Debt is ${debt}\n"
                  "   Supply is ${supply}\n",
                  ("debt", debt_itr->second)
                  ("supply", supply_itr->second)
                );
         }
      }
      ++it;
   }
   FC_ASSERT( !has_imbalanced_assets );

   // Save tallied supplies
   for( const auto& item : total_supplies )
   {
       const auto asset_id = item.first;
       const auto total_supply = item.second;

       modify( get( asset_id ), [ & ]( asset_object& asset ) {
           modify( get( asset.dynamic_asset_data_id ), [ & ]( asset_dynamic_data_object& asset_data ) {
               asset_data.current_supply = total_supply;
           } );
       } );
   }

   // Create special witness account
   const witness_object& wit = create<witness_object>([&](witness_object& w) {});
   FC_ASSERT( wit.id == GRAPHENE_NULL_WITNESS );
   remove(wit);

   // Create initial witnesses
   std::for_each(genesis_state.initial_witness_candidates.begin(), genesis_state.initial_witness_candidates.end(),
                 [&](const genesis_state_type::initial_witness_type& witness) {
      witness_create_operation op;
      op.witness_account = get_account_id(witness.owner_name);
      op.block_signing_key = witness.block_signing_key;
      apply_operation(_genesis_eval_state, op);
   });

   // Create initial committee members
   std::for_each(genesis_state.initial_committee_candidates.begin(), genesis_state.initial_committee_candidates.end(),
                 [&](const genesis_state_type::initial_committee_member_type& member) {
      committee_member_create_operation op;
      op.committee_member_account = get_account_id(member.owner_name);
      apply_operation(_genesis_eval_state, op);
   });

   // Create initial workers
   std::for_each(genesis_state.initial_worker_candidates.begin(), genesis_state.initial_worker_candidates.end(),
                  [&](const genesis_state_type::initial_worker_type& worker)
   {
       worker_create_operation op;
       op.owner = get_account_id(worker.owner_name);
       op.work_begin_date = genesis_state.initial_timestamp;
       op.work_end_date = time_point_sec::maximum();
       op.daily_pay = worker.daily_pay;
       op.name = "Genesis-Worker-" + worker.owner_name;
       op.initializer = vesting_balance_worker_initializer{uint16_t(0)};

       apply_operation(_genesis_eval_state, std::move(op));
   });

   initialize_chain_authority("root_administrator", genesis_state.initial_root_authority.owner_name);

   initialize_chain_authority("license_administrator", genesis_state.initial_license_administration_authority.owner_name);
   initialize_chain_authority("license_issuer", genesis_state.initial_license_issuing_authority.owner_name);
   initialize_chain_authority("webasset_issuer", genesis_state.initial_webasset_issuing_authority.owner_name);
   initialize_chain_authority("webasset_authenticator", genesis_state.initial_webasset_authentication_authority.owner_name);
   initialize_chain_authority("cycle_issuer", genesis_state.initial_cycle_issuing_authority.owner_name);
   initialize_chain_authority("cycle_authenticator", genesis_state.initial_cycle_authentication_authority.owner_name);
   initialize_chain_authority("registrar", genesis_state.initial_registrar.owner_name);
   initialize_chain_authority("pi_validator", genesis_state.initial_personal_identity_validation_authority.owner_name);
   initialize_chain_authority("wire_out_handler", genesis_state.initial_wire_out_handler.owner_name);
   if (genesis_state.initial_daspay_administrator_authority.owner_name.length() > 0)
   {
     initialize_chain_authority("daspay_administrator", genesis_state.initial_daspay_administrator_authority.owner_name);
   }
   if (genesis_state.initial_das33_administrator_authority.owner_name.length() > 0)
   {
     initialize_chain_authority("das33_administrator", genesis_state.initial_das33_administrator_authority.owner_name);
   }

   // Set up web asset issuer and authenticator:
   // TODO: refactor this to be handled all at once.
   modify(web_asset, [&](asset_object& a){
      auto& ca = get_chain_authorities();
      a.issuer = ca.webasset_issuer;
      a.authenticator = ca.webasset_authenticator;
   });

   modify(dasc_asset, [&](asset_object& a){
      auto& ca = get_chain_authorities();
      a.issuer = ca.webasset_issuer;
      a.authenticator = ca.webasset_authenticator;
   });

   modify(btc_asset, [&](asset_object& a){
      auto& ca = get_chain_authorities();
      a.issuer = ca.webasset_issuer;
      a.authenticator = ca.webasset_authenticator;
   });

   modify(placeholder_asset_obj, [&](asset_object& a){
     auto& ca = get_chain_authorities();
     a.issuer = ca.webasset_issuer;
     a.authenticator = ca.webasset_authenticator;
   });

   // Initialize licenses:
   // NOTE: preserve the order of licenses to avoid breaking compatibility.
   {
      // No license placeholder:
      FC_ASSERT( create_license_type(license_kind::none, "no_license", 0, {}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_ADVOCATE) == DASCOIN_NULL_LICENSE );

      create_license_type(license_kind::regular, "standard", DASCOIN_BASE_STANDARD_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_STANDARD);
      create_license_type(license_kind::regular, "manager", DASCOIN_BASE_MANAGER_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_MANAGER);
      create_license_type(license_kind::regular, "pro", DASCOIN_BASE_PRO_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRO);
      create_license_type(license_kind::regular, "executive", DASCOIN_BASE_EXECUTIVE_CYCLES, {2,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_EXECUTIVE);
      create_license_type(license_kind::regular, "vice_president", DASCOIN_BASE_VICE_PRESIDENT_CYCLES, {2,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_VICE_PRESIDENT);
      create_license_type(license_kind::regular, "president", DASCOIN_BASE_PRESIDENT_CYCLES, {2,2,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRESIDENT);

      create_license_type(license_kind::chartered, "standard_charter", DASCOIN_BASE_STANDARD_CYCLES, {1}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_STANDARD);
      create_license_type(license_kind::chartered, "manager_charter", DASCOIN_BASE_MANAGER_CYCLES, {1}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_MANAGER);
      create_license_type(license_kind::chartered, "pro_charter", DASCOIN_BASE_PRO_CYCLES, {1}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRO);
      create_license_type(license_kind::chartered, "executive_charter", DASCOIN_BASE_EXECUTIVE_CYCLES, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_EXECUTIVE);
      create_license_type(license_kind::chartered, "vice_president_charter", DASCOIN_BASE_VICE_PRESIDENT_CYCLES, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_VICE_PRESIDENT);
      create_license_type(license_kind::chartered, "president_charter", DASCOIN_BASE_PRESIDENT_CYCLES, {1,2,4}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRESIDENT);

      create_license_type(license_kind::locked_frequency, "standard_locked", DASCOIN_BASE_STANDARD_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_STANDARD);
      create_license_type(license_kind::locked_frequency, "manager_locked", DASCOIN_BASE_MANAGER_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_MANAGER);
      create_license_type(license_kind::locked_frequency, "pro_locked", DASCOIN_BASE_PRO_CYCLES, {2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRO);
      create_license_type(license_kind::locked_frequency, "executive_locked", DASCOIN_BASE_EXECUTIVE_CYCLES, {2,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_EXECUTIVE);
      create_license_type(license_kind::locked_frequency, "vice_president_locked", DASCOIN_BASE_VICE_PRESIDENT_CYCLES, {2,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_VICE_PRESIDENT);
      create_license_type(license_kind::locked_frequency, "president_locked", DASCOIN_BASE_PRESIDENT_CYCLES, {1,2,4}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRESIDENT, license_type_object::upgrade_policy::president);

      create_license_type(license_kind::utility, "standard_utility", DASCOIN_BASE_STANDARD_CYCLES, {1,2,4,8}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_STANDARD, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::utility, "manager_utility", DASCOIN_BASE_MANAGER_CYCLES, {1,2,4,8}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_MANAGER, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::utility, "pro_utility", DASCOIN_BASE_PRO_CYCLES, {1,2,4,8}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRO, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::utility, "executive_utility", DASCOIN_BASE_EXECUTIVE_CYCLES_NEW_VALUE, {1,2,4,8}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_EXECUTIVE, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::utility, "vice_president_utility", DASCOIN_BASE_VICE_PRESIDENT_CYCLES_NEW_VALUE, {1,2,4,8}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_VICE_PRESIDENT, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::utility, "president_utility", DASCOIN_BASE_PRESIDENT_CYCLES, {1,2,4,8,16}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRESIDENT, license_type_object::upgrade_policy::utility);

      create_license_type(license_kind::package, "starter_package", DASCOIN_BASE_STANDARD_CYCLES, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_STANDARD, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::package, "basic_package", DASCOIN_BASE_MANAGER_CYCLES, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_MANAGER, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::package, "power_package", DASCOIN_BASE_PRO_CYCLES, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRO, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::package, "prime_package", DASCOIN_BASE_EXECUTIVE_CYCLES_NEW_VALUE, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_EXECUTIVE, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::package, "superior_package", DASCOIN_BASE_VICE_PRESIDENT_CYCLES_NEW_VALUE, {1,2}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_VICE_PRESIDENT, license_type_object::upgrade_policy::utility);
      create_license_type(license_kind::package, "ultimate_package", DASCOIN_BASE_PRESIDENT_CYCLES, {1,2,4}, {}, {}, DASCOIN_DEFAULT_EUR_LIMIT_PRESIDENT, license_type_object::upgrade_policy::utility);
   }

   // Create historic upgrade events:
   for (const auto& historic_upgrade : genesis_state.historic_upgrade_events)
   {
     create<upgrade_event_object>([&historic_upgrade](upgrade_event_object &o) {
       o.execution_time = historic_upgrade.execution_time;
       o.cutoff_time = historic_upgrade.cutoff_time;
       o.subsequent_execution_times = historic_upgrade.subsequent_executions;
       o.comment = historic_upgrade.comment;
       o.historic = true;
     });
   }

   // Set active witnesses
   modify(get_global_properties(), [&](global_property_object& p) {
      for( uint32_t i = 1; i <= genesis_state.initial_active_witnesses; ++i )
      {
         p.active_witnesses.insert(witness_id_type(i));
      }
   });

   // Enable fees
   modify(get_global_properties(), [&genesis_state](global_property_object& p) {
      p.parameters.current_fees = genesis_state.initial_parameters.current_fees;
   });

   // Create witness scheduler
   create<witness_schedule_object>([&]( witness_schedule_object& wso )
   {
      for( const witness_id_type& wid : get_global_properties().active_witnesses )
         wso.current_shuffled_witnesses.push_back( wid );
   });

   // Create FBA counters
   create<fba_accumulator_object>([&]( fba_accumulator_object& acc )
   {
      FC_ASSERT( acc.id == fba_accumulator_id_type( fba_accumulator_id_transfer_to_blind ) );
      acc.accumulated_fba_fees = 0;
#ifdef GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET
      acc.designated_asset = GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET;
#endif
   });

   create<fba_accumulator_object>([&]( fba_accumulator_object& acc )
   {
      FC_ASSERT( acc.id == fba_accumulator_id_type( fba_accumulator_id_blind_transfer ) );
      acc.accumulated_fba_fees = 0;
#ifdef GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET
      acc.designated_asset = GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET;
#endif
   });

   create<fba_accumulator_object>([&]( fba_accumulator_object& acc )
   {
      FC_ASSERT( acc.id == fba_accumulator_id_type( fba_accumulator_id_transfer_from_blind ) );
      acc.accumulated_fba_fees = 0;
#ifdef GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET
      acc.designated_asset = GRAPHENE_FBA_STEALTH_DESIGNATED_ASSET;
#endif
   });

   FC_ASSERT( get_index<fba_accumulator_object>().get_next_id() == fba_accumulator_id_type( fba_accumulator_id_count ) );

   debug_dump();

   _undo_db.enable();
} FC_CAPTURE_AND_RETHROW() }

} }

max_stars_repo_name: powerchain-ltd/greenpower-blockchain


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2014 Roshan <thisisroshansmail@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//

#ifndef BOOST_COMPUTE_ALGORITHM_DETAIL_SEARCH_ALL_HPP
#define BOOST_COMPUTE_ALGORITHM_DETAIL_SEARCH_ALL_HPP

#include <boost/compute/algorithm/copy.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/detail/iterator_range_size.hpp>
#include <boost/compute/detail/meta_kernel.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/system.hpp>

namespace boost {
namespace compute {
namespace detail {

///
/// \brief Search kernel class
///
/// Subclass of meta_kernel which is capable of performing pattern matching
///
template<class PatternIterator, class TextIterator, class OutputIterator>
class search_kernel : public meta_kernel
{
public:
    search_kernel() : meta_kernel("search")
    {}

    void set_range(PatternIterator p_first,
                   PatternIterator p_last,
                   TextIterator t_first,
                   TextIterator t_last,
                   OutputIterator result)
    {
        m_p_count = iterator_range_size(p_first, p_last);
        m_p_count_arg = add_arg<uint_>("p_count");

        m_count = iterator_range_size(t_first, t_last);
        m_count = m_count + 1 - m_p_count;

        *this <<
            "uint i = get_global_id(0);\n" <<
            "uint i1 = i;\n" <<
            "uint j;\n" <<
            "for(j = 0; j<p_count; j++,i++)\n" <<
            "{\n" <<
            "   if(" << p_first[expr<uint_>("j")] << " != " <<
                    t_first[expr<uint_>("i")] << ")\n" <<
            "       j = p_count + 1;\n" <<
            "}\n" <<
            "if(j == p_count)\n" <<
            result[expr<uint_>("i1")] << " = 1;\n" <<
            "else\n" <<
            result[expr<uint_>("i1")] << " = 0;\n";
    }

    event exec(command_queue &queue)
    {
        if(m_count == 0) {
            return event();
        }

        set_arg(m_p_count_arg, uint_(m_p_count));

        return exec_1d(queue, 0, m_count);
    }

private:
    size_t m_p_count;
    size_t m_p_count_arg;
    size_t m_count;
};

} //end detail namespace
} //end compute namespace
} //end boost namespace

#endif // BOOST_COMPUTE_ALGORITHM_DETAIL_SEARCH_ALL_HPP

ext: hpp


text:
#include "stdafx.h"
#include <boost/log/common.hpp>
#include <boost/thread/tss.hpp>
#include "LogStream.h"
#include "Logging.h"

using namespace boost::log;

namespace Logging
{
	/*static*/ sources::severity_logger<Logging::Severity>& LogStream::GetLogger()
	{
		static boost::thread_specific_ptr<sources::severity_logger<Logging::Severity>> s_threadLocalLogger;
		if (!s_threadLocalLogger.get())
		{
			s_threadLocalLogger.reset(new sources::severity_logger<Logging::Severity>());
		}
		return *(s_threadLocalLogger.get());
	}

	/*static*/ record LogStream::OpenRecord(std::string&& eventId, Severity severity)
	{
		if (!LoggingModule::IsEnabled())
			return record{};

		auto& logger = GetLogger();
		auto attributeToRemove = logger.add_attribute("EventId", attributes::constant<std::string>(std::move(eventId))).first;
		auto record = logger.open_record(::keywords::severity = severity);
		logger.remove_attribute(attributeToRemove);
		return record;
	}

	LogStream::LogStream(std::string&& eventId, Severity severity) :
		m_record(OpenRecord(std::move(eventId), severity))
	{
		if (m_record)
			m_stream.attach_record(m_record);
	}

	LogStream::~LogStream()
	{
		if (m_record)
		{
			m_stream.flush();
			auto& logger = GetLogger();
			logger.push_record(std::move(m_record));
		}
	}
}

ext: cpp

max_stars_repo_name: cmarcusreid/git-status-cache

max_issues_repo_name: cmarcusreid/git-status-cache

max_forks_repo_name: cmarcusreid/git-status-cache


text:
#include <boost/function.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <boost/thread/thread.hpp>
#include <eosio/chain/micropython_interface.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/apply_context.hpp>

#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "Runtime/Runtime.h"
#include "Runtime/Linker.h"
#include "Runtime/Intrinsics.h"
#include "IR/Module.h"
#include "IR/Operators.h"
#include "IR/Validate.h"
#include <chrono>
#include <appbase/application.hpp>
#include <fc/crypto/xxhash.h>

#include <eosio/chain/db_api.hpp>

#include "micropython/mpeoslib.h"
//#include "rpc_interface/rpc_interface.hpp"

#if 0
extern "C" void print_time() {
   ilog("fc::time_point::microseconds() ${n}", ("n", fc::time_point::now()));
}
#endif

namespace eosio {
namespace chain {

bool get_code(uint64_t _account, std::vector<uint8_t>& v) {
   return apply_context::ctx().get_code(_account, v);
}
bool get_code_size(uint64_t _account, int& size) {
   return apply_context::ctx().get_code_size(_account, size);
}

micropython_interface::micropython_interface() {
}

micropython_interface& micropython_interface::get() {
   static micropython_interface* python = nullptr;
   if (!python) {
      wlog("micropython_interface::init");
      python = new micropython_interface();
   }
   return *python;
}

// 'storage.py'
const char * init_mp = "" \
"libs = ('asset.py', 'token.py', 'cache.py', 'garden.py', 'solidity.py', 'storage.py')\n" \
"for lib in libs:\n" \
"    mod = 'backyard.'+lib[:-3]\n" \
"    print(mod)\n"
"    __import__(mod)\n"
;

void init() {
   if (get_mpapi().init) {
      return;
   }
   wlog("Initialize common library.");

   uint64_t hash = XXH64("storage.mpy", strlen("storage.mpy"), 0);

   int itr = db_api::get().db_find_i64(N(backyard), N(backyard), N(backyard), hash);
   if (itr < 0) {
      return;
   }
   wlog("Execute script");
   get_mpapi().execute_from_str(init_mp);
   get_mpapi().init = 1;
}

void micropython_interface::on_server_setcode(uint64_t _account, bytes& code) {
#if 0
   if (rpc_interface::get().ready()) {
      rpc_interface::get().on_setcode(_account, code);
      return;
   }
#endif
}

void micropython_interface::on_client_setcode(uint64_t _account) {
   string code;
   db_api::get().get_code(_account, code);
   vector<char> _code(code.begin(), code.end());
   on_setcode(_account, _code);
}

void micropython_interface::on_setcode(uint64_t _account, bytes& code) {
   if (code.size() <= 0) {
      return;
   }

   if (appbase::app().client_mode()) {
      //called by client
   } else {
      //called by server
      if (!db_api::get().is_in_whitelist(_account)) {
#if 0
         if (rpc_interface::get().ready()) {
            rpc_interface::get().on_setcode(_account, code);
            return;
         }
#endif
         //FC_ASSERT(false, "RPC not ready");
      }
   }

   init();

   std::thread::id this_id = std::this_thread::get_id();
   auto itr = module_cache.find(this_id);
   if (itr == module_cache.end()) {
      module_cache[this_id] = std::map<uint64_t, py_module*>();
   }
   std::map<uint64_t, py_module*>& pymodules = module_cache[this_id];

   auto _itr = pymodules.find(_account);

   if (_itr != pymodules.end()) {
      fc::sha256 hash = fc::sha256::hash( code.data(), code.size() );
      //FIXME: handle hash conflict
      if (_itr->second->hash == hash) {
         return;
      }
   }
//   ilog("++++++++++update code ${n1}", ("n1", name(_account).to_string()));
   mp_obj_t obj = nullptr;
   mp_raw_code_t* raw_code = nullptr;
   get_mpapi().execution_start();
   if (code.data()[0] == 0) {//py
      obj = get_mpapi().micropy_load_from_py(name(_account).to_string().c_str(), (const char*)&code.data()[1], code.size()-1);
   } else if (code.data()[0] == 1) {//mpy
      obj = get_mpapi().micropy_load_from_mpy(name(_account).to_string().c_str(), (const char*)&code.data()[1], code.size()-1, &raw_code);
   } else {
      FC_ASSERT(false, "unknown micropython code!");
   }

   uint64_t execution_time = get_mpapi().get_execution_time();
   if (execution_time > 1000) {
      elog("+++++++load module ${n1}, cost: ${n2}", ("n1", name(_account).to_string())("n2", execution_time));
   }

   get_mpapi().execution_end();

   if (obj != NULL) {
      if (_itr != pymodules.end()) {
         delete _itr->second;
      }
      py_module* mod = new py_module();
      mod->obj = obj;
      mod->raw_code = raw_code;
      mod->hash = fc::sha256::hash( code.data(), code.size() );
      pymodules[_account] = mod;
   } else {
      FC_ASSERT(false, "load micropython code failed!");
   }
}

void micropython_interface::apply(uint64_t receiver, uint64_t account, uint64_t act, const shared_string& code) {
   init();
   get_mpapi().execution_start();

   try {
      mp_obj_t obj = nullptr;
      mp_raw_code_t* raw_code = nullptr;
      nlr_buf_t nlr;

      std::thread::id this_id = std::this_thread::get_id();

      auto _itr = module_cache.find(this_id);
      if (_itr == module_cache.end()) {
         module_cache[this_id] = std::map<uint64_t, py_module*>();
      }

      std::map<uint64_t, py_module*>& pymodules = module_cache[this_id];

      auto itr = pymodules.find(receiver);
      if (itr != pymodules.end()) {
         obj = itr->second->obj;
         raw_code = itr->second->raw_code;
      } else {
         if (code.data()[0] == 0) {//py
            obj = get_mpapi().micropy_load_from_py(account_name(account).to_string().c_str(), (const char*)&code.data()[1], code.size()-1);
         } else if (code.data()[0] == 1) {//mpy
            obj = get_mpapi().micropy_load_from_mpy(account_name(account).to_string().c_str(), (const char*)&code.data()[1], code.size()-1, &raw_code);
         } else {
            FC_ASSERT(false, "unknown micropython code!");
         }

         if (obj != NULL) {
            py_module* mod = new py_module();
            mod->obj = obj;
            mod->raw_code = raw_code;
            mod->hash = fc::sha256::hash( code.data(), code.size() );
            pymodules[account] = mod;
         }
      }
      mp_obj_t ret = 0;
      if (obj) {
         ret = get_mpapi().micropy_call_3(obj, raw_code, "apply", receiver, account, act);
      }
      uint64_t execution_time = get_mpapi().get_execution_time();
      if (execution_time > 1000) {
         elog("+++++++call module ${n1}, cost: ${n2}", ("n1", name(account).to_string())("n2", execution_time));
      }
      get_mpapi().execution_end();
      FC_ASSERT(ret != 0, "code execution with exception!");
   } catch(...) {
      get_mpapi().execution_end();
      throw;
   }

}

void micropython_interface::apply(uint64_t receiver, uint64_t account, uint64_t act) {
   const shared_string& src = db_api::get().get_code(receiver);
   apply(receiver, account, act, src);
}

}
}
using namespace eosio::chain;
//called by rpc client
extern "C" int micropython_on_apply(uint64_t receiver, uint64_t account, uint64_t act, char** err) {
   string _err;
   try {
      if (account == N(eosio) && act == N(setcode)) {
         micropython_interface::get().on_client_setcode(receiver);
      } else {
         micropython_interface::get().apply(receiver, account, act);
      }
      return 0;
   } catch (fc::assert_exception& e) {
      _err = e.to_detail_string();
      elog(_err);
   } catch (fc::exception& e) {
      _err = e.to_detail_string();
      elog(_err);
   } catch (boost::exception& ex) {
      _err = boost::diagnostic_information(ex);
      elog(_err);
   }
   if (!_err.empty()) {
      wlog(_err);
      *err = (char*)calloc(_err.length()+1, sizeof(char));
      memcpy(*err, _err.c_str(), _err.length());
   }
   return 1;
}

max_stars_repo_name: learnforpractice/pyeos

max_issues_repo_name: openchatproject/safeos

max_forks_repo_name: learnforpractice/pyeos


text:
/********************************************************************
 * (C) 2019 Michael Toutonghi
 *
 * Distributed under the MIT software license, see the accompanying
 * file COPYING or http://www.opensource.org/licenses/mit-license.php.
 *
 * This provides support for PBaaS cross chain communication.
 *
 * In merge mining and notarization, Verus acts as a hub that other PBaaS chains
 * call via RPC in order to get information that allows earning and submitting
 * notarizations.
 *
 * All PBaaS chains communicate with their primary reserve chain, which is either Verus
 * or the chain that is their reserve coin. The child PBaaS chain initiates all of
 * the communication with the parent / reserve daemon.
 *
 * Generally, the PBaaS chain will call the Verus chain to either get information needed
 * to create an earned or accepted notarization. If there is no Verus daemon available
 * staking and mining of a PBaaS chain proceeds as usual, but without notarization
 * reward opportunities.
 *
 */

#include "chainparamsbase.h"
#include "clientversion.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include "utilstrencodings.h"

#include <boost/filesystem/operations.hpp>
#include <stdio.h>

#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include "support/events.h"

#include <univalue.h>

#include "uint256.h"
#include "hash.h"
#include "pbaas/crosschainrpc.h"

using namespace std;

extern string PBAAS_HOST;
extern string PBAAS_USERPASS;
extern int32_t PBAAS_PORT;

//
// Exception thrown on connection error.  This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:

    explicit inline CConnectionFailed(const std::string& msg) :
        std::runtime_error(msg)
    {}

};

/** Reply structure for request_done to fill in */
struct HTTPReply
{
    HTTPReply(): status(0), error(-1) {}

    int status;
    int error;
    std::string body;
};

const char *http_errorstring(int code)
{
    switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
    case EVREQ_HTTP_TIMEOUT:
        return "timeout reached";
    case EVREQ_HTTP_EOF:
        return "EOF reached";
    case EVREQ_HTTP_INVALID_HEADER:
        return "error while reading header, or invalid header";
    case EVREQ_HTTP_BUFFER_ERROR:
        return "error encountered while reading or writing";
    case EVREQ_HTTP_REQUEST_CANCEL:
        return "request was canceled";
    case EVREQ_HTTP_DATA_TOO_LONG:
        return "response body is larger than allowed";
#endif
    default:
        return "unknown";
    }
}

static void http_request_done(struct evhttp_request *req, void *ctx)
{
    HTTPReply *reply = static_cast<HTTPReply*>(ctx);

    if (req == NULL) {
        /* If req is NULL, it means an error occurred while connecting: the
         * error code will have been passed to http_error_cb.
         */
        reply->status = 0;
        return;
    }

    reply->status = evhttp_request_get_response_code(req);

    struct evbuffer *buf = evhttp_request_get_input_buffer(req);
    if (buf)
    {
        size_t size = evbuffer_get_length(buf);
        const char *data = (const char*)evbuffer_pullup(buf, size);
        if (data)
            reply->body = std::string(data, size);
        evbuffer_drain(buf, size);
    }
}

#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
    HTTPReply *reply = static_cast<HTTPReply*>(ctx);
    reply->error = err;
}
#endif

static CCrossChainRPCData LoadFromConfig(std::string name)
{
    map<string, string> settings;
    map<string, vector<string>> settingsmulti;
    CCrossChainRPCData ret;

    // if we are requested to automatically load the information from the Verus chain, do it if we can find the daemon
    if (ReadConfigFile(name, settings, settingsmulti))
    {
        auto rpcuser = settings.find("-rpcuser");
        auto rpcpwd = settings.find("-rpcpassword");
        auto rpcport = settings.find("-rpcport");
        auto rpchost = settings.find("-rpchost");
        ret.credentials = rpcuser != settings.end() ? rpcuser->second + ":" : "";
        ret.credentials += rpcpwd != settings.end() ? rpcpwd->second : "";
        ret.port = rpcport != settings.end() ? atoi(rpcport->second) : (name == "VRSC" ? 27486 : 0);
        ret.host = rpchost != settings.end() ? rpchost->second : "127.0.0.1";
    }
    return ret;
}

// credentials for now are "user:password"
UniValue RPCCall(const string& strMethod, const UniValue& params, const string credentials, int port, const string host, int timeout)
{
    // Used for inter-daemon communicatoin to enable merge mining and notarization without a client
    //

    // Obtain event base
    raii_event_base base = obtain_event_base();

    // Synchronously look up hostname
    raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
    evhttp_connection_set_timeout(evcon.get(), timeout);

    HTTPReply response;
    raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
    if (req == NULL)
        throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
    evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif

    struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
    assert(output_headers);
    evhttp_add_header(output_headers, "Host", host.c_str());
    evhttp_add_header(output_headers, "Connection", "close");
    evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(credentials)).c_str());

    // Attach request data
    std::string strRequest = JSONRPCRequest(strMethod, params, 1);
    struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
    assert(output_buffer);
    evbuffer_add(output_buffer, strRequest.data(), strRequest.size());

    int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
    req.release(); // ownership moved to evcon in above call
    if (r != 0) {
        throw CConnectionFailed("send http request failed");
    }

    event_base_dispatch(base.get());

    if (response.status == 0)
        throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
    else if (response.status == HTTP_UNAUTHORIZED)
        throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
    else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
        throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
    else if (response.body.empty())
        throw std::runtime_error("no response from server");

    // Parse reply
    UniValue valReply(UniValue::VSTR);
    if (!valReply.read(response.body))
        throw std::runtime_error("couldn't parse reply from server");
    const UniValue& reply = valReply.get_obj();
    if (reply.empty())
        throw std::runtime_error("expected reply to have result, error and id properties");

    return reply;
}

UniValue RPCCallRoot(const string& strMethod, const UniValue& params, int timeout)
{
    string host, credentials;
    int port;
    map<string, string> settings;
    map<string, vector<string>> settingsmulti;

    if (PBAAS_HOST != "" && PBAAS_PORT != 0)
    {
        return RPCCall(strMethod, params, PBAAS_USERPASS, PBAAS_PORT, PBAAS_HOST);
    }
    else if (ReadConfigFile(PBAAS_TESTMODE ? "VRSCTEST" : "VRSC", settings, settingsmulti))
    {
        PBAAS_USERPASS = settingsmulti.find("-rpcuser")->second[0] + ":" + settingsmulti.find("-rpcpassword")->second[0];
        PBAAS_PORT = atoi(settingsmulti.find("-rpcport")->second[0]);
        PBAAS_HOST = settingsmulti.find("-rpchost")->second[0];
        if (!PBAAS_HOST.size())
        {
            PBAAS_HOST = "127.0.0.1";
        }
        return RPCCall(strMethod, params, credentials, port, host, timeout);
    }
    return UniValue(UniValue::VNULL);
}

int32_t uni_get_int(UniValue uv, int32_t def)
{
    try
    {
        return uv.get_int();
    }
    catch(const std::exception& e)
    {
        return def;
    }
}

int64_t uni_get_int64(UniValue uv, int64_t def)
{
    try
    {
        return uv.get_int64();
    }
    catch(const std::exception& e)
    {
        return def;
    }
}

std::string uni_get_str(UniValue uv, std::string def)
{
    try
    {
        return uv.get_str();
    }
    catch(const std::exception& e)
    {
        return def;
    }
}

std::vector<UniValue> uni_getValues(UniValue uv, std::vector<UniValue> def)
{
    try
    {
        return uv.getValues();
    }
    catch(const std::exception& e)
    {
        return def;
    }
}

UniValue CCrossChainRPCData::ToUniValue() const
{
    UniValue obj(UniValue::VOBJ);
    obj.push_back(Pair("host", host));
    obj.push_back(Pair("port", port));
    obj.push_back(Pair("credentials", credentials));
    return obj;
}

uint160 CCrossChainRPCData::GetConditionID(uint160 cid, int32_t condition)
{
    CHashWriter hw(SER_GETHASH, PROTOCOL_VERSION);
    hw << condition;
    hw << cid;
    uint256 chainHash = hw.GetHash();
    return Hash160(chainHash.begin(), chainHash.end());
}

uint160 CCrossChainRPCData::GetConditionID(std::string name, int32_t condition)
{
    uint160 cid = GetChainID(name);

    CHashWriter hw(SER_GETHASH, PROTOCOL_VERSION);
    hw << condition;
    hw << cid;
    uint256 chainHash = hw.GetHash();
    return Hash160(chainHash.begin(), chainHash.end());
}

max_stars_repo_name: denza/VerusCoin

max_issues_repo_name: denza/VerusCoin

max_forks_repo_name: denza/VerusCoin


text:
/*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/

#pragma once

#include "utility/rect.hpp"
#include "utility/vector2.hpp"

#include <boost/container/small_vector.hpp>
#include <boost/variant.hpp>

#include <cstdint>
#include <array>

namespace ts
{
  namespace resources
  {
    namespace collision_shapes
    {
      struct Circle
      {
        Vector2f center;
        float radius;
        std::uint32_t height = 1;
      };

      struct Polygon
      {
        struct Point
        {
          Vector2f position;
        };

        std::array<Point, 8> points;
        std::uint32_t num_points;
        std::uint32_t height = 1;
      };

      struct SubShape
      {
        boost::variant<Circle, Polygon> data;
        float bounciness;
      };
    }

    struct CollisionShape
    {
      boost::container::small_vector<collision_shapes::SubShape, 4> sub_shapes;
    };
  }
}

max_stars_repo_name: mnewhouse/tselements

max_issues_repo_name: mnewhouse/tselements

max_forks_repo_name: mnewhouse/tselements


text:
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <string>
#include <fstream>
#include <istream>
#include <random>
#include <cmath>
#include <Eigen/Dense>
#include <boost/program_options.hpp>
#include "options.hpp"
#include "options_parser.hpp"
#include "LagrangianState.h"
#include "ParticlePhysics.h"
#include "TimeIntegration.h"
#include "Inputfile.hpp"

using namespace std;
using namespace Eigen;

int main(int argc, char* argv[]) {
  printf("*********** DRIVER PROGRAM FOR LAGRANGIAN PARTICLE SOLVER ***********\n\n");

  // Parse input file options
  Options options;
  if (!parseOptions(argc,argv,options)){
   return 0;
  }
  cout << options << endl;

  // Load state
  MatrixXd input = load_csv<MatrixXd>(options.inputfile);

  // Pass parsed program options to simulation
  LagrangianState state(input);
  ParticlePhysics physics(options, state);
  TimeIntegration integrator(options, physics, state);

  // Solve
  integrator.euler();

  // Output
  state.writeXY(options.outputfile+"_final.csv");

  return 0;
}

max_stars_repo_name: adegenna/HardSphereDynamics

max_issues_repo_name: adegenna/HardSphereDynamics

max_forks_repo_name: adegenna/HardSphereDynamics


text:
#include <chrono>
#include <exception>
#include <iostream>
#include <thread>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>

void standard_candle(int size_, int interval_, int iterations_) {
  float *a = new float[size_ * size_];
  float *b = new float[size_ * size_];
  float *c = new float[size_ * size_];
  for (int iter = 0; iter < iterations_; ++iter) {
    std::cout << " iterate " << std::endl;
    //Initialize numbers to some arbitrary value
    for (int i = 0; i < size_ * size_; ++i) {
      a[i] = float(i) / (float(i)+1.0);
    }
    for (int i = 0; i < size_; ++i) {
      for (int j = 0; j < size_; ++j) {
        float acc = 0;
        for (int k = 0; k < size_; ++k) {
          acc += a[i * size_ + k] + b[k * size_ + j];
        }
        c[i*size_+j] = acc;
      }
    }
    std::cout << " sleep " << std::endl;
    if (interval_) { // Sometimes we don't actually want this
      std::this_thread::sleep_for(std::chrono::milliseconds(interval_));
    }
    std::cout << "busy add wait " << std::endl;
    for (uint64_t count = 0; count < 1073741824; ++count) {}
    std::cout << "busy sub wait " << std::endl;
    for (uint64_t count = 1073741824; count > 0; --count) {}
    std::cout << "busy add mul wait " << std::endl;
    for (uint64_t count = 0; (count * 2) < 2147483648; ++count) {}
    std::cout << "busy add /sub wait" << std::endl;
    for(uint64_t count_up = 0, count_down = 2147483648; count_up!=count_down; ++count_up, --count_down) {}
  }
  delete [] a;
  delete [] b;
  delete [] c;
}

int main(int argc, char* argv[]) {
  // Parse arguments
  int size, interval, iterations;
  try {
    namespace po = boost::program_options;
    po::options_description desc("Allowed Options");
    desc.add_options()("help", "produce help message")
      ("size", po::value<int>(&size)->default_value(750),
      "Size of square matrix to compute")
      ("interval", po::value<int>(&interval)->default_value(1000),
      "sleep interval")
      ("iterations", po::value<int>(&iterations)->default_value(10),
      "cycle iterations");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help")) {
      std::cerr << "Usage:\n" << desc << std::endl;
      return 1;
    }
  } catch (std::exception& ex) {
    std::cerr << "Exception Caught:" << ex.what() << std::endl;
    return 1;
  } catch (...) {
    std::cerr << "Unknown Error! Exiting." << std::endl;
    return 1;
  }
  std::cout << "Standard Candle application.\n"
            << "\tMatrix size: " << size << "x" << size
            << "\tSleep interval: " << interval << "ms"
            << "\tIterations: " << iterations << std::endl;

  standard_candle(size, interval, iterations);
  return 0;
}

ext: cc

max_stars_repo_name: csrhau/Iconoclast

max_issues_repo_name: csrhau/Iconoclast

max_forks_repo_name: csrhau/Iconoclast


text:
/*
Copyright 2019 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX14_CONSTEXPR)
#include <boost/core/first_scalar.hpp>
#include <boost/static_assert.hpp>

static int i1 = 0;
BOOST_STATIC_ASSERT(boost::first_scalar(&i1) == &i1);
static int i2[4] = { };
BOOST_STATIC_ASSERT(boost::first_scalar(i2) == &i2[0]);
static int i3[2][4][6] = { };
BOOST_STATIC_ASSERT(boost::first_scalar(i3) == &i3[0][0][0]);
#endif


text:
//
// Copyright 2021 Autodesk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "pythonObjectRegistry.h"
#include "wrapSparseValueWriter.h"

#include <mayaUsd/fileio/primReaderArgs.h>
#include <mayaUsd/fileio/primReaderContext.h>
#include <mayaUsd/fileio/registryHelper.h>
#include <mayaUsd/fileio/schemaApiAdaptor.h>
#include <mayaUsd/fileio/schemaApiAdaptorRegistry.h>

#include <pxr/base/tf/pyPolymorphic.h>

#include <maya/MTypes.h>

#include <boost/python/args.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/make_constructor.hpp>
#include <boost/python/return_internal_reference.hpp>
#include <boost/python/wrapper.hpp>

PXR_NAMESPACE_USING_DIRECTIVE

//----------------------------------------------------------------------------------------------------------------------
/// \brief  boost python binding for the UsdMayaSchemaApiAdaptor
//----------------------------------------------------------------------------------------------------------------------
class SchemaApiAdaptorWrapper
    : public UsdMayaSchemaApiAdaptor
    , public TfPyPolymorphic<UsdMayaSchemaApiAdaptor>
{
public:
    typedef SchemaApiAdaptorWrapper This;
    typedef UsdMayaSchemaApiAdaptor base_t;

    SchemaApiAdaptorWrapper() { }

    SchemaApiAdaptorWrapper(
        const MObjectHandle&     object,
        const TfToken&           schemaName,
        const UsdPrimDefinition* schemaPrimDef)
        : base_t(object, schemaName, schemaPrimDef)
    {
    }

    static std::shared_ptr<This> New(uintptr_t createdWrapper)
    {
        return *((std::shared_ptr<This>*)createdWrapper);
    }

    virtual ~SchemaApiAdaptorWrapper() { }

    bool default_CopyFromPrim(
        const UsdPrim&               prim,
        const UsdMayaPrimReaderArgs& args,
        UsdMayaPrimReaderContext&    context)
    {
        return base_t::CopyFromPrim(prim, args, context);
    }
    bool CopyFromPrim(
        const UsdPrim&               prim,
        const UsdMayaPrimReaderArgs& args,
        UsdMayaPrimReaderContext&    context) override
    {
        return this->CallVirtual("CopyFromPrim", &This::default_CopyFromPrim)(prim, args, context);
    }

    bool default_CopyToPrim(
        const UsdPrim&              prim,
        const UsdTimeCode&          usdTime,
        MayaUsdLibSparseValueWriter valueWriter) const
    {
        return base_t::CopyToPrim(prim, usdTime, valueWriter.Get());
    }
    bool CopyToPrim(
        const UsdPrim&             prim,
        const UsdTimeCode&         usdTime,
        UsdUtilsSparseValueWriter* valueWriter) const override
    {
        return python_CopyToPrim(prim, usdTime, MayaUsdLibSparseValueWriter(valueWriter));
    }
    virtual bool python_CopyToPrim(
        const UsdPrim&              prim,
        const UsdTimeCode&          usdTime,
        MayaUsdLibSparseValueWriter valueWriter) const
    {
        return this->template CallVirtual<bool>("CopyToPrim", &This::default_CopyToPrim)(
            prim, usdTime, valueWriter);
    }

    bool default_CanAdapt() const { return base_t::CanAdapt(); }
    bool CanAdapt() const override
    {
        return this->template CallVirtual<bool>("CanAdapt", &This::default_CanAdapt)();
    }

    bool default_CanAdaptForExport(const UsdMayaJobExportArgs& args) const
    {
        return base_t::CanAdaptForExport(args);
    }
    bool CanAdaptForExport(const UsdMayaJobExportArgs& args) const override
    {
        return this->template CallVirtual<bool>(
            "CanAdaptForExport", &This::default_CanAdaptForExport)(args);
    }

    bool default_CanAdaptForImport(const UsdMayaJobImportArgs& args) const
    {
        return base_t::CanAdaptForImport(args);
    }
    bool CanAdaptForImport(const UsdMayaJobImportArgs& args) const override
    {
        return this->template CallVirtual<bool>(
            "CanAdaptForImport", &This::default_CanAdaptForImport)(args);
    }

    bool default_ApplySchema(MDGModifier& modifier) { return base_t::ApplySchema(modifier); }
    bool ApplySchema(MDGModifier& modifier) override
    {
        // The TfPolymorphic CallVirtual mechanism uses variadic arguments with parameter packs. A
        // major flaw of this technique is that references and other cv qualifiers are lost in the
        // parameter pack deduction phase, leading to parameter being passed by copy instead of by
        // reference. This fails with MDGModifier because the copy semantics are private. Use the
        // internals of TfPolymorphic::CallVirtual() as a way to preserve the reference on the
        // "modifier" parameter.
        TfPyLock pyLock;
        auto     pyOverride = this->GetOverride("ApplySchema");
        if (pyOverride) {
            // Do *not* call through if there's an active python exception.
            if (!PyErr_Occurred()) {
                try {
                    return boost::python::call<bool>(pyOverride.ptr(), modifier);
                } catch (boost::python::error_already_set const&) {
                    // Convert any exception to TF_ERRORs.
                    TfPyConvertPythonExceptionToTfErrors();
                    PyErr_Clear();
                }
            }
        }
        return default_ApplySchema(modifier);
    }

    bool default_ApplySchemaForImport(
        const UsdMayaPrimReaderArgs& primReaderArgs,
        UsdMayaPrimReaderContext&    context)
    {
        return base_t::ApplySchema(primReaderArgs, context);
    }
    bool ApplySchema(const UsdMayaPrimReaderArgs& primReaderArgs, UsdMayaPrimReaderContext& context)
        override
    {
        // Note the different function name Python-side. Python does not do overload resolution
        // based on argument types because every argument is a PyObject.
        return this->CallVirtual("ApplySchemaForImport", &This::default_ApplySchemaForImport)(
            primReaderArgs, context);
    }

    bool default_UnapplySchema(MDGModifier& modifier) { return base_t::UnapplySchema(modifier); }
    bool UnapplySchema(MDGModifier& modifier) override
    {
        // Not using TfPolymorphic::CallVirtual. See ApplySchema(MDGModifier&) above for details.
        TfPyLock pyLock;
        auto     pyOverride = this->GetOverride("UnapplySchema");
        if (pyOverride) {
            // Do *not* call through if there's an active python exception.
            if (!PyErr_Occurred()) {
                try {
                    return boost::python::call<bool>(pyOverride.ptr(), modifier);
                } catch (boost::python::error_already_set const&) {
                    // Convert any exception to TF_ERRORs.
                    TfPyConvertPythonExceptionToTfErrors();
                    PyErr_Clear();
                }
            }
        }
        return default_UnapplySchema(modifier);
    }

    MObject default_GetMayaObjectForSchema() const { return base_t::GetMayaObjectForSchema(); }
    MObject GetMayaObjectForSchema() const override
    {
        return this->template CallVirtual<MObject>(
            "GetMayaObjectForSchema", &This::default_GetMayaObjectForSchema)();
    }

    TfToken default_GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const
    {
        return base_t::GetMayaNameForUsdAttrName(usdAttrName);
    }
    TfToken GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const override
    {
        return this->template CallVirtual<TfToken>(
            "GetMayaNameForUsdAttrName", &This::default_GetMayaNameForUsdAttrName)(usdAttrName);
    }

    TfTokenVector default_GetAdaptedAttributeNames() const
    {
        return base_t::GetAdaptedAttributeNames();
    }
    TfTokenVector GetAdaptedAttributeNames() const override
    {
        return this->template CallVirtual<TfTokenVector>(
            "GetAdaptedAttributeNames", &This::default_GetAdaptedAttributeNames)();
    }

    //---------------------------------------------------------------------------------------------
    /// \brief  wraps a factory function that allows registering an updated Python class
    //---------------------------------------------------------------------------------------------
    class AdaptorFactoryFnWrapper : public UsdMayaPythonObjectRegistry
    {
    public:
        // Instances of this class act as "function objects" that are fully compatible with the
        // std::function requested by UsdMayaSchemaApiAdaptorRegistry::Register. These will create
        // python wrappers based on the latest class registered.
        UsdMayaSchemaApiAdaptorPtr operator()(
            const MObjectHandle&     object,
            const TfToken&           schemaName,
            const UsdPrimDefinition* schemaPrimDef)
        {
            boost::python::object pyClass = GetPythonObject(_classIndex);
            if (!pyClass) {
                // Prototype was unregistered
                return nullptr;
            }
            auto                  sptr = std::make_shared<This>(object, schemaName, schemaPrimDef);
            TfPyLock              pyLock;
            boost::python::object instance = pyClass((uintptr_t)&sptr);
            boost::python::incref(instance.ptr());
            initialize_wrapper(instance.ptr(), sptr.get());
            return sptr;
        }

        // Create a new wrapper for a Python class that is seen for the first time for a given
        // purpose. If we already have a registration for this purpose: update the class to
        // allow the previously issued factory function to use it.
        static UsdMayaSchemaApiAdaptorRegistry::AdaptorFactoryFn Register(
            boost::python::object cl,
            const std::string&    mayaType,
            const std::string&    schemaApiName)
        {
            size_t classIndex = RegisterPythonObject(cl, GetKey(cl, mayaType, schemaApiName));
            if (classIndex != UsdMayaPythonObjectRegistry::UPDATED) {
                // Return a new factory function:
                return AdaptorFactoryFnWrapper { classIndex };
            } else {
                // We already registered a factory function for this purpose:
                return nullptr;
            }
        }

        // Unregister a class for a given purpose. This will cause the associated factory
        // function to stop producing this Python class.
        static void Unregister(
            boost::python::object cl,
            const std::string&    mayaType,
            const std::string&    schemaApiName)
        {
            UnregisterPythonObject(cl, GetKey(cl, mayaType, schemaApiName));
        }

    private:
        // Function object constructor. Requires only the index of the Python class to use.
        AdaptorFactoryFnWrapper(size_t classIndex)
            : _classIndex(classIndex) {};

        size_t _classIndex;

        // Generates a unique key based on the name of the class, along with the class
        // purpose:
        static std::string GetKey(
            boost::python::object cl,
            const std::string&    mayaType,
            const std::string&    schemaApiName)
        {
            return ClassName(cl) + "," + mayaType + "," + schemaApiName + ",SchemaApiAdaptor";
        }
    };

    static void Register(
        boost::python::object cl,
        const std::string&    mayaType,
        const std::string&    schemaApiName)
    {
        UsdMayaSchemaApiAdaptorRegistry::AdaptorFactoryFn fn
            = AdaptorFactoryFnWrapper::Register(cl, mayaType, schemaApiName);
        if (fn) {
            UsdMayaSchemaApiAdaptorRegistry::Register(mayaType, schemaApiName, fn, true);
        }
    }

    static void Unregister(
        boost::python::object cl,
        const std::string&    mayaType,
        const std::string&    schemaApiName)
    {
        AdaptorFactoryFnWrapper::Unregister(cl, mayaType, schemaApiName);
    }

    MObject _GetMayaObject() const { return _handle.object(); }
};

void wrapSchemaApiAdaptor()
{
    typedef UsdMayaSchemaApiAdaptor This;

    boost::python::class_<
        SchemaApiAdaptorWrapper,
        boost::python::bases<UsdMayaSchemaAdaptor>,
        boost::noncopyable>("SchemaApiAdaptor", boost::python::no_init)
        .def("__init__", make_constructor(&SchemaApiAdaptorWrapper::New))

        .def("CanAdapt", &This::CanAdapt, &SchemaApiAdaptorWrapper::default_CanAdapt)
        .def(
            "CanAdaptForExport",
            &This::CanAdaptForExport,
            &SchemaApiAdaptorWrapper::default_CanAdaptForExport)
        .def(
            "CanAdaptForImport",
            &This::CanAdaptForImport,
            &SchemaApiAdaptorWrapper::default_CanAdaptForImport)
        .def(
            "ApplySchema",
            (bool (This::*)(MDGModifier&)) & This::ApplySchema,
            (bool (This::*)(MDGModifier&)) & SchemaApiAdaptorWrapper::default_ApplySchema)
        .def(
            "ApplySchemaForImport",
            (bool (This::*)(const UsdMayaPrimReaderArgs&, UsdMayaPrimReaderContext&))
                & This::ApplySchema,
            &SchemaApiAdaptorWrapper::default_ApplySchemaForImport)
        .def("UnapplySchema", &This::UnapplySchema, &SchemaApiAdaptorWrapper::default_UnapplySchema)
        .def(
            "GetMayaObjectForSchema",
            &This::GetMayaObjectForSchema,
            &SchemaApiAdaptorWrapper::default_GetMayaObjectForSchema)
        .def(
            "GetMayaNameForUsdAttrName",
            &This::GetMayaNameForUsdAttrName,
            &SchemaApiAdaptorWrapper::default_GetMayaNameForUsdAttrName)
        .def(
            "GetAdaptedAttributeNames",
            &This::GetAdaptedAttributeNames,
            &SchemaApiAdaptorWrapper::default_GetAdaptedAttributeNames)
        .def(
            "CopyToPrim",
            &SchemaApiAdaptorWrapper::python_CopyToPrim,
            &SchemaApiAdaptorWrapper::default_CopyToPrim)
        .def("CopyFromPrim", &This::CopyFromPrim, &SchemaApiAdaptorWrapper::default_CopyFromPrim)
        .def("Register", &SchemaApiAdaptorWrapper::Register)
        .staticmethod("Register")
        .def("Unregister", &SchemaApiAdaptorWrapper::Unregister)
        .staticmethod("Unregister")
        .add_property("mayaObject", &SchemaApiAdaptorWrapper::_GetMayaObject);
}

max_stars_repo_name: sun-frog/maya-usd

max_issues_repo_name: sun-frog/maya-usd

max_forks_repo_name: sun-frog/maya-usd