def do_store(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print('Unknown sub-command, expecting one of {0}'.format(subcommands)) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': transaction_type_name = web_client.get_store_list() print(pretty_print_dict(transaction_type_name)) return elif args.subcommand == 'show': store_info = \ web_client.get_store_by_name( txn_type_or_name=args.transactionTypeName, key=args.key, block_id=args.blockID, delta=args.incremental) print(pretty_print_dict(store_info)) return except MessageException as e: raise CliException(e)
def do_store(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format(subcommands) return web_client = _get_webclient(args) try: if args.subcommand == 'list': transaction_type_name = web_client.get_store_by_name() print pretty_print_dict(transaction_type_name) return elif args.subcommand == 'show': if args.blockID is not None: block_id = args.blockID else: block_id = '' if args.key is not None: key = args.key else: key = '' store_info = web_client.get_store_by_name(args.transactionTypeName, key, block_id, args.incremental) print pretty_print_dict(store_info) return except MessageException as e: raise CliException(e)
def do_block(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format( subcommands) return web_client = _get_webclient(args) try: if args.subcommand == 'list': if args.all: blockids = web_client.get_block_list() else: blockids = web_client.get_block_list(args.blockcount) for block_id in blockids: print block_id return elif args.subcommand == 'show': if args.key is not None: block_info = web_client.get_block(args.blockID, args.key) else: block_info = web_client.get_block(args.blockID) print pretty_print_dict(block_info) return except MessageException as e: raise CliException(e)
def do_block(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format(subcommands) return web_client = _get_webclient(args) try: if args.subcommand == 'list': if args.all: blockids = web_client.get_block_list() else: blockids = web_client.get_block_list(args.blockcount) for block_id in blockids: print block_id return elif args.subcommand == 'show': if args.key is not None: block_info = web_client.get_block(args.blockID, args.key) else: block_info = web_client.get_block(args.blockID) print pretty_print_dict(block_info) return except MessageException as e: raise CliException(e)
def do_store(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format( subcommands) return web_client = _get_webclient(args) try: if args.subcommand == 'list': transaction_type_name = web_client.get_store_by_name() print pretty_print_dict(transaction_type_name) return elif args.subcommand == 'show': if args.blockID is not None: block_id = args.blockID else: block_id = '' if args.key is not None: key = args.key else: key = '' store_info = web_client.get_store_by_name(args.transactionTypeName, key, block_id, args.incremental) print pretty_print_dict(store_info) return except MessageException as e: raise CliException(e)
def do_store(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print('Unknown sub-command, expecting one of {0}'.format( subcommands)) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': transaction_type_name = web_client.get_store_list() print(pretty_print_dict(transaction_type_name)) return elif args.subcommand == 'show': store_info = \ web_client.get_store_by_name( txn_type_or_name=args.transactionTypeName, key=args.key, block_id=args.blockID, delta=args.incremental) print(pretty_print_dict(store_info)) return except MessageException as e: raise CliException(e)
def sign_and_post(self, msg): msg.SenderID = self.LocalNode.Identifier msg.sign_from_node(self.LocalNode) try: result = self.LedgerWebClient.post_message(msg) if result: pretty_print_dict(result) except ledger_web_client.MessageException as me: print me
def sign_and_post(self, msg): msg.SenderID = self.LocalNode.Identifier msg.sign_from_node(self.LocalNode) try: result = self.LedgerWebClient.post_message(msg) if result: pretty_print_dict(result) except MessageException as me: print me
def sign_and_post(self, msg): msg.SenderID = self._local_node.Identifier msg.sign_from_node(self._local_node) try: result = self._client.forward_message(msg) if result: pretty_print_dict(result) except MessageException as me: print me
def do_transaction(args): subcommands = ['list', 'show', 'status'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format( subcommands) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': if args.all: tsctids = web_client.get_transaction_list() else: tsctids = \ web_client.get_transaction_list( block_count=args.blockcount) print_trans_info(args, web_client, tsctids) elif args.subcommand == 'show': tsct_info = \ web_client.get_transaction( transaction_id=args.transactionID, field=args.key) print pretty_print_dict(tsct_info) return elif args.subcommand == 'status': tsct_status = web_client.get_transaction_status(args.transactionID) if tsct_status == transaction.Status.committed: print 'transaction committed' elif tsct_status == transaction.Status.pending: print 'transaction still uncommitted' elif tsct_status == transaction.Status.unknown: print 'unknown transaction' elif tsct_status == transaction.Status.failed: print 'transaction failed to validate.' else: print 'transaction returned unexpected status code {0}'\ .format(tsct_status) return except MessageException as e: raise CliException(e)
def do_transaction(args): subcommands = ['list', 'show', 'status'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format( subcommands) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': if args.all: tsctids = web_client.get_transaction_list() else: tsctids = \ web_client.get_transaction_list( block_count=args.blockcount) for txn_id in tsctids: print txn_id return elif args.subcommand == 'show': tsct_info = \ web_client.get_transaction( transaction_id=args.transactionID, field=args.key) print pretty_print_dict(tsct_info) return elif args.subcommand == 'status': tsct_status = web_client.get_transaction_status(args.transactionID) if tsct_status == transaction.Status.committed: print 'transaction committed' elif tsct_status == transaction.Status.pending: print 'transaction still uncommitted' elif tsct_status == transaction.Status.unknown: print 'unknown transaction' elif tsct_status == transaction.Status.failed: print 'transaction failed to validate.' else: print 'transaction returned unexpected status code {0}'\ .format(tsct_status) return except MessageException as e: raise CliException(e)
def do_get(self, request): """ Handle a GET request on the HTTP interface. Three paths are accepted: /store[/<storename>[/<key>|*]] /block[/<blockid>] /transaction[/<txnid>] """ # pylint: disable=invalid-name # split the request path removing leading duplicate slashes components = request.path.split('/') while components and components[0] == '': components.pop(0) prefix = components.pop(0) if components else 'error' if prefix not in self.GetPageMap: # attempt to serve static content if present. resource = self.static_content.getChild(request.path[1:], request) return resource.render(request) test_only = (request.method == 'HEAD') try: response = self.GetPageMap[prefix](components, request.args, test_only) if test_only: return '' cbor = (request.getHeader('Accept') == 'application/cbor') if cbor: request.responseHeaders.addRawHeader(b"content-type", b"application/cbor") return dict2cbor(response) request.responseHeaders.addRawHeader(b"content-type", b"application/json") pretty = 'p' in request.args if pretty: result = pretty_print_dict(response) + '\n' else: result = dict2json(response) return result except Error as e: return self.error_response( request, int(e.status), 'exception while processing http request {0}; {1}', request.path, str(e)) except: logger.warn('error processing http request %s; %s', request.path, traceback.format_exc(20)) return self.error_response(request, http.BAD_REQUEST, 'error processing http request {0}', request.path)
def render_GET(self, request): """ Handle a GET request on the HTTP interface. Three paths are accepted: /store[/<storename>[/<key>|*]] /block[/<blockid>] /transaction[/<txnid>] """ # pylint: disable=invalid-name # split the request path removing leading duplicate slashes components = request.path.split('/') while components and components[0] == '': components.pop(0) prefix = components.pop(0) if components else 'error' if prefix not in self.GetPageMap: return self.error_response(request, http.BAD_REQUEST, 'unknown request {0}', request.path) testonly = (request.method == 'HEAD') try: response = self.GetPageMap[prefix](components, request.args, testonly) if testonly: return '' cbor = (request.getHeader('Accept') == 'application/cbor') if cbor: request.responseHeaders.addRawHeader(b"content-type", b"application/cbor") return dict2cbor(response) request.responseHeaders.addRawHeader(b"content-type", b"application/json") pretty = 'p' in request.args if pretty: result = pretty_print_dict(response) + '\n' else: result = dict2json(response) return result except Error as e: return self.error_response( request, int(e.status), 'exception while processing http request {0}; {1}', request.path, str(e)) except: logger.warn('error processing http request %s; %s', request.path, traceback.format_exc(20)) return self.error_response(request, http.BAD_REQUEST, 'error processing http request {0}', request.path)
def do_get(self, request): """ Handle a GET request on the HTTP interface. Three paths are accepted: /store[/<storename>[/<key>|*]] /block[/<blockid>] /transaction[/<txnid>] """ # pylint: disable=invalid-name # split the request path removing leading duplicate slashes LOGGER.info("%s.do_get %s", self.__class__.__name__, request.path) components = request.path.split('/') while components and components[0] == '': components.pop(0) if components[0] != self.page_name: return self.error_response(request, http.NOT_FOUND, "Invalid page name: {}", request.path) else: components.pop(0) test_only = (request.method == 'HEAD') try: response = self.render_get(request, components, request.args) if test_only: return '' cbor = (request.getHeader('Accept') == 'application/cbor') if cbor: request.responseHeaders.addRawHeader(b"content-type", b"application/cbor") return dict2cbor(response) request.responseHeaders.addRawHeader(b"content-type", b"application/json") pretty = False if 'p' in request.args: pretty = request.args['p'] == ['1'] if pretty: result = pretty_print_dict(response) + '\n' else: result = dict2json(response) return result except Error as e: return self.error_response( request, int(e.status), 'exception while processing http request {0}; {1}', request.path, str(e)) except: LOGGER.warn('error processing http request %s; %s', request.path, traceback.format_exc(20)) return self.error_response(request, http.BAD_REQUEST, 'error processing http request {0}', request.path)
def list_validator_registry(args): validator_url = 'http://localhost:8800' if args.url is not None: validator_url = args.url client =\ PermissionedValidatorRegistryClient(keyfile=args.keyfile, base_url=validator_url) print(pretty_print_dict(client.get_validator_list()))
def do_transaction(args): subcommands = ['list', 'show', 'status'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format(subcommands) return web_client = _get_webclient(args) try: if args.subcommand == 'list': if args.all: tsctids = web_client.get_transaction_list() else: tsctids = web_client.get_transaction_list(args.blockcount) for txn_id in tsctids: print txn_id return elif args.subcommand == 'show': if args.key is not None: tsct_info = web_client.get_transaction(args.transactionID, args.key) else: tsct_info = web_client.get_transaction(args.transactionID) print pretty_print_dict(tsct_info) return elif args.subcommand == 'status': tsct_status = web_client.get_transaction_status(args.transactionID) if tsct_status == transaction.Status.committed: print 'transaction committed' elif tsct_status == transaction.Status.pending: print 'transaction still uncommitted' elif tsct_status == transaction.Status.unknown: print 'unknown transaction' elif tsct_status == transaction.Status.failed: print 'transaction failed to validate.' else: print 'transaction returned unexpected status code {0}'\ .format(tsct_status) return except MessageException as e: raise CliException(e)
def postmsg(self, msgtype, info): """ Post a transaction message to the validator, parse the returning CBOR and return the corresponding dictionary. """ logger.debug(dict2json(info)) data = dict2cbor(info) datalen = len(data) url = self.BaseURL + msgtype logger.debug( 'post transaction to %s with DATALEN=%d, ' 'base64(DATA)=<%s>', url, datalen, base64.b64encode(data)) try: request = urllib2.Request(url, data, { 'Content-Type': 'application/cbor', 'Content-Length': datalen }) opener = urllib2.build_opener(self.ProxyHandler) response = opener.open(request, timeout=10) except urllib2.HTTPError as err: logger.warn('operation failed with response: %s', err.code) raise MessageException( 'operation failed with response: {0}'.format(err.code)) except urllib2.URLError as err: logger.warn('operation failed: %s', err.reason) raise MessageException('operation failed: {0}'.format(err.reason)) except: logger.warn('no response from server') raise MessageException('no response from server') content = response.read() headers = response.info() response.close() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: logger.info('server responds with message %s of type %s', content, encoding) return None logger.debug(pretty_print_dict(value)) return value
def do_get(self, request): """ Handle a GET request on the HTTP interface. Three paths are accepted: /store[/<storename>[/<key>|*]] /block[/<blockid>] /transaction[/<txnid>] """ # pylint: disable=invalid-name # split the request path removing leading duplicate slashes LOGGER.info("%s.do_get %s", self.__class__.__name__, request.path) components = request.path.split('/') while components and components[0] == '': components.pop(0) if components[0] != self.page_name: return self._error_response( request, http.NOT_FOUND, "Invalid page name: {}", request.path) else: components.pop(0) test_only = (request.method == 'HEAD') try: response = self.render_get(request, components, request.args) if test_only: return '' cbor = (request.getHeader('Accept') == 'application/cbor') if cbor: request.responseHeaders.addRawHeader(b"content-type", b"application/cbor") result = dict2cbor(response) else: request.responseHeaders.addRawHeader(b"content-type", b"application/json") pretty = False if 'p' in request.args: pretty = request.args['p'] == ['1'] if pretty: result = pretty_print_dict(response) + '\n' else: result = dict2json(response) return result except Exception as e: LOGGER.warn('error processing http request %s; %s', request.path, traceback.format_exc(20)) return self._encode_error_response( request, http.INTERNAL_SERVER_ERROR, e)
def postmsg(self, msgtype, info): """ Post a transaction message to the validator, parse the returning CBOR and return the corresponding dictionary. """ logger.debug(dict2json(info)) data = dict2cbor(info) datalen = len(data) url = self.BaseURL + msgtype logger.debug('post transaction to %s with DATALEN=%d, ' 'base64(DATA)=<%s>', url, datalen, base64.b64encode(data)) try: request = urllib2.Request(url, data, {'Content-Type': 'application/cbor', 'Content-Length': datalen}) opener = urllib2.build_opener(self.ProxyHandler) response = opener.open(request, timeout=10) except urllib2.HTTPError as err: logger.warn('operation failed with response: %s', err.code) raise MessageException( 'operation failed with response: {0}'.format(err.code)) except urllib2.URLError as err: logger.warn('operation failed: %s', err.reason) raise MessageException('operation failed: {0}'.format(err.reason)) except: logger.warn('no response from server') raise MessageException('no response from server') content = response.read() headers = response.info() response.close() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: logger.info('server responds with message %s of type %s', content, encoding) return None logger.debug(pretty_print_dict(value)) return value
def getmsg(self, path): """ Send an HTTP get request to the validator. If the resulting content is in JSON form, parse it & return the corresponding dictionary. """ url = "{0}/{1}".format(self.BaseURL, path.strip('/')) logger.debug('get content from url <%s>', url) try: request = urllib2.Request(url, headers=self.GET_HEADER) opener = urllib2.build_opener(self.ProxyHandler) if path == '/prevalidation': if self._cookie: request.add_header('cookie', self._cookie) response = opener.open(request, timeout=10) except urllib2.HTTPError as err: logger.warn('operation failed with response: %s', err.code) self._print_error_information_from_server(err) raise MessageException( 'operation failed with response: {0}'.format(err.code)) except urllib2.URLError as err: logger.warn('operation failed: %s', err.reason) raise MessageException('operation failed: {0}'.format(err.reason)) except: logger.warn('no response from server') raise MessageException('no response from server') content = response.read() headers = response.info() response.close() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: logger.debug('get content <%s> from url <%s>', content, url) return content logger.debug(pretty_print_dict(value)) return value
def do_transaction(args): subcommands = ['list', 'show', 'status'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format(subcommands) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': if args.all: tsctids = web_client.get_transaction_list() else: tsctids = \ web_client.get_transaction_list( block_count=args.blockcount) if args.format == 'default': print '{:20} {:20} {:6} {:30} {:12} {:18} {:40}'.format( 'TRANS', 'BLOCK', 'STATUS', 'TXNTYPE', 'NODENAME', 'HOST', 'DOMAIN') for txn_id in tsctids: trans_id, in_block, tran_status, txn_type, node_name,\ host, domain = get_trans_info(web_client, txn_id) print '{:20} {:20} {:6} {:30} {:12} {:18} {:40}'.format( trans_id, in_block, tran_status, txn_type, node_name, host, domain) return elif args.format == 'csv': try: writer = csv.writer(sys.stdout) writer.writerow(('TRANS', 'BLOCK', 'STATUS', 'TXNTYPE', 'NODENAME', 'HOST', 'DOMAIN')) for txn_id in tsctids: writer.writerow((get_trans_info(web_client, txn_id))) except csv.Error as e: raise CliException(e) elif args.format == 'json' or args.format == 'yaml': json_dict = [] for txn_id in tsctids: trans_id, in_block, tran_status, txn_type, node_name,\ host, domain = get_trans_info(web_client, txn_id) json_block = { 'TRANS': trans_id, 'BLOCK': in_block, 'STATUS': tran_status, 'TXNTYPE': txn_type, 'NODENAME': node_name, 'HOST': host, 'DOMAIN': domain } json_dict.append(json_block) if args.format == 'json': print json.dumps(json_dict) else: print yaml.dump(json_dict, default_flow_style=False) else: raise CliException("unknown format option: {}".format( args.format)) elif args.subcommand == 'show': tsct_info = \ web_client.get_transaction( transaction_id=args.transactionID, field=args.key) print pretty_print_dict(tsct_info) return elif args.subcommand == 'status': tsct_status = web_client.get_transaction_status(args.transactionID) if tsct_status == transaction.Status.committed: print 'transaction committed' elif tsct_status == transaction.Status.pending: print 'transaction still uncommitted' elif tsct_status == transaction.Status.unknown: print 'unknown transaction' elif tsct_status == transaction.Status.failed: print 'transaction failed to validate.' else: print 'transaction returned unexpected status code {0}'\ .format(tsct_status) return except MessageException as e: raise CliException(e)
def do_block(args): subcommands = ['list', 'show'] if args.subcommand not in subcommands: print 'Unknown sub-command, expecting one of {0}'.format( subcommands) return if args.url is not None: url = args.url else: url = 'http://localhost:8800' web_client = SawtoothClient(url) try: if args.subcommand == 'list': if args.blockcount is None: blockids = web_client.get_block_list() else: blockids = web_client.get_block_list(count=args.blockcount) if args.format == 'default': print '{:6} {:20} {:4} {:10} {:10} {:50}'.format( 'NUM', 'BLOCK', 'TXNS', 'DURATION', 'LOCALMEAN', 'VALIDATOR') for block_id in blockids: block_num, blockid, txns, duration, local_mean,\ validator_dest = get_block_info(web_client, block_id) print '{:6} {:20} {:4} {:10} {:10} {:50}'.format( block_num, blockid, txns, duration, local_mean, validator_dest) elif args.format == 'csv': try: writer = csv.writer(sys.stdout) writer.writerow( ( 'NUM', 'BLOCK', 'TXNS', 'DURATION', 'LOCALMEAN', 'VALIDATOR')) for block_id in blockids: writer.writerow( (get_block_info(web_client, block_id))) except csv.Error: raise CliException('Error writing CSV.') elif args.format == 'json' or args.format == 'yaml': json_dict = [] for block_id in blockids: block_num, blockid, txns, duration, local_mean,\ validator_dest = get_block_info(web_client, block_id) json_block = { 'NUM': block_num, 'BLOCK': blockid, 'TXNS': txns, 'DURATION': duration, 'LOCALMEAN': local_mean, 'VALIDATOR': validator_dest} json_dict.append(json_block) if args.format == 'json': print json.dumps(json_dict) else: print yaml.dump(json_dict, default_flow_style=False) else: raise CliException( "unknown format option: {}".format(args.format)) elif args.subcommand == 'show': block_info = \ web_client.get_block( block_id=args.blockID, field=args.key) print pretty_print_dict(block_info) return except MessageException as e: raise CliException(e)
def _preparetransaction(self, addtxns, deltxns, store, txn): """ Determine if a particular transaction is valid Args: addtxns (list of Transaction.Transaction) -- transaction to be added to the current block deltxns (list of Transaction.Transaction) -- invalid transactions store (GlobalStore) -- current global store txn -- the transaction to be tested Returns: True if the transaction is valid """ logger.debug('add transaction %s with id %s', str(txn), txn.Identifier[:8]) # Because the dependencies may reorder transactions in the block # in a way that is different from the arrival order, this transaction # might already be in the block if txn.Identifier in addtxns: return True # First step in adding the transaction to the list is to make # sure that all dependent transactions are in the list already ready = True for dependencyID in txn.Dependencies: logger.debug('check dependency %s of transaction %s', dependencyID[:8], txn.Identifier[:8]) # check to see if the dependency has already been committed if (dependencyID in self.TransactionStore and (self.TransactionStore[dependencyID].Status == transaction.Status.committed)): continue # check to see if the dependency is already in this block if dependencyID in addtxns: continue # check to see if the dependency is among the transactions to be # deleted, if so then this transaction will never be valid and we # can just get rid of it if dependencyID in deltxns: logger.info('transaction %s depends on deleted transaction %s', txn.Identifier[:8], dependencyID[:8]) deltxns.append(txn.Identifier) ready = False continue # recurse into the dependency, note that we need to make sure there # are no loops in the dependencies but not doing that right now deptxn = self.TransactionStore.get(dependencyID) if deptxn and self._preparetransaction(addtxns, deltxns, store, deptxn): continue # at this point we cannot find the dependency so send out a request # for it and wait, we should set a timer on this transaction so we # can just throw it away if the dependencies cannot be met ready = False self.request_missing_txn(dependencyID) # if all of the dependencies have not been met then there isn't any # point in continuing on so bail out if not ready: return False # after all that work... we know the dependencies are met, so see if # the transaction is valid, that is that all of the preconditions # encoded in the transaction itself are met txnstore = store.get_transaction_store(txn.TransactionTypeName) if txn.is_valid(txnstore): logger.debug('txn with id %s is valid, adding to block', txn.Identifier[:8]) addtxns.append(txn.Identifier) txn.apply(txnstore) return True # because we have all of the dependencies but the transaction is still # invalid we know that this transaction is broken and we can simply # throw it away logger.warn( 'transaction %s with id %s is not valid for this block, dropping', str(txn), txn.Identifier[:8]) logger.info(common.pretty_print_dict(txn.dump())) deltxns.append(txn.Identifier) return False
def _preparetransaction(self, addtxns, deltxns, store, txn): """ Determine if a particular transaction is valid Args: addtxns (list of Transaction.Transaction) -- transaction to be added to the current block deltxns (list of Transaction.Transaction) -- invalid transactions store (GlobalStore) -- current global store txn -- the transaction to be tested Returns: True if the transaction is valid """ logger.debug('add transaction %s with id %s', str(txn), txn.Identifier[:8]) # Because the dependencies may reorder transactions in the block # in a way that is different from the arrival order, this transaction # might already be in the block if txn.Identifier in addtxns: return True # First step in adding the transaction to the list is to make # sure that all dependent transactions are in the list already ready = True for dependencyID in txn.Dependencies: logger.debug('check dependency %s of transaction %s', dependencyID[:8], txn.Identifier[:8]) # check to see if the dependency has already been commited if (dependencyID in self.TransactionStore and (self.TransactionStore[dependencyID].Status == transaction.Status.committed)): continue # check to see if the dependency is already in this block if dependencyID in addtxns: continue # check to see if the dependency is among the transactions to be # deleted, if so then this transaction will never be valid and we # can just get rid of it if dependencyID in deltxns: logger.info('transaction %s depends on deleted transaction %s', txn.Identifier[:8], dependencyID[:8]) deltxns.append(txn.Identifier) ready = False continue # recurse into the dependency, note that we need to make sure there # are no loops in the dependencies but not doing that right now deptxn = self.TransactionStore.get(dependencyID) if deptxn and self._preparetransaction(addtxns, deltxns, store, deptxn): continue # at this point we cannot find the dependency so send out a request # for it and wait, we should set a timer on this transaction so we # can just throw it away if the dependencies cannot be met ready = False self.request_missing_txn(dependencyID) # if all of the dependencies have not been met then there isn't any # point in continuing on so bail out if not ready: return False # after all that work... we know the dependencies are met, so see if # the transaction is valid, that is that all of the preconditions # encoded in the transaction itself are met txnstore = store.get_transaction_store(txn.TransactionTypeName) if txn.is_valid(txnstore): logger.debug('txn with id %s is valid, adding to block', txn.Identifier[:8]) addtxns.append(txn.Identifier) txn.apply(txnstore) return True # because we have all of the dependencies but the transaction is still # invalid we know that this transaction is broken and we can simply # throw it away logger.warn( 'transaction %s with id %s is not valid for this block, dropping', str(txn), txn.Identifier[:8]) logger.info(common.pretty_print_dict(txn.dump())) deltxns.append(txn.Identifier) return False
def postmsg(self, msgtype, info): """ Post a transaction message to the validator, parse the returning CBOR and return the corresponding dictionary. """ data = dict2cbor(info) datalen = len(data) url = urlparse.urljoin(self._base_url, msgtype) LOGGER.debug('post transaction to %s with DATALEN=%d, DATA=<%s>', url, datalen, data) try: request = urllib2.Request(url, data, {'Content-Type': 'application/cbor', 'Content-Length': datalen}) if self._cookie: request.add_header('cookie', self._cookie) opener = urllib2.build_opener(self._proxy_handler) response = opener.open(request, timeout=10) if not self._cookie: self._cookie = response.headers.get('Set-Cookie') except urllib2.HTTPError as err: content = err.read() if content is not None: headers = err.info() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: LOGGER.warn('operation failed with response: %s', err.code) raise MessageException( 'operation failed with response: {0}'.format(err.code)) LOGGER.warn('operation failed with response: %s %s', err.code, str(value)) if "errorType" in value: if value['errorType'] == "InvalidTransactionError": raise InvalidTransactionError( value['error'] if 'error' in value else value) else: raise MessageException(str(value)) else: raise MessageException( 'operation failed with response: {0}'.format(err.code)) except urllib2.URLError as err: LOGGER.warn('operation failed: %s', err.reason) raise MessageException('operation failed: {0}'.format(err.reason)) except: LOGGER.warn('no response from server') raise MessageException('no response from server') content = response.read() headers = response.info() response.close() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: LOGGER.info('server responds with message %s of type %s', content, encoding) return None LOGGER.debug(pretty_print_dict(value)) return value
def postmsg(self, msgtype, info): """ Post a transaction message to the validator, parse the returning CBOR and return the corresponding dictionary. """ data = dict2cbor(info) datalen = len(data) url = urlparse.urljoin(self._base_url, msgtype) LOGGER.debug('post transaction to %s with DATALEN=%d, DATA=<%s>', url, datalen, data) try: request = urllib2.Request(url, data, { 'Content-Type': 'application/cbor', 'Content-Length': datalen }) if self._cookie: request.add_header('cookie', self._cookie) opener = urllib2.build_opener(self._proxy_handler) response = opener.open(request, timeout=10) if not self._cookie: self._cookie = response.headers.get('Set-Cookie') except urllib2.HTTPError as err: content = err.read() if content is not None: headers = err.info() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: LOGGER.warn('operation failed with response: %s', err.code) raise MessageException( 'operation failed with response: {0}'.format(err.code)) LOGGER.warn('operation failed with response: %s %s', err.code, str(value)) if "errorType" in value: if value['errorType'] == "InvalidTransactionError": raise InvalidTransactionError( value['error'] if 'error' in value else value) else: raise MessageException(str(value)) else: raise MessageException( 'operation failed with response: {0}'.format(err.code)) except urllib2.URLError as err: LOGGER.warn('operation failed: %s', err.reason) raise MessageException('operation failed: {0}'.format(err.reason)) except: LOGGER.warn('no response from server') raise MessageException('no response from server') content = response.read() headers = response.info() response.close() encoding = headers.get('Content-Type') if encoding == 'application/json': value = json2dict(content) elif encoding == 'application/cbor': value = cbor2dict(content) else: LOGGER.info('server responds with message %s of type %s', content, encoding) return None LOGGER.debug(pretty_print_dict(value)) return value