class LiteIDContract: def __init__(self, ip='127.0.0.1', port=8545, contract_id=None): self.connection = EthJsonRpc(ip, port) self.contract_id = contract_id self.abi_def = [{ "constant": False, "inputs": [], "name": "dumpSaltedHashArray", "outputs": [{ "name": "Hashes", "type": "bytes32[]" }, { "name": "Salts", "type": "bytes32[]" }, { "name": "Timestamps", "type": "uint256[]" }], "payable": False, "type": "function" }, { "constant": False, "inputs": [{ "name": "Hash", "type": "bytes32" }, { "name": "Salt", "type": "bytes32" }], "name": "addHash", "outputs": [], "payable": False, "type": "function" }, { "inputs": [{ "name": "Hash", "type": "bytes32" }, { "name": "Salt", "type": "bytes32" }], "payable": False, "type": "constructor" }] def _caculate_hash(self, data): salt = bytearray(random.getrandbits(8) for i in range(32)) origanal_hash = hashlib.sha256(data) salted_hash = hashlib.sha256(origanal_hash.digest() + salt) salt = (''.join('{:02x}'.format(x) for x in salt)).decode("hex") origanal_hash = origanal_hash.hexdigest().decode("hex") salted_hash = salted_hash.hexdigest().decode("hex") return salted_hash, salt, origanal_hash def unlockAccount(self, account, password): self.connection._call('personal_unlockAccount', params=[account, password, 36000]) def addHash(self, data): if self.contract_id is None: raise IOError salted_hash, salt, origanal_hash = self._caculate_hash(data) tx = self.connection.call_with_transaction( self.connection.eth_coinbase(), self.contract_id, 'addHash(bytes32,bytes32)', [salted_hash, salt]) print "Waiting for addHash to be mined" while self.connection.eth_getTransactionReceipt(tx) is None: time.sleep(1) return origanal_hash def create_contranct(self, data): if not hasattr(self, 'byte_code'): file = open('LiteID-Contranct.sol') code_data = self.connection.eth_compileSolidity(file.read()) self.byte_code = code_data['ID']['code'] self.abi_def = code_data['ID']['info']['abiDefinition'] salted_hash, salt, origanal_hash = self._caculate_hash(data) tx_id = self.connection.create_contract(self.connection.eth_coinbase(), self.byte_code, 300000, sig='addHash(bytes32,bytes32)', args=[salted_hash, salt]) print "Waiting for contranct to be mined" while self.connection.eth_getTransactionReceipt(tx_id) is None: time.sleep(1) self.contract_id = self.connection.eth_getTransactionReceipt( tx_id)['contractAddress'] return self.contract_id def dump_hashes(self): return_types = list() for item in self.abi_def: try: if item['name'] == 'dumpSaltedHashArray': for i in item['outputs']: return_types.append(i['type']) except KeyError: pass return_types = ['bytes32[]', 'bytes32[]', 'uint256[]'] return self.connection.call(self.contract_id, 'dumpSaltedHashArray()', [], return_types)
#code = '' #print c.eth_compileLLL(code) ################################################################################ print '*' * 80 b = (246236, '0xcd43703a1ead33ffa1f317636c7b67453c5cc03a3350cd71dbbdd70fcbe0987a') index = 2 print c.eth_getTransactionByBlockHashAndIndex(b[1], index) for x in ['earliest', 'latest', 'pending', b[0]]: print c.eth_getTransactionByBlockNumberAndIndex(b[0], index) tx = '0x27191ea9e8228c98bc4418fa60843540937b0c615b2db5e828756800f533f8cd' print c.eth_getTransactionReceipt(tx) b = (246294, '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16') index = 0 print c.eth_getUncleByBlockHashAndIndex(b[1], index) for x in ['earliest', 'latest', 'pending', b[0]]: print c.eth_getUncleByBlockNumberAndIndex(b[0], index) ################################################################################ print '*' * 80 addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe' for x in ['earliest', 'latest', 'pending', 150000]: print c.eth_getBalance(addr, x)
if __name__ == "__main__": a = LiteIDContract( contract_id=u'0xB2a045bb7D0eb64BD044763ae572077E5182247B') a.unlockAccount("0x2fe84be2806ecef45adef9699d5a6f1939d0a377", "mypassword") #a.create_contranct("lol") a.addHash("hi") c = EthJsonRpc('127.0.0.1', 8545) tx = c.call_with_transaction( c.eth_coinbase(), a.contract_id, 'addHash(bytes32,bytes32)', [ '79d3b5b20c84c399e403048359def1398b729ac9a2d88485972be2e691af46de'. decode("hex"), '5e408dafb1164edde8e95527f9a4bd2abb3bd55fb4e32f8f5ea806a683fccbd6'. decode("hex") ]) while c.eth_getTransactionReceipt(tx) is None: pass print "Contranct id: {}".format(a.contract_id) for item in a.dump_hashes(): print item # Salted Hash: 0x62335b41ea49e29b99bd8767324dc4b5e3453a77c74883078ebcafc7589f0605 # Salt: 0xecf438e57277a4191c1875ccc9fedefb4b5feb9b62a4f38de457392a30814822 # 0x64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c
class Deploy: def __init__(self, protocol, host, port, add_dev_code, verify_code, contract_dir, gas, gas_price, private_key): self.pp = PreProcessor() self.s = t.state() self.s.block.number = 1150000 # Homestead t.gas_limit = int(gas) self.json_rpc = EthJsonRpc(protocol=protocol, host=host, port=port) if private_key: self.user_address = '0x' + privtoaddr( private_key.decode('hex')).encode('hex') else: self.user_address = self.json_rpc.eth_coinbase()["result"] self.add_dev_code = add_dev_code == 'true' self.verify_code = verify_code == 'true' self.contract_dir = contract_dir self.gas = int(gas) self.gas_price = int(gas_price) self.private_key = private_key self.contract_addresses = {} self.contract_abis = {} def wait_for_transaction_receipt(self, transaction_hash): while self.json_rpc.eth_getTransactionReceipt( transaction_hash)['result'] is None: logging.info( 'Waiting for transaction receipt {}'.format(transaction_hash)) time.sleep(5) def replace_address(self, a): if isinstance(a, list): return [self.replace_address(i) for i in a] else: return self.contract_addresses[a] if isinstance( a, basestring) and a in self.contract_addresses else a def get_nonce(self): return int( self.json_rpc.eth_getTransactionCount( self.user_address)["result"][2:], 16) def get_raw_transaction(self, data, contract_address=''): nonce = self.get_nonce() tx = Transaction(nonce, self.gas_price, self.gas, contract_address, 0, data.decode('hex')) tx.sign(self.private_key.decode('hex')) return rlp.encode(tx).encode('hex') def code_is_valid(self, contract_address, compiled_code): deployed_code = self.json_rpc.eth_getCode(contract_address)["result"] locally_deployed_code_address = self.s.evm( compiled_code.decode("hex")).encode("hex") locally_deployed_code = self.s.block.get_code( locally_deployed_code_address).encode("hex") return deployed_code == "0x" + locally_deployed_code @staticmethod def compile_code(code, language): combined = languages[language].combined(code) compiled_code = combined[-1][1]["bin_hex"] abi = combined[-1][1]["abi"] return compiled_code, abi @staticmethod def replace_library_placeholders(bytecode, addresses): if addresses: for library_name, library_address in addresses.iteritems(): bytecode = bytecode.replace( "__{}{}".format(library_name, "_" * (38 - len(library_name))), library_address[2:]) return bytecode def deploy_code(self, file_path, reference, params, addresses): if addresses: addresses = dict([(k, self.replace_address(v)) for k, v in addresses.iteritems()]) language = "solidity" if file_path.endswith(".sol") else "serpent" code = self.pp.process(file_path, add_dev_code=self.add_dev_code, contract_dir=self.contract_dir, addresses=addresses) # compile code bytecode, abi = self.compile_code(code, language) # replace library placeholders bytecode = self.replace_library_placeholders(bytecode, addresses) if params: translator = ContractTranslator(abi) # replace constructor placeholders params = [self.replace_address(p) for p in params] bytecode += translator.encode_constructor_arguments(params).encode( "hex") logging.info( 'Try to create contract with length {} based on code in file: {}'. format(len(bytecode), file_path)) if self.private_key: raw_tx = self.get_raw_transaction(bytecode) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) while "error" in tx_response: logging.info('Deploy failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) else: tx_response = self.json_rpc.eth_sendTransaction( self.user_address, data=bytecode, gas=self.gas, gas_price=self.gas_price) while "error" in tx_response: logging.info('Deploy failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendTransaction( self.user_address, data=bytecode, gas=self.gas, gas_price=self.gas_price) transaction_hash = tx_response['result'] self.wait_for_transaction_receipt(transaction_hash) contract_address = self.json_rpc.eth_getTransactionReceipt( transaction_hash)["result"]["contractAddress"] # Verify deployed code with locally deployed code if self.verify_code and not self.code_is_valid(contract_address, bytecode): logging.info('Deploy of {} failed. Retry!'.format(file_path)) self.deploy_code(file_path, params, addresses) if reference: contract_name = reference else: contract_name = file_path.split("/")[-1].split(".")[0] self.contract_addresses[contract_name] = contract_address self.contract_abis[contract_name] = abi logging.info('Contract {} was created at address {}.'.format( reference if reference else file_path, contract_address)) def send_transaction(self, contract, name, params): contract_address = self.replace_address(contract) contract_abi = self.contract_abis[contract] translator = ContractTranslator(contract_abi) data = translator.encode(name, self.replace_address(params)).encode("hex") logging.info('Try to send {} transaction to contract {}.'.format( name, contract)) if self.private_key: raw_tx = self.get_raw_transaction(data, contract_address) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) while 'error' in tx_response: logging.info('Transaction failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendRawTransaction("0x" + raw_tx) else: tx_response = self.json_rpc.eth_sendTransaction( self.user_address, to_address=contract_address, data=data, gas=self.gas, gas_price=self.gas_price) while 'error' in tx_response: logging.info('Transaction failed with error {}. Retry!'.format( tx_response['error'])) time.sleep(5) tx_response = self.json_rpc.eth_sendTransaction( self.user_address, to_address=contract_address, data=data, gas=self.gas, gas_price=self.gas_price) transaction_hash = tx_response['result'] self.wait_for_transaction_receipt(transaction_hash) logging.info('Transaction {} for contract {} completed.'.format( name, contract)) @staticmethod def strip_0x(string): if string.startswith("0x"): return string[2:] return string def assert_call(self, contract, name, params, return_value): contract_address = self.replace_address(contract) return_value = self.replace_address(return_value) contract_abi = self.contract_abis[contract] translator = ContractTranslator(contract_abi) data = "0x" + translator.encode( name, [self.replace_address(p) for p in params]).encode("hex") logging.info('Try to assert return value of {} in contract {}.'.format( name, contract)) response = self.json_rpc.eth_call(from_address=self.user_address, to_address=contract_address, data=data) bc_return_val = response["result"] result_decoded = translator.decode(name, bc_return_val[2:].decode("hex")) result_decoded = result_decoded if len( result_decoded) > 1 else result_decoded[0] if isinstance(return_value, int) or isinstance(return_value, long): assert result_decoded == return_value else: assert result_decoded.lower() == self.strip_0x( return_value.lower()) logging.info( 'Assertion successful for return value of {} in contract {}.'. format(name, contract)) def process(self, f): with open(f) as data_file: instructions = json.load(data_file) logging.info('Your address: {}'.format(self.user_address)) for instruction in instructions: logging.info('Your balance: {} Wei'.format( int( self.json_rpc.eth_getBalance( self.user_address)['result'], 16))) if instruction["type"] == "deployment": self.deploy_code( instruction["file"], instruction["reference"] if "reference" in instruction else None, instruction["params"] if "params" in instruction else None, instruction["addresses"] if "addresses" in instruction else None, ) elif instruction["type"] == "transaction": self.send_transaction( instruction["contract"], instruction["name"], instruction["params"] if "params" in instruction else [], ) elif instruction["type"] == "assertion": self.assert_call( instruction["contract"], instruction["name"], instruction["params"] if "params" in instruction else [], instruction["return"]) for contract_name, contract_address in self.contract_addresses.iteritems( ): logging.info('Contract {} was created at address {}.'.format( contract_name, contract_address))
class EthDeploy: def __init__(self, protocol, host, port, gas, gas_price, contract_dir, optimize, account, private_key_path): # establish rpc connection self.json_rpc = EthJsonRpc(protocol=protocol, host=host, port=port) self.solidity = _solidity.solc_wrapper() self._from = None self.private_key = None # set sending account if account: self._from = self.add_0x(account) elif private_key_path: with open(private_key_path, 'r') as private_key_file: self.private_key = private_key_file.read().strip() self._from = self.add_0x( privtoaddr(self.private_key.decode('hex')).encode('hex')) else: accounts = self.json_rpc.eth_accounts()['result'] if len(accounts) == 0: raise ValueError('No account unlocked') self._from = self.add_0x(accounts[0]) # account address in right format if not self.is_address(self._from): raise ValueError('Account address is wrong') self.optimize = optimize self.contract_dir = contract_dir self.gas = gas self.gas_price = gas_price # references dict maps labels to addresses self.references = {} # abis dict maps addresses to abis self.abis = {} # total consumed gas self.total_gas = 0 self.log('Instructions are sent from address: {}'.format(self._from)) balance = self.hex2int( self.json_rpc.eth_getBalance(self._from)['result']) self.log('Address balance: {} Ether / {} Wei'.format( balance / 10.0**18, balance)) def is_address(self, string): return len(self.add_0x(string)) == 42 @staticmethod def hex2int(_hex): return int(_hex, 16) @staticmethod def add_0x(string): if not string.startswith('0x'): return '0x' + string return string @staticmethod def strip_0x(string): if string.startswith('0x'): return string[2:] return string @staticmethod def log(string): logger.info(string) def format_reference(self, string): return self.add_0x(string) if self.is_address(string) else string def log_transaction_receipt(self, transaction_receipt): gas_used = self.hex2int(transaction_receipt['gasUsed']) self.total_gas += gas_used self.log( 'Transaction receipt: {} block number, {} gas used, {} cumulative gas used' .format(self.hex2int(transaction_receipt['blockNumber']), gas_used, self.hex2int(transaction_receipt['cumulativeGasUsed']))) def get_transaction_receipt(self, transaction_hash): return self.json_rpc.eth_getTransactionReceipt( transaction_hash)['result'] def wait_for_transaction_receipt(self, transaction_hash): while self.get_transaction_receipt(transaction_hash) is None: self.log( 'Waiting for transaction receipt {}'.format(transaction_hash)) time.sleep(5) return self.get_transaction_receipt(transaction_hash) def replace_references(self, a): if isinstance(a, list): return [self.replace_references(i) for i in a] else: return self.references[a] if isinstance( a, basestring) and a in self.references else a def get_nonce(self): transaction_count = self.json_rpc.eth_getTransactionCount( self._from, default_block='pending')['result'] return self.hex2int(self.strip_0x(transaction_count)) def get_raw_transaction(self, to='', value=0, data=''): nonce = self.get_nonce() tx = Transaction(nonce, self.gas_price, self.gas, to, value, data.decode('hex')) tx.sign(self.private_key.decode('hex')) return self.add_0x(rlp.encode(tx).encode('hex')) def compile_code(self, code=None, path=None): # create list of valid paths absolute_path = self.contract_dir if self.contract_dir.startswith( '/') else '{}/{}'.format(os.getcwd(), self.contract_dir) sub_dirs = [x[0] for x in os.walk(absolute_path)] extra_args = ' '.join( ['{}={}'.format(d.split('/')[-1], d) for d in sub_dirs]) # compile code combined = self.solidity.combined(code, path=path, libraries=self.references, optimize=self.optimize, extra_args=extra_args) bytecode = combined[-1][1]['bin_hex'] abi = combined[-1][1]['abi'] return bytecode, abi def deploy(self, _from, file_path, bytecode, sourcecode, libraries, value, params, label, abi): # replace library placeholders if libraries: for library_name, library_address in libraries.iteritems(): self.references[library_name] = self.replace_references( self.strip_0x(library_address)) if file_path: if self.contract_dir: file_path = '{}/{}'.format(self.contract_dir, file_path) bytecode, abi = self.compile_code(path=file_path) if not label: label = file_path.split("/")[-1].split(".")[0] if sourcecode: # compile code bytecode, abi = self.compile_code(code=sourcecode) if params: translator = ContractTranslator(abi) # replace constructor placeholders params = [self.replace_references(p) for p in params] bytecode += translator.encode_constructor_arguments(params).encode( 'hex') # deploy contract self.log('Deployment transaction for {} sent'.format( label if label else 'unknown')) tx_response = None if self.private_key: raw_tx = self.get_raw_transaction(value=value, data=bytecode) while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Deploy failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx) else: while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Deploy failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) tx_response = self.json_rpc.eth_sendTransaction( self.add_0x(_from if _from else self._from), value=value, data=self.add_0x(bytecode), gas=self.gas, gas_price=self.gas_price) transaction_receipt = self.wait_for_transaction_receipt( self.add_0x(tx_response['result'])) contract_address = self.strip_0x( transaction_receipt['contractAddress']) self.references[label] = contract_address self.abis[contract_address] = abi self.log('Contract {} created at address {}'.format( label if label else 'unknown', self.add_0x(contract_address))) self.log_transaction_receipt(transaction_receipt) def send_transaction(self, _from, to, value, name, params, abi): reference = to to = self.replace_references(to) data = '' if name or abi: if not name: name = abi['name'] abi = self.abis[to] if to in self.abis else [abi] translator = ContractTranslator(abi) data = translator.encode( name, self.replace_references(params)).encode("hex") self.log('Transaction to {}{} sent'.format( self.format_reference(reference), ' calling {} function'.format(name) if name else '')) tx_response = None if self.private_key: raw_tx = self.get_raw_transaction(to=to, value=value, data=data) while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Transaction failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) tx_response = self.json_rpc.eth_sendRawTransaction(raw_tx) else: while tx_response is None or 'error' in tx_response: if tx_response and 'error' in tx_response: self.log('Transaction failed with error {}'.format( tx_response['error']['message'])) time.sleep(5) tx_response = self.json_rpc.eth_sendTransaction( self.add_0x(_from if _from else self._from), to_address=self.add_0x(to), value=value, data=self.add_0x(data), gas=self.gas, gas_price=self.gas_price) transaction_hash = tx_response['result'] transaction_receipt = self.wait_for_transaction_receipt( self.add_0x(transaction_hash)) self.log('Transaction to {}{} successful'.format( self.format_reference(reference), ' calling {} function'.format(name) if name else '')) self.log_transaction_receipt(transaction_receipt) def call(self, _from, to, value, name, params, label, assertion, abi): reference = to to = self.replace_references(to) if not name: name = abi['name'] abi = self.abis[to] if to in self.abis else [abi] translator = ContractTranslator(abi) data = translator.encode(name, self.replace_references(params)).encode('hex') response = self.json_rpc.eth_call( self.add_0x(to), from_address=self.add_0x(_from if _from else self._from), value=value, data=self.add_0x(data), gas=self.gas, gas_price=self.gas_price) result = translator.decode( name, self.strip_0x(response['result']).decode('hex')) result = result if len(result) > 1 else result[0] if label: self.references[label] = result if assertion: expected_result = self.replace_references(assertion) if isinstance(expected_result, int) or isinstance( expected_result, long): assert result == expected_result else: assert result.lower() == self.strip_0x(expected_result.lower()) self.log('Assertion of {} at {} successful'.format( name, self.format_reference(reference))) else: self.log('Call to {} calling function {} successful'.format( self.format_reference(reference), name)) def process(self, f): # read instructions file with open(f, 'r') as instructions_file: instructions = json.load(instructions_file) for i in instructions: if i['type'] == 'abi': for address in i['addresses']: self.abis[self.strip_0x(address)] = i['abi'] if i['type'] == 'deployment': self.deploy(i['from'] if 'from' in i else None, i['file'] if 'file' in i else None, i['bytecode'] if 'bytecode' in i else None, i['sourcecode'] if 'sourcecode' in i else None, i['libraries'] if 'libraries' in i else None, i['value'] if 'value' in i else 0, i['params'] if 'params' in i else (), i['label'] if 'label' in i else None, i['abi'] if 'abi' in i else None) elif i["type"] == "transaction": self.send_transaction( i['from'] if 'from' in i else None, i['to'] if 'to' in i else None, i['value'] if 'value' in i else 0, i['name'] if 'name' in i else None, i['params'] if 'params' in i else (), i['abi'] if 'abi' in i else None, ) elif i["type"] == "call": self.call( i['from'] if 'from' in i else None, i['to'] if 'to' in i else None, i['value'] if 'value' in i else 0, i['name'] if 'name' in i else None, i['params'] if 'params' in i else (), i['label'] if 'label' in i else None, i['assertion'] if 'assertion' in i else None, i['abi'] if 'abi' in i else None, ) self.log('-' * 96) self.log('Summary: {} gas used, {} Ether / {} Wei spent on gas'.format( self.total_gas, self.total_gas * self.gas_price / 10.0**18, self.total_gas * self.gas_price)) for reference, value in self.references.iteritems(): self.log('{} references {}'.format( reference, self.add_0x(value) if isinstance(value, unicode) else value)) self.log('-' * 96)
#code = '' #print(geth_client.eth_compileLLL(code) ################################################################################ print('*' * 80) b = (246236, '0xcd43703a1ead33ffa1f317636c7b67453c5cc03a3350cd71dbbdd70fcbe0987a') index = 2 print(geth_client.eth_getTransactionByBlockHashAndIndex(b[1], index)) for x in ['earliest', 'latest', 'pending', b[0]]: print(geth_client.eth_getTransactionByBlockNumberAndIndex(b[0], index)) tx = '0x27191ea9e8228c98bc4418fa60843540937b0c615b2db5e828756800f533f8cd' print(geth_client.eth_getTransactionReceipt(tx)) b = (246294, '0x3d596ca3c7b344419567957b41b2132bb339d365b6b6b3b6a7645e5444914a16') index = 0 print(geth_client.eth_getUncleByBlockHashAndIndex(b[1], index)) for x in ['earliest', 'latest', 'pending', b[0]]: print(geth_client.eth_getUncleByBlockNumberAndIndex(b[0], index)) ################################################################################ print('*' * 80) addr = '0x1dcb8d1f0fcc8cbc8c2d76528e877f915e299fbe' for x in ['earliest', 'latest', 'pending', 150000]: print(geth_client.eth_getBalance(addr, x))