github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/integration/sawtooth_integration/tests/intkey_client.py (about) 1 # Copyright 2016 Intel Corporation 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 # ------------------------------------------------------------------------------ 15 16 import logging 17 import time 18 from urllib.parse import urlparse, parse_qs 19 20 from sawtooth_cli.rest_client import RestClient 21 from sawtooth_cli.exceptions import CliException 22 from sawtooth_cli.exceptions import RestClientException 23 from sawtooth_intkey.intkey_message_factory import IntkeyMessageFactory 24 25 LOGGER = logging.getLogger(__name__) 26 27 28 class IntkeyClient(RestClient): 29 def __init__(self, url, wait=30): 30 super().__init__(url) 31 self.url = url 32 self.factory = IntkeyMessageFactory() 33 self.wait = wait 34 35 def send_txns(self, txns): 36 batch = self.factory.create_batch(txns) 37 38 attempts = 0 39 response = None 40 while True: 41 try: 42 response = self.send_batches(batch) 43 id_query = urlparse(response['link']).query 44 return parse_qs(id_query)['id'][0] 45 except CliException: 46 if attempts < 8: 47 LOGGER.info('responding to back-pressure, retrying...') 48 attempts += 1 49 time.sleep(0.2 * (2 ** attempts)) 50 else: 51 raise 52 53 def recent_block_signatures(self, tolerance): 54 return self.list_block_signatures()[:tolerance] 55 56 def list_block_signatures(self): 57 return [block['header_signature'] for block in self.list_blocks()] 58 59 def calculate_tolerance(self): 60 length = len(list(self.list_blocks())) 61 # the most recent nth of the chain, at least 2 blocks 62 return max(2, length // 5) 63 64 def poll_for_batches(self, batch_ids): 65 """Poll timeout seconds for a batch status to become 66 non-pending 67 68 Args: 69 batch_id (str): The id to get the status of 70 """ 71 time_waited = 0 72 start_time = time.time() 73 74 while time_waited < self.wait: 75 76 res = self._get( 77 '/batch_statuses', 78 id=','.join(batch_ids), 79 wait=(self.wait - time_waited)) 80 81 if 'PENDING' not in [data['status'] for data in res['data']]: 82 return 83 84 time_waited = time.time() - start_time 85 86 raise RestClientException( 87 'Request timed out after %d seconds' % self.wait)