def test_arg_ipc_provider(self): ipc_provider = IPCProvider(ipc_path='', testnet=True) service1 = Web3Service() self.assertIsInstance(service1.web3.currentProvider, RPCProvider) service2 = Web3Service(ipc_provider) self.assertIsInstance(service2.web3.currentProvider, IPCProvider) self.assertEquals(service2.web3.currentProvider, ipc_provider)
def setUp(self): os.environ.update({'TESTRPC_GAS_LIMIT': '10000000000'}) self.provider = TestRPCProvider() web3_service = Web3Service(self.provider) self.web3 = web3_service.web3 # Mock web3 self.daemon = DaemonFactory() self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 1000000} # create oracles centralized_contract_factory = self.web3.eth.contract( abi=centralized_oracle_abi, bytecode=centralized_oracle_bytecode) tx_hash = centralized_contract_factory.deploy() self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt( tx_hash).get('contractAddress') self.centralized_oracle_factory = self.web3.eth.contract( self.centralized_oracle_factory_address, abi=centralized_oracle_abi) self.contracts = [{ 'NAME': 'Centralized Oracle Factory', 'EVENT_ABI': centralized_oracle_abi, 'EVENT_DATA_RECEIVER': 'django_eth_events.tests.utils.CentralizedOraclesReceiver', 'ADDRESSES': [self.centralized_oracle_factory_address[2::]] }] self.listener_under_test = EventListener(contract_map=self.contracts, provider=self.provider) CentralizedOracle().reset()
def setUp(self): self.web3 = Web3Service( provider=EthereumTesterProvider(EthereumTester())).web3 self.provider = self.web3.providers[0] self.web3.eth.defaultAccount = self.web3.eth.coinbase # Mock web3 self.daemon = DaemonFactory() self.ipfs = Ipfs() self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 1000000} # create oracles centralized_contract_factory = self.web3.eth.contract( abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')), bytecode=centralized_oracle_bytecode) tx_hash = centralized_contract_factory.constructor().transact() self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt( tx_hash).get('contractAddress') self.centralized_oracle_factory = self.web3.eth.contract( self.centralized_oracle_factory_address, abi=load_json_file(abi_file_path('CentralizedOracleFactory.json'))) self.contracts = [{ 'NAME': 'Centralized Oracle Factory', 'EVENT_ABI': load_json_file(abi_file_path('CentralizedOracleFactory.json')), 'EVENT_DATA_RECEIVER': 'chainevents.event_receivers.CentralizedOracleFactoryReceiver', 'ADDRESSES': [self.centralized_oracle_factory_address[2::]] }] self.listener_under_test = EventListener(contract_map=self.contracts, provider=self.provider)
def setUp(self): os.environ.update({'TESTRPC_GAS_LIMIT': '10000000000'}) self.rpc = TestRPCProvider() web3_service = Web3Service(self.rpc) self.web3 = web3_service.web3 # Mock web3 self.daemon = DaemonFactory() self.ipfs = Ipfs() self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 100000000} # create oracles centralized_contract_factory = self.web3.eth.contract( abi=load_json_file(abi_file_path('CentralizedOracleFactory.json')), bytecode=centralized_oracle_bytecode) tx_hash = centralized_contract_factory.deploy() self.centralized_oracle_factory_address = self.web3.eth.getTransactionReceipt( tx_hash).get('contractAddress') self.centralized_oracle_factory = self.web3.eth.contract( self.centralized_oracle_factory_address, abi=load_json_file(abi_file_path('CentralizedOracleFactory.json'))) self.contracts = [{ 'NAME': 'Centralized Oracle Factory', 'EVENT_ABI': load_json_file(abi_file_path('CentralizedOracleFactory.json')), 'EVENT_DATA_RECEIVER': 'chainevents.event_receivers.CentralizedOracleFactoryReceiver', 'ADDRESSES': [self.centralized_oracle_factory_address[2::]] }] self.listener_under_test = EventListener(self.contracts)
def test_reorg_centralized_oracle(self): # initial transaction, to set reorg init accounts = self.web3.eth.accounts self.web3.eth.sendTransaction({ 'from': accounts[0], 'to': accounts[1], 'value': 5000000 }) self.assertEqual(0, Block.objects.all().count()) self.assertEqual(CentralizedOracle().length(), 0) self.assertEqual(1, self.web3.eth.blockNumber) # Create centralized oracle tx_hash = self.centralized_oracle_factory.transact( self.tx_data).createCentralizedOracle( 'QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG') self.assertIsNotNone(tx_hash) self.listener_under_test.execute() self.assertEqual(CentralizedOracle().length(), 1) self.assertEqual(2, Daemon.get_solo().block_number) self.assertEqual(2, Block.objects.all().count()) self.assertEqual(2, self.web3.eth.blockNumber) # Reset blockchain (simulates reorg) self.provider.server.shutdown() self.provider.server.server_close() self.provider = TestRPCProvider() web3_service = Web3Service(self.provider) self.web3 = web3_service.web3 self.assertEqual(0, self.web3.eth.blockNumber) self.web3.eth.sendTransaction({ 'from': accounts[0], 'to': accounts[1], 'value': 1000000 }) self.web3.eth.sendTransaction({ 'from': accounts[0], 'to': accounts[1], 'value': 1000000 }) self.web3.eth.sendTransaction({ 'from': accounts[0], 'to': accounts[1], 'value': 1000000 }) self.assertEqual(2, self.web3.eth.blockNumber) # force block_hash change (cannot recreate a real reorg with python testrpc) block_hash = remove_0x_head(self.web3.eth.getBlock(1)['hash']) Block.objects.filter(block_number=1).update(block_hash=block_hash) self.listener_under_test.execute() self.assertEqual(CentralizedOracle().length(), 0) self.assertEqual(2, Daemon.get_solo().block_number) self.assertEqual(2, Block.objects.all().count())
def __init__(self, contract_map=None, provider=None): self.decoder = Decoder() # Decodes Ethereum logs self.web3 = Web3Service( provider=provider ).web3 # Gets transaction and block info from ethereum if not contract_map: contract_map = settings.ETH_EVENTS self.contract_map = contract_map # Taken from settings, it's the contracts we listen to self.provider = provider
def setUp(self): # Run mocked testrpc for reorgs print('Starting httpd...') self.server_process = Process(target=start_mock_server) self.server_process.start() cache.set('block_number', '0x0') sleep(1) print('served') self.rpc = RPCProvider(host='127.0.0.1', port='8545', ssl=0) web3_service = Web3Service(self.rpc) self.web3 = web3_service.web3 # Mock web3 self.daemon = DaemonFactory()
def test_single_istance(self): service1 = Web3Service() service2 = Web3Service() self.assertEquals(service1.web3, service2.web3)
def test_arg_rpc_provider(self): rpc_provider = RPCProvider(host='localhost', port=8545, ssl=0) service1 = Web3Service() service2 = Web3Service(rpc_provider) self.assertEquals(service1.web3, service2.web3)
def test_save_generic_tournament_participant(self): oracle = CentralizedOracleFactory() block = { 'number': oracle.creation_block, 'timestamp': mktime(oracle.creation_date_time.timetuple()) } contract_address = "d833215cbcc3f914bd1c9ece3ee7bf8b14f841bb" registrant_address = "90f8bf6a479f320ead074411a4b0e7944ea8c9c1" registrant_address2 = "80f8bf6a479f320ead074411a4b0e7944ea8c9c2" registered_mainnet_address = "ffcf8fdee72ac11b5c542428b35eef5769c409f0" participant_event = { "address": contract_address, "name": "AddressRegistration", "params": [{ "name": "registrant", "value": registrant_address, }, { "name": "registeredMainnetAddress", "value": registered_mainnet_address, }] } s = GenericTournamentParticipantEventSerializerTimestamped( data=participant_event, block=block) self.assertTrue(s.is_valid(), s.errors) self.assertEqual(TournamentParticipant.objects.all().count(), 0) instance = s.save() self.assertEqual(TournamentParticipant.objects.all().count(), 1) self.assertEqual( TournamentParticipant.objects.first().tournament_balance.balance, 0) self.assertIsNotNone(instance) self.assertEqual(instance.address, registrant_address) self.assertEqual(instance.mainnet_address, registered_mainnet_address) web3_service = Web3Service( provider=EthereumTesterProvider(EthereumTester())) web3 = web3_service.web3 checksumed_registrant_address2 = web3.toChecksumAddress( '0x' + registrant_address2) tournament_token_abi = load_json_file( abi_file_path('TournamentToken.json')) # create tournament token tournament_token = web3.eth.contract( abi=tournament_token_abi, bytecode=tournament_token_bytecode) tx_hash = tournament_token.constructor().transact() tournament_token_address = web3.eth.getTransactionReceipt(tx_hash).get( 'contractAddress') self.assertIsNotNone(tournament_token_address) # Get token instance token_contract = web3.eth.contract(abi=tournament_token_abi, address=tournament_token_address) # Issue tokens tokens_amount = 100 tx_hash = token_contract.functions.issue( [checksumed_registrant_address2], tokens_amount).transact({'from': web3.eth.coinbase}) blockchain_balance = token_contract.functions.balanceOf( checksumed_registrant_address2).call() self.assertEqual(blockchain_balance, tokens_amount) # Save participant 2 oracle = CentralizedOracleFactory() block = { 'number': oracle.creation_block, 'timestamp': mktime(oracle.creation_date_time.timetuple()) } participant_with_tokens_event = { "address": contract_address, "name": "AddressRegistration", "params": [{ "name": "registrant", "value": checksumed_registrant_address2[2:], }, { "name": "registeredMainnetAddress", "value": registered_mainnet_address, }] } # Mocks with self.settings(TOURNAMENT_TOKEN=tournament_token_address): # Mock Web3Service __new__ method to retrieve the same web3 instance used to deploy the contract Web3ServiceProvider.instance = web3_service s = GenericTournamentParticipantEventSerializerTimestamped( data=participant_with_tokens_event, block=block) self.assertTrue(s.is_valid(), s.errors) instance = s.save() self.assertEqual(TournamentParticipant.objects.all().count(), 2) self.assertEqual( TournamentParticipant.objects.first().tournament_balance. balance, tokens_amount)
def setUp(self): os.environ.update({'TESTRPC_GAS_LIMIT': '10000000000'}) self.rpc = TestRPCProvider() self.web3 = Web3Service().web3 self.tx_data = {'from': self.web3.eth.accounts[0], 'gas': 1000000} self.event_receivers = []
def check_reorg(provider=None): """ Checks for reorgs to happening :param provider: optional Web3 provider instance :return: Tuple (True|False, None|Block number) :raise NetworkReorgException :raise UnknownBlockReorg :raise NoBackup """ web3 = None saved_block_number = Daemon.get_solo().block_number try: web3 = Web3Service(provider=provider).web3 if web3.isConnected(): current_block_number = web3.eth.blockNumber else: raise Exception() except: raise NetworkReorgException( 'Unable to get block number from current node. Check the node is up and running.' ) if current_block_number >= saved_block_number: # check last saved block hash haven't changed blocks = Block.objects.all().order_by('-block_number') if blocks.count(): # check if there was reorg for block in blocks: try: node_block_hash = remove_0x_head( web3.eth.getBlock(block.block_number)['hash']) except: raise UnknownBlockReorg if block.block_hash == node_block_hash: # if is last saved block, no reorg if block.block_number == saved_block_number: return False, None else: # there was a reorg from a saved block, we can do rollback return True, block.block_number # Exception, no saved history enough errors = { 'saved_block_number': saved_block_number, 'current_block_number': current_block_number, 'las_saved_block_hash': blocks[0].block_hash } raise NoBackup( message='Not enough backup blocks, reorg cannot be rollback', errors=errors) else: # No backup data return False, None else: # check last common block hash haven't changed blocks = Block.objects.filter( block_number__lte=current_block_number).order_by('-block_number') if blocks.count(): # check if there was reorg for block in blocks: try: node_block_hash = remove_0x_head( web3.eth.getBlock(block.block_number)['hash']) except: raise UnknownBlockReorg if block.block_hash == node_block_hash: # if is last saved block, no reorg if block.block_number == saved_block_number: return False, None else: # there was a reorg from a saved block, we can do rollback return True, block.block_number # Exception, no saved history enough errors = { 'saved_block_number': saved_block_number, 'current_block_number': current_block_number, 'las_saved_block_hash': blocks[0].block_hash } raise NoBackup( message='Not enough backup blocks, reorg cannot be rollback', errors=errors) else: # No backup data return False, None