class AddressToUrlTestCase(unittest.TestCase): def setUp(self): with open('compiled.evm') as f: compiled = f.read().rstrip() self.c = EthJsonRpc() self.c._call('evm_reset') self.cb = self.c.eth_coinbase() self.contract_addr = self.AddressToUrl(self.cb, compiled) def tearDown(self): pass def test_set(self): url = 'http://www.yahoo.com' self.set_url(self.cb, self.contract_addr, url) result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual(url, result) def test_set_clear(self): url = 'http://www.yahoo.com' self.set_url(self.cb, self.contract_addr, url) result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual(url, result) self.set_url(self.cb, self.contract_addr, '') result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual('', result) def test_get(self): result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual('', result) ################################################################################ def AddressToUrl(self, sender, compiled): ''' constructor ''' sig = 'AddressToUrl()' args = [] tx = self.c.create_contract(sender, compiled, 300000, sig, args) return self.c.get_contract_address(tx) def set_url(self, sender, contract_addr, ip): sig = 'set_url(string)' args = [ip] self.c.call_with_transaction(sender, contract_addr, sig, args) def get_url(self, contract_addr, addr): sig = 'get_url(address)' args = [addr] result_types = ['string'] return self.c.call(contract_addr, sig, args, result_types)[0]
class AddressToUrlTestCase(unittest.TestCase): def setUp(self): with open('compiled.evm') as f: compiled = f.read().rstrip() self.c = EthJsonRpc() self.c._call('evm_reset') self.cb = self.c.eth_coinbase() self.contract_addr = self.AddressToUrl(self.cb, compiled) def tearDown(self): pass def test_set(self): url = 'http://www.yahoo.com' self.set_url(self.cb, self.contract_addr, url) result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual(url, result) def test_set_clear(self): url = 'http://www.yahoo.com' self.set_url(self.cb, self.contract_addr, url) result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual(url, result) self.set_url(self.cb, self.contract_addr, '') result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual('', result) def test_get(self): result = self.get_url(self.contract_addr, self.cb[2:]) self.assertEqual('', result) ################################################################################ def AddressToUrl(self, sender, compiled): ''' constructor ''' sig = 'AddressToUrl()' args = [] tx = self.c.create_contract(sender, compiled, 300000, sig, args) return self.c.get_contract_address(tx) def set_url(self, sender, contract_addr, ip): sig = 'set_url(string)' args = [ip] self.c.call_with_transaction(sender, contract_addr, sig, args) def get_url(self, contract_addr, addr): sig = 'get_url(address)' args = [addr] result_types = ['string'] return self.c.call(contract_addr, sig, args, result_types)[0]
def main(): # # create rpc interface # try: rpc = EthJsonRpc(RPC_HOST, RPC_PORT) except: print('unable to connect to rpc server at {}:{}'.format( RPC_HOST, RPC_PORT)) sys.exit(-1) method = sys.argv[1] if method == "newContract": owner = sys.argv[2] partner = sys.argv[3] text = sys.argv[4] tx = rpc.call_with_transaction(owner, CONTRACT_STORAGE_ADDRESS, 'createNewContract(string,string)', [partner, text], gas=GAS) print(format(tx)) elif method == "contractData": trans_addr = sys.argv[2] trans = rpc.eth_getTransactionByHash(trans_addr) res = Decoder.decodeABI(trans['input'], 'createNewContract(string,string)', ['string', 'string']) print(res) elif method == "newUser": address = sys.argv[2] dataString = sys.argv[3] tx = rpc.call_with_transaction(address, USER_STORAGE_ADDRESS, 'setUserIdentityDocs(string)', [dataString], gas=GAS) elif method == "identification": account_addr = sys.argv[2] transactionHashes, identityDocuments = rpc.call( USER_STORAGE_ADDRESS, 'getUser(address)', [account_addr], ['string', 'string']) print(identityDocuments) elif method == "accounts": account_id = sys.argv[2] print(rpc.eth_accounts()[int(account_id)]) else: print("method not recognized!")
def get_eth(key_from, task_price): # Тут стучимся в эфир compiled = u"0x6060604052341561000f57600080fd5b5b61099c8061001f6000396000f30060606040523615610076576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007b57806318160ddd146100d557806323b872dd146100fe57806370a0823114610177578063a9059cbb146101c4578063dd62ed3e1461021e575b600080fd5b341561008657600080fd5b6100bb600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061028a565b604051808215151515815260200191505060405180910390f35b34156100e057600080fd5b6100e8610412565b6040518082815260200191505060405180910390f35b341561010957600080fd5b61015d600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610418565b604051808215151515815260200191505060405180910390f35b341561018257600080fd5b6101ae600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506106c9565b6040518082815260200191505060405180910390f35b34156101cf57600080fd5b610204600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610713565b604051808215151515815260200191505060405180910390f35b341561022957600080fd5b610274600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108af565b6040518082815260200191505060405180910390f35b60008082148061031657506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b151561032157600080fd5b81600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506104ec83600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061058183600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506105d7838261095690919063ffffffff16565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505b509392505050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b600061076782600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506107fc82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b92915050565b600080828401905083811015151561094b57fe5b8091505b5092915050565b600082821115151561096457fe5b81830390505b929150505600a165627a7a72305820555bd5fd700426621f595ca4d327cb2441e425da32bc02af1980faedabc29e880029" c = EthJsonRpc('127.0.0.1', 8545) c.net_version() # continued from above contract_tx = c.create_contract(settings.GENERAL_KEY, compiled, gas=300000) contract_addr = c.get_contract_address(contract_tx) value = task_price/(10**18) tx = c.call_with_transaction(settings.GENERAL_KEY, contract_addr, 'transferFrom({0}, {1}, {2})'.format( settings.GENERAL_KEY, key_from, value), ['Hello, world']) return tx
def synchronize(backend, strategy, user, response, is_new=False, *args, **kwargs): compiled = u"0x6060604052341561000f57600080fd5b5b61099c8061001f6000396000f30060606040523615610076576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063095ea7b31461007b57806318160ddd146100d557806323b872dd146100fe57806370a0823114610177578063a9059cbb146101c4578063dd62ed3e1461021e575b600080fd5b341561008657600080fd5b6100bb600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061028a565b604051808215151515815260200191505060405180910390f35b34156100e057600080fd5b6100e8610412565b6040518082815260200191505060405180910390f35b341561010957600080fd5b61015d600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610418565b604051808215151515815260200191505060405180910390f35b341561018257600080fd5b6101ae600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506106c9565b6040518082815260200191505060405180910390f35b34156101cf57600080fd5b610204600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610713565b604051808215151515815260200191505060405180910390f35b341561022957600080fd5b610274600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108af565b6040518082815260200191505060405180910390f35b60008082148061031657506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b151561032157600080fd5b81600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b92915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506104ec83600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061058183600160008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506105d7838261095690919063ffffffff16565b600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505b509392505050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b919050565b600061076782600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461095690919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506107fc82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461093790919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b92915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490505b92915050565b600080828401905083811015151561094b57fe5b8091505b5092915050565b600082821115151561096457fe5b81830390505b929150505600a165627a7a72305820555bd5fd700426621f595ca4d327cb2441e425da32bc02af1980faedabc29e880029" c = EthJsonRpc('127.0.0.1', 8545) c.net_version() # continued from above contract_tx = c.create_contract(settings.GENERAL_KEY, compiled, gas=300000) contract_addr = c.get_contract_address(contract_tx) balans = c.call_with_transaction( settings.GENERAL_KEY, contract_addr, 'eth.getBalance("{0}")'.format(settings.GENERAL_KEY), ['Hello, world']) user.balans = balans user.save() return True
def main(): # # receive contract addr # if len(sys.argv) != 3: print('Usage:\npython user.py <contract addr> <account addr>') sys.exit(-1) contract_addr = sys.argv[1] account_addr = sys.argv[2] # # create rpc interface # try: print('-' * 80) rpc = EthJsonRpc(RPC_HOST, RPC_PORT) print('client software: {}'.format(rpc.web3_clientVersion())) print('block: {}'.format(rpc.eth_blockNumber())) print('address: {}'.format(rpc.eth_coinbase())) except: print('unable to connect to rpc server at {}:{}'.format( RPC_HOST, RPC_PORT)) sys.exit(-1) # # check contract is online # print('-' * 80) if rpc.eth_getCode(contract_addr) == '0x0': print('!!! contract code not available on blockchain !!!') sys.exit(-1) print('found contract on blockchain!') # # console # topics = [] print('-' * 80) print('starting chat command line...') while True: # # simply read input # sys.stdout.write('>> ') command = sys.stdin.readline() # # quit? # if 'q' in command: sys.exit(0) # # show help # elif command == '\n' or 'help' in command: print('commands: help, send, status, topics, search, listen') # # compose new message # elif 'send' in command: print('-' * 80) print('[composing new message]') sys.stdout.write('message....: ') msg = sys.stdin.readline().strip() sys.stdout.write('image file.: ') img = sys.stdin.readline().strip() sys.stdout.write('custom tags: ') tag = sys.stdin.readline().strip() print('-' * 80) print('sending...') # loading image try: image = Image.open(img) except Exception as e: print('loading {} failed'.format(img)) continue # prediction print('precessing image...') label = ImageClassifier.predict(img) if label is None: print('classification failed') continue print('label: {}'.format(label)) tag += ' #' + label bs = ImageHelper.imgToBytes(image) tx = rpc.call_with_transaction( account_addr, contract_addr, 'setNewUserState(string,bytes,string)', [msg, bs, tag], gas=GAS) print('done, transaction id: {}'.format(tx)) # # get own last post # elif 'status' in command: print('-' * 80) print('[receiving last post]') userMessage, userImage, userTags = rpc.call( contract_addr, 'getUserState(address)', [account_addr], ['string', 'bytes', 'string']) if not userMessage: print('nothing posted yet') continue print(' content: {}'.format(userMessage)) print(' tags...: {}'.format(userTags)) ImageHelper.bytesToImg(userImage).show() # # set tag filters # elif 'topics' in command: topics = [t.strip() for t in command.split()[1:]] if len(topics) == 0: print('please provide actual topics after <topics> command') continue print('filter set for messages on topics: {}'.format(topics)) # # search complete blockchain for messages with certain tags # elif 'search' in command: if len(topics) == 0: print('call topics first') continue curBlock = rpc.eth_blockNumber() for i in range(curBlock + 1): for trans in rpc.eth_getBlockByNumber(i)['transactions']: res = Decoder.decodeABI(trans['input']) if res is None: continue msg, code, tags = res if all(t not in tags for t in topics): continue print('-' * 80) print('message from user {} (block {}):'.format( trans['from'], i)) print(' content: {}'.format(msg)) print(' tags...: {}'.format(tags)) ImageHelper.bytesToImg(code).show(title='{}'.format(tags)) # # start listening for messages # elif 'listen' in command: if len(topics) == 0: print('call topics first') continue global LISTENING LISTENING = True curBlock = rpc.eth_blockNumber() while LISTENING: newBlock = rpc.eth_blockNumber() if newBlock > curBlock: print('new block detected ({})'.format(newBlock)) curBlock = newBlock for trans in rpc.eth_getBlockByNumber( newBlock)['transactions']: res = Decoder.decodeABI(trans['input']) if res is None: continue msg, code, tags = res if all(t not in tags for t in topics): continue print('-' * 80) print('message from user {} (block {}):'.format( trans['from'], newBlock)) print(' content: {}'.format(msg)) print(' tags...: {}'.format(tags)) ImageHelper.bytesToImg(code).show( title='{}'.format(tags)) time.sleep(1) # # default response # else: print('command not recognized')
class Ipv4TestCase(unittest.TestCase): def setUp(self): with open('compiled.evm') as f: compiled = f.read().rstrip() self.c = EthJsonRpc() self.c._call('evm_reset') self.cb = self.c.eth_coinbase() self.contract_addr = self.AddressToIPv4(self.cb, compiled) def tearDown(self): pass ################################################################################ def test_read(self): result = self.get_ip(self.contract_addr, self.cb[2:]) unchained_ip = self.ip_from_chain(result) self.assertEqual('0.0.0.0', unchained_ip) def test_set_read(self): ip = u'192.168.1.1' chained_ip = self.ip_to_chain(ip) self.set_ip(self.cb, self.contract_addr, chained_ip) result = self.get_ip(self.contract_addr, self.cb[2:]) unchained_ip = self.ip_from_chain(result) self.assertEqual(ip, unchained_ip) def test_set_delete_read(self): ip = u'192.168.1.1' chained_ip = self.ip_to_chain(ip) self.set_ip(self.cb, self.contract_addr, chained_ip) self.delete_ip(self.cb, self.contract_addr) result = self.get_ip(self.contract_addr, self.cb[2:]) unchained_ip = self.ip_from_chain(result) self.assertEqual('0.0.0.0', unchained_ip) ################################################################################ def ip_to_chain(self, ip): return int(IPv4Address(ip)) def ip_from_chain(self, ip): return str(IPv4Address(ip)) ################################################################################ def AddressToIPv4(self, sender, compiled): ''' constructor ''' sig = 'AddressToIPv4()' args = [] tx = self.c.create_contract(sender, compiled, sig, args) return self.c.get_contract_address(tx) def set_ip(self, sender, contract_addr, ip): sig = 'set_ip(uint32)' args = [ip] self.c.call_with_transaction(sender, contract_addr, sig, args) def delete_ip(self, sender, contract_addr): sig = 'delete_ip()' args = [] self.c.call_with_transaction(sender, contract_addr, sig, args) def get_ip(self, contract_addr, addr): sig = 'get_ip(address)' args = [addr] result_types = ['uint32'] return self.c.call(contract_addr, sig, args, result_types)[0]
def main(): # # create rpc interface # try: rpc = EthJsonRpc(RPC_HOST, RPC_PORT) except: print('unable to connect to rpc server at {}:{}'.format( RPC_HOST, RPC_PORT)) sys.exit(-1) if sys.argv[1] == "contracts": transactionHashes, identityDocuments = rpc.call( USER_STORAGE_ADDRESS, 'getUser(address)', [0x866d9f0b315afa2dcf31be291882ae9a1965f86a], ['string', 'string']) print(transactionHashes) elif sys.argv[1] == "newContract": owner = sys.argv[2] partner = sys.argv[3] text = sys.argv[4] tx = rpc.call_with_transaction(owner, CONTRACT_STORAGE_ADDRESS, 'createNewContract(string,string)', [partner, text], gas=GAS) print('done, transaction id: {}'.format(tx)) transHash = format(tx) trans = rpc.eth_getTransactionByHash(transHash) res = Decoder.decodeABI(trans['input'], 'createNewContract(string,string)', ['string', 'string']) print(res) transHashes = transHash #rpc.call(USER_STORAGE_ADDRESS, 'getUserTransactions(address)', [owner], ['string']) #transHashes += "," + transHash; tx = rpc.call_with_transaction(owner, USER_STORAGE_ADDRESS, 'setUserTransactions(string)', [transHashes], gas=GAS) trans = rpc.eth_getTransactionByHash(format(tx)) res = Decoder.decodeABI(trans['input'], 'setUserTransactions(string)', ['string']) print(res) transHashes = transHash #rpc.call(USER_STORAGE_ADDRESS, 'getUserTransactions(address)', [partner], ['string']) #transHashes += "," + transHash; tx = rpc.call_with_transaction(partner, USER_STORAGE_ADDRESS, 'setUserTransactions(string)', [transHashes], gas=GAS) print('done, transaction id: {}'.format(tx)) trans = rpc.eth_getTransactionByHash(format(tx)) res = Decoder.decodeABI(trans['input'], 'setUserTransactions(string)', ['string']) print(res) owner = "0x866d9f0b315afa2dcf31be291882ae9a1965f86a" partner = "0x115908c9272fc6b915286de90e25a24862d69988"
vibrationCountThreshold = 1000 while True: line = serialTTL.readline() data = line.split(',') vibration = data[0] temperature = data[1] if (vibration > vibrationThreshold): vibrationCount = vibrationCount + 1 if (temperature > tempThreshold): tempCount = tempCount + 1 ts = int(time.time()) if (vibrationCount > vibrationCountThreshold): #Send a transaction to requestService function of #MachineService contract with Machine-ID c.call_with_transaction(c.eth_coinbase(), contract_addr, 'requestService(uint256,uint256,string)', [ts, machineID, 'High vibrations']) vibrationCount = 0 if (tempCount > tempCountThreshold): c.call_with_transaction(c.eth_coinbase(), contract_addr, 'requestService(uint256,uint256,string)', [ts, machineID, 'High temperature']) tempCount = 0 time.sleep(1)
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" }] @staticmethod def _calculate_hash(data_to_hash): salt = SHA256.new() salt.update(bytes(random.getrandbits(256))) original_hash = SHA256.new() original_hash.update(data_to_hash) salted_hash = SHA256.new() salted_hash.update(original_hash.digest() + salt.digest()) salt = salt.hexdigest().decode("hex") original_hash = original_hash.hexdigest().decode("hex") salted_hash = salted_hash.hexdigest().decode("hex") return salted_hash, salt, original_hash, data_to_hash def unlock_account(self, account, password): self.connection._call('personal_unlockAccount', params=[account, password, 36000]) def add_hash(self, data): if self.contract_id is None: raise IOError salted_hash, salt, original_hash, _ = self._calculate_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 original_hash def create_contract(self, data): if not hasattr(self, 'byte_code'): contract_file = open(__file__[:-11] + '\LiteID-Contract.sol') code_data = self.connection.eth_compileSolidity( contract_file.read()) self.byte_code = code_data['ID']['code'] self.abi_def = code_data['ID']['info']['abiDefinition'] salted_hash, salt, original_hash, _ = self._calculate_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 contract 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)
contract_address = '0x016D9579a34F7855D5A954d127469260e7F3A5a4' machineID = 123 # Connect to Blockchain network -- Ganache # c = EthJsonRpc('192.168.1.4', 8101) tempCount = 0 tempThreshold = 20 #Celcius tempCountThreshold = 10 while True: f = open(device_file, 'r') lines = f.readlines() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temperature = float(temp_string)/1000.0 print "Temp:", temperature, "C" if(temperature>tempThreshold): tempCount = tempCount + 1 ts = int(time.time()) print ("ts: ", ts) if(tempCount>tempCountThreshold): c.call_with_transaction(c.eth_coinbase(), contract_address, 'requestService(uint256,uint256,string)', [ts, machineID, 'High']) tempCount = 0 time.sleep(1):
while True: ## f = open(device_file, 'r') ## lines = f.readlines() ## ## while lines[0].strip()[-3:] != 'YES': ## time.sleep(0.2) ## lines = read_temp_raw() ## equals_pos = lines[1].find('t=') ## if(equals_pos != -1): ## temp_string = lines[1][equals_pos+2:] ## temperature = float(temp_string)/1000.0 ## print "Temp:", temperature, "C" humidity, temperature = Adafruit_DHT.read_retry(11, 4) print("Temperature") print(temperature) if (temperature > tempThreshold): tempCount = tempCount + 1 ts = int(time.time()) print("ts: ", ts) if (tempCount > tempCountThreshold): print("temp gt threshol") #c.call_with_transaction(c.eth_coinbase(), contract_address, 'requestService(uint256,uint256,string)', [ts, machineID1, "Temperature is crossed Treshold"]) c.call_with_transaction( c.eth_coinbase(), contract_address, 'requestService(uint256,uint256,string)', [ts, machineID1, "Please update your Software"]) print("aftre transaction") tempCount = 0 time.sleep(1)
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
vibrationCountThreshold = 1000 while True: line = serialTTL.readline() data = line.split(',') vibration = data[0] temperature = data[1] if(vibration>vibrationThreshold): vibrationCount = vibrationCount+1 if(temperature>tempThreshold): tempCount = tempCount+1 ts = int(time.time()) if(vibrationCount>vibrationCountThreshold): #Send a transaction to requestService function of #MachineService contract with Machine-ID c.call_with_transaction(c.eth_coinbase(), contract_addr, 'requestService(uint256,uint256,string)', [ts, machineID, 'High vibrations']) vibrationCount = 0 if(tempCount>tempCountThreshold): c.call_with_transaction(c.eth_coinbase(), contract_addr, 'requestService(uint256,uint256,string)', [ts, machineID, 'High temperature']) tempCount = 0 time.sleep(1)
from ethjsonrpc import EthJsonRpc # to use Parity-specific methods, import ParityEthJsonRpc base_address = "0xbb1588c5debc2871cd8852c4bd6c6e4cb1d9fe15" c = EthJsonRpc('127.0.0.1', 8545) print(c.net_version()) print(c.web3_clientVersion()) print(c.net_listening()) print(c.net_peerCount()) print(c.eth_mining()) print(c.eth_gasPrice()) contract_addr = "0xc1bba31875a1a66eb4794e6e4dd07811fb58b5c5" my_addr = str(c.eth_coinbase()) print my_addr tx = c.call_with_transaction(my_addr, contract_addr, 'pushByte(string)', ['Hello, world']) print(tx) results = c.call(contract_addr, 'getdata()', [], ['string']) print(results)