def ensure_blockchain_databases_identical(base_db_1, base_db_2): node_1 = MainnetChain(base_db_1, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) node_2 = MainnetChain(base_db_2, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) # Get all of the addresses of every chain next_head_hashes = node_1.chain_head_db.get_head_block_hashes_list() wallet_addresses = [] for next_head_hash in next_head_hashes: chain_address = node_1.chaindb.get_chain_wallet_address_for_block_hash(next_head_hash) wallet_addresses.append(chain_address) next_head_hashes_node_2 = node_2.chain_head_db.get_head_block_hashes_list() # This gaurantees both have all the same chains assert (next_head_hashes == next_head_hashes_node_2) for wallet_address in wallet_addresses: # Compare all properties of each account with the hashes node_1_account_hash = node_1.get_vm().state.account_db.get_account_hash(wallet_address) node_2_account_hash = node_2.get_vm().state.account_db.get_account_hash(wallet_address) assert (node_1_account_hash == node_2_account_hash) # Compare all chains in database node_1_chain = node_1.get_all_blocks_on_chain(wallet_address) node_2_chain = node_2.get_all_blocks_on_chain(wallet_address) assert (node_1_chain == node_2_chain) # Compare the blocks at a deeper level for i in range(len(node_1_chain)): assert (node_1_chain[i].hash == node_2_chain[i].hash) assert_var_1 = node_1.chaindb.get_all_descendant_block_hashes(node_1_chain[i].hash) assert_var_2 = node_2.chaindb.get_all_descendant_block_hashes(node_2_chain[i].hash) assert ( assert_var_1==assert_var_2 )
def create_mainnet_genesis_transactions(base_db): import sys sys.path.append('/d:/Google Drive/forex/blockchain_coding/Helios/prototype desktop/helios_deploy/') from deploy_params import ( genesis_private_key, airdrop_private_key, bounties_private_key, exchange_listings_private_key, dapp_incubator_private_key, bootnode_1_private_key, bootnode_2_private_key, masternode_1_private_key, ) chain = MainnetChain(base_db, TESTNET_GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), TESTNET_GENESIS_PRIVATE_KEY) genesis_block_timestamp = chain.genesis_block_timestamp min_time_between_blocks = chain.get_vm(timestamp=genesis_block_timestamp).min_time_between_blocks time_between_head_hash_save = TIME_BETWEEN_HEAD_HASH_SAVE start_time = genesis_block_timestamp + time_between_head_hash_save tx_list = [] # main accounts tx_list.append([genesis_private_key, airdrop_private_key, to_wei(110000000, 'ether'), start_time + min_time_between_blocks]) tx_list.append([genesis_private_key, dapp_incubator_private_key, to_wei(70000000, 'ether'), start_time + min_time_between_blocks*2]) tx_list.append([genesis_private_key, bounties_private_key, to_wei(50000000, 'ether'), start_time + min_time_between_blocks*3]) tx_list.append([genesis_private_key, exchange_listings_private_key, to_wei(40000000, 'ether'), start_time + min_time_between_blocks*4]) # stake for bootnodes (this is large for now to prevent 51% attacks until the network has grown to a sufficiently stable size) tx_list.append([airdrop_private_key, bootnode_1_private_key, to_wei(10000000, 'ether'), start_time + min_time_between_blocks*6]) tx_list.append([airdrop_private_key, bootnode_2_private_key, to_wei(10000000, 'ether'), start_time + min_time_between_blocks*7]) tx_list.append([airdrop_private_key, masternode_1_private_key, to_wei(10000000, 'ether'), start_time + min_time_between_blocks*8]) add_transactions_to_blockchain_db(base_db, tx_list)
def create_reward_test_blockchain_database(): testdb = MemoryDB() chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks required_stake_for_reward_type_2_proof = chain.get_consensus_db(timestamp=Timestamp(int(time.time()))).required_stake_for_reward_type_2_proof now = int(time.time()) start = now - max((coin_mature_time * 2), (min_time_between_blocks * 20)) key_balance_dict = {} for i in range(10): key_balance_dict[private_keys[i]] = ( required_stake_for_reward_type_2_proof, start + min_time_between_blocks * i) create_dev_fixed_blockchain_database(testdb, key_balance_dict) return testdb
def test_invalid_proofs_timestamp_in_past(): testdb = create_reward_test_blockchain_database() chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks tx_list = [[private_keys[1], private_keys[0], to_wei(1, 'ether'), int(int(time.time())-min_time_between_blocks*10)]] add_transactions_to_blockchain_db(testdb, tx_list) chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(timestamp=Timestamp(int(time.time()))).required_number_of_proofs_for_reward_type_2_proof node_staking_scores = [] # First score/proof with timestamp far in future current_private_key = private_keys[1] node_staking_score = NodeStakingScore( recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(), score=int(1000000), since_block_number=0, timestamp=int(time.time())-60*10, head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash( current_private_key.public_key.to_canonical_address()), v=0, r=0, s=0, ) signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID) node_staking_scores.append(signed_node_staking_score) score = 100000 for i in range(2, 10): # Second score/proof is from instance 1 current_private_key = private_keys[i] node_staking_score = NodeStakingScore( recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(), score=int(score-i), since_block_number=1, timestamp=int(time.time()), head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash( current_private_key.public_key.to_canonical_address()), v=0, r=0, s=0, ) signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID) node_staking_scores.append(signed_node_staking_score) # Now we try to import the reward block with instance 0 reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) with pytest.raises(ValidationError): reward_chain.import_current_queue_block_with_reward(node_staking_scores)
def test_invalid_proofs_no_proofs(): testdb = create_reward_test_blockchain_database() chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks tx_list = [[private_keys[1], private_keys[0], to_wei(1, 'ether'), int(int(time.time())-min_time_between_blocks*10)]] add_transactions_to_blockchain_db(testdb, tx_list) chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) required_number_of_proofs_for_reward_type_2_proof = chain.get_consensus_db(timestamp=Timestamp(int(time.time()))).required_number_of_proofs_for_reward_type_2_proof # Now we try to import the reward block with instance 0 reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) with pytest.raises(RewardAmountRoundsToZero): imported_block = reward_chain.import_current_queue_block_with_reward([])
def create_valid_block_at_timestamp(base_db, private_key, transactions = None, receive_transactions = None, reward_bundle = None, timestamp = None): ''' Tries to create a valid block based in the invalid block. The transactions and reward bundle must already be valid :param base_db: :param private_key: :param invalid_block: :return: ''' if timestamp == None: timestamp = int(time.time()) chain = MainnetChain(JournalDB(base_db), private_key.public_key.to_canonical_address(), private_key) queue_block = chain.get_queue_block() queue_block = queue_block.copy(header = queue_block.header.copy(timestamp = timestamp), transactions=transactions, receive_transactions=receive_transactions, reward_bundle=reward_bundle) valid_block = chain.get_vm(timestamp = timestamp).import_block(queue_block, validate = False, private_key = chain.private_key) return valid_block
def test_invalid_proofs_not_enough_stake(): testdb = MemoryDB() chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks now = int(time.time()) start = now - max((coin_mature_time * 2), (min_time_between_blocks * 20)) key_balance_dict = { private_keys[0]: (to_wei(1, 'ether'), start), private_keys[1]: (to_wei(1, 'ether'), start + min_time_between_blocks * 1), private_keys[2]: (to_wei(1, 'ether'), start + min_time_between_blocks * 2), private_keys[3]: (to_wei(1, 'ether'), start + min_time_between_blocks * 3), private_keys[4]: (to_wei(1, 'ether'), start + min_time_between_blocks * 4), private_keys[5]: (to_wei(1, 'ether'), start + min_time_between_blocks * 5), private_keys[6]: (to_wei(1, 'ether'), start + min_time_between_blocks * 6), private_keys[7]: (to_wei(1, 'ether'), start + min_time_between_blocks * 7), private_keys[8]: (to_wei(1, 'ether'), start + min_time_between_blocks * 8), private_keys[9]: (to_wei(1, 'ether'), now - coin_mature_time + 1), # immature } create_dev_fixed_blockchain_database(testdb, key_balance_dict) chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) node_staking_scores = [] # First score/proof with timestamp far in future current_private_key = private_keys[1] node_staking_score = NodeStakingScore( recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(), score=int(1000000), since_block_number=0, timestamp=int(time.time())-60*10, head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash( current_private_key.public_key.to_canonical_address()), v=0, r=0, s=0, ) signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID) node_staking_scores.append(signed_node_staking_score) score = 100000 for i in range(2, 10): # Second score/proof is from instance 1 current_private_key = private_keys[i] node_staking_score = NodeStakingScore( recipient_node_wallet_address=private_keys[0].public_key.to_canonical_address(), score=int(score-i), since_block_number=1, timestamp=int(time.time()), head_hash_of_sender_chain=chain.chaindb.get_canonical_head_hash( current_private_key.public_key.to_canonical_address()), v=0, r=0, s=0, ) signed_node_staking_score = node_staking_score.get_signed(current_private_key, MAINNET_NETWORK_ID) node_staking_scores.append(signed_node_staking_score) # Now we try to import the reward block with instance 0 reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) with pytest.raises(NotEnoughProofsOrStakeForRewardType2Proof): reward_chain.import_current_queue_block_with_reward(node_staking_scores)
def _test_block_rewards_system(): #The genesis chain will be adding a reward block. We need to generate fake NodeStakingScores from a bunch of other #nodes # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/') # testdb = JournalDB(testdb) testdb = create_reward_test_blockchain_database() chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) coin_mature_time = chain.get_vm(timestamp=Timestamp(int(time.time()))).consensus_db.coin_mature_time_for_staking min_time_between_blocks = chain.get_vm(timestamp=Timestamp(int(time.time()))).min_time_between_blocks # now = int(time.time()) # start = now - max((coin_mature_time * 2), (min_time_between_blocks*20)) # key_balance_dict = { # private_keys[0]: (to_wei(10, 'ether'), start), # private_keys[1]: (to_wei(200, 'ether'), start + min_time_between_blocks * 1), # private_keys[2]: (to_wei(340, 'ether'), start + min_time_between_blocks * 2), # private_keys[3]: (to_wei(1000, 'ether'), start + min_time_between_blocks * 3), # private_keys[4]: (to_wei(1400, 'ether'), start + min_time_between_blocks * 4), # private_keys[5]: (to_wei(2400, 'ether'), start + min_time_between_blocks * 5), # private_keys[6]: (to_wei(3000, 'ether'), start + min_time_between_blocks * 6), # private_keys[7]: (to_wei(4000, 'ether'), start + min_time_between_blocks * 7), # private_keys[8]: (to_wei(1000, 'ether'), start + min_time_between_blocks * 8), # private_keys[9]: (to_wei(10000, 'ether'), now-coin_mature_time+1),# immature # } # create_dev_fixed_blockchain_database(testdb, key_balance_dict) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) # class NodeStakingScore(rlp.Serializable, metaclass=ABCMeta): # fields = [ # ('recipient_node_wallet_address', address), # ('score', f_big_endian_int), # ('since_block_number', f_big_endian_int), # ('timestamp', f_big_endian_int), # ('v', big_endian_int), # ('r', big_endian_int), # ('s', big_endian_int), # ] node_staking_scores = [] score = 1000000 for private_key in private_keys: node_staking_score = NodeStakingScore(recipient_node_wallet_address = GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), score = int(score), since_block_number = 0, timestamp = int(time.time()), head_hash_of_sender_chain = chain.chaindb.get_canonical_head_hash(private_key.public_key.to_canonical_address()), v = 0, r = 0, s = 0, ) signed_node_staking_score = node_staking_score.get_signed(private_key,MAINNET_NETWORK_ID) node_staking_scores.append(signed_node_staking_score) score = score/5 chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) node_staking_scores.sort(key=lambda x: -1* x.score) for node_staking_score in node_staking_scores: node_staking_score.validate() print(node_staking_score.is_signature_valid) print(node_staking_score.sender) print(node_staking_score.score, chain.get_mature_stake(node_staking_score.sender, node_staking_score.timestamp)) reward_bundle = chain.get_consensus_db().create_reward_bundle_for_block(GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), node_staking_scores, at_timestamp = int(time.time())) chain.get_consensus_db().validate_reward_bundle(reward_bundle, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), int(time.time())) print('AAAAAAAAAAA') print(reward_bundle.reward_type_1.amount) print(reward_bundle.reward_type_2.amount) print(reward_bundle.reward_type_2.proof[0].score) initial_balance = chain.get_vm().state.account_db.get_balance(GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) print("balance before reward = ", initial_balance) chain.import_current_queue_block_with_reward(reward_bundle.reward_type_2.proof) final_balance = chain.get_vm().state.account_db.get_balance(GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) print("balance after reward = ",final_balance) assert((reward_bundle.reward_type_1.amount + reward_bundle.reward_type_2.amount) == (final_balance- initial_balance)) print("waiting {} seconds before importing the next block".format(min_time_between_blocks)) time.sleep(min_time_between_blocks) proof_chain = MainnetChain(testdb, private_keys[1].public_key.to_canonical_address(), private_keys[1]) mature_stake = proof_chain.get_mature_stake() print("proof chain mature stake") print(mature_stake) staking_score = proof_chain.get_signed_peer_score_string_private_key(private_keys[1].to_bytes(), private_keys[0].public_key.to_canonical_address()) staking_score = staking_score.copy(score=1532) staking_score = staking_score.get_signed(private_keys[1], proof_chain.network_id) print('staking score') print(staking_score.score) # fields = [ # ('recipient_node_wallet_address', address), # ('score', f_big_endian_int), # a score out of 1,000,000 # ('since_block_number', f_big_endian_int), # ('timestamp', f_big_endian_int), # ('head_hash_of_sender_chain', hash32), # ('v', big_endian_int), # ('r', big_endian_int), # ('s', big_endian_int), # ] # reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) reward_bundle = reward_chain.get_consensus_db().create_reward_bundle_for_block(private_keys[0].public_key.to_canonical_address(), [staking_score],at_timestamp=Timestamp(int(time.time()))) print("reward type 2 amount") print(reward_bundle.reward_type_2.amount) print("reward type 2 proof") print(reward_bundle.reward_type_2.proof) reward_chain.import_current_queue_block_with_reward([staking_score]) # todo: this will fail if the reward block time is too long. Need to manually set it to a small number for the test... or manually make the blocks older? print("waiting {} seconds before importing the next block".format(min_time_between_blocks)) time.sleep(min_time_between_blocks) proof_chain = MainnetChain(testdb, private_keys[1].public_key.to_canonical_address(), private_keys[1]) mature_stake = proof_chain.get_mature_stake() print("proof chain mature stake") print(mature_stake) staking_score = proof_chain.get_signed_peer_score_string_private_key(private_keys[1].to_bytes(), private_keys[ 0].public_key.to_canonical_address()) staking_score = staking_score.copy(score=1000000) staking_score = staking_score.get_signed(private_keys[1], proof_chain.network_id) print('staking score') print(staking_score.score) # fields = [ # ('recipient_node_wallet_address', address), # ('score', f_big_endian_int), # a score out of 1,000,000 # ('since_block_number', f_big_endian_int), # ('timestamp', f_big_endian_int), # ('head_hash_of_sender_chain', hash32), # ('v', big_endian_int), # ('r', big_endian_int), # ('s', big_endian_int), # ] # reward_chain = MainnetChain(testdb, private_keys[0].public_key.to_canonical_address(), private_keys[0]) reward_bundle = reward_chain.get_consensus_db().create_reward_bundle_for_block( private_keys[0].public_key.to_canonical_address(), [staking_score], at_timestamp=Timestamp(int(time.time()))) print("reward type 2 amount") print(reward_bundle.reward_type_2.amount) print("reward type 2 proof") print(reward_bundle.reward_type_2.proof) reward_chain.import_current_queue_block_with_reward([staking_score])
def test_boson_vm_calculate_reward_based_on_fractional_interest(): testdb = MemoryDB() masternode_level_3_required_balance = MASTERNODE_LEVEL_3_REQUIRED_BALANCE masternode_level_3_multiplier = MASTERNODE_LEVEL_3_REWARD_TYPE_2_MULTIPLIER masternode_level_2_required_balance = MASTERNODE_LEVEL_2_REQUIRED_BALANCE masternode_level_2_multiplier = MASTERNODE_LEVEL_2_REWARD_TYPE_2_MULTIPLIER masternode_level_1_required_balance = MASTERNODE_LEVEL_1_REQUIRED_BALANCE masternode_level_1_multiplier = MASTERNODE_LEVEL_1_REWARD_TYPE_2_MULTIPLIER genesis_block_time = int(time.time()) - 10000000 genesis_params, genesis_state = create_new_genesis_params_and_state( GENESIS_PRIVATE_KEY, masternode_level_3_required_balance * 2, genesis_block_time) time_between_blocks = max(MIN_TIME_BETWEEN_BLOCKS, 1) # import genesis block MainnetChain.from_genesis( testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), genesis_params, genesis_state) stake_start = genesis_block_time + time_between_blocks tx_list = [[ GENESIS_PRIVATE_KEY, RECEIVER, masternode_level_3_required_balance, stake_start ], [ RECEIVER, RECEIVER2, (masternode_level_3_required_balance - masternode_level_2_required_balance - GAS_TX), stake_start + 100000 ], [ RECEIVER, RECEIVER2, (masternode_level_2_required_balance - masternode_level_1_required_balance - GAS_TX), stake_start + 200000 ], [ RECEIVER, RECEIVER2, (masternode_level_1_required_balance - 1000000 - GAS_TX), stake_start + 300000 ]] add_transactions_to_blockchain_db(testdb, tx_list) receiver_chain = MainnetChain(testdb, RECEIVER.public_key.to_canonical_address(), RECEIVER) fractional_interest = REWARD_TYPE_2_AMOUNT_FACTOR boson_fork_timestamp = 0 for timestamp_vm_config in MainnetChain.vm_configuration: if timestamp_vm_config[1].fork == 'boson': boson_fork_timestamp = timestamp_vm_config[0] boson_vm = receiver_chain.get_vm(timestamp=boson_fork_timestamp) consensus_db = boson_vm.consensus_db calculate_at_timestamp = int(time.time()) reward = consensus_db.calculate_reward_based_on_fractional_interest( RECEIVER.public_key.to_canonical_address(), fractional_interest, calculate_at_timestamp) if calculate_at_timestamp < EARLY_BIRD_BONUS_CUTOFF_TIMESTAMP: early_bird_bonus = EARLY_BIRD_BONUS_FACTOR else: early_bird_bonus = 1 expected_reward_part_1 = fractional_interest * early_bird_bonus * ( masternode_level_3_required_balance * 100000 * masternode_level_3_multiplier) expected_reward_part_2 = fractional_interest * early_bird_bonus * ( masternode_level_2_required_balance * 100000 * masternode_level_2_multiplier) expected_reward_part_3 = fractional_interest * early_bird_bonus * ( masternode_level_1_required_balance * 100000 * masternode_level_1_multiplier) expected_reward_part_4 = fractional_interest * early_bird_bonus * ( 1000000) * (calculate_at_timestamp - (stake_start + 300000) - consensus_db.coin_mature_time_for_staking) # print("Expected calculation = {} * {} * {} * {}".format((calculate_at_timestamp-(stake_start+300000)-COIN_MATURE_TIME_FOR_STAKING), 1000000, fractional_interest, 1)) # print("Expected calculation = {} * {} * {} * {}".format(100000, masternode_level_1_required_balance, fractional_interest, masternode_level_1_multiplier)) # print("Expected calculation = {} * {} * {} * {}".format(100000, masternode_level_2_required_balance, fractional_interest, masternode_level_2_multiplier)) # print("Expected calculation = {} * {} * {} * {}".format(100000, masternode_level_3_required_balance, fractional_interest, masternode_level_3_multiplier)) # # print("Expected reward {}".format(int(expected_reward_part_4))) # print("Expected reward {}".format(int(expected_reward_part_4)+int(expected_reward_part_3))) # print("Expected reward {}".format(int(expected_reward_part_4)+int(expected_reward_part_3)+int(expected_reward_part_2))) # print("Expected reward {}".format(int(expected_reward_part_4)+int(expected_reward_part_3)+int(expected_reward_part_2)+int(expected_reward_part_1))) expected_reward = int(expected_reward_part_1) + int( expected_reward_part_2) + int(expected_reward_part_3) + int( expected_reward_part_4) assert (reward == expected_reward)
def create_dev_test_random_blockchain_db_with_reward_blocks(base_db = None, num_iterations = 5): # initialize db if base_db == None: base_db = MemoryDB() create_dev_test_random_blockchain_database(base_db, timestamp = 'genesis') node_1 = MainnetChain(base_db, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) MIN_TIME_BETWEEN_BLOCKS = node_1.get_vm(timestamp = Timestamp(int(time.time()))).min_time_between_blocks chain_head_hashes = node_1.chain_head_db.get_head_block_hashes_list() last_block_timestamp = 0 for head_hash in chain_head_hashes: header = node_1.chaindb.get_block_header_by_hash(head_hash) if header.timestamp > last_block_timestamp: last_block_timestamp = header.timestamp private_keys_dict = {} for random_private_key in random_private_keys: priv_key = keys.PrivateKey(random_private_key) private_keys_dict[priv_key.public_key.to_address()] = priv_key private_keys_dict[GENESIS_PRIVATE_KEY.public_key.to_address()] = GENESIS_PRIVATE_KEY for i in range(num_iterations): # random_int = random.randint(0,len(private_keys_dict)-1) # numbers = [x in range(0, len(private_keys_dict)-1) if x != random_int] # random_int = random.choice(numbers) if i == 0: numbers = [x for x in range(0, len(private_keys_dict) - 1)] random_int = random.choice(numbers) privkey = GENESIS_PRIVATE_KEY receiver_privkey = private_keys_dict[list(private_keys_dict.keys())[random_int]] else: numbers = [x for x in range(0, len(private_keys_dict) - 1) if x != random_int] random_int = random.choice(numbers) privkey = receiver_privkey receiver_privkey = private_keys_dict[list(private_keys_dict.keys())[random_int]] tx_timestamp = last_block_timestamp + MIN_TIME_BETWEEN_BLOCKS+2 tx_list = [[privkey, receiver_privkey, 10000000*10**18-i*100000*10**18-random.randint(0,1000), tx_timestamp]] add_transactions_to_blockchain_db(base_db, tx_list) node_1 = MainnetChain(base_db, privkey.public_key.to_canonical_address(), privkey) chain_head_hashes = node_1.chain_head_db.get_head_block_hashes_list() reward_block_time = tx_timestamp + node_1.get_vm(timestamp = tx_timestamp).consensus_db.min_time_between_reward_blocks+ MIN_TIME_BETWEEN_BLOCKS+2+node_1.get_vm(timestamp = tx_timestamp).consensus_db.coin_mature_time_for_staking # print('BBBBBBB') # print(node_1.get_vm(timestamp=tx_timestamp).state.account_db.get_balance(receiver_privkey.public_key.to_canonical_address())) # print(node_1.chaindb.get_mature_stake(receiver_privkey.public_key.to_canonical_address(), node_1.get_consensus_db(timestamp=tx_timestamp).coin_mature_time_for_staking, reward_block_time)) node_staking_scores = [] for head_hash in chain_head_hashes: address = node_1.chaindb.get_chain_wallet_address_for_block_hash(head_hash) if not (address == privkey.public_key.to_canonical_address()): after_block_number = node_1.chaindb.get_latest_reward_block_number(privkey.public_key.to_canonical_address()) node_staking_score = NodeStakingScore(privkey.public_key.to_canonical_address(), 1, after_block_number, reward_block_time, head_hash, v=0, r=0, s=0) signed_node_staking_score = node_staking_score.get_signed(private_keys_dict[encode_hex(address)], node_1.network_id) node_staking_scores.append(signed_node_staking_score) if len(node_staking_scores) >= node_1.get_consensus_db(timestamp = tx_timestamp).required_number_of_proofs_for_reward_type_2_proof: # print('AAAAAAAAAAAA') # print(len(node_staking_scores)) # print(node_1.get_consensus_db(timestamp = tx_timestamp).required_number_of_proofs_for_reward_type_2_proof) reward_bundle = node_1.get_consensus_db(timestamp=tx_timestamp).create_reward_bundle_for_block(privkey.public_key.to_canonical_address(), node_staking_scores, reward_block_time) valid_block = create_valid_block_at_timestamp(base_db, privkey, reward_bundle = reward_bundle, timestamp = reward_block_time) assert(valid_block.header.timestamp == reward_block_time) node_1.import_block(valid_block) last_block_timestamp = reward_block_time return base_db
def test_get_receipts(): testdb2 = MemoryDB() MainnetChain.from_genesis( testdb2, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), MAINNET_GENESIS_PARAMS, MAINNET_GENESIS_STATE) """ Create some receive transactions for RECEIVER """ sender_chain = MainnetChain(testdb2, SENDER.public_key.to_canonical_address(), SENDER) min_time_between_blocks = sender_chain.get_vm( timestamp=Timestamp(int(time.time()))).min_time_between_blocks for i in range(6): sender_chain.create_and_sign_transaction_for_queue_block( gas_price=i + 1, gas=0x0c3500, to=RECEIVER.public_key.to_canonical_address(), value=i + 100000000000, data=b"", v=0, r=0, s=0) sender_chain.import_current_queue_block() receiver_chain = MainnetChain(testdb2, RECEIVER.public_key.to_canonical_address(), RECEIVER) receiver_chain.populate_queue_block_with_receive_tx() imported_block_1 = receiver_chain.import_current_queue_block() """ Create some send transactions for RECEIVER """ receiver_chain = MainnetChain(testdb2, RECEIVER.public_key.to_canonical_address(), RECEIVER) for i in range(6): receiver_chain.create_and_sign_transaction_for_queue_block( gas_price=i + 1, gas=0x0c3500, to=SENDER.public_key.to_canonical_address(), value=i, data=b"", v=0, r=0, s=0) """ Create a transaction with data in it. """ compiled_sol = load_compiled_sol_dict('contract_data/erc20_compiled.pkl') contract_interface = compiled_sol['contract_data/erc20.sol:SimpleToken'] w3 = Web3() SimpleToken = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # Build transaction to deploy the contract w3_tx1 = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS) from hvm.constants import CREATE_CONTRACT_ADDRESS receiver_chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=1375666, to=CREATE_CONTRACT_ADDRESS, value=0, data=decode_hex(w3_tx1['data']), v=0, r=0, s=0) receiver_chain.populate_queue_block_with_receive_tx() print("waiting {} seconds before importing next block".format( min_time_between_blocks)) time.sleep(min_time_between_blocks) imported_block = receiver_chain.import_current_queue_block() for i in range(7): if i < 6: receipt = sender_chain.chaindb.get_transaction_receipt( imported_block.transactions[i].hash) assert (receipt.status_code == b'\x01') assert (receipt.gas_used == GAS_TX) assert (receipt.bloom == 0) assert (receipt.logs == ()) if i == 6: receipt = sender_chain.chaindb.get_transaction_receipt( imported_block.transactions[i].hash) assert (receipt.status_code == b'\x01') assert (receipt.gas_used == 1375666) assert ( receipt.bloom == 243379359099696592952569079439667912256345493617967967903663341910531480774353059570732838085077727505416158987674861080353852392619637689071728561054211502067278701792094127192831079015338935810676425927305370163403783027301927515372719270157454901551766020292792184739669125690737609931485501648741152187826071626833444578979111366057983284511641401113379885201162016756050289195516614302086913696386892161910800529278878068496138240 ) assert (len(receipt.logs) == 1) for i in range(6): receipt = sender_chain.chaindb.get_transaction_receipt( imported_block_1.receive_transactions[i].hash) assert (receipt.status_code == b'\x01') assert (receipt.gas_used == 0) assert (receipt.bloom == 0) assert (receipt.logs == ()) # test_get_receipts()
def _test_airdrop_calling_erc_20(): # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/') # testdb = JournalDB(testdb) testdb = MemoryDB() chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) coin_mature_time = chain.get_vm(timestamp=Timestamp(int( time.time()))).consensus_db.coin_mature_time_for_staking genesis_params, genesis_state = create_new_genesis_params_and_state( GENESIS_PRIVATE_KEY, 1000000 * 10**18, int(time.time()) - coin_mature_time * 10000) # import genesis block chain = MainnetChain.from_genesis( testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), genesis_params, genesis_state, GENESIS_PRIVATE_KEY) # # erc20 contract deploy # compiled_erc20_sol = load_compiled_sol_dict( 'contract_data/erc20_compiled.pkl') EXPECTED_TOTAL_SUPPLY = 10000000000000000000000 erc20_contract_interface = compiled_erc20_sol[ 'contract_data/erc20.sol:SimpleToken'] w3 = Web3() SimpleToken = w3.eth.contract(abi=erc20_contract_interface['abi'], bytecode=erc20_contract_interface['bin']) # Build transaction to deploy the contract w3_erc20_tx = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS) max_gas = 20000000 chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=CREATE_CONTRACT_ADDRESS, value=0, data=decode_hex(w3_erc20_tx['data']), v=0, r=0, s=0) #time.sleep(1) print("deploying erc20 smart contract") imported_block = chain.import_current_queue_block() #now we need to add the block to the smart contract list_of_smart_contracts = chain.get_vm( ).state.account_db.get_smart_contracts_with_pending_transactions() erc20_contract_address = list_of_smart_contracts[0] chain = MainnetChain(testdb, erc20_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() # # airdrop contract deploy # compiled_airdrop_sol = load_compiled_sol_dict( 'contract_data/airdrop_compiled.pkl') EXPECTED_TOTAL_SUPPLY = 10000000000000000000000 airdrop_contract_interface = compiled_airdrop_sol[ 'contract_data/airdrop.sol:Airdrop'] Airdrop = w3.eth.contract(abi=airdrop_contract_interface['abi'], bytecode=airdrop_contract_interface['bin']) # Build transaction to deploy the contract w3_airdrop_tx = Airdrop.constructor().buildTransaction(W3_TX_DEFAULTS) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=CREATE_CONTRACT_ADDRESS, value=0, data=decode_hex(w3_airdrop_tx['data']), v=0, r=0, s=0) print("deploying airdrop smart contract") imported_block = chain.import_current_queue_block() # now we need to add the block to the smart contract list_of_smart_contracts = chain.get_vm( ).state.account_db.get_smart_contracts_with_pending_transactions() airdrop_contract_address = list_of_smart_contracts[0] chain = MainnetChain(testdb, airdrop_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() # # Interacting with deployed smart contract step 1) add send transaction # chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) print(erc20_contract_interface['abi']) simple_token = w3.eth.contract( address=Web3.toChecksumAddress(erc20_contract_address), abi=erc20_contract_interface['abi'], ) airdrop_token_balance = 1000 w3_erc20_send = simple_token.functions.transfer( Web3.toChecksumAddress(airdrop_contract_address), airdrop_token_balance).buildTransaction(W3_TX_DEFAULTS) chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=erc20_contract_address, value=0, data=decode_hex(w3_erc20_send['data']), v=0, r=0, s=0) imported_block = chain.import_current_queue_block() chain = MainnetChain(testdb, erc20_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() from pprint import pprint receipt = chain.chaindb.get_receipts(imported_block.header, Receipt)[0] receipt_dict = format_receipt_for_web3_to_extract_events( receipt, imported_block.receive_transactions[0].hash, chain) rich_logs = simple_token.events.Transfer().processReceipt(receipt_dict) print(rich_logs) print(rich_logs[0]['args']) print('a') assert (to_int( chain.chaindb.get_receipts( imported_block.header, Receipt)[0].logs[0].data) == airdrop_token_balance) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) w3_erc20_balance = simple_token.functions.balanceOf( Web3.toChecksumAddress(airdrop_contract_address)).buildTransaction( W3_TX_DEFAULTS) chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=erc20_contract_address, value=0, data=decode_hex(w3_erc20_balance['data']), v=0, r=0, s=0) imported_block = chain.import_current_queue_block() chain = MainnetChain(testdb, erc20_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() print(chain.chaindb.get_receipts(imported_block.header, Receipt)[0].logs) exit() #now lets look at the reciept to see the result assert (to_int( chain.chaindb.get_receipts( imported_block.header, Receipt)[0].logs[0].data) == EXPECTED_TOTAL_SUPPLY) print("Total supply call gave expected result!") gas_used = to_int( chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used) # # Interacting with deployed smart contract step 3) Receiving refund of extra gas that wasn't used in the computation # initial_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() final_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) assert ((final_balance - initial_balance) == (max_gas - gas_used)) print("Refunded gas is the expected amount.")
def test_erc_20_smart_contract_deploy_system(): # testdb = LevelDB('/home/tommy/.local/share/helios/instance_test/mainnet/chain/full/') # testdb = JournalDB(testdb) testdb = MemoryDB() chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) coin_mature_time = chain.get_vm(timestamp=Timestamp(int( time.time()))).consensus_db.coin_mature_time_for_staking now = int(time.time()) key_balance_dict = { private_keys[0]: (1000000000000, now - coin_mature_time * 10 - 100) } create_dev_fixed_blockchain_database(testdb, key_balance_dict) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) min_time_between_blocks = chain.get_vm( timestamp=Timestamp(int(time.time()))).min_time_between_blocks for private_key, balance_time in key_balance_dict.items(): assert (chain.get_vm().state.account_db.get_balance( private_key.public_key.to_canonical_address()) == balance_time[0]) SOLIDITY_SRC_FILE = 'contract_data/erc20.sol' EXPECTED_TOTAL_SUPPLY = 10000000000000000000000 #compiled_sol = compile_files([SOLIDITY_SRC_FILE]) compiled_sol = load_compiled_sol_dict('contract_data/erc20_compiled.pkl') contract_interface = compiled_sol['{}:SimpleToken'.format( SOLIDITY_SRC_FILE)] w3 = Web3() SimpleToken = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # Build transaction to deploy the contract w3_tx1 = SimpleToken.constructor().buildTransaction(W3_TX_DEFAULTS) max_gas = 20000000 chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=CREATE_CONTRACT_ADDRESS, value=0, data=decode_hex(w3_tx1['data']), v=0, r=0, s=0) #time.sleep(1) print("deploying smart contract") initial_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) imported_block = chain.import_current_queue_block() final_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) gas_used = to_int( chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used) assert ((initial_balance - final_balance) == gas_used) print(GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) print( generate_contract_address( GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), imported_block.transactions[0].nonce)) print( chain.chaindb.get_receipts(imported_block.header, Receipt)[0].logs[0].address) #contractAddress print("Used the correct amount of gas.") #now we need to add the block to the smart contract list_of_smart_contracts = chain.get_vm( ).state.account_db.get_smart_contracts_with_pending_transactions() deployed_contract_address = list_of_smart_contracts[0] print(list_of_smart_contracts) chain = MainnetChain(testdb, deployed_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() imported_block = chain.import_current_queue_block() list_of_smart_contracts = chain.get_vm( ).state.account_db.get_smart_contracts_with_pending_transactions() print(list_of_smart_contracts) #lets make sure it didn't create a refund transaction for the initial sender. print(chain.get_vm().state.account_db.has_receivable_transactions( GENESIS_PRIVATE_KEY.public_key.to_canonical_address())) # print('ASDASD') # print(chain.chaindb.get_receipts(imported_block.header, Receipt)[0].logs[0].data) # # Interacting with deployed smart contract step 1) add send transaction # chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) simple_token = w3.eth.contract( address=Web3.toChecksumAddress(deployed_contract_address), abi=contract_interface['abi'], ) w3_tx2 = simple_token.functions.totalSupply().buildTransaction( W3_TX_DEFAULTS) chain.create_and_sign_transaction_for_queue_block( gas_price=0x01, gas=max_gas, to=deployed_contract_address, value=0, data=decode_hex(w3_tx2['data']), v=0, r=0, s=0) #lets make sure it subtracts the entire max gas initial_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) print("waiting {} seconds before importing next block".format( min_time_between_blocks)) time.sleep(min_time_between_blocks) chain.import_current_queue_block() final_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) assert ((initial_balance - final_balance) == max_gas) # # Interacting with deployed smart contract step 2) add receive transaction to smart contract chain # chain = MainnetChain(testdb, deployed_contract_address, private_keys[0]) chain.populate_queue_block_with_receive_tx() print("waiting {} seconds before importing next block".format( min_time_between_blocks)) time.sleep(min_time_between_blocks) imported_block = chain.import_current_queue_block() receipt = chain.chaindb.get_receipts(imported_block.header, Receipt)[0] receipt_dict = format_receipt_for_web3_to_extract_events( receipt, imported_block.receive_transactions[0].hash, chain) rich_logs = simple_token.events.Print().processReceipt(receipt_dict) print(rich_logs[0]['args']) print('a') #now lets look at the reciept to see the result assert (to_int( chain.chaindb.get_receipts( imported_block.header, Receipt)[0].logs[0].data) == EXPECTED_TOTAL_SUPPLY) print("Total supply call gave expected result!") gas_used = to_int( chain.chaindb.get_receipts(imported_block.header, Receipt)[0].gas_used) # # Interacting with deployed smart contract step 3) Receiving refund of extra gas that wasn't used in the computation # initial_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) chain = MainnetChain(testdb, GENESIS_PRIVATE_KEY.public_key.to_canonical_address(), GENESIS_PRIVATE_KEY) chain.populate_queue_block_with_receive_tx() print("waiting {} seconds before importing next block".format( min_time_between_blocks)) time.sleep(min_time_between_blocks) imported_block = chain.import_current_queue_block() final_balance = chain.get_vm().state.account_db.get_balance( GENESIS_PRIVATE_KEY.public_key.to_canonical_address()) assert ((final_balance - initial_balance) == (max_gas - gas_used)) print("Refunded gas is the expected amount.")