├── .editorconfig ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README-dev.rst ├── README.rst ├── bts ├── __init__.py ├── http_rpc.py ├── main.py ├── metadata.py └── ws │ ├── __init__.py │ ├── base_protocol.py │ ├── statistics_protocol.py │ ├── trade_protocol.py │ └── transfer_protocol.py ├── docs ├── Makefile ├── make.bat └── source │ ├── README │ ├── _static │ └── .gitkeep │ ├── conf.py │ └── index.rst ├── pavement.py ├── requirements-dev.txt ├── requirements.txt ├── setup.py ├── tests └── test_main.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # -*- mode: conf-unix; -*- 2 | 3 | # EditorConfig is awesome: http://EditorConfig.org 4 | 5 | # top-most EditorConfig file 6 | root = true 7 | 8 | # defaults 9 | [*] 10 | insert_final_newline = true 11 | 12 | # 4 space indentation 13 | [*.{ini,py,py.tpl,rst}] 14 | indent_style = space 15 | indent_size = 4 16 | 17 | # 4-width tabbed indentation 18 | [*.{sh,bat.tpl,Makefile.tpl}] 19 | indent_style = tab 20 | indent_size = 4 21 | 22 | # and travis does its own thing 23 | [.travis.yml] 24 | indent_style = space 25 | indent_size = 2 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Emacs rope configuration 2 | .ropeproject 3 | .project 4 | .pydevproject 5 | .settings 6 | 7 | # pyenv version file 8 | .python-version 9 | 10 | # Python 11 | *.py[co] 12 | 13 | ## Packages 14 | *.egg 15 | *.egg-info 16 | dist 17 | build 18 | eggs 19 | parts 20 | bin 21 | var 22 | sdist 23 | deb_dist 24 | develop-eggs 25 | .installed.cfg 26 | 27 | ## Installer logs 28 | pip-log.txt 29 | 30 | ## Unit test / coverage reports 31 | .coverage 32 | .tox 33 | 34 | ## Translations 35 | *.mo 36 | 37 | ## paver generated files 38 | /paver-minilib.zip 39 | 40 | config.json 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Alt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all 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 21 | THE SOFTWARE. 22 | CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | THE SOFTWARE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Informational files 2 | include README.rst 3 | include LICENSE 4 | 5 | # Include docs and tests. It's unclear whether convention dictates 6 | # including built docs. However, Sphinx doesn't include built docs, so 7 | # we are following their lead. 8 | graft docs 9 | prune docs/build 10 | graft tests 11 | graft bts 12 | 13 | # Exclude any compile Python files (most likely grafted by tests/ directory). 14 | global-exclude *.pyc 15 | 16 | # Setup-related things 17 | include pavement.py 18 | include requirements-dev.txt 19 | include requirements.txt 20 | include setup.py 21 | include tox.ini 22 | -------------------------------------------------------------------------------- /README-dev.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | bitshares api for python 3 | ========================= 4 | 5 | .. image:: https://bitsharestalk.org/BitSharesFinalTM200.png 6 | :target: https://bitsharestalk.org 7 | 8 | This project provides bitshares api for python project 9 | 10 | Project Setup 11 | ============= 12 | 13 | Instructions 14 | ------------ 15 | #. Clone the project :: 16 | 17 | git clone git@github.com:pch957/python-bts.git 18 | cd python-bts 19 | 20 | #. Install the project's development and runtime requirements:: 21 | 22 | sudo pip install -r requirements-dev.txt 23 | 24 | #. Install ``argparse`` package when developing for Python 2.6:: 25 | 26 | sudo pip install argparse 27 | 28 | #. Run the tests:: 29 | 30 | paver test_all 31 | 32 | You should see output similar to this:: 33 | 34 | $ paver test_all 35 | ---> pavement.test_all 36 | No style errors 37 | ========================================================================= test session starts ========================================================================== 38 | platform linux2 -- Python 2.7.3[pypy-2.2.1-final] -- pytest-2.5.1 39 | collected 7 items 40 | 41 | tests/test_main.py ....... 42 | 43 | ======================================================================= 7 passed in 0.59 seconds ======================================================================= 44 | ___ _ ___ ___ ___ ___ 45 | | _ \/_\ / __/ __| __| \ 46 | | _/ _ \\__ \__ \ _|| |) | 47 | |_|/_/ \_\___/___/___|___/ 48 | 49 | The substitution performed is rather naive, so some style errors may be reported if the description or name cause lines to be too long. Correct these manually before moving to the next step. If any unit tests fail to pass, please report an issue. 50 | 51 | #. build and install:: 52 | 53 | paver build 54 | sudo paver install 55 | 56 | Supported Python Versions 57 | ========================= 58 | 59 | supports the following versions out of the box: 60 | 61 | * CPython 2.6, 2.7, 3.3 62 | * PyPy 1.9 63 | 64 | CPython 3.0-3.2 may also work but are at this point unsupported. PyPy 2.0.2 is known to work but is not run on Travis-CI. 65 | 66 | Jython_ and IronPython_ may also work, but have not been tested. If there is interest in support for these alternative implementations, please open a feature request! 67 | 68 | .. _Jython: http://jython.org/ 69 | .. _IronPython: http://ironpython.net/ 70 | 71 | Licenses 72 | ======== 73 | The code which makes up this project is licensed under the MIT/X11 license. Feel free to use it in your free software/open-source or proprietary projects. 74 | 75 | Issues 76 | ====== 77 | 78 | Please report any bugs or requests that you have using the GitHub issue tracker! 79 | 80 | Authors 81 | ======= 82 | 83 | * Alt 84 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | bitshares api for python 3 | ========================= 4 | 5 | .. image:: https://bitsharestalk.org/BitSharesFinalTM200.png 6 | :target: https://bitsharestalk.org 7 | 8 | This project provides bitshares api for python project 9 | and some tools 10 | 11 | Project Setup 12 | ============= 13 | 14 | Quick Start 15 | ------------ 16 | #. Install:: 17 | 18 | $ sudo pip install bts 19 | 20 | Configuration 21 | ------------ 22 | todo 23 | 24 | Supported Python Versions 25 | ========================= 26 | 27 | supports the following versions out of the box: 28 | 29 | * CPython 2.6, 2.7, 3.3 30 | * PyPy 1.9 31 | 32 | CPython 3.0-3.2 may also work but are at this point unsupported. PyPy 2.0.2 is known to work but is not run on Travis-CI. 33 | 34 | Jython_ and IronPython_ may also work, but have not been tested. If there is interest in support for these alternative implementations, please open a feature request! 35 | 36 | .. _Jython: http://jython.org/ 37 | .. _IronPython: http://ironpython.net/ 38 | 39 | Licenses 40 | ======== 41 | The code which makes up this project is licensed under the MIT/X11 license. Feel free to use it in your free software/open-source or proprietary projects. 42 | 43 | Issues 44 | ====== 45 | 46 | Please report any bugs or requests that you have using the GitHub issue tracker! 47 | 48 | Authors 49 | ======= 50 | 51 | * Alt 52 | -------------------------------------------------------------------------------- /bts/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from bts.http_rpc import HTTPRPC # noqa 4 | 5 | from bts import metadata 6 | 7 | 8 | __version__ = metadata.version 9 | __author__ = metadata.authors[0] 10 | __license__ = metadata.license 11 | __copyright__ = metadata.copyright 12 | -------------------------------------------------------------------------------- /bts/http_rpc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | ############################################################################### 3 | # 4 | # The MIT License (MIT) 5 | # 6 | # Copyright (c) Tavendo GmbH 7 | # 8 | # Permission is hereby granted, free of charge, to any person obtaining a copy 9 | # of this software and associated documentation files (the "Software"), to deal 10 | # in the Software without restriction, including without limitation the rights 11 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | # copies of the Software, and to permit persons to whom the Software is 13 | # furnished to do so, subject to the following conditions: 14 | # 15 | # The above copyright notice and this permission notice shall be included in 16 | # all copies or substantial portions of the Software. 17 | # 18 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | # THE SOFTWARE. 25 | # 26 | ############################################################################### 27 | 28 | import json 29 | 30 | try: 31 | import requests 32 | except ImportError: 33 | raise ImportError("Missing dependency: python-requests") 34 | 35 | """ 36 | Error Classes 37 | """ 38 | 39 | 40 | class UnauthorizedError(Exception): 41 | pass 42 | 43 | 44 | class RPCError(Exception): 45 | pass 46 | 47 | 48 | class RPCConnection(Exception): 49 | pass 50 | 51 | 52 | class HTTPRPC(object): 53 | def __init__(self, uri="", username="", password=""): 54 | if not uri: 55 | uri = "https://bitshares.openledger.info/ws" 56 | uri = uri.replace("wss://", "https://") 57 | self.uri = uri 58 | self.username = "" 59 | self.password = "" 60 | self.headers = {'content-type': 'application/json'} 61 | 62 | def rpcexec(self, payload): 63 | try: 64 | response = requests.post( 65 | self.uri, 66 | data=json.dumps(payload), 67 | headers=self.headers, 68 | auth=(self.username, self.password)) 69 | if response.status_code == 401: 70 | raise UnauthorizedError 71 | ret = json.loads(response.text) 72 | if 'error' in ret: 73 | if 'detail' in ret['error']: 74 | raise RPCError("call %s, error %s" % ( 75 | ret['error']['detail'], json.dumps(payload))) 76 | else: 77 | raise RPCError("call %s, error %s" % ( 78 | ret['error']['message'], json.dumps(payload))) 79 | except requests.exceptions.RequestException: 80 | raise RPCConnection("Error connecting. Check hostname and port!") 81 | except UnauthorizedError: 82 | raise UnauthorizedError("Invalid login credentials!") 83 | except ValueError: 84 | raise ValueError("Client returned invalid format. Expected JSON!") 85 | except RPCError as err: 86 | raise err 87 | return ret["result"] 88 | 89 | """ 90 | Meta:Map all methods to RPC calls and pass through the arguments and result 91 | """ 92 | def __getattr__(self, name): 93 | def method(*args): 94 | query = { 95 | "method": "call", 96 | "params": [0, name, args], 97 | "jsonrpc": "2.0", 98 | "id": 0 99 | } 100 | r = self.rpcexec(query) 101 | return r 102 | return method 103 | 104 | if __name__ == '__main__': 105 | import sys 106 | from pprint import pprint 107 | uri = "" 108 | if len(sys.argv) >= 2: 109 | uri = sys.argv[1] 110 | 111 | rpc = HTTPRPC(uri) 112 | pprint(rpc.get_dynamic_global_properties()) 113 | -------------------------------------------------------------------------------- /bts/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """Program entry point""" 4 | 5 | from __future__ import print_function 6 | 7 | import argparse 8 | import sys 9 | 10 | from bts import metadata 11 | import json 12 | 13 | 14 | def main(argv): 15 | """Program entry point. 16 | 17 | :param argv: command-line arguments 18 | :type argv: :class:`list` 19 | """ 20 | author_strings = [] 21 | for name, email in zip(metadata.authors, metadata.emails): 22 | author_strings.append('Author: {0} <{1}>'.format(name, email)) 23 | 24 | epilog = ''' 25 | {project} {version} 26 | 27 | {authors} 28 | URL: <{url}> 29 | '''.format( 30 | project=metadata.project, 31 | version=metadata.version, 32 | authors='\n'.join(author_strings), 33 | url=metadata.url) 34 | 35 | arg_parser = argparse.ArgumentParser( 36 | prog=argv[0], 37 | formatter_class=argparse.RawDescriptionHelpFormatter, 38 | description=metadata.description, 39 | epilog=epilog) 40 | arg_parser.add_argument( 41 | '--config', type=argparse.FileType('r'), 42 | help='config file') 43 | arg_parser.add_argument( 44 | '-V', '--version', 45 | action='version', 46 | version='{0} {1}'.format(metadata.project, metadata.version)) 47 | 48 | args = arg_parser.parse_args(args=argv[1:]) 49 | 50 | config_info = {} 51 | if (args.config): 52 | config_info = json.load(args.config) 53 | 54 | print(config_info) 55 | 56 | return 0 57 | 58 | 59 | def entry_point(): 60 | """Zero-argument entry point for use with setuptools/distribute.""" 61 | raise SystemExit(main(sys.argv)) 62 | 63 | 64 | if __name__ == '__main__': 65 | entry_point() 66 | -------------------------------------------------------------------------------- /bts/metadata.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """Project python-bts 3 | 4 | Information describing the project. 5 | """ 6 | 7 | # The package name, which is also the "UNIX name" for the project. 8 | package = 'bts' 9 | project = "python api for BitShares" 10 | project_no_spaces = project.replace(' ', '') 11 | version = '0.6.17' 12 | description = 'api for BitShares' 13 | authors = ['Alt'] 14 | authors_string = ', '.join(authors) 15 | emails = ['pch957@gmail.com'] 16 | license = 'MIT' 17 | copyright = '2015 ' + authors_string 18 | url = 'https://github.com/pch957/python-bts' 19 | -------------------------------------------------------------------------------- /bts/ws/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from bts.ws.base_protocol import BaseProtocol # noqa 4 | from bts.ws.statistics_protocol import StatisticsProtocol # noqa 5 | from bts.ws.transfer_protocol import TransferProtocol # noqa 6 | -------------------------------------------------------------------------------- /bts/ws/base_protocol.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ############################################################################### 3 | # 4 | # The MIT License (MIT) 5 | # 6 | # Copyright (c) Tavendo GmbH 7 | # 8 | # Permission is hereby granted, free of charge, to any person obtaining a copy 9 | # of this software and associated documentation files (the "Software"), to deal 10 | # in the Software without restriction, including without limitation the rights 11 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | # copies of the Software, and to permit persons to whom the Software is 13 | # furnished to do so, subject to the following conditions: 14 | # 15 | # The above copyright notice and this permission notice shall be included in 16 | # all copies or substantial portions of the Software. 17 | # 18 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | # THE SOFTWARE. 25 | # 26 | ############################################################################### 27 | 28 | # from pprint import pprint 29 | import json 30 | import websockets 31 | 32 | try: 33 | import asyncio 34 | except ImportError: 35 | import trollius as asyncio 36 | 37 | 38 | class RPCError(Exception): 39 | pass 40 | 41 | 42 | class BaseProtocol(object): 43 | def __init__(self, uri=""): 44 | if not uri: 45 | uri = "wss://bitshares.openledger.info/ws" 46 | self.uri = uri 47 | self.request_id = 0 48 | self.history_api = 0 49 | self.network_api = 0 50 | self.database_api = 0 51 | self.result = {} 52 | self.callbacks = {} 53 | 54 | async def rpc(self, params): 55 | request_id = self.request_id 56 | self.request_id += 1 57 | request = {"id": request_id, "method": "call", "params": params} 58 | future = self.result[request_id] = asyncio.Future() 59 | await self.websocket.send(json.dumps(request).encode('utf8')) 60 | await asyncio.wait_for(future, None) 61 | self.result.pop(request_id) 62 | ret = future.result() 63 | if 'error' in ret: 64 | if 'detail' in ret['error']: 65 | raise RPCError(ret['error']['detail']) 66 | else: 67 | raise RPCError(ret['error']['message']) 68 | return ret["result"] 69 | 70 | def subscribe(self, object_id, callback): 71 | if object_id not in self.callbacks: 72 | self.callbacks[object_id] = [callback] 73 | else: 74 | self.callbacks[object_id].append(callback) 75 | 76 | async def handler_message(self): 77 | while True: 78 | payload = await self.websocket.recv() 79 | self.onMessage(payload) 80 | 81 | async def onOpen(self): 82 | await self.rpc([1, "login", ["", ""]]) 83 | self.database_api = await self.rpc([1, "database", []]) 84 | self.history_api = await self.rpc([1, "history", []]) 85 | self.network_api = await self.rpc([1, "network_broadcast", []]) 86 | await self.rpc( 87 | [self.database_api, "set_subscribe_callback", [200, False]]) 88 | 89 | async def handler(self): 90 | # can handle message less than 8M 91 | async with websockets.connect( 92 | self.uri, max_size=2**20*8, max_queue=2**5*2) as websocket: 93 | print("WebSocket connection open.") 94 | self.websocket = websocket 95 | task1 = asyncio.ensure_future(self.handler_message()) 96 | task2 = asyncio.ensure_future(self.onOpen()) 97 | await asyncio.wait([task1, task2]) 98 | 99 | def onMessage(self, payload): 100 | res = json.loads(payload) 101 | if "id" in res and res["id"] in self.result: 102 | self.result[res["id"]].set_result(res) 103 | elif "method" in res: 104 | for notice in res["params"][1][0]: 105 | if "id" not in notice: 106 | # means the object have removed from chain 107 | if "removed" in self.callbacks: 108 | for _cb in self.callbacks["removed"]: 109 | _cb(notice) 110 | continue 111 | for _id in self.callbacks: 112 | if _id == notice["id"][:len(_id)]: 113 | for _cb in self.callbacks[_id]: 114 | _cb(notice) 115 | 116 | 117 | if __name__ == '__main__': 118 | import sys 119 | uri = "" 120 | if len(sys.argv) >= 2: 121 | uri = sys.argv[1] 122 | 123 | ws = BaseProtocol(uri) 124 | asyncio.get_event_loop().run_until_complete(ws.handler()) 125 | -------------------------------------------------------------------------------- /bts/ws/statistics_protocol.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ############################################################################### 3 | # 4 | # The MIT License (MIT) 5 | # 6 | # Copyright (c) Tavendo GmbH 7 | # 8 | # Permission is hereby granted, free of charge, to any person obtaining a copy 9 | # of this software and associated documentation files (the "Software"), to deal 10 | # in the Software without restriction, including without limitation the rights 11 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | # copies of the Software, and to permit persons to whom the Software is 13 | # furnished to do so, subject to the following conditions: 14 | # 15 | # The above copyright notice and this permission notice shall be included in 16 | # all copies or substantial portions of the Software. 17 | # 18 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | # THE SOFTWARE. 25 | # 26 | ############################################################################### 27 | 28 | # from pprint import pprint 29 | from bts.ws.base_protocol import BaseProtocol 30 | from bts.http_rpc import HTTPRPC 31 | 32 | try: 33 | import asyncio 34 | except ImportError: 35 | import trollius as asyncio 36 | 37 | 38 | def id_to_int(id): 39 | return int(id.split('.')[-1]) 40 | 41 | 42 | class StatisticsProtocol(BaseProtocol): 43 | account = {"name": "exchange.btsbots", "id": "", "statistics": ""} 44 | last_trx = "" 45 | last_op = "2.9.1" 46 | node_api = None 47 | 48 | def init_statistics(self, node_api, account_name): 49 | self.node_api = node_api 50 | self.account["name"] = account_name 51 | 52 | def process_operations(self, op_id): 53 | op_info = self.node_api.get_objects([op_id]) 54 | print(op_info) 55 | 56 | def onStatistics(self, notify): 57 | # TODO: if network is ont sync, return 58 | trx_last = self.last_trx 59 | trx_current = notify["most_recent_op"] 60 | if id_to_int(trx_current) > id_to_int(trx_last): 61 | self.last_trx = trx_current 62 | else: 63 | return 64 | while True: 65 | if id_to_int(trx_current) <= id_to_int(trx_last): 66 | return 67 | trx_info = self.node_api.get_objects([trx_current])[0] 68 | if id_to_int(trx_info["operation_id"]) <= id_to_int(self.last_op): 69 | return 70 | self.process_operations(trx_info["operation_id"]) 71 | trx_current = trx_info["next"] 72 | 73 | @asyncio.coroutine 74 | def onOpen(self): 75 | yield from super().onOpen() 76 | response = yield from self.rpc( 77 | [self.database_api, "get_account_by_name", [self.account["name"]]]) 78 | self.account["statistics"] = response["statistics"] 79 | self.account["id"] = response["id"] 80 | statistics_info = self.node_api.get_objects( 81 | [self.account["statistics"]])[0] 82 | if self.last_trx == "": 83 | self.last_trx = statistics_info["most_recent_op"] 84 | print("monitor account %s, begin from trx: %s" % ( 85 | self.account["name"], self.last_trx)) 86 | self.onStatistics(statistics_info) 87 | self.subscribe(self.account["statistics"], self.onStatistics) 88 | 89 | 90 | if __name__ == '__main__': 91 | import sys 92 | uri = "" 93 | if len(sys.argv) >= 2: 94 | uri = sys.argv[1] 95 | 96 | ws = StatisticsProtocol(uri) 97 | node_api = HTTPRPC(uri) 98 | ws.init_statistics( 99 | node_api, "exchange.btsbots") 100 | asyncio.get_event_loop().run_until_complete(ws.handler()) 101 | -------------------------------------------------------------------------------- /bts/ws/trade_protocol.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ############################################################################### 3 | # 4 | # The MIT License (MIT) 5 | # 6 | # Copyright (c) Tavendo GmbH 7 | # 8 | # Permission is hereby granted, free of charge, to any person obtaining a copy 9 | # of this software and associated documentation files (the "Software"), to deal 10 | # in the Software without restriction, including without limitation the rights 11 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | # copies of the Software, and to permit persons to whom the Software is 13 | # furnished to do so, subject to the following conditions: 14 | # 15 | # The above copyright notice and this permission notice shall be included in 16 | # all copies or substantial portions of the Software. 17 | # 18 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | # THE SOFTWARE. 25 | # 26 | ############################################################################### 27 | 28 | # from pprint import pprint 29 | from bts.ws.statistics_protocol import StatisticsProtocol 30 | from bts.http_rpc import HTTPRPC 31 | 32 | try: 33 | import asyncio 34 | except ImportError: 35 | import trollius as asyncio 36 | 37 | 38 | def id_to_int(id): 39 | return int(id.split('.')[-1]) 40 | 41 | 42 | class TradeProtocol(StatisticsProtocol): 43 | asset_info = {} 44 | 45 | def get_asset_info(self, asset_id): 46 | if asset_id not in self.asset_info: 47 | _asset_info = self.node_api.get_objects([asset_id])[0] 48 | self.asset_info[asset_id] = _asset_info 49 | self.asset_info[_asset_info["symbol"]] = _asset_info 50 | return self.asset_info[asset_id] 51 | 52 | def onTrade(self, trx): 53 | print("sent %s" % trx) 54 | 55 | def process_operations(self, op_id): 56 | op_info = self.node_api.get_objects([op_id]) 57 | for operation in op_info[::-1]: 58 | if operation["op"][0] != 4: 59 | return 60 | op = operation["op"][1] 61 | trx = {} 62 | 63 | trx["block_num"] = operation["block_num"] 64 | block_info = self.node_api.get_block(trx["block_num"]) 65 | trx["timestamp"] = block_info["timestamp"] 66 | trx["trx_id"] = operation["id"] 67 | # Get trade info 68 | for _type in ["pays", "receives", "fee"]: 69 | trx[_type] = [0, ""] 70 | asset_info = self.get_asset_info(op[_type]["asset_id"]) 71 | trx[_type][1] = asset_info["symbol"] 72 | trx[_type][0] = float(op[_type]["amount"])/float( 73 | 10**int(asset_info["precision"])) 74 | 75 | self.onTrade(trx) 76 | 77 | 78 | if __name__ == '__main__': 79 | import sys 80 | uri = "" 81 | if len(sys.argv) >= 2: 82 | uri = sys.argv[1] 83 | 84 | ws = TradeProtocol(uri) 85 | node_api = HTTPRPC(uri) 86 | ws.init_statistics( 87 | node_api, "exchange.btsbots") 88 | asyncio.get_event_loop().run_until_complete(ws.handler()) 89 | -------------------------------------------------------------------------------- /bts/ws/transfer_protocol.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ############################################################################### 3 | # 4 | # The MIT License (MIT) 5 | # 6 | # Copyright (c) Tavendo GmbH 7 | # 8 | # Permission is hereby granted, free of charge, to any person obtaining a copy 9 | # of this software and associated documentation files (the "Software"), to deal 10 | # in the Software without restriction, including without limitation the rights 11 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | # copies of the Software, and to permit persons to whom the Software is 13 | # furnished to do so, subject to the following conditions: 14 | # 15 | # The above copyright notice and this permission notice shall be included in 16 | # all copies or substantial portions of the Software. 17 | # 18 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 24 | # THE SOFTWARE. 25 | # 26 | ############################################################################### 27 | 28 | # from pprint import pprint 29 | from bts.ws.statistics_protocol import StatisticsProtocol 30 | from bts.http_rpc import HTTPRPC 31 | try: 32 | from graphenebase import Memo, PrivateKey, PublicKey 33 | except ImportError: 34 | print("[warnning] need python-graphinelib to use transfer protocol") 35 | 36 | try: 37 | import asyncio 38 | except ImportError: 39 | import trollius as asyncio 40 | 41 | 42 | def id_to_int(id): 43 | return int(id.split('.')[-1]) 44 | 45 | 46 | class TransferProtocol(StatisticsProtocol): 47 | prefix = "BTS" 48 | memo_key = "" 49 | asset_info = {} 50 | 51 | def init_transfer_monitor(self, node_api, prefix, account_name, memo_key): 52 | self.init_statistics(node_api, account_name) 53 | self.prefix = prefix 54 | self.memo_key = memo_key 55 | 56 | def get_asset_info(self, asset_id): 57 | if asset_id not in self.asset_info: 58 | _asset_info = self.node_api.get_objects([asset_id])[0] 59 | self.asset_info[asset_id] = _asset_info 60 | self.asset_info[_asset_info["symbol"]] = _asset_info 61 | return self.asset_info[asset_id] 62 | 63 | def onSent(self, trx): 64 | print("sent %s" % trx) 65 | 66 | def onReceive(self, trx): 67 | print("receive %s" % trx) 68 | 69 | def process_operations(self, op_id): 70 | op_info = self.node_api.get_objects([op_id]) 71 | for operation in op_info[::-1]: 72 | if operation["op"][0] != 0: 73 | return 74 | op = operation["op"][1] 75 | trx = {} 76 | 77 | # trx["timestamp"] = datetime.datetime.utcnow().strftime( 78 | # "%Y%m%d %H:%M") 79 | trx["block_num"] = operation["block_num"] 80 | block_info = self.node_api.get_block(trx["block_num"]) 81 | trx["timestamp"] = block_info["timestamp"] 82 | trx["trx_id"] = operation["id"] 83 | # Get amount 84 | asset_info = self.get_asset_info(op["amount"]["asset_id"]) 85 | trx["asset"] = asset_info["symbol"] 86 | trx["amount"] = float(op["amount"]["amount"])/float( 87 | 10**int(asset_info["precision"])) 88 | 89 | # Get accounts involved 90 | trx["from_id"] = op["from"] 91 | trx["to_id"] = op["to"] 92 | trx["from"] = self.node_api.get_objects([op["from"]])[0]["name"] 93 | trx["to"] = self.node_api.get_objects([op["to"]])[0]["name"] 94 | 95 | # Decode the memo 96 | if "memo" in op: 97 | memo = op["memo"] 98 | trx["nonce"] = memo["nonce"] 99 | try: 100 | privkey = PrivateKey(self.memo_key) 101 | if trx["to_id"] == self.account["id"]: 102 | pubkey = PublicKey(memo["from"], prefix=self.prefix) 103 | else: 104 | pubkey = PublicKey(memo["to"], prefix=self.prefix) 105 | trx["memo"] = Memo.decode_memo( 106 | privkey, pubkey, memo["nonce"], memo["message"]) 107 | except Exception: 108 | trx["memo"] = None 109 | else: 110 | trx["nonce"] = None 111 | trx["memo"] = None 112 | 113 | if trx["from_id"] == self.account["id"]: 114 | self.onSent(trx) 115 | elif trx["to_id"] == self.account["id"]: 116 | self.onReceive(trx) 117 | 118 | 119 | if __name__ == '__main__': 120 | import sys 121 | uri = "" 122 | if len(sys.argv) >= 2: 123 | uri = sys.argv[1] 124 | 125 | ws = TransferProtocol(uri) 126 | node_api = HTTPRPC(uri) 127 | ws.init_transfer_monitor( 128 | node_api, "BTS", "nathan", 129 | "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3") 130 | asyncio.get_event_loop().run_until_complete(ws.handler()) 131 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = -W 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pythonapiforBitshares.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pythonapiforBitshares.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $HOME/.local/share/devhelp/pythonapiforBitshares" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $HOME/.local/share/devhelp/pythonapiforBitshares" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set SPHINXOPTS=-W 10 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 11 | set I18NSPHINXOPTS=%SPHINXOPTS% source 12 | if NOT "%PAPER%" == "" ( 13 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 14 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 15 | ) 16 | 17 | if "%1" == "" goto help 18 | 19 | if "%1" == "help" ( 20 | :help 21 | echo.Please use `make ^` where ^ is one of 22 | echo. html to make standalone HTML files 23 | echo. dirhtml to make HTML files named index.html in directories 24 | echo. singlehtml to make a single large HTML file 25 | echo. pickle to make pickle files 26 | echo. json to make JSON files 27 | echo. htmlhelp to make HTML files and a HTML help project 28 | echo. qthelp to make HTML files and a qthelp project 29 | echo. devhelp to make HTML files and a Devhelp project 30 | echo. epub to make an epub 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. linkcheck to check all external links for integrity 38 | echo. doctest to run all doctests embedded in the documentation if enabled 39 | goto end 40 | ) 41 | 42 | if "%1" == "clean" ( 43 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 44 | del /q /s %BUILDDIR%\* 45 | goto end 46 | ) 47 | 48 | if "%1" == "html" ( 49 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 50 | if errorlevel 1 exit /b 1 51 | echo. 52 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 53 | goto end 54 | ) 55 | 56 | if "%1" == "dirhtml" ( 57 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 58 | if errorlevel 1 exit /b 1 59 | echo. 60 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 61 | goto end 62 | ) 63 | 64 | if "%1" == "singlehtml" ( 65 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 66 | if errorlevel 1 exit /b 1 67 | echo. 68 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 69 | goto end 70 | ) 71 | 72 | if "%1" == "pickle" ( 73 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 74 | if errorlevel 1 exit /b 1 75 | echo. 76 | echo.Build finished; now you can process the pickle files. 77 | goto end 78 | ) 79 | 80 | if "%1" == "json" ( 81 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 82 | if errorlevel 1 exit /b 1 83 | echo. 84 | echo.Build finished; now you can process the JSON files. 85 | goto end 86 | ) 87 | 88 | if "%1" == "htmlhelp" ( 89 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 90 | if errorlevel 1 exit /b 1 91 | echo. 92 | echo.Build finished; now you can run HTML Help Workshop with the ^ 93 | .hhp project file in %BUILDDIR%/htmlhelp. 94 | goto end 95 | ) 96 | 97 | if "%1" == "qthelp" ( 98 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 99 | if errorlevel 1 exit /b 1 100 | echo. 101 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 102 | .qhcp project file in %BUILDDIR%/qthelp, like this: 103 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pythonapiforBitshares.qhcp 104 | echo.To view the help file: 105 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pythonapiforBitshares.qhc 106 | goto end 107 | ) 108 | 109 | if "%1" == "devhelp" ( 110 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished. 114 | goto end 115 | ) 116 | 117 | if "%1" == "epub" ( 118 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 122 | goto end 123 | ) 124 | 125 | if "%1" == "latex" ( 126 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 127 | if errorlevel 1 exit /b 1 128 | echo. 129 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 130 | goto end 131 | ) 132 | 133 | if "%1" == "text" ( 134 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 135 | if errorlevel 1 exit /b 1 136 | echo. 137 | echo.Build finished. The text files are in %BUILDDIR%/text. 138 | goto end 139 | ) 140 | 141 | if "%1" == "man" ( 142 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 143 | if errorlevel 1 exit /b 1 144 | echo. 145 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 146 | goto end 147 | ) 148 | 149 | if "%1" == "texinfo" ( 150 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 151 | if errorlevel 1 exit /b 1 152 | echo. 153 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 154 | goto end 155 | ) 156 | 157 | if "%1" == "gettext" ( 158 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 159 | if errorlevel 1 exit /b 1 160 | echo. 161 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 162 | goto end 163 | ) 164 | 165 | if "%1" == "changes" ( 166 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 167 | if errorlevel 1 exit /b 1 168 | echo. 169 | echo.The overview file is in %BUILDDIR%/changes. 170 | goto end 171 | ) 172 | 173 | if "%1" == "linkcheck" ( 174 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 175 | if errorlevel 1 exit /b 1 176 | echo. 177 | echo.Link check complete; look for any errors in the above output ^ 178 | or in %BUILDDIR%/linkcheck/output.txt. 179 | goto end 180 | ) 181 | 182 | if "%1" == "doctest" ( 183 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 184 | if errorlevel 1 exit /b 1 185 | echo. 186 | echo.Testing of doctests in the sources finished, look at the ^ 187 | results in %BUILDDIR%/doctest/output.txt. 188 | goto end 189 | ) 190 | 191 | :end 192 | -------------------------------------------------------------------------------- /docs/source/README: -------------------------------------------------------------------------------- 1 | Run `sphinx-apidoc -o . ../../bts' in this directory. 2 | 3 | This will generate `modules.rst' and `bts.rst'. 4 | 5 | Then include `modules.rst' in your `index.rst' file. -------------------------------------------------------------------------------- /docs/source/_static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pch957/python-bts/9db0ab8dad015f684de2d5a03a21547b515cd2c2/docs/source/_static/.gitkeep -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # This file is based upon the file generated by sphinx-quickstart. However, 4 | # where sphinx-quickstart hardcodes values in this file that you input, this 5 | # file has been changed to pull from your module's metadata module. 6 | # 7 | # This file is execfile()d with the current directory set to its containing 8 | # dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import os 17 | import sys 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | sys.path.insert(0, os.path.abspath('../..')) 23 | 24 | # Import project metadata 25 | from bts import metadata 26 | 27 | # -- General configuration ---------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 35 | 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode'] 36 | 37 | # show todos 38 | todo_include_todos = True 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['_templates'] 42 | 43 | # The suffix of source filenames. 44 | source_suffix = '.rst' 45 | 46 | # The encoding of source files. 47 | #source_encoding = 'utf-8-sig' 48 | 49 | # The master toctree document. 50 | master_doc = 'index' 51 | 52 | # General information about the project. 53 | project = metadata.project 54 | copyright = metadata.copyright 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | # The short X.Y version. 61 | version = metadata.version 62 | # The full version, including alpha/beta/rc tags. 63 | release = metadata.version 64 | 65 | # The language for content autogenerated by Sphinx. Refer to documentation 66 | # for a list of supported languages. 67 | #language = None 68 | 69 | # There are two options for replacing |today|: either, you set today to some 70 | # non-false value, then it is used: 71 | #today = '' 72 | # Else, today_fmt is used as the format for a strftime call. 73 | #today_fmt = '%B %d, %Y' 74 | 75 | # List of patterns, relative to source directory, that match files and 76 | # directories to ignore when looking for source files. 77 | exclude_patterns = [] 78 | 79 | # The reST default role (used for this markup: `text`) to use for all 80 | # documents. 81 | #default_role = None 82 | 83 | # If true, '()' will be appended to :func: etc. cross-reference text. 84 | #add_function_parentheses = True 85 | 86 | # If true, the current module name will be prepended to all description 87 | # unit titles (such as .. function::). 88 | #add_module_names = True 89 | 90 | # If true, sectionauthor and moduleauthor directives will be shown in the 91 | # output. They are ignored by default. 92 | #show_authors = False 93 | 94 | # The name of the Pygments (syntax highlighting) style to use. 95 | pygments_style = 'sphinx' 96 | 97 | # A list of ignored prefixes for module index sorting. 98 | #modindex_common_prefix = [] 99 | 100 | 101 | # -- Options for HTML output -------------------------------------------------- 102 | 103 | # The theme to use for HTML and HTML Help pages. See the documentation for 104 | # a list of builtin themes. 105 | html_theme = 'nature' 106 | 107 | # Theme options are theme-specific and customize the look and feel of a theme 108 | # further. For a list of options available for each theme, see the 109 | # documentation. 110 | #html_theme_options = {} 111 | 112 | # Add any paths that contain custom themes here, relative to this directory. 113 | #html_theme_path = [] 114 | 115 | # The name for this set of Sphinx documents. If None, it defaults to 116 | # " v documentation". 117 | #html_title = None 118 | 119 | # A shorter title for the navigation bar. Default is the same as html_title. 120 | #html_short_title = None 121 | 122 | # The name of an image file (relative to this directory) to place at the top 123 | # of the sidebar. 124 | #html_logo = None 125 | 126 | # The name of an image file (within the static path) to use as favicon of the 127 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 128 | # pixels large. 129 | #html_favicon = None 130 | 131 | # Add any paths that contain custom static files (such as style sheets) here, 132 | # relative to this directory. They are copied after the builtin static files, 133 | # so a file named "default.css" will overwrite the builtin "default.css". 134 | html_static_path = ['_static'] 135 | 136 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 137 | # using the given strftime format. 138 | #html_last_updated_fmt = '%b %d, %Y' 139 | 140 | # If true, SmartyPants will be used to convert quotes and dashes to 141 | # typographically correct entities. 142 | #html_use_smartypants = True 143 | 144 | # Custom sidebar templates, maps document names to template names. 145 | #html_sidebars = {} 146 | 147 | # Additional templates that should be rendered to pages, maps page names to 148 | # template names. 149 | #html_additional_pages = {} 150 | 151 | # If false, no module index is generated. 152 | #html_domain_indices = True 153 | 154 | # If false, no index is generated. 155 | #html_use_index = True 156 | 157 | # If true, the index is split into individual pages for each letter. 158 | #html_split_index = False 159 | 160 | # If true, links to the reST sources are added to the pages. 161 | #html_show_sourcelink = True 162 | 163 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 164 | #html_show_sphinx = True 165 | 166 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 167 | #html_show_copyright = True 168 | 169 | # If true, an OpenSearch description file will be output, and all pages will 170 | # contain a tag referring to it. The value of this option must be the 171 | # base URL from which the finished HTML is served. 172 | #html_use_opensearch = '' 173 | 174 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 175 | #html_file_suffix = None 176 | 177 | # Output file base name for HTML help builder. 178 | htmlhelp_basename = metadata.project_no_spaces + 'doc' 179 | 180 | 181 | # -- Options for LaTeX output ------------------------------------------------- 182 | 183 | latex_elements = { 184 | # The paper size ('letterpaper' or 'a4paper'). 185 | #'papersize': 'letterpaper', 186 | 187 | # The font size ('10pt', '11pt' or '12pt'). 188 | #'pointsize': '10pt', 189 | 190 | # Additional stuff for the LaTeX preamble. 191 | #'preamble': '', 192 | } 193 | 194 | # Grouping the document tree into LaTeX files. List of tuples 195 | # (source start file, target name, title, author, 196 | # documentclass [howto/manual]). 197 | latex_documents = [ 198 | ('index', metadata.project_no_spaces + '.tex', 199 | metadata.project + ' Documentation', metadata.authors_string, 200 | 'manual'), 201 | ] 202 | 203 | # The name of an image file (relative to this directory) to place at the top of 204 | # the title page. 205 | #latex_logo = None 206 | 207 | # For "manual" documents, if this is true, then toplevel headings are parts, 208 | # not chapters. 209 | #latex_use_parts = False 210 | 211 | # If true, show page references after internal links. 212 | #latex_show_pagerefs = False 213 | 214 | # If true, show URL addresses after external links. 215 | #latex_show_urls = False 216 | 217 | # Documents to append as an appendix to all manuals. 218 | #latex_appendices = [] 219 | 220 | # If false, no module index is generated. 221 | #latex_domain_indices = True 222 | 223 | 224 | # -- Options for manual page output ------------------------------------------- 225 | 226 | # One entry per manual page. List of tuples 227 | # (source start file, name, description, authors, manual section). 228 | man_pages = [ 229 | ('index', metadata.package, metadata.project + ' Documentation', 230 | metadata.authors_string, 1) 231 | ] 232 | 233 | # If true, show URL addresses after external links. 234 | #man_show_urls = False 235 | 236 | 237 | # -- Options for Texinfo output ----------------------------------------------- 238 | 239 | # Grouping the document tree into Texinfo files. List of tuples 240 | # (source start file, target name, title, author, 241 | # dir menu entry, description, category) 242 | texinfo_documents = [ 243 | ('index', metadata.project_no_spaces, 244 | metadata.project + ' Documentation', metadata.authors_string, 245 | metadata.project_no_spaces, metadata.description, 'Miscellaneous'), 246 | ] 247 | 248 | # Documents to append as an appendix to all manuals. 249 | #texinfo_appendices = [] 250 | 251 | # If false, no module index is generated. 252 | #texinfo_domain_indices = True 253 | 254 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 255 | #texinfo_show_urls = 'footnote' 256 | 257 | 258 | # Example configuration for intersphinx: refer to the Python standard library. 259 | intersphinx_mapping = { 260 | 'python': ('http://docs.python.org/', None), 261 | } 262 | 263 | # Extra local configuration. This is useful for placing the class description 264 | # in the class docstring and the __init__ parameter documentation in the 265 | # __init__ docstring. See 266 | # for more 267 | # information. 268 | autoclass_content = 'both' 269 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | python api for Bitshares 2 | ======================== 3 | 4 | Contents: 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | 10 | .. only:: html 11 | 12 | Indices and tables 13 | ================== 14 | 15 | * :ref:`genindex` 16 | * :ref:`modindex` 17 | * :ref:`search` 18 | -------------------------------------------------------------------------------- /pavement.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import print_function 4 | 5 | import os 6 | import sys 7 | import time 8 | import subprocess 9 | 10 | # Import parameters from the setup file. 11 | sys.path.append('.') 12 | from setup import ( 13 | setup_dict, get_project_files, print_success_message, 14 | print_failure_message, _lint, _test, _test_all, 15 | CODE_DIRECTORY, DOCS_DIRECTORY, TESTS_DIRECTORY, PYTEST_FLAGS) 16 | 17 | from paver.easy import options, task, needs, consume_args 18 | from paver.setuputils import install_distutils_tasks 19 | 20 | options(setup=setup_dict) 21 | 22 | install_distutils_tasks() 23 | 24 | # Miscellaneous helper functions 25 | 26 | 27 | def print_passed(): 28 | # generated on http://patorjk.com/software/taag/#p=display&f=Small&t=PASSED 29 | print_success_message(r''' ___ _ ___ ___ ___ ___ 30 | | _ \/_\ / __/ __| __| \ 31 | | _/ _ \\__ \__ \ _|| |) | 32 | |_|/_/ \_\___/___/___|___/ 33 | ''') 34 | 35 | 36 | def print_failed(): 37 | # generated on http://patorjk.com/software/taag/#p=display&f=Small&t=FAILED 38 | print_failure_message(r''' ___ _ ___ _ ___ ___ 39 | | __/_\ |_ _| | | __| \ 40 | | _/ _ \ | || |__| _|| |) | 41 | |_/_/ \_\___|____|___|___/ 42 | ''') 43 | 44 | 45 | class cwd(object): 46 | """Class used for temporarily changing directories. Can be though of 47 | as a `pushd /my/dir' then a `popd' at the end. 48 | """ 49 | def __init__(self, newcwd): 50 | """:param newcwd: directory to make the cwd 51 | :type newcwd: :class:`str` 52 | """ 53 | self.newcwd = newcwd 54 | 55 | def __enter__(self): 56 | self.oldcwd = os.getcwd() 57 | os.chdir(self.newcwd) 58 | return os.getcwd() 59 | 60 | def __exit__(self, type_, value, traceback): 61 | # This acts like a `finally' clause: it will always be executed. 62 | os.chdir(self.oldcwd) 63 | 64 | 65 | # Task-related functions 66 | 67 | def _doc_make(*make_args): 68 | """Run make in sphinx' docs directory. 69 | 70 | :return: exit code 71 | """ 72 | if sys.platform == 'win32': 73 | # Windows 74 | make_cmd = ['make.bat'] 75 | else: 76 | # Linux, Mac OS X, and others 77 | make_cmd = ['make'] 78 | make_cmd.extend(make_args) 79 | 80 | # Account for a stupid Python "bug" on Windows: 81 | # 82 | with cwd(DOCS_DIRECTORY): 83 | retcode = subprocess.call(make_cmd) 84 | return retcode 85 | 86 | 87 | # Tasks 88 | 89 | @task 90 | @needs('doc_html', 'setuptools.command.sdist') 91 | def sdist(): 92 | """Build the HTML docs and the tarball.""" 93 | pass 94 | 95 | 96 | @task 97 | def test(): 98 | """Run the unit tests.""" 99 | raise SystemExit(_test()) 100 | 101 | 102 | @task 103 | def lint(): 104 | # This refuses to format properly when running `paver help' unless 105 | # this ugliness is used. 106 | ('Perform PEP8 style check, run PyFlakes, and run McCabe complexity ' 107 | 'metrics on the code.') 108 | raise SystemExit(_lint()) 109 | 110 | 111 | @task 112 | def test_all(): 113 | """Perform a style check and run all unit tests.""" 114 | retcode = _test_all() 115 | if retcode == 0: 116 | print_passed() 117 | else: 118 | print_failed() 119 | raise SystemExit(retcode) 120 | 121 | 122 | @task 123 | @consume_args 124 | def run(args): 125 | """Run the package's main script. All arguments are passed to it.""" 126 | # The main script expects to get the called executable's name as 127 | # argv[0]. However, paver doesn't provide that in args. Even if it did (or 128 | # we dove into sys.argv), it wouldn't be useful because it would be paver's 129 | # executable. So we just pass the package name in as the executable name, 130 | # since it's close enough. This should never be seen by an end user 131 | # installing through Setuptools anyway. 132 | from bts.main import main 133 | raise SystemExit(main([CODE_DIRECTORY] + args)) 134 | 135 | 136 | @task 137 | def commit(): 138 | """Commit only if all the tests pass.""" 139 | if _test_all() == 0: 140 | subprocess.check_call(['git', 'commit']) 141 | else: 142 | print_failure_message('\nTests failed, not committing.') 143 | 144 | 145 | @task 146 | def coverage(): 147 | """Run tests and show test coverage report.""" 148 | try: 149 | import pytest_cov # NOQA 150 | except ImportError: 151 | print_failure_message( 152 | 'Install the pytest coverage plugin to use this task, ' 153 | "i.e., `pip install pytest-cov'.") 154 | raise SystemExit(1) 155 | import pytest 156 | pytest.main(PYTEST_FLAGS + [ 157 | '--cov', CODE_DIRECTORY, 158 | '--cov-report', 'term-missing', 159 | TESTS_DIRECTORY]) 160 | 161 | 162 | @task # NOQA 163 | def doc_watch(): 164 | """Watch for changes in the docs and rebuild HTML docs when changed.""" 165 | try: 166 | from watchdog.events import FileSystemEventHandler 167 | from watchdog.observers import Observer 168 | except ImportError: 169 | print_failure_message('Install the watchdog package to use this task, ' 170 | "i.e., `pip install watchdog'.") 171 | raise SystemExit(1) 172 | 173 | class RebuildDocsEventHandler(FileSystemEventHandler): 174 | def __init__(self, base_paths): 175 | self.base_paths = base_paths 176 | 177 | def dispatch(self, event): 178 | """Dispatches events to the appropriate methods. 179 | :param event: The event object representing the file system event. 180 | :type event: :class:`watchdog.events.FileSystemEvent` 181 | """ 182 | for base_path in self.base_paths: 183 | if event.src_path.endswith(base_path): 184 | super(RebuildDocsEventHandler, self).dispatch(event) 185 | # We found one that matches. We're done. 186 | return 187 | 188 | def on_modified(self, event): 189 | print_failure_message('Modification detected. Rebuilding docs.') 190 | # # Strip off the path prefix. 191 | # import os 192 | # if event.src_path[len(os.getcwd()) + 1:].startswith( 193 | # CODE_DIRECTORY): 194 | # # sphinx-build doesn't always pick up changes on code files, 195 | # # even though they are used to generate the documentation. As 196 | # # a workaround, just clean before building. 197 | doc_html() 198 | print_success_message('Docs have been rebuilt.') 199 | 200 | print_success_message( 201 | 'Watching for changes in project files, press Ctrl-C to cancel...') 202 | handler = RebuildDocsEventHandler(get_project_files()) 203 | observer = Observer() 204 | observer.schedule(handler, path='.', recursive=True) 205 | observer.start() 206 | try: 207 | while True: 208 | time.sleep(1) 209 | except KeyboardInterrupt: 210 | observer.stop() 211 | observer.join() 212 | 213 | 214 | @task 215 | @needs('doc_html') 216 | def doc_open(): 217 | """Build the HTML docs and open them in a web browser.""" 218 | doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') 219 | if sys.platform == 'darwin': 220 | # Mac OS X 221 | subprocess.check_call(['open', doc_index]) 222 | elif sys.platform == 'win32': 223 | # Windows 224 | subprocess.check_call(['start', doc_index], shell=True) 225 | elif sys.platform == 'linux2': 226 | # All freedesktop-compatible desktops 227 | subprocess.check_call(['xdg-open', doc_index]) 228 | else: 229 | print_failure_message( 230 | "Unsupported platform. Please open `{0}' manually.".format( 231 | doc_index)) 232 | 233 | 234 | @task 235 | def get_tasks(): 236 | """Get all paver-defined tasks.""" 237 | from paver.tasks import environment 238 | for _task in environment.get_tasks(): 239 | print(_task.shortname) 240 | 241 | 242 | @task 243 | def doc_html(): 244 | """Build the HTML docs.""" 245 | retcode = _doc_make('html') 246 | 247 | if retcode: 248 | raise SystemExit(retcode) 249 | 250 | 251 | @task 252 | def doc_clean(): 253 | """Clean (delete) the built docs.""" 254 | retcode = _doc_make('clean') 255 | 256 | if retcode: 257 | raise SystemExit(retcode) 258 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | # Runtime requirements 2 | --requirement requirements.txt 3 | 4 | # Testing 5 | pytest==2.5.1 6 | py==1.4.19 7 | mock==1.0.1 8 | 9 | # Linting 10 | flake8==2.1.0 11 | mccabe==0.2.1 12 | pep8==1.4.6 13 | pyflakes==0.7.3 14 | 15 | # Documentation 16 | Sphinx==1.2 17 | docutils==0.11 18 | Jinja2==2.7.1 19 | MarkupSafe==0.18 20 | Pygments==1.6 21 | 22 | # Miscellaneous 23 | Paver==1.2.1 24 | colorama==0.2.7 25 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | graphenelib==0.4.8 2 | requests==2.10.0 3 | scrypt==0.7.1 4 | ecdsa==0.13 5 | websockets 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | 4 | import os 5 | import sys 6 | import imp 7 | import subprocess 8 | 9 | ## Python 2.6 subprocess.check_output compatibility. Thanks Greg Hewgill! 10 | if 'check_output' not in dir(subprocess): 11 | def check_output(cmd_args, *args, **kwargs): 12 | proc = subprocess.Popen( 13 | cmd_args, *args, 14 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) 15 | out, err = proc.communicate() 16 | if proc.returncode != 0: 17 | raise subprocess.CalledProcessError(args) 18 | return out 19 | subprocess.check_output = check_output 20 | 21 | from setuptools import setup, find_packages 22 | from setuptools.command.test import test as TestCommand 23 | from distutils import spawn 24 | 25 | try: 26 | import colorama 27 | colorama.init() # Initialize colorama on Windows 28 | except ImportError: 29 | # Don't require colorama just for running paver tasks. This allows us to 30 | # run `paver install' without requiring the user to first have colorama 31 | # installed. 32 | pass 33 | 34 | # Add the current directory to the module search path. 35 | sys.path.insert(0, os.path.abspath('.')) 36 | 37 | ## Constants 38 | CODE_DIRECTORY = 'bts' 39 | DOCS_DIRECTORY = 'docs' 40 | TESTS_DIRECTORY = 'tests' 41 | PYTEST_FLAGS = ['--doctest-modules'] 42 | 43 | # Import metadata. Normally this would just be: 44 | # 45 | # from bts import metadata 46 | # 47 | # However, when we do this, we also import `bts/__init__.py'. If this 48 | # imports names from some other modules and these modules have third-party 49 | # dependencies that need installing (which happens after this file is run), the 50 | # script will crash. What we do instead is to load the metadata module by path 51 | # instead, effectively side-stepping the dependency problem. Please make sure 52 | # metadata has no dependencies, otherwise they will need to be added to 53 | # the setup_requires keyword. 54 | metadata = imp.load_source( 55 | 'metadata', os.path.join(CODE_DIRECTORY, 'metadata.py')) 56 | 57 | 58 | ## Miscellaneous helper functions 59 | 60 | def get_project_files(): 61 | """Retrieve a list of project files, ignoring hidden files. 62 | 63 | :return: sorted list of project files 64 | :rtype: :class:`list` 65 | """ 66 | if is_git_project() and has_git(): 67 | return get_git_project_files() 68 | 69 | project_files = [] 70 | for top, subdirs, files in os.walk('.'): 71 | for subdir in subdirs: 72 | if subdir.startswith('.'): 73 | subdirs.remove(subdir) 74 | 75 | for f in files: 76 | if f.startswith('.'): 77 | continue 78 | project_files.append(os.path.join(top, f)) 79 | 80 | return project_files 81 | 82 | 83 | def is_git_project(): 84 | return os.path.isdir('.git') 85 | 86 | 87 | def has_git(): 88 | return bool(spawn.find_executable("git")) 89 | 90 | 91 | def get_git_project_files(): 92 | """Retrieve a list of all non-ignored files, including untracked files, 93 | excluding deleted files. 94 | 95 | :return: sorted list of git project files 96 | :rtype: :class:`list` 97 | """ 98 | cached_and_untracked_files = git_ls_files( 99 | '--cached', # All files cached in the index 100 | '--others', # Untracked files 101 | # Exclude untracked files that would be excluded by .gitignore, etc. 102 | '--exclude-standard') 103 | uncommitted_deleted_files = git_ls_files('--deleted') 104 | 105 | # Since sorting of files in a set is arbitrary, return a sorted list to 106 | # provide a well-defined order to tools like flake8, etc. 107 | return sorted(cached_and_untracked_files - uncommitted_deleted_files) 108 | 109 | 110 | def git_ls_files(*cmd_args): 111 | """Run ``git ls-files`` in the top-level project directory. Arguments go 112 | directly to execution call. 113 | 114 | :return: set of file names 115 | :rtype: :class:`set` 116 | """ 117 | cmd = ['git', 'ls-files'] 118 | cmd.extend(cmd_args) 119 | return set(subprocess.check_output(cmd).splitlines()) 120 | 121 | 122 | def print_success_message(message): 123 | """Print a message indicating success in green color to STDOUT. 124 | 125 | :param message: the message to print 126 | :type message: :class:`str` 127 | """ 128 | try: 129 | import colorama 130 | print(colorama.Fore.GREEN + message + colorama.Fore.RESET) 131 | except ImportError: 132 | print(message) 133 | 134 | 135 | def print_failure_message(message): 136 | """Print a message indicating failure in red color to STDERR. 137 | 138 | :param message: the message to print 139 | :type message: :class:`str` 140 | """ 141 | try: 142 | import colorama 143 | print(colorama.Fore.RED + message + colorama.Fore.RESET, 144 | file=sys.stderr) 145 | except ImportError: 146 | print(message, file=sys.stderr) 147 | 148 | 149 | def read(filename): 150 | """Return the contents of a file. 151 | 152 | :param filename: file path 153 | :type filename: :class:`str` 154 | :return: the file's content 155 | :rtype: :class:`str` 156 | """ 157 | with open(os.path.join(os.path.dirname(__file__), filename)) as f: 158 | return f.read() 159 | 160 | 161 | def _lint(): 162 | """Run lint and return an exit code.""" 163 | # Flake8 doesn't have an easy way to run checks using a Python function, so 164 | # just fork off another process to do it. 165 | 166 | # Python 3 compat: 167 | # - The result of subprocess call outputs are byte strings, meaning we need 168 | # to pass a byte string to endswith. 169 | project_python_files = [filename for filename in get_project_files() 170 | if filename.endswith(b'.py')] 171 | retcode = subprocess.call( 172 | ['flake8', '--max-complexity=10'] + project_python_files) 173 | if retcode == 0: 174 | print_success_message('No style errors') 175 | return retcode 176 | 177 | 178 | def _test(): 179 | """Run the unit tests. 180 | 181 | :return: exit code 182 | """ 183 | # Make sure to import pytest in this function. For the reason, see here: 184 | # # NOPEP8 185 | import pytest 186 | # This runs the unit tests. 187 | # It also runs doctest, but only on the modules in TESTS_DIRECTORY. 188 | return pytest.main(PYTEST_FLAGS + [TESTS_DIRECTORY]) 189 | 190 | 191 | def _test_all(): 192 | """Run lint and tests. 193 | 194 | :return: exit code 195 | """ 196 | return _lint() + _test() 197 | 198 | 199 | # The following code is to allow tests to be run with `python setup.py test'. 200 | # The main reason to make this possible is to allow tests to be run as part of 201 | # Setuptools' automatic run of 2to3 on the source code. The recommended way to 202 | # run tests is still `paver test_all'. 203 | # See 204 | # Code based on # NOPEP8 205 | class TestAllCommand(TestCommand): 206 | def finalize_options(self): 207 | TestCommand.finalize_options(self) 208 | # These are fake, and just set to appease distutils and setuptools. 209 | self.test_suite = True 210 | self.test_args = [] 211 | 212 | def run_tests(self): 213 | raise SystemExit(_test_all()) 214 | 215 | 216 | # define install_requires for specific Python versions 217 | python_version_specific_requires = [] 218 | 219 | # as of Python >= 2.7 and >= 3.2, the argparse module is maintained within 220 | # the Python standard library, otherwise we install it as a separate package 221 | if sys.version_info < (2, 7) or (3, 0) <= sys.version_info < (3, 3): 222 | python_version_specific_requires.append('argparse') 223 | 224 | 225 | # See here for more options: 226 | # 227 | setup_dict = dict( 228 | name=metadata.package, 229 | version=metadata.version, 230 | author=metadata.authors[0], 231 | author_email=metadata.emails[0], 232 | maintainer=metadata.authors[0], 233 | maintainer_email=metadata.emails[0], 234 | url=metadata.url, 235 | include_package_data=True, 236 | description=metadata.description, 237 | long_description=read('README.rst'), 238 | # Find a list of classifiers here: 239 | # 240 | classifiers=[ 241 | 'Development Status :: 1 - Planning', 242 | 'Environment :: Console', 243 | 'Intended Audience :: Developers', 244 | 'License :: OSI Approved :: MIT License', 245 | 'Natural Language :: English', 246 | 'Operating System :: OS Independent', 247 | 'Programming Language :: Python :: 2.6', 248 | 'Programming Language :: Python :: 2.7', 249 | 'Programming Language :: Python :: 3.3', 250 | 'Programming Language :: Python :: Implementation :: PyPy', 251 | 'Topic :: Documentation', 252 | 'Topic :: Software Development :: Libraries :: Python Modules', 253 | 'Topic :: System :: Installation/Setup', 254 | 'Topic :: System :: Software Distribution', 255 | ], 256 | packages=find_packages(exclude=(TESTS_DIRECTORY,)), 257 | install_requires=[ 258 | "graphenelib==0.4.8", "requests==2.10.0", 259 | "scrypt==0.7.1", "ecdsa==0.13", "websockets" 260 | # your module dependencies 261 | ] + python_version_specific_requires, 262 | # Allow tests to be run with `python setup.py test'. 263 | tests_require=[ 264 | 'pytest==2.5.1', 265 | 'mock==1.0.1', 266 | 'flake8==2.1.0', 267 | ], 268 | cmdclass={'test': TestAllCommand}, 269 | zip_safe=False, # don't use eggs 270 | entry_points={ 271 | 'console_scripts': [ 272 | 'pybts= bts.main:entry_point' 273 | ], 274 | } 275 | ) 276 | 277 | 278 | def main(): 279 | setup(**setup_dict) 280 | 281 | 282 | if __name__ == '__main__': 283 | main() 284 | -------------------------------------------------------------------------------- /tests/test_main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # from pytest import raises 3 | 4 | # The parametrize function is generated, so this doesn't work: 5 | # 6 | # from pytest.mark import parametrize 7 | # 8 | import pytest 9 | parametrize = pytest.mark.parametrize 10 | from bts import HTTPRPC 11 | from pprint import pprint 12 | 13 | 14 | class TestMain(object): 15 | logfile = open("/tmp/test-python-bts.log", 'a') 16 | host = "localhost" 17 | node_port = "4090" 18 | cli_port = "4092" 19 | cli_rpc = HTTPRPC(host, cli_port, "", "") 20 | 21 | def test_cli_rpc(self): 22 | pprint("======= test_cli_rpc =========", self.logfile) 23 | result = self.cli_rpc.about() 24 | pprint(result, self.logfile) 25 | result = self.cli_rpc.get_dynamic_global_properties() 26 | pprint(result, self.logfile) 27 | assert result["head_block_number"] > 0 28 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # Tox (http://tox.testrun.org/) is a tool for running tests in 2 | # multiple virtualenvs. This configuration file will run the test 3 | # suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | # 6 | # To run tox faster, check out Detox 7 | # (https://pypi.python.org/pypi/detox), which runs your tox runs in 8 | # parallel. To use it, "pip install detox" and then run "detox" from 9 | # this directory. 10 | 11 | [tox] 12 | envlist = py26,py27,py33,pypy,docs 13 | 14 | [testenv] 15 | deps = 16 | --no-deps 17 | --requirement 18 | {toxinidir}/requirements-dev.txt 19 | commands = paver test_all 20 | 21 | [testenv:docs] 22 | basepython = python 23 | commands = paver doc_html 24 | --------------------------------------------------------------------------------