Coverage for admin/rsk_client.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-07-10 13:43 +0000

1# The MIT License (MIT) 

2# 

3# Copyright (c) 2021 RSK Labs Ltd 

4# 

5# Permission is hereby granted, free of charge, to any person obtaining a copy of 

6# this software and associated documentation files (the "Software"), to deal in 

7# the Software without restriction, including without limitation the rights to 

8# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 

9# of the Software, and to permit persons to whom the Software is furnished to do 

10# so, subject to the following conditions: 

11# 

12# The above copyright notice and this permission notice shall be included in all 

13# copies or substantial portions of the Software. 

14# 

15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 

16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 

18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 

19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 

20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 

21# SOFTWARE. 

22 

23import os 

24import requests 

25import json 

26 

27 

28class RskClientError(RuntimeError): 

29 pass 

30 

31 

32class RskClient: 

33 def __init__(self, url): 

34 self._url = url 

35 

36 @property 

37 def url(self): 

38 return self._url 

39 

40 def get_best_block_number(self): 

41 try: 

42 return int(self._request("eth_blockNumber", []), 16) 

43 except Exception as e: 

44 raise RskClientError(f"While getting the best block number: {str(e)}") 

45 

46 def get_block_by_number(self, number): 

47 try: 

48 return self._request("eth_getBlockByNumber", [hex(number), False]) 

49 except Exception as e: 

50 raise RskClientError(f"While getting the block by number: {str(e)}") 

51 

52 def _request(self, method, params): 

53 try: 

54 request_id = int.from_bytes(os.urandom(2), byteorder="big", signed=False) 

55 response = requests.post( 

56 self.url, 

57 headers={"content-type": "application/json"}, 

58 data=json.dumps({ 

59 "jsonrpc": "2.0", 

60 "id": request_id, 

61 "method": method, 

62 "params": params, 

63 }), 

64 ) 

65 

66 if response.status_code != 200: 

67 raise ValueError(f"Got {response.status_code} response from the server") 

68 

69 result = json.loads(response.text) 

70 

71 if result["id"] != request_id: 

72 raise ValueError( 

73 f"Unexpected response id {result['id']} (expecting {request_id})") 

74 

75 return result["result"] 

76 except Exception as e: 

77 raise RskClientError(f"While calling the '{method}' method: {str(e)}")