We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Support rlp==0.4.7
* Version: 3.7.2
* Python: 2.7
* OS: osx

### What was wrong?
https://github.com/ethereum/pydevp2p requires `rlp==0.4.7` ([here](https://github.com/ethereum/pydevp2p/blob/develop/requirements.txt#L11)), but `web3.py` requires `rlp>=0.4.6,<0.4.7`. This causes headaches when a project requires both packages as well as `rlp` independently.

I've created a repo with updated requirements here: https://github.com/karlfloersch/web3.py, but I haven't verified that everything is working properly.

#### Cute Animal Picture

![Cute animal picture](http://cdn.9appsdownloading.com/group1/M01/E8/54/pYYBAFbW5uiAUpNuAACUkuW7ZCQ868.png)
Thank you!


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `setup.py`
Content:
```
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import os
4 import sys
5 
6 from setuptools import (
7     setup,
8     find_packages,
9 )
10 
11 
12 DIR = os.path.dirname(os.path.abspath(__file__))
13 
14 
15 readme = open(os.path.join(DIR, 'README.md')).read()
16 
17 install_requires=[
18     "ethereum-abi-utils>=0.4.0",
19     "ethereum-utils>=0.2.0",
20     "pylru>=1.0.9",
21     "pysha3>=0.3",
22     "requests>=2.12.4",
23     "rlp>=0.4.6,<0.4.7",
24 ]
25 
26 if sys.platform == 'win32':
27     install_requires.append('pypiwin32')
28 
29 setup(
30     name='web3',
31     version='3.7.2',
32     description="""Web3.py""",
33     long_description=readme,
34     author='Piper Merriam',
35     author_email='pipermerriam@gmail.com',
36     url='https://github.com/pipermerriam/web3.py',
37     include_package_data=True,
38     install_requires=install_requires,
39     extras_require={
40         'Tester': ["eth-testrpc>=1.1.0"],
41         'tester': ["eth-testrpc>=1.1.0"],
42         'gevent': [
43             "gevent>=1.1.1,<1.2.0",
44             "geventhttpclient>=1.3.1",
45         ],
46     },
47     py_modules=['web3'],
48     license="MIT",
49     zip_safe=False,
50     keywords='ethereum',
51     packages=find_packages(exclude=["tests", "tests.*"]),
52     classifiers=[
53         'Development Status :: 2 - Pre-Alpha',
54         'Intended Audience :: Developers',
55         'License :: OSI Approved :: MIT License',
56         'Natural Language :: English',
57         'Programming Language :: Python :: 2',
58         'Programming Language :: Python :: 2.7',
59         'Programming Language :: Python :: 3',
60         'Programming Language :: Python :: 3.4',
61         'Programming Language :: Python :: 3.5',
62     ],
63 )
64
```

Path: `web3/providers/manager.py`
Content:
```
1 import uuid
2 import json
3 import collections
4 
5 import rlp
6 
7 from eth_utils import (
8     force_text,
9     to_normalized_address,
10     is_string,
11     is_dict,
12     encode_hex,
13     decode_hex,
14     keccak,
15 )
16 
17 from web3.utils.encoding import (
18     to_decimal,
19 )
20 from web3.utils.transactions import (
21     is_bitcoin_available,
22     Transaction,
23     serialize_transaction,
24     add_signature_to_transaction,
25 )
26 from web3.utils.compat import (
27     spawn,
28 )
29 
30 
31 class RequestManager(object):
32     def __init__(self, provider):
33         self.pending_requests = {}
34         self.provider = provider
35 
36     def setProvider(self, provider):
37         self.provider = provider
38 
39     def request_blocking(self, method, params):
40         """
41         Make a synchronous request using the provider
42         """
43         response_raw = self.provider.make_request(method, params)
44 
45         if is_string(response_raw):
46             response = json.loads(force_text(response_raw))
47         elif is_dict(response_raw):
48             response = response_raw
49 
50         if "error" in response:
51             raise ValueError(response["error"])
52 
53         return response['result']
54 
55     def request_async(self, method, params):
56         request_id = uuid.uuid4()
57         self.pending_requests[request_id] = spawn(
58             self.request_blocking,
59             method,
60             params,
61         )
62         return request_id
63 
64     def receive_blocking(self, request_id, timeout=None):
65         try:
66             request = self.pending_requests.pop(request_id)
67         except KeyError:
68             raise KeyError("Request for id:{0} not found".format(request_id))
69         else:
70             response_raw = request.get(timeout=timeout)
71 
72         response = json.loads(response_raw)
73 
74         if "error" in response:
75             raise ValueError(response["error"])
76 
77         return response['result']
78 
79     def receive_async(self, request_id, *args, **kwargs):
80         raise NotImplementedError("Callback pattern not implemented")
81 
82 
83 class ManagerWrapper(object):
84     def __init__(self, wrapped_manager):
85         self.wrapped_manager = wrapped_manager
86 
87     @property
88     def provider(self):
89         return self.wrapped_manager.provider
90 
91     @property
92     def pending_requests(self):
93         return self.wrapped_manager.pending_requests
94 
95     def setProvider(self, provider):
96         self.wrapped_manager.provider = provider
97 
98     def request_blocking(self, *args, **kwargs):
99         return self.wrapped_manager.request_blocking(*args, **kwargs)
100 
101     def request_async(self, *args, **kwargs):
102         return self.wrapped_manager.request_async(*args, **kwargs)
103 
104     def receive_blocking(self, *args, **kwargs):
105         return self.wrapped_manager.receive_blocking(*args, **kwargs)
106 
107     def receive_async(self, *args, **kwargs):
108         return self.wrapped_manager.receive_async(*args, **kwargs)
109 
110 
111 class BaseSendRawTransactionMixin(ManagerWrapper):
112     _known_transactions = None
113     _known_nonces = None
114 
115     def __init__(self, *args, **kwargs):
116         self._known_transactions = collections.defaultdict(set)
117         self._known_nonces = collections.defaultdict(set)
118         super(BaseSendRawTransactionMixin, self).__init__(*args, **kwargs)
119 
120     def _get_nonces_and_cleanup(self, addr, chain_nonce):
121         all_txns = {
122             txn_hash: self.request_blocking(
123                 'eth_getTransactionByHash',
124                 [txn_hash],
125             ) for txn_hash in self._known_transactions[addr]
126         }
127         for txn_hash, txn in all_txns.items():
128             if txn is None:
129                 continue
130             txn_nonce = to_decimal(txn['nonce'])
131             if txn_nonce < chain_nonce:
132                 self._known_transactions[addr].discard(txn_hash)
133             else:
134                 yield txn_nonce
135 
136         all_known_nonces = tuple(self._known_nonces[addr])
137         for nonce in all_known_nonces:
138             if nonce < chain_nonce:
139                 self._known_nonces[addr].discard(nonce)
140             else:
141                 yield nonce
142 
143     def get_chain_nonce(self, addr):
144         chain_nonce = to_decimal(self.request_blocking(
145             'eth_getTransactionCount',
146             [addr, 'pending']
147         ))
148         return chain_nonce
149 
150     def get_nonce(self, addr):
151         chain_nonce = self.get_chain_nonce(addr)
152         tracked_txn_nonces = tuple(self._get_nonces_and_cleanup(addr, chain_nonce))
153         nonce = max(0, chain_nonce, *tracked_txn_nonces)
154         if nonce == 0 and not tracked_txn_nonces:
155             return -1
156         else:
157             return nonce
158 
159     def get_transaction_signature(self, serialized_txn):
160         raise NotImplementedError("Must be implemented by subclasses")
161 
162     def sign_and_serialize_transaction(self, transaction):
163         serialized_txn = serialize_transaction(transaction)
164         signature = self.get_transaction_signature(transaction)
165         signed_transaction = add_signature_to_transaction(
166             serialized_txn,
167             signature,
168         )
169         signed_and_serialized_txn = rlp.encode(signed_transaction, Transaction)
170         return signed_and_serialized_txn
171 
172     def construct_full_transaction(self, base_transaction):
173         txn_from = base_transaction['from']
174         full_txn = dict(**base_transaction)
175         full_txn.setdefault('nonce', self.get_nonce(txn_from) + 1)
176         full_txn.setdefault('gasPrice', self.request_blocking(
177             'eth_gasPrice', []
178         ))
179         full_txn.setdefault('gas', hex(90000))
180         full_txn.setdefault('value', '0x0')
181         full_txn.setdefault('to', '')
182         full_txn.setdefault('data', '')
183         return full_txn
184 
185     TXN_SENDING_METHODS = {
186         'eth_sendTransaction',
187         'eth_sendRawTransaction',
188         'personal_signAndSendTransaction',
189         'personal_sendTransaction',
190     }
191 
192     def request_blocking(self, method, params):
193         if method == 'eth_sendTransaction':
194             base_transaction = params[0]
195             # create a fully signed transaction and send through the
196             # `eth_sendRawTransaction` endpoint instead.
197             full_transaction = self.construct_full_transaction(base_transaction)
198             raw_transaction_bytes = self.sign_and_serialize_transaction(
199                 full_transaction,
200             )
201             raw_transaction_bytes_as_hex = encode_hex(raw_transaction_bytes)
202             return self.request_blocking(
203                 'eth_sendRawTransaction', [raw_transaction_bytes_as_hex],
204             )
205 
206         result = super(BaseSendRawTransactionMixin, self).request_blocking(
207             method, params,
208         )
209         if method in self.TXN_SENDING_METHODS:
210             if method == 'eth_sendRawTransaction':
211                 txn = rlp.decode(decode_hex(params[0]), Transaction)
212                 self._known_transactions[to_normalized_address(txn.sender)].add(result)
213                 self._known_nonces[to_normalized_address(txn.sender)].add(txn.nonce)
214             else:
215                 txn = params[0]
216                 self._known_transactions[to_normalized_address(txn['from'])].add(result)
217                 if 'nonce' in txn:
218                     self._known_nonces[to_normalized_address(txn['from'])].add(
219                         to_decimal(txn['nonce'])
220                     )
221         return result
222 
223 
224 class DelegatedSigningManager(BaseSendRawTransactionMixin):
225     def __init__(self, *args, **kwargs):
226         self.signing_manager = kwargs.pop('signing_manager')
227         super(DelegatedSigningManager, self).__init__(*args, **kwargs)
228 
229     def get_chain_nonce(self, addr):
230         signer_nonce = to_decimal(self.signing_manager.request_blocking(
231             'eth_getTransactionCount',
232             [addr, 'pending']
233         ))
234         wrapped_nonce = to_decimal(self.wrapped_manager.request_blocking(
235             'eth_getTransactionCount',
236             [addr, 'pending']
237         ))
238         return max(signer_nonce, wrapped_nonce)
239 
240     def get_transaction_signature(self, transaction):
241         serialized_txn = serialize_transaction(transaction)
242         hash_to_sign = self.signing_manager.request_blocking(
243             'web3_sha3', [encode_hex(serialized_txn)],
244         )
245         signature_hex = self.signing_manager.request_blocking(
246             'eth_sign',
247             [
248                 transaction['from'],
249                 hash_to_sign,
250             ],
251         )
252         signature = decode_hex(signature_hex)
253         return signature
254 
255 
256 class PrivateKeySigningManager(BaseSendRawTransactionMixin):
257     def __init__(self, *args, **kwargs):
258         if not is_bitcoin_available():
259             raise ImportError(
260                 "In order to use the `PrivateKeySigningManager` the "
261                 "`bitcoin` and `secp256k1` packages must be installed."
262             )
263         self.keys = kwargs.pop('keys', {})
264         super(PrivateKeySigningManager, self).__init__(*args, **kwargs)
265 
266     def register_private_key(self, key):
267         from bitcoin import privtopub
268         address = to_normalized_address(keccak(privtopub(key)[1:])[-20:])
269         self.keys[address] = key
270 
271     def sign_and_serialize_transaction(self, transaction):
272         txn_from = to_normalized_address(transaction['from'])
273         if txn_from not in self.keys:
274             raise KeyError("No signing key registered for from address: {0}".format(txn_from))
275         transaction = Transaction(
276             nonce=to_decimal(transaction['nonce']),
277             gasprice=to_decimal(transaction['gasPrice']),
278             startgas=to_decimal(transaction['gas']),
279             to=transaction['to'],
280             value=to_decimal(transaction['value']),
281             data=decode_hex(transaction['data']),
282         )
283         transaction.sign(self.keys[txn_from])
284         assert to_normalized_address(transaction.sender) == txn_from
285         return rlp.encode(transaction, Transaction)
286
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -20,7 +20,7 @@
     "pylru>=1.0.9",
     "pysha3>=0.3",
     "requests>=2.12.4",
-    "rlp>=0.4.6,<0.4.7",
+    "rlp>=0.4.7",
 ]
 
 if sys.platform == 'win32':
@@ -37,8 +37,7 @@
     include_package_data=True,
     install_requires=install_requires,
     extras_require={
-        'Tester': ["eth-testrpc>=1.1.0"],
-        'tester': ["eth-testrpc>=1.1.0"],
+        'tester': ["eth-testrpc>=1.2.0"],
         'gevent': [
             "gevent>=1.1.1,<1.2.0",
             "geventhttpclient>=1.3.1",
diff --git a/web3/providers/manager.py b/web3/providers/manager.py
--- a/web3/providers/manager.py
+++ b/web3/providers/manager.py
@@ -1,17 +1,18 @@
-import uuid
-import json
 import collections
+import json
+import uuid
+import warnings
 
 import rlp
 
 from eth_utils import (
+    decode_hex,
+    encode_hex,
     force_text,
-    to_normalized_address,
-    is_string,
     is_dict,
-    encode_hex,
-    decode_hex,
+    is_string,
     keccak,
+    to_normalized_address,
 )
 
 from web3.utils.encoding import (
@@ -82,6 +83,10 @@
 
 class ManagerWrapper(object):
     def __init__(self, wrapped_manager):
+        warnings.warn(DeprecationWarning(
+            "ManagerWrapper has been deprecated and will be removed from"
+            "web3.py in subsequen releases."
+        ))
         self.wrapped_manager = wrapped_manager
 
     @property
@@ -223,6 +228,10 @@
 
 class DelegatedSigningManager(BaseSendRawTransactionMixin):
     def __init__(self, *args, **kwargs):
+        warnings.warn(DeprecationWarning(
+            "DelegatedSigningManager has been deprecated and will be removed from"
+            "web3.py in subsequen releases."
+        ))
         self.signing_manager = kwargs.pop('signing_manager')
         super(DelegatedSigningManager, self).__init__(*args, **kwargs)
 
@@ -255,6 +264,10 @@
 
 class PrivateKeySigningManager(BaseSendRawTransactionMixin):
     def __init__(self, *args, **kwargs):
+        warnings.warn(DeprecationWarning(
+            "PrivateKeySigningManager has been deprecated and will be removed from"
+            "web3.py in subsequen releases."
+        ))
         if not is_bitcoin_available():
             raise ImportError(
                 "In order to use the `PrivateKeySigningManager` the "

{"golden_diff": "diff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -20,7 +20,7 @@\n     \"pylru>=1.0.9\",\n     \"pysha3>=0.3\",\n     \"requests>=2.12.4\",\n-    \"rlp>=0.4.6,<0.4.7\",\n+    \"rlp>=0.4.7\",\n ]\n \n if sys.platform == 'win32':\n@@ -37,8 +37,7 @@\n     include_package_data=True,\n     install_requires=install_requires,\n     extras_require={\n-        'Tester': [\"eth-testrpc>=1.1.0\"],\n-        'tester': [\"eth-testrpc>=1.1.0\"],\n+        'tester': [\"eth-testrpc>=1.2.0\"],\n         'gevent': [\n             \"gevent>=1.1.1,<1.2.0\",\n             \"geventhttpclient>=1.3.1\",\ndiff --git a/web3/providers/manager.py b/web3/providers/manager.py\n--- a/web3/providers/manager.py\n+++ b/web3/providers/manager.py\n@@ -1,17 +1,18 @@\n-import uuid\n-import json\n import collections\n+import json\n+import uuid\n+import warnings\n \n import rlp\n \n from eth_utils import (\n+    decode_hex,\n+    encode_hex,\n     force_text,\n-    to_normalized_address,\n-    is_string,\n     is_dict,\n-    encode_hex,\n-    decode_hex,\n+    is_string,\n     keccak,\n+    to_normalized_address,\n )\n \n from web3.utils.encoding import (\n@@ -82,6 +83,10 @@\n \n class ManagerWrapper(object):\n     def __init__(self, wrapped_manager):\n+        warnings.warn(DeprecationWarning(\n+            \"ManagerWrapper has been deprecated and will be removed from\"\n+            \"web3.py in subsequen releases.\"\n+        ))\n         self.wrapped_manager = wrapped_manager\n \n     @property\n@@ -223,6 +228,10 @@\n \n class DelegatedSigningManager(BaseSendRawTransactionMixin):\n     def __init__(self, *args, **kwargs):\n+        warnings.warn(DeprecationWarning(\n+            \"DelegatedSigningManager has been deprecated and will be removed from\"\n+            \"web3.py in subsequen releases.\"\n+        ))\n         self.signing_manager = kwargs.pop('signing_manager')\n         super(DelegatedSigningManager, self).__init__(*args, **kwargs)\n \n@@ -255,6 +264,10 @@\n \n class PrivateKeySigningManager(BaseSendRawTransactionMixin):\n     def __init__(self, *args, **kwargs):\n+        warnings.warn(DeprecationWarning(\n+            \"PrivateKeySigningManager has been deprecated and will be removed from\"\n+            \"web3.py in subsequen releases.\"\n+        ))\n         if not is_bitcoin_available():\n             raise ImportError(\n                 \"In order to use the `PrivateKeySigningManager` the \"\n", "issue": "Support rlp==0.4.7\n* Version: 3.7.2\r\n* Python: 2.7\r\n* OS: osx\r\n\r\n### What was wrong?\r\nhttps://github.com/ethereum/pydevp2p requires `rlp==0.4.7` ([here](https://github.com/ethereum/pydevp2p/blob/develop/requirements.txt#L11)), but `web3.py` requires `rlp>=0.4.6,<0.4.7`. This causes headaches when a project requires both packages as well as `rlp` independently.\r\n\r\nI've created a repo with updated requirements here: https://github.com/karlfloersch/web3.py, but I haven't verified that everything is working properly.\r\n\r\n#### Cute Animal Picture\r\n\r\n![Cute animal picture](http://cdn.9appsdownloading.com/group1/M01/E8/54/pYYBAFbW5uiAUpNuAACUkuW7ZCQ868.png)\r\nThank you!\r\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nfrom setuptools import (\n    setup,\n    find_packages,\n)\n\n\nDIR = os.path.dirname(os.path.abspath(__file__))\n\n\nreadme = open(os.path.join(DIR, 'README.md')).read()\n\ninstall_requires=[\n    \"ethereum-abi-utils>=0.4.0\",\n    \"ethereum-utils>=0.2.0\",\n    \"pylru>=1.0.9\",\n    \"pysha3>=0.3\",\n    \"requests>=2.12.4\",\n    \"rlp>=0.4.6,<0.4.7\",\n]\n\nif sys.platform == 'win32':\n    install_requires.append('pypiwin32')\n\nsetup(\n    name='web3',\n    version='3.7.2',\n    description=\"\"\"Web3.py\"\"\",\n    long_description=readme,\n    author='Piper Merriam',\n    author_email='pipermerriam@gmail.com',\n    url='https://github.com/pipermerriam/web3.py',\n    include_package_data=True,\n    install_requires=install_requires,\n    extras_require={\n        'Tester': [\"eth-testrpc>=1.1.0\"],\n        'tester': [\"eth-testrpc>=1.1.0\"],\n        'gevent': [\n            \"gevent>=1.1.1,<1.2.0\",\n            \"geventhttpclient>=1.3.1\",\n        ],\n    },\n    py_modules=['web3'],\n    license=\"MIT\",\n    zip_safe=False,\n    keywords='ethereum',\n    packages=find_packages(exclude=[\"tests\", \"tests.*\"]),\n    classifiers=[\n        'Development Status :: 2 - Pre-Alpha',\n        'Intended Audience :: Developers',\n        'License :: OSI Approved :: MIT License',\n        'Natural Language :: English',\n        'Programming Language :: Python :: 2',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n    ],\n)\n", "path": "setup.py"}, {"content": "import uuid\nimport json\nimport collections\n\nimport rlp\n\nfrom eth_utils import (\n    force_text,\n    to_normalized_address,\n    is_string,\n    is_dict,\n    encode_hex,\n    decode_hex,\n    keccak,\n)\n\nfrom web3.utils.encoding import (\n    to_decimal,\n)\nfrom web3.utils.transactions import (\n    is_bitcoin_available,\n    Transaction,\n    serialize_transaction,\n    add_signature_to_transaction,\n)\nfrom web3.utils.compat import (\n    spawn,\n)\n\n\nclass RequestManager(object):\n    def __init__(self, provider):\n        self.pending_requests = {}\n        self.provider = provider\n\n    def setProvider(self, provider):\n        self.provider = provider\n\n    def request_blocking(self, method, params):\n        \"\"\"\n        Make a synchronous request using the provider\n        \"\"\"\n        response_raw = self.provider.make_request(method, params)\n\n        if is_string(response_raw):\n            response = json.loads(force_text(response_raw))\n        elif is_dict(response_raw):\n            response = response_raw\n\n        if \"error\" in response:\n            raise ValueError(response[\"error\"])\n\n        return response['result']\n\n    def request_async(self, method, params):\n        request_id = uuid.uuid4()\n        self.pending_requests[request_id] = spawn(\n            self.request_blocking,\n            method,\n            params,\n        )\n        return request_id\n\n    def receive_blocking(self, request_id, timeout=None):\n        try:\n            request = self.pending_requests.pop(request_id)\n        except KeyError:\n            raise KeyError(\"Request for id:{0} not found\".format(request_id))\n        else:\n            response_raw = request.get(timeout=timeout)\n\n        response = json.loads(response_raw)\n\n        if \"error\" in response:\n            raise ValueError(response[\"error\"])\n\n        return response['result']\n\n    def receive_async(self, request_id, *args, **kwargs):\n        raise NotImplementedError(\"Callback pattern not implemented\")\n\n\nclass ManagerWrapper(object):\n    def __init__(self, wrapped_manager):\n        self.wrapped_manager = wrapped_manager\n\n    @property\n    def provider(self):\n        return self.wrapped_manager.provider\n\n    @property\n    def pending_requests(self):\n        return self.wrapped_manager.pending_requests\n\n    def setProvider(self, provider):\n        self.wrapped_manager.provider = provider\n\n    def request_blocking(self, *args, **kwargs):\n        return self.wrapped_manager.request_blocking(*args, **kwargs)\n\n    def request_async(self, *args, **kwargs):\n        return self.wrapped_manager.request_async(*args, **kwargs)\n\n    def receive_blocking(self, *args, **kwargs):\n        return self.wrapped_manager.receive_blocking(*args, **kwargs)\n\n    def receive_async(self, *args, **kwargs):\n        return self.wrapped_manager.receive_async(*args, **kwargs)\n\n\nclass BaseSendRawTransactionMixin(ManagerWrapper):\n    _known_transactions = None\n    _known_nonces = None\n\n    def __init__(self, *args, **kwargs):\n        self._known_transactions = collections.defaultdict(set)\n        self._known_nonces = collections.defaultdict(set)\n        super(BaseSendRawTransactionMixin, self).__init__(*args, **kwargs)\n\n    def _get_nonces_and_cleanup(self, addr, chain_nonce):\n        all_txns = {\n            txn_hash: self.request_blocking(\n                'eth_getTransactionByHash',\n                [txn_hash],\n            ) for txn_hash in self._known_transactions[addr]\n        }\n        for txn_hash, txn in all_txns.items():\n            if txn is None:\n                continue\n            txn_nonce = to_decimal(txn['nonce'])\n            if txn_nonce < chain_nonce:\n                self._known_transactions[addr].discard(txn_hash)\n            else:\n                yield txn_nonce\n\n        all_known_nonces = tuple(self._known_nonces[addr])\n        for nonce in all_known_nonces:\n            if nonce < chain_nonce:\n                self._known_nonces[addr].discard(nonce)\n            else:\n                yield nonce\n\n    def get_chain_nonce(self, addr):\n        chain_nonce = to_decimal(self.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        return chain_nonce\n\n    def get_nonce(self, addr):\n        chain_nonce = self.get_chain_nonce(addr)\n        tracked_txn_nonces = tuple(self._get_nonces_and_cleanup(addr, chain_nonce))\n        nonce = max(0, chain_nonce, *tracked_txn_nonces)\n        if nonce == 0 and not tracked_txn_nonces:\n            return -1\n        else:\n            return nonce\n\n    def get_transaction_signature(self, serialized_txn):\n        raise NotImplementedError(\"Must be implemented by subclasses\")\n\n    def sign_and_serialize_transaction(self, transaction):\n        serialized_txn = serialize_transaction(transaction)\n        signature = self.get_transaction_signature(transaction)\n        signed_transaction = add_signature_to_transaction(\n            serialized_txn,\n            signature,\n        )\n        signed_and_serialized_txn = rlp.encode(signed_transaction, Transaction)\n        return signed_and_serialized_txn\n\n    def construct_full_transaction(self, base_transaction):\n        txn_from = base_transaction['from']\n        full_txn = dict(**base_transaction)\n        full_txn.setdefault('nonce', self.get_nonce(txn_from) + 1)\n        full_txn.setdefault('gasPrice', self.request_blocking(\n            'eth_gasPrice', []\n        ))\n        full_txn.setdefault('gas', hex(90000))\n        full_txn.setdefault('value', '0x0')\n        full_txn.setdefault('to', '')\n        full_txn.setdefault('data', '')\n        return full_txn\n\n    TXN_SENDING_METHODS = {\n        'eth_sendTransaction',\n        'eth_sendRawTransaction',\n        'personal_signAndSendTransaction',\n        'personal_sendTransaction',\n    }\n\n    def request_blocking(self, method, params):\n        if method == 'eth_sendTransaction':\n            base_transaction = params[0]\n            # create a fully signed transaction and send through the\n            # `eth_sendRawTransaction` endpoint instead.\n            full_transaction = self.construct_full_transaction(base_transaction)\n            raw_transaction_bytes = self.sign_and_serialize_transaction(\n                full_transaction,\n            )\n            raw_transaction_bytes_as_hex = encode_hex(raw_transaction_bytes)\n            return self.request_blocking(\n                'eth_sendRawTransaction', [raw_transaction_bytes_as_hex],\n            )\n\n        result = super(BaseSendRawTransactionMixin, self).request_blocking(\n            method, params,\n        )\n        if method in self.TXN_SENDING_METHODS:\n            if method == 'eth_sendRawTransaction':\n                txn = rlp.decode(decode_hex(params[0]), Transaction)\n                self._known_transactions[to_normalized_address(txn.sender)].add(result)\n                self._known_nonces[to_normalized_address(txn.sender)].add(txn.nonce)\n            else:\n                txn = params[0]\n                self._known_transactions[to_normalized_address(txn['from'])].add(result)\n                if 'nonce' in txn:\n                    self._known_nonces[to_normalized_address(txn['from'])].add(\n                        to_decimal(txn['nonce'])\n                    )\n        return result\n\n\nclass DelegatedSigningManager(BaseSendRawTransactionMixin):\n    def __init__(self, *args, **kwargs):\n        self.signing_manager = kwargs.pop('signing_manager')\n        super(DelegatedSigningManager, self).__init__(*args, **kwargs)\n\n    def get_chain_nonce(self, addr):\n        signer_nonce = to_decimal(self.signing_manager.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        wrapped_nonce = to_decimal(self.wrapped_manager.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        return max(signer_nonce, wrapped_nonce)\n\n    def get_transaction_signature(self, transaction):\n        serialized_txn = serialize_transaction(transaction)\n        hash_to_sign = self.signing_manager.request_blocking(\n            'web3_sha3', [encode_hex(serialized_txn)],\n        )\n        signature_hex = self.signing_manager.request_blocking(\n            'eth_sign',\n            [\n                transaction['from'],\n                hash_to_sign,\n            ],\n        )\n        signature = decode_hex(signature_hex)\n        return signature\n\n\nclass PrivateKeySigningManager(BaseSendRawTransactionMixin):\n    def __init__(self, *args, **kwargs):\n        if not is_bitcoin_available():\n            raise ImportError(\n                \"In order to use the `PrivateKeySigningManager` the \"\n                \"`bitcoin` and `secp256k1` packages must be installed.\"\n            )\n        self.keys = kwargs.pop('keys', {})\n        super(PrivateKeySigningManager, self).__init__(*args, **kwargs)\n\n    def register_private_key(self, key):\n        from bitcoin import privtopub\n        address = to_normalized_address(keccak(privtopub(key)[1:])[-20:])\n        self.keys[address] = key\n\n    def sign_and_serialize_transaction(self, transaction):\n        txn_from = to_normalized_address(transaction['from'])\n        if txn_from not in self.keys:\n            raise KeyError(\"No signing key registered for from address: {0}\".format(txn_from))\n        transaction = Transaction(\n            nonce=to_decimal(transaction['nonce']),\n            gasprice=to_decimal(transaction['gasPrice']),\n            startgas=to_decimal(transaction['gas']),\n            to=transaction['to'],\n            value=to_decimal(transaction['value']),\n            data=decode_hex(transaction['data']),\n        )\n        transaction.sign(self.keys[txn_from])\n        assert to_normalized_address(transaction.sender) == txn_from\n        return rlp.encode(transaction, Transaction)\n", "path": "web3/providers/manager.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\nfrom setuptools import (\n    setup,\n    find_packages,\n)\n\n\nDIR = os.path.dirname(os.path.abspath(__file__))\n\n\nreadme = open(os.path.join(DIR, 'README.md')).read()\n\ninstall_requires=[\n    \"ethereum-abi-utils>=0.4.0\",\n    \"ethereum-utils>=0.2.0\",\n    \"pylru>=1.0.9\",\n    \"pysha3>=0.3\",\n    \"requests>=2.12.4\",\n    \"rlp>=0.4.7\",\n]\n\nif sys.platform == 'win32':\n    install_requires.append('pypiwin32')\n\nsetup(\n    name='web3',\n    version='3.7.2',\n    description=\"\"\"Web3.py\"\"\",\n    long_description=readme,\n    author='Piper Merriam',\n    author_email='pipermerriam@gmail.com',\n    url='https://github.com/pipermerriam/web3.py',\n    include_package_data=True,\n    install_requires=install_requires,\n    extras_require={\n        'tester': [\"eth-testrpc>=1.2.0\"],\n        'gevent': [\n            \"gevent>=1.1.1,<1.2.0\",\n            \"geventhttpclient>=1.3.1\",\n        ],\n    },\n    py_modules=['web3'],\n    license=\"MIT\",\n    zip_safe=False,\n    keywords='ethereum',\n    packages=find_packages(exclude=[\"tests\", \"tests.*\"]),\n    classifiers=[\n        'Development Status :: 2 - Pre-Alpha',\n        'Intended Audience :: Developers',\n        'License :: OSI Approved :: MIT License',\n        'Natural Language :: English',\n        'Programming Language :: Python :: 2',\n        'Programming Language :: Python :: 2.7',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.4',\n        'Programming Language :: Python :: 3.5',\n    ],\n)\n", "path": "setup.py"}, {"content": "import collections\nimport json\nimport uuid\nimport warnings\n\nimport rlp\n\nfrom eth_utils import (\n    decode_hex,\n    encode_hex,\n    force_text,\n    is_dict,\n    is_string,\n    keccak,\n    to_normalized_address,\n)\n\nfrom web3.utils.encoding import (\n    to_decimal,\n)\nfrom web3.utils.transactions import (\n    is_bitcoin_available,\n    Transaction,\n    serialize_transaction,\n    add_signature_to_transaction,\n)\nfrom web3.utils.compat import (\n    spawn,\n)\n\n\nclass RequestManager(object):\n    def __init__(self, provider):\n        self.pending_requests = {}\n        self.provider = provider\n\n    def setProvider(self, provider):\n        self.provider = provider\n\n    def request_blocking(self, method, params):\n        \"\"\"\n        Make a synchronous request using the provider\n        \"\"\"\n        response_raw = self.provider.make_request(method, params)\n\n        if is_string(response_raw):\n            response = json.loads(force_text(response_raw))\n        elif is_dict(response_raw):\n            response = response_raw\n\n        if \"error\" in response:\n            raise ValueError(response[\"error\"])\n\n        return response['result']\n\n    def request_async(self, method, params):\n        request_id = uuid.uuid4()\n        self.pending_requests[request_id] = spawn(\n            self.request_blocking,\n            method,\n            params,\n        )\n        return request_id\n\n    def receive_blocking(self, request_id, timeout=None):\n        try:\n            request = self.pending_requests.pop(request_id)\n        except KeyError:\n            raise KeyError(\"Request for id:{0} not found\".format(request_id))\n        else:\n            response_raw = request.get(timeout=timeout)\n\n        response = json.loads(response_raw)\n\n        if \"error\" in response:\n            raise ValueError(response[\"error\"])\n\n        return response['result']\n\n    def receive_async(self, request_id, *args, **kwargs):\n        raise NotImplementedError(\"Callback pattern not implemented\")\n\n\nclass ManagerWrapper(object):\n    def __init__(self, wrapped_manager):\n        warnings.warn(DeprecationWarning(\n            \"ManagerWrapper has been deprecated and will be removed from\"\n            \"web3.py in subsequen releases.\"\n        ))\n        self.wrapped_manager = wrapped_manager\n\n    @property\n    def provider(self):\n        return self.wrapped_manager.provider\n\n    @property\n    def pending_requests(self):\n        return self.wrapped_manager.pending_requests\n\n    def setProvider(self, provider):\n        self.wrapped_manager.provider = provider\n\n    def request_blocking(self, *args, **kwargs):\n        return self.wrapped_manager.request_blocking(*args, **kwargs)\n\n    def request_async(self, *args, **kwargs):\n        return self.wrapped_manager.request_async(*args, **kwargs)\n\n    def receive_blocking(self, *args, **kwargs):\n        return self.wrapped_manager.receive_blocking(*args, **kwargs)\n\n    def receive_async(self, *args, **kwargs):\n        return self.wrapped_manager.receive_async(*args, **kwargs)\n\n\nclass BaseSendRawTransactionMixin(ManagerWrapper):\n    _known_transactions = None\n    _known_nonces = None\n\n    def __init__(self, *args, **kwargs):\n        self._known_transactions = collections.defaultdict(set)\n        self._known_nonces = collections.defaultdict(set)\n        super(BaseSendRawTransactionMixin, self).__init__(*args, **kwargs)\n\n    def _get_nonces_and_cleanup(self, addr, chain_nonce):\n        all_txns = {\n            txn_hash: self.request_blocking(\n                'eth_getTransactionByHash',\n                [txn_hash],\n            ) for txn_hash in self._known_transactions[addr]\n        }\n        for txn_hash, txn in all_txns.items():\n            if txn is None:\n                continue\n            txn_nonce = to_decimal(txn['nonce'])\n            if txn_nonce < chain_nonce:\n                self._known_transactions[addr].discard(txn_hash)\n            else:\n                yield txn_nonce\n\n        all_known_nonces = tuple(self._known_nonces[addr])\n        for nonce in all_known_nonces:\n            if nonce < chain_nonce:\n                self._known_nonces[addr].discard(nonce)\n            else:\n                yield nonce\n\n    def get_chain_nonce(self, addr):\n        chain_nonce = to_decimal(self.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        return chain_nonce\n\n    def get_nonce(self, addr):\n        chain_nonce = self.get_chain_nonce(addr)\n        tracked_txn_nonces = tuple(self._get_nonces_and_cleanup(addr, chain_nonce))\n        nonce = max(0, chain_nonce, *tracked_txn_nonces)\n        if nonce == 0 and not tracked_txn_nonces:\n            return -1\n        else:\n            return nonce\n\n    def get_transaction_signature(self, serialized_txn):\n        raise NotImplementedError(\"Must be implemented by subclasses\")\n\n    def sign_and_serialize_transaction(self, transaction):\n        serialized_txn = serialize_transaction(transaction)\n        signature = self.get_transaction_signature(transaction)\n        signed_transaction = add_signature_to_transaction(\n            serialized_txn,\n            signature,\n        )\n        signed_and_serialized_txn = rlp.encode(signed_transaction, Transaction)\n        return signed_and_serialized_txn\n\n    def construct_full_transaction(self, base_transaction):\n        txn_from = base_transaction['from']\n        full_txn = dict(**base_transaction)\n        full_txn.setdefault('nonce', self.get_nonce(txn_from) + 1)\n        full_txn.setdefault('gasPrice', self.request_blocking(\n            'eth_gasPrice', []\n        ))\n        full_txn.setdefault('gas', hex(90000))\n        full_txn.setdefault('value', '0x0')\n        full_txn.setdefault('to', '')\n        full_txn.setdefault('data', '')\n        return full_txn\n\n    TXN_SENDING_METHODS = {\n        'eth_sendTransaction',\n        'eth_sendRawTransaction',\n        'personal_signAndSendTransaction',\n        'personal_sendTransaction',\n    }\n\n    def request_blocking(self, method, params):\n        if method == 'eth_sendTransaction':\n            base_transaction = params[0]\n            # create a fully signed transaction and send through the\n            # `eth_sendRawTransaction` endpoint instead.\n            full_transaction = self.construct_full_transaction(base_transaction)\n            raw_transaction_bytes = self.sign_and_serialize_transaction(\n                full_transaction,\n            )\n            raw_transaction_bytes_as_hex = encode_hex(raw_transaction_bytes)\n            return self.request_blocking(\n                'eth_sendRawTransaction', [raw_transaction_bytes_as_hex],\n            )\n\n        result = super(BaseSendRawTransactionMixin, self).request_blocking(\n            method, params,\n        )\n        if method in self.TXN_SENDING_METHODS:\n            if method == 'eth_sendRawTransaction':\n                txn = rlp.decode(decode_hex(params[0]), Transaction)\n                self._known_transactions[to_normalized_address(txn.sender)].add(result)\n                self._known_nonces[to_normalized_address(txn.sender)].add(txn.nonce)\n            else:\n                txn = params[0]\n                self._known_transactions[to_normalized_address(txn['from'])].add(result)\n                if 'nonce' in txn:\n                    self._known_nonces[to_normalized_address(txn['from'])].add(\n                        to_decimal(txn['nonce'])\n                    )\n        return result\n\n\nclass DelegatedSigningManager(BaseSendRawTransactionMixin):\n    def __init__(self, *args, **kwargs):\n        warnings.warn(DeprecationWarning(\n            \"DelegatedSigningManager has been deprecated and will be removed from\"\n            \"web3.py in subsequen releases.\"\n        ))\n        self.signing_manager = kwargs.pop('signing_manager')\n        super(DelegatedSigningManager, self).__init__(*args, **kwargs)\n\n    def get_chain_nonce(self, addr):\n        signer_nonce = to_decimal(self.signing_manager.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        wrapped_nonce = to_decimal(self.wrapped_manager.request_blocking(\n            'eth_getTransactionCount',\n            [addr, 'pending']\n        ))\n        return max(signer_nonce, wrapped_nonce)\n\n    def get_transaction_signature(self, transaction):\n        serialized_txn = serialize_transaction(transaction)\n        hash_to_sign = self.signing_manager.request_blocking(\n            'web3_sha3', [encode_hex(serialized_txn)],\n        )\n        signature_hex = self.signing_manager.request_blocking(\n            'eth_sign',\n            [\n                transaction['from'],\n                hash_to_sign,\n            ],\n        )\n        signature = decode_hex(signature_hex)\n        return signature\n\n\nclass PrivateKeySigningManager(BaseSendRawTransactionMixin):\n    def __init__(self, *args, **kwargs):\n        warnings.warn(DeprecationWarning(\n            \"PrivateKeySigningManager has been deprecated and will be removed from\"\n            \"web3.py in subsequen releases.\"\n        ))\n        if not is_bitcoin_available():\n            raise ImportError(\n                \"In order to use the `PrivateKeySigningManager` the \"\n                \"`bitcoin` and `secp256k1` packages must be installed.\"\n            )\n        self.keys = kwargs.pop('keys', {})\n        super(PrivateKeySigningManager, self).__init__(*args, **kwargs)\n\n    def register_private_key(self, key):\n        from bitcoin import privtopub\n        address = to_normalized_address(keccak(privtopub(key)[1:])[-20:])\n        self.keys[address] = key\n\n    def sign_and_serialize_transaction(self, transaction):\n        txn_from = to_normalized_address(transaction['from'])\n        if txn_from not in self.keys:\n            raise KeyError(\"No signing key registered for from address: {0}\".format(txn_from))\n        transaction = Transaction(\n            nonce=to_decimal(transaction['nonce']),\n            gasprice=to_decimal(transaction['gasPrice']),\n            startgas=to_decimal(transaction['gas']),\n            to=transaction['to'],\n            value=to_decimal(transaction['value']),\n            data=decode_hex(transaction['data']),\n        )\n        transaction.sign(self.keys[txn_from])\n        assert to_normalized_address(transaction.sender) == txn_from\n        return rlp.encode(transaction, Transaction)\n", "path": "web3/providers/manager.py"}]}