mirror of
https://github.com/FlipsideCrypto/web3.py.git
synced 2026-02-06 10:56:47 +00:00
more cleanup
This commit is contained in:
parent
4b74d0087b
commit
a19219e845
@ -98,7 +98,7 @@ def tempdir():
|
||||
def setup_tester_rpc_provider():
|
||||
from testrpc import testrpc
|
||||
|
||||
from web3.web3.rpcprovider import TestRPCProvider
|
||||
from web3.providers.rpc import TestRPCProvider
|
||||
port = get_open_port()
|
||||
provider = TestRPCProvider(port=port)
|
||||
|
||||
@ -116,7 +116,7 @@ def setup_tester_rpc_provider():
|
||||
|
||||
@contextlib.contextmanager
|
||||
def setup_rpc_provider():
|
||||
from web3.web3.rpcprovider import RPCProvider
|
||||
from web3.providers.rpc import RPCProvider
|
||||
|
||||
with tempdir() as base_dir:
|
||||
geth = GethProcess('testing', base_dir=base_dir)
|
||||
@ -130,7 +130,7 @@ def setup_rpc_provider():
|
||||
|
||||
@contextlib.contextmanager
|
||||
def setup_ipc_provider():
|
||||
from web3.web3.ipcprovider import IPCProvider
|
||||
from web3.providers.ipc import IPCProvider
|
||||
|
||||
with tempdir() as base_dir:
|
||||
geth = GethProcess('testing', base_dir=base_dir)
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from web3.utils.encoding import (
|
||||
from web3.utils.types import (
|
||||
is_integer,
|
||||
)
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from web3.utils.encoding import (
|
||||
from web3.utils.string import (
|
||||
force_bytes,
|
||||
)
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@ import collections
|
||||
import itertools
|
||||
import pytest
|
||||
|
||||
from web3.web3.rpcprovider import TestRPCProvider
|
||||
from web3.providers.rpc import TestRPCProvider
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from web3.utils.encoding import force_bytes
|
||||
from web3.utils.string import force_bytes
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@ -2,7 +2,7 @@ import collections
|
||||
import itertools
|
||||
import pytest
|
||||
|
||||
from web3.web3.rpcprovider import TestRPCProvider
|
||||
from web3.providers.rpc import TestRPCProvider
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from web3.utils.encoding import force_bytes
|
||||
from web3.utils.string import force_bytes
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@ -9,7 +9,7 @@ from eth_tester_client.utils import (
|
||||
encode_data,
|
||||
)
|
||||
|
||||
from web3.web3.rpcprovider import TestRPCProvider
|
||||
from web3.providers.rpc import TestRPCProvider
|
||||
|
||||
|
||||
def test_eth_sendRawTransaction(web3, wait_for_transaction, extra_accounts):
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
|
||||
from web3.utils.encoding import force_bytes
|
||||
from web3.utils.string import force_bytes
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@ -12,13 +12,19 @@ from eth_tester_client.utils import (
|
||||
coerce_args_to_bytes,
|
||||
)
|
||||
|
||||
from web3.web3.rpcprovider import TestRPCProvider
|
||||
from web3.utils.encoding import (
|
||||
from web3.providers.rpc import TestRPCProvider
|
||||
from web3.utils.string import (
|
||||
force_bytes,
|
||||
)
|
||||
from web3.utils.types import (
|
||||
is_string,
|
||||
)
|
||||
from web3.utils.formatting import (
|
||||
add_0x_prefix,
|
||||
)
|
||||
from web3.utils.encoding import (
|
||||
encode_hex,
|
||||
decode_hex,
|
||||
add_0x_prefix,
|
||||
is_string,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
import pytest
|
||||
import socket
|
||||
|
||||
from web3.web3.requestmanager import RequestManager
|
||||
from web3.web3.rpcprovider import TestRPCProvider, is_testrpc_available
|
||||
from web3.providers.manager import RequestManager
|
||||
from web3.providers.rpc import (
|
||||
TestRPCProvider,
|
||||
is_testrpc_available,
|
||||
)
|
||||
|
||||
|
||||
def get_open_port():
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import pytest
|
||||
from web3.web3 import formatters
|
||||
from web3 import formatters
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import pytest
|
||||
|
||||
import web3.utils.types import (
|
||||
from web3.utils.types import (
|
||||
is_integer,
|
||||
is_number,
|
||||
is_boolean,
|
||||
is_string,
|
||||
is_bytes,
|
||||
is_text,
|
||||
is_array,
|
||||
is_object,
|
||||
)
|
||||
|
||||
|
||||
@ -31,22 +31,8 @@ def test_is_integer(value, expected):
|
||||
({}, False),
|
||||
]
|
||||
)
|
||||
def test_isString(value, expected):
|
||||
assert isString(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
(lambda : None, True),
|
||||
(3, False),
|
||||
(None, False),
|
||||
("3", False),
|
||||
("0x3", False),
|
||||
]
|
||||
)
|
||||
def test_isFunction(value, expected):
|
||||
assert isFunction(value) == expected
|
||||
def test_is_string(value, expected):
|
||||
assert is_string(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@ -61,8 +47,8 @@ def test_isFunction(value, expected):
|
||||
({"test": 3}, True)
|
||||
]
|
||||
)
|
||||
def test_isObject(value, expected):
|
||||
assert isObject(value) == expected
|
||||
def test_is_object(value, expected):
|
||||
assert is_object(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@ -77,8 +63,8 @@ def test_isObject(value, expected):
|
||||
(False, True)
|
||||
]
|
||||
)
|
||||
def test_isBoolean(value, expected):
|
||||
assert isBoolean(value) == expected
|
||||
def test_is_boolean(value, expected):
|
||||
assert is_boolean(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@ -96,21 +82,4 @@ def test_isBoolean(value, expected):
|
||||
]
|
||||
)
|
||||
def test_isArray(value, expected):
|
||||
assert isArray(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
(lambda : None, False),
|
||||
(3, False),
|
||||
(None, False),
|
||||
("3", True),
|
||||
("0x3", False),
|
||||
("{}", True),
|
||||
('{"test":3}', True),
|
||||
("{3}", False)
|
||||
]
|
||||
)
|
||||
def test_isJson(value, expected):
|
||||
assert utils.isJson(value) == expected
|
||||
assert is_array(value) == expected
|
||||
|
||||
@ -4,8 +4,8 @@ import pkg_resources
|
||||
|
||||
|
||||
from web3.main import Web3 # NOQA
|
||||
from web3.web3.rpcprovider import RPCProvider # NOQA
|
||||
from web3.web3.ipcprovider import IPCProvider # NOQA
|
||||
from web3.providers.rpc import RPCProvider # NOQA
|
||||
from web3.providers.ipc import IPCProvider # NOQA
|
||||
|
||||
__version__ = pkg_resources.get_distribution("web3").version
|
||||
|
||||
|
||||
29
web3/eth.py
29
web3/eth.py
@ -1,10 +1,17 @@
|
||||
import web3.web3.formatters as formatters
|
||||
from web3 import formatters
|
||||
from web3.iban import Iban
|
||||
|
||||
import web3.utils.config as config
|
||||
import web3.utils.encoding as encoding
|
||||
|
||||
from web3.utils.encoding import (
|
||||
to_decimal,
|
||||
)
|
||||
from web3.utils.types import (
|
||||
is_integer,
|
||||
)
|
||||
from web3.utils.functional import (
|
||||
apply_formatters_to_return,
|
||||
)
|
||||
from web3.web3.iban import Iban
|
||||
|
||||
|
||||
class DefaultAccount(object):
|
||||
@ -63,7 +70,7 @@ class Eth(object):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@property
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def gasPrice(self):
|
||||
return self.request_manager.request_blocking("eth_gasPrice", [])
|
||||
|
||||
@ -78,14 +85,14 @@ class Eth(object):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@property
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def blockNumber(self):
|
||||
return self.request_manager.request_blocking("eth_blockNumber", [])
|
||||
|
||||
def getBlockNumber(self, *args, **kwargs):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def getBalance(self, account, block_number=None):
|
||||
if block_number is None:
|
||||
block_number = self.defaultBlock
|
||||
@ -116,7 +123,7 @@ class Eth(object):
|
||||
`eth_getBlockByHash`
|
||||
`eth_getBlockByNumber`
|
||||
"""
|
||||
if encoding.is_integer(block_identifier):
|
||||
if is_integer(block_identifier):
|
||||
method = 'eth_getBlockByNumber'
|
||||
else:
|
||||
method = 'eth_getBlockByHash'
|
||||
@ -126,13 +133,13 @@ class Eth(object):
|
||||
[block_identifier, full_txns],
|
||||
)
|
||||
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def getBlockTransactionCount(self, block_identifier):
|
||||
"""
|
||||
`eth_getBlockTransactionCountByHash`
|
||||
`eth_getBlockTransactionCountByNumber`
|
||||
"""
|
||||
if encoding.is_integer(block_identifier):
|
||||
if is_integer(block_identifier):
|
||||
method = 'eth_getBlockTransactionCountByNumber'
|
||||
else:
|
||||
method = 'eth_getBlockTransactionCountByHash'
|
||||
@ -158,7 +165,7 @@ class Eth(object):
|
||||
`eth_getTransactionByBlockHashAndIndex`
|
||||
`eth_getTransactionByBlockNumberAndIndex`
|
||||
"""
|
||||
if encoding.is_integer(block_identifier):
|
||||
if is_integer(block_identifier):
|
||||
method = 'eth_getTransactionByBlockNumberAndIndex'
|
||||
else:
|
||||
method = 'eth_getTransactionByBlockHashAndIndex'
|
||||
@ -174,7 +181,7 @@ class Eth(object):
|
||||
[txn_hash],
|
||||
)
|
||||
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def getTransactionCount(self, account, block_number=None):
|
||||
if block_number is None:
|
||||
block_number = self.defaultBlock
|
||||
|
||||
@ -1,15 +1,31 @@
|
||||
import web3.utils.address as address
|
||||
import web3.utils.encoding as encoding
|
||||
import web3.utils.utils as utils
|
||||
import web3.utils.config as config
|
||||
from web3.web3.iban import Iban
|
||||
from web3.iban import Iban
|
||||
|
||||
fromDecimal = encoding.fromDecimal
|
||||
toDecimal = encoding.toDecimal
|
||||
from web3.utils.string import (
|
||||
force_text,
|
||||
)
|
||||
from web3.utils.address import (
|
||||
is_address,
|
||||
is_strict_address,
|
||||
)
|
||||
from web3.utils.types import (
|
||||
is_array,
|
||||
is_string,
|
||||
)
|
||||
from web3.utils.formatting import (
|
||||
is_0x_prefixed,
|
||||
)
|
||||
from web3.utils.encoding import (
|
||||
to_hex,
|
||||
encode_hex,
|
||||
decode_hex,
|
||||
from_decimal,
|
||||
to_decimal,
|
||||
)
|
||||
import web3.utils.config as config
|
||||
|
||||
|
||||
def isPredefinedBlockNumber(blockNumber):
|
||||
return blockNumber in ["latest", "pending", "earliest"]
|
||||
return force_text(blockNumber) in {"latest", "pending", "earliest"}
|
||||
|
||||
|
||||
def inputDefaultBlockNumberFormatter(blockNumber=None):
|
||||
@ -24,7 +40,7 @@ def inputBlockNumberFormatter(blockNumber):
|
||||
return None
|
||||
elif isPredefinedBlockNumber(blockNumber):
|
||||
return blockNumber
|
||||
return encoding.to_hex(blockNumber)
|
||||
return to_hex(blockNumber)
|
||||
|
||||
|
||||
def inputCallFormatter(options):
|
||||
@ -42,7 +58,7 @@ def inputCallFormatter(options):
|
||||
|
||||
for key in ("gasPrice", "gas", "value", "nonce"):
|
||||
if key in options:
|
||||
options[key] = encoding.fromDecimal(options[key])
|
||||
options[key] = from_decimal(options[key])
|
||||
|
||||
return options
|
||||
|
||||
@ -59,7 +75,7 @@ def inputTransactionFormatter(options):
|
||||
|
||||
for key in ("gasPrice", "gas", "value", "nonce"):
|
||||
if key in options:
|
||||
options[key] = encoding.fromDecimal(options[key])
|
||||
options[key] = from_decimal(options[key])
|
||||
|
||||
return options
|
||||
|
||||
@ -69,14 +85,14 @@ def outputTransactionFormatter(tx):
|
||||
Formats the output of a transaction to its proper values
|
||||
"""
|
||||
if tx.get("blockNumber"):
|
||||
tx["blockNumber"] = toDecimal(tx["blockNumber"])
|
||||
tx["blockNumber"] = to_decimal(tx["blockNumber"])
|
||||
if tx.get("transactionIndex"):
|
||||
tx["transactionIndex"] = toDecimal(tx["transactionIndex"])
|
||||
tx["transactionIndex"] = to_decimal(tx["transactionIndex"])
|
||||
|
||||
tx["nonce"] = toDecimal(tx["nonce"])
|
||||
tx["gas"] = toDecimal(tx["gas"])
|
||||
tx["gasPrice"] = toDecimal(tx["gasPrice"])
|
||||
tx["value"] = toDecimal(tx["value"])
|
||||
tx["nonce"] = to_decimal(tx["nonce"])
|
||||
tx["gas"] = to_decimal(tx["gas"])
|
||||
tx["gasPrice"] = to_decimal(tx["gasPrice"])
|
||||
tx["value"] = to_decimal(tx["value"])
|
||||
return tx
|
||||
|
||||
|
||||
@ -88,13 +104,13 @@ def outputTransactionReceiptFormatter(receipt):
|
||||
return None
|
||||
|
||||
if receipt.get("blockNumber"):
|
||||
receipt["blockNumber"] = toDecimal(receipt["blockNumber"])
|
||||
receipt["blockNumber"] = to_decimal(receipt["blockNumber"])
|
||||
if receipt.get("transactionIndex"):
|
||||
receipt["transactionIndex"] = toDecimal(receipt["transactionIndex"])
|
||||
receipt["cumulativeGasUsed"] = toDecimal(receipt["cumulativeGasUsed"])
|
||||
receipt["gasUsed"] = toDecimal(receipt["gasUsed"])
|
||||
receipt["transactionIndex"] = to_decimal(receipt["transactionIndex"])
|
||||
receipt["cumulativeGasUsed"] = to_decimal(receipt["cumulativeGasUsed"])
|
||||
receipt["gasUsed"] = to_decimal(receipt["gasUsed"])
|
||||
|
||||
if utils.isArray(receipt.get("logs")):
|
||||
if is_array(receipt.get("logs")):
|
||||
receipt["logs"] = [outputLogFormatter(log) for log in receipt["logs"]]
|
||||
|
||||
return receipt
|
||||
@ -106,20 +122,20 @@ def outputBlockFormatter(block):
|
||||
"""
|
||||
|
||||
# Transform to number
|
||||
block["gasLimit"] = toDecimal(block["gasLimit"])
|
||||
block["gasUsed"] = toDecimal(block["gasUsed"])
|
||||
block["size"] = toDecimal(block["size"])
|
||||
block["timestamp"] = toDecimal(block["timestamp"])
|
||||
block["gasLimit"] = to_decimal(block["gasLimit"])
|
||||
block["gasUsed"] = to_decimal(block["gasUsed"])
|
||||
block["size"] = to_decimal(block["size"])
|
||||
block["timestamp"] = to_decimal(block["timestamp"])
|
||||
|
||||
if block.get("number"):
|
||||
block["number"] = toDecimal(block["number"])
|
||||
block["number"] = to_decimal(block["number"])
|
||||
|
||||
block["difficulty"] = toDecimal(block["difficulty"])
|
||||
block["totalDifficulty"] = toDecimal(block["totalDifficulty"])
|
||||
block["difficulty"] = to_decimal(block["difficulty"])
|
||||
block["totalDifficulty"] = to_decimal(block["totalDifficulty"])
|
||||
|
||||
if utils.isArray(block.get("transactions")):
|
||||
if is_array(block.get("transactions")):
|
||||
for item in block["transactions"]:
|
||||
if not utils.isString(item):
|
||||
if is_string(item):
|
||||
item = outputTransactionFormatter(item)
|
||||
|
||||
return block
|
||||
@ -130,11 +146,11 @@ def outputLogFormatter(log):
|
||||
Formats the output of a log
|
||||
"""
|
||||
if log.get("blockNumber"):
|
||||
log["blockNumber"] = toDecimal(log["blockNumber"])
|
||||
log["blockNumber"] = to_decimal(log["blockNumber"])
|
||||
if log.get("transactionIndex"):
|
||||
log["transactionIndex"] = toDecimal(log["transactionIndex"])
|
||||
log["transactionIndex"] = to_decimal(log["transactionIndex"])
|
||||
if log.get("logIndex"):
|
||||
log["logIndex"] = toDecimal(log["logIndex"])
|
||||
log["logIndex"] = to_decimal(log["logIndex"])
|
||||
|
||||
return log
|
||||
|
||||
@ -144,14 +160,14 @@ def inputPostFormatter(post):
|
||||
Formats the input of a whisper post and converts all values to HEX
|
||||
"""
|
||||
|
||||
post["ttl"] = fromDecimal(post["ttl"])
|
||||
post["workToProve"] = fromDecimal(post.get("workToProve", 0))
|
||||
post["priority"] = fromDecimal(post["priority"])
|
||||
post["ttl"] = from_decimal(post["ttl"])
|
||||
post["workToProve"] = from_decimal(post.get("workToProve", 0))
|
||||
post["priority"] = from_decimal(post["priority"])
|
||||
|
||||
if not utils.isArray(post.get("topics")):
|
||||
if not is_array(post.get("topics")):
|
||||
post["topics"] = [post["topics"]] if post.get("topics") else []
|
||||
|
||||
post["topics"] = [topic if topic.startswith("0x") else encoding.fromUtf8(topic)
|
||||
post["topics"] = [topic if is_0x_prefixed(topic) else encode_hex(topic)
|
||||
for topic in post["topics"]]
|
||||
|
||||
return post
|
||||
@ -162,15 +178,15 @@ def outputPostFormatter(post):
|
||||
Formats the output of a received post message
|
||||
"""
|
||||
|
||||
post["expiry"] = toDecimal(post["expiry"])
|
||||
post["sent"] = toDecimal(post["sent"])
|
||||
post["ttl"] = toDecimal(post["ttl"])
|
||||
post["workProved"] = toDecimal(post["workProved"])
|
||||
post["expiry"] = to_decimal(post["expiry"])
|
||||
post["sent"] = to_decimal(post["sent"])
|
||||
post["ttl"] = to_decimal(post["ttl"])
|
||||
post["workProved"] = to_decimal(post["workProved"])
|
||||
|
||||
if not post.get("topics"):
|
||||
post["topics"] = []
|
||||
|
||||
post["topics"] = [encoding.toAscii(topic) for topic in post["topics"]]
|
||||
post["topics"] = [decode_hex(topic) for topic in post["topics"]]
|
||||
|
||||
return post
|
||||
|
||||
@ -179,17 +195,17 @@ def inputAddressFormatter(addr):
|
||||
iban = Iban(addr)
|
||||
if iban.isValid() and iban.isDirect():
|
||||
return "0x" + iban.address()
|
||||
elif address.isStrictAddress(addr):
|
||||
elif is_strict_address(addr):
|
||||
return addr
|
||||
elif address.isAddress(addr):
|
||||
elif is_address(addr):
|
||||
return "0x" + addr
|
||||
|
||||
raise ValueError("invalid address")
|
||||
|
||||
|
||||
def outputSyncingFormatter(result):
|
||||
result["startingBlock"] = toDecimal(result["startingBlock"])
|
||||
result["currentBlock"] = toDecimal(result["currentBlock"])
|
||||
result["highestBlock"] = toDecimal(result["highestBlock"])
|
||||
result["startingBlock"] = to_decimal(result["startingBlock"])
|
||||
result["currentBlock"] = to_decimal(result["currentBlock"])
|
||||
result["highestBlock"] = to_decimal(result["highestBlock"])
|
||||
|
||||
return result
|
||||
|
||||
@ -1,50 +0,0 @@
|
||||
import json
|
||||
import web3.web3.exceptions as exceptions
|
||||
import web3.utils.utils as utils
|
||||
import six
|
||||
|
||||
|
||||
class Jsonrpc(object):
|
||||
|
||||
@staticmethod
|
||||
def toPayload(reqid, method, params):
|
||||
"""
|
||||
Should be called to valid json create payload object
|
||||
"""
|
||||
if not method:
|
||||
raise Exception("jsonrpc method should be specified!")
|
||||
|
||||
rawrequest = json.dumps({
|
||||
"jsonrpc": "2.0",
|
||||
"method": method,
|
||||
"params": params or [],
|
||||
"id": reqid
|
||||
})
|
||||
|
||||
if six.PY3:
|
||||
rawrequest = rawrequest.encode("utf8")
|
||||
return (reqid, rawrequest)
|
||||
|
||||
@staticmethod
|
||||
def fromPayload(raw):
|
||||
try:
|
||||
result = json.loads(raw)
|
||||
except IndexError:
|
||||
raise exceptions.InvalidResponseException("Invalid response")
|
||||
|
||||
if not Jsonrpc.isValidResponse(result):
|
||||
raise exceptions.InvalidResponseException(result)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def isValidResponse(response):
|
||||
"""
|
||||
Should be called to check if jsonrpc response is valid
|
||||
"""
|
||||
return response is not None and "error" not in response and \
|
||||
response["jsonrpc"] == "2.0" and \
|
||||
utils.isInteger(response["id"]) and \
|
||||
response["result"] is not None
|
||||
|
||||
# def toBatchPayload(self, messages):
|
||||
# return [self.toPayload(message["method"], message["params"]) for]
|
||||
75
web3/main.py
75
web3/main.py
@ -1,7 +1,5 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import copy
|
||||
|
||||
from web3.eth import Eth
|
||||
from web3.db import Db
|
||||
from web3.shh import Shh
|
||||
@ -12,32 +10,35 @@ from web3.version import Version
|
||||
from web3.providers.rpc import (
|
||||
RPCProvider,
|
||||
TestRPCProvider,
|
||||
is_testrpc_available,
|
||||
)
|
||||
from web3.providers.ipc import IPCProvider
|
||||
from web3.providers.manager import RequestManager
|
||||
|
||||
from web3.utils.functional import (
|
||||
compose,
|
||||
)
|
||||
from web3.utils.string import (
|
||||
force_bytes,
|
||||
force_text,
|
||||
)
|
||||
from web3.utils.encoding import (
|
||||
to_hex,
|
||||
decode_hex,
|
||||
encode_hex,
|
||||
to_decimal,
|
||||
from_decimal,
|
||||
)
|
||||
from web3.utils.currency import(
|
||||
to_wei,
|
||||
from_wei,
|
||||
)
|
||||
from web3.utils.address import(
|
||||
is_address,
|
||||
is_checksum_address,
|
||||
to_checksum_address,
|
||||
)
|
||||
import web3.utils.encoding as encoding
|
||||
import web3.utils.currency as currency
|
||||
import web3.utils.address as address
|
||||
import web3.utils.config as config
|
||||
|
||||
|
||||
DEFAULT_PROVIDERS = {
|
||||
"RPCProvider": RPCProvider,
|
||||
"IPCProvider": IPCProvider
|
||||
}
|
||||
|
||||
if is_testrpc_available():
|
||||
DEFAULT_PROVIDERS['TestRPCProvider'] = TestRPCProvider
|
||||
|
||||
|
||||
class Web3(object):
|
||||
def __init__(self, provider):
|
||||
self._requestManager = RequestManager(provider)
|
||||
@ -50,7 +51,15 @@ class Web3(object):
|
||||
self.personal = Personal(self._requestManager)
|
||||
self.version = Version(self._requestManager)
|
||||
|
||||
self.providers = copy.copy(DEFAULT_PROVIDERS)
|
||||
self.providers = {
|
||||
'RPCProvider': RPCProvider,
|
||||
'IPCProvider': IPCProvider,
|
||||
'TestRPCProvider': TestRPCProvider,
|
||||
}
|
||||
|
||||
self.RPCProvider = RPCProvider
|
||||
self.IPCProvider = IPCProvider
|
||||
self.TestRPCProvider = TestRPCProvider
|
||||
|
||||
class Config:
|
||||
|
||||
@ -68,23 +77,23 @@ class Web3(object):
|
||||
|
||||
self.config = Config()
|
||||
|
||||
# Expose providers on the class
|
||||
for class_name, klass in DEFAULT_PROVIDERS.items():
|
||||
setattr(self, class_name, klass)
|
||||
|
||||
# Expose utility functions
|
||||
self.toHex = self.to_hex = encoding.to_hex
|
||||
self.toAscii = self.to_ascii = self.to_bytes = force_bytes
|
||||
self.toUtf8 = encoding.toUtf8
|
||||
self.fromAscii = encoding.fromAscii
|
||||
# Encoding and Decoding
|
||||
self.toHex = to_hex
|
||||
self.toAscii = decode_hex
|
||||
self.toUtf8 = compose(decode_hex, force_text)
|
||||
self.fromAscii = encode_hex
|
||||
self.fromUtf8 = encode_hex
|
||||
self.toDecimal = encoding.toDecimal
|
||||
self.fromDecimal = encoding.fromDecimal
|
||||
self.toWei = currency.toWei
|
||||
self.fromWei = currency.fromWei
|
||||
self.isAddress = address.isAddress
|
||||
self.isChecksumAddress = address.isChecksumAddress
|
||||
self.toChecksumAddress = address.toChecksumAddress
|
||||
self.toDecimal = to_decimal
|
||||
self.fromDecimal = from_decimal
|
||||
|
||||
# Currency Utility
|
||||
self.toWei = to_wei
|
||||
self.fromWei = from_wei
|
||||
|
||||
# Address Utility
|
||||
self.isAddress = is_address
|
||||
self.isChecksumAddress = is_checksum_address
|
||||
self.toChecksumAddress = to_checksum_address
|
||||
|
||||
def setProvider(self, provider):
|
||||
self._requestManager.setProvider(provider)
|
||||
|
||||
18
web3/net.py
18
web3/net.py
@ -1,20 +1,10 @@
|
||||
import web3.utils.encoding as encoding
|
||||
from web3.utils.encoding import (
|
||||
to_decimal,
|
||||
)
|
||||
from web3.utils.functional import (
|
||||
apply_formatters_to_return,
|
||||
)
|
||||
|
||||
properties = [
|
||||
{
|
||||
"name": "listening",
|
||||
"call": "net_listening",
|
||||
},
|
||||
{
|
||||
"name": "peerCount",
|
||||
"call": "net_peerCount",
|
||||
"outputFormatter": encoding.toDecimal
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class Net(object):
|
||||
|
||||
@ -29,7 +19,7 @@ class Net(object):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@property
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def peerCount(self):
|
||||
return self.request_manager.request_blocking("net_peerCount", [])
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ from __future__ import absolute_import
|
||||
import json
|
||||
import itertools
|
||||
|
||||
from web3.utils.encoding import (
|
||||
from web3.utils.string import (
|
||||
force_bytes,
|
||||
force_obj_to_text,
|
||||
force_text)
|
||||
|
||||
@ -1,10 +1,23 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import socket
|
||||
import sys
|
||||
import os
|
||||
import threading
|
||||
import contextlib
|
||||
|
||||
from web3.web3.provider import BaseProvider
|
||||
from web3.utils.networking import get_ipc_socket
|
||||
from .base import BaseProvider
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def get_ipc_socket(ipc_path, timeout=0.1):
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(ipc_path)
|
||||
sock.settimeout(timeout)
|
||||
|
||||
yield sock
|
||||
|
||||
sock.close()
|
||||
|
||||
|
||||
def get_default_ipc_path(testnet=False):
|
||||
|
||||
@ -2,7 +2,7 @@ import uuid
|
||||
import json
|
||||
import gevent
|
||||
|
||||
from web3.utils.encoding import force_text
|
||||
from web3.utils.string import force_text
|
||||
|
||||
|
||||
class RequestManager(object):
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import requests
|
||||
import threading
|
||||
import gevent
|
||||
|
||||
from web3.web3.provider import BaseProvider
|
||||
from .base import BaseProvider
|
||||
|
||||
|
||||
class RPCProvider(BaseProvider):
|
||||
@ -44,8 +44,6 @@ class TestRPCProvider(RPCProvider):
|
||||
|
||||
self.server = make_server(host, port, application)
|
||||
|
||||
self.thread = threading.Thread(target=self.server.serve_forever)
|
||||
self.thread.daemon = True
|
||||
self.thread.start()
|
||||
self.thread = gevent.spawn(self.server.serve_forever)
|
||||
|
||||
super(TestRPCProvider, self).__init__(host, str(port), *args, **kwargs)
|
||||
|
||||
34
web3/shh.py
34
web3/shh.py
@ -1,37 +1,3 @@
|
||||
import web3.web3.formatters as formatters
|
||||
|
||||
|
||||
# TODO: remove this list
|
||||
methods = [
|
||||
{
|
||||
"name": "post",
|
||||
"call": "shh_post",
|
||||
"params": 1,
|
||||
"inputFormatter": [formatters.inputPostFormatter]
|
||||
},
|
||||
{
|
||||
"name": "newIdentity",
|
||||
"call": "shh_newIdentity",
|
||||
"params": 0
|
||||
},
|
||||
{
|
||||
"name": "hasIdentity",
|
||||
"call": "shh_hasIdentity",
|
||||
"params": 1
|
||||
},
|
||||
{
|
||||
"name": "newGroup",
|
||||
"call": "shh_newGroup",
|
||||
"params": 0
|
||||
},
|
||||
{
|
||||
"name": "addToGroup",
|
||||
"call": "shh_addToGroup",
|
||||
"params": 0
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class Shh(object):
|
||||
"""
|
||||
TODO: flesh this out.
|
||||
|
||||
@ -7,14 +7,14 @@ from .crypto import (
|
||||
sha3,
|
||||
)
|
||||
from .encoding import (
|
||||
to_hex,
|
||||
encode_hex,
|
||||
)
|
||||
from .types import (
|
||||
is_string,
|
||||
)
|
||||
from .formatting import (
|
||||
add_0x_prefix,
|
||||
remove_0x_prefix,
|
||||
pad_left,
|
||||
)
|
||||
|
||||
|
||||
@ -48,26 +48,25 @@ def is_checksum_address(address):
|
||||
return address == checksum_address
|
||||
|
||||
|
||||
def isStrictAddress(address):
|
||||
def is_strict_address(address):
|
||||
"""
|
||||
Checks if the given string is strictly an address
|
||||
"""
|
||||
|
||||
if not utils.isString(address):
|
||||
if not is_string(address):
|
||||
return False
|
||||
|
||||
return re.match(r"^0x[0-9a-fA-F]{40}$", address) is not None
|
||||
|
||||
|
||||
def toChecksumAddress(address):
|
||||
def to_checksum_address(address):
|
||||
"""
|
||||
Makes a checksum address
|
||||
"""
|
||||
|
||||
if not utils.isString(address):
|
||||
if not is_string(address):
|
||||
return False
|
||||
|
||||
address = address.lower().replace("0x", "")
|
||||
address = remove_0x_prefix(address.lower())
|
||||
addressHash = sha3(address)
|
||||
checksumAddress = "0x"
|
||||
|
||||
@ -80,18 +79,17 @@ def toChecksumAddress(address):
|
||||
return checksumAddress
|
||||
|
||||
|
||||
def toAddress(address):
|
||||
def to_address(address):
|
||||
"""
|
||||
Transforms given string to valid 20 bytes-length addres with 0x prefix
|
||||
"""
|
||||
|
||||
if not utils.isString(address):
|
||||
return False
|
||||
if is_string(address):
|
||||
if len(address) == 42:
|
||||
return address
|
||||
elif len(address) == 40:
|
||||
return add_0x_prefix(address)
|
||||
elif len(address) == 20:
|
||||
return encode_hex(address)
|
||||
|
||||
if isStrictAddress(address):
|
||||
return address
|
||||
|
||||
if re.match(r"^[0-9a-f]{3}$", address):
|
||||
return "0x"+address
|
||||
|
||||
return "0x" + pad_left(to_hex(address)[2:], 40)
|
||||
raise ValueError("Unknown address format")
|
||||
|
||||
@ -1,55 +1,58 @@
|
||||
# Currency unit converters
|
||||
import decimal
|
||||
|
||||
unitMap = {
|
||||
'noether': '0',
|
||||
'wei': '1',
|
||||
'kwei': '1000',
|
||||
'Kwei': '1000',
|
||||
'babbage': '1000',
|
||||
'femtoether': '1000',
|
||||
'mwei': '1000000',
|
||||
'Mwei': '1000000',
|
||||
'lovelace': '1000000',
|
||||
'picoether': '1000000',
|
||||
'gwei': '1000000000',
|
||||
'Gwei': '1000000000',
|
||||
'shannon': '1000000000',
|
||||
'nanoether': '1000000000',
|
||||
'nano': '1000000000',
|
||||
'szabo': '1000000000000',
|
||||
'microether': '1000000000000',
|
||||
'micro': '1000000000000',
|
||||
'finney': '1000000000000000',
|
||||
'milliether': '1000000000000000',
|
||||
'milli': '1000000000000000',
|
||||
'ether': '1000000000000000000',
|
||||
'kether': '1000000000000000000000',
|
||||
'grand': '1000000000000000000000',
|
||||
'mether': '1000000000000000000000000',
|
||||
'gether': '1000000000000000000000000000',
|
||||
'tether': '1000000000000000000000000000000'
|
||||
|
||||
units = {
|
||||
'noether': decimal.Decimal(0),
|
||||
'wei': decimal.Decimal(1e0),
|
||||
'kwei': decimal.Decimal(1e3),
|
||||
'babbage': decimal.Decimal(1e3),
|
||||
'femtoether': decimal.Decimal(1e3),
|
||||
'mwei': decimal.Decimal(1e6),
|
||||
'lovelace': decimal.Decimal(1e6),
|
||||
'picoether': decimal.Decimal(1e6),
|
||||
'gwei': decimal.Decimal(1e9),
|
||||
'shannon': decimal.Decimal(1e9),
|
||||
'nanoether': decimal.Decimal(1e9),
|
||||
'nano': decimal.Decimal(1e9),
|
||||
'szabo': decimal.Decimal(1e12),
|
||||
'microether': decimal.Decimal(1e12),
|
||||
'micro': decimal.Decimal(1e12),
|
||||
'finney': decimal.Decimal(1e15),
|
||||
'milliether': decimal.Decimal(1e15),
|
||||
'milli': decimal.Decimal(1e15),
|
||||
'ether': decimal.Decimal(1e18),
|
||||
'kether': decimal.Decimal(1e21),
|
||||
'grand': decimal.Decimal(1e21),
|
||||
'mether': decimal.Decimal(1e24),
|
||||
'gether': decimal.Decimal(1e27),
|
||||
'tether': decimal.Decimal(1e30),
|
||||
}
|
||||
|
||||
|
||||
def getValueOfUnit(unit="ether"):
|
||||
"""
|
||||
Returns value of unit in Wei
|
||||
"""
|
||||
unit = unit.lower()
|
||||
return unitMap[unit]
|
||||
|
||||
|
||||
def fromWei(number, unit):
|
||||
def from_wei(number, unit):
|
||||
"""
|
||||
Takes a number of wei and converts it to any other ether unit.
|
||||
"""
|
||||
result = "%.15f" % (int(number) / float(getValueOfUnit(unit)))
|
||||
return result.rstrip("0").rstrip(".")
|
||||
if unit.lower() not in units:
|
||||
raise ValueError(
|
||||
"Unknown unit. Must be one of {0}".format('/'.join(units.keys()))
|
||||
)
|
||||
|
||||
d_number = decimal.Decimal(number)
|
||||
unit_value = units[unit.lower()]
|
||||
|
||||
return d_number / unit_value
|
||||
|
||||
|
||||
def toWei(number, unit):
|
||||
def to_wei(number, unit):
|
||||
"""
|
||||
Takes a number of a unit and converts it to wei.
|
||||
"""
|
||||
returnValue = int(number)*int(getValueOfUnit(unit))
|
||||
return str(returnValue)
|
||||
if unit.lower() not in units:
|
||||
raise ValueError(
|
||||
"Unknown unit. Must be one of {0}".format('/'.join(units.keys()))
|
||||
)
|
||||
d_number = decimal.Decimal(number)
|
||||
unit_value = units[unit.lower()]
|
||||
|
||||
return d_number * unit_value
|
||||
|
||||
@ -1,15 +1,10 @@
|
||||
# String encodings and numeric representations
|
||||
import functools
|
||||
import sys
|
||||
import binascii
|
||||
import json
|
||||
|
||||
from .types import (
|
||||
is_bytes,
|
||||
is_text,
|
||||
is_string,
|
||||
is_number,
|
||||
is_integer,
|
||||
is_boolean,
|
||||
is_object,
|
||||
)
|
||||
@ -62,14 +57,14 @@ def to_hex(value):
|
||||
return encode_hex(json.dumps(value))
|
||||
|
||||
if is_string(value):
|
||||
if value.startswith("-0x"):
|
||||
return fromDecimal(value)
|
||||
elif value.startswith("0x"):
|
||||
if is_prefixed(value, '-0x'):
|
||||
return from_decimal(value)
|
||||
elif is_0x_prefixed(value):
|
||||
return value
|
||||
elif not is_number(value):
|
||||
return fromAscii(value)
|
||||
else:
|
||||
return encode_hex(value)
|
||||
|
||||
return from_decimal(val)
|
||||
return from_decimal(value)
|
||||
|
||||
|
||||
def to_decimal(value):
|
||||
@ -77,7 +72,7 @@ def to_decimal(value):
|
||||
Converts value to it's decimal representation in string
|
||||
"""
|
||||
if is_string(value):
|
||||
if value.startswith("0x") or value.startswith("-0x"):
|
||||
if is_0x_prefixed(value) or is_prefixed(value, '-0x'):
|
||||
value = int(value, 16)
|
||||
else:
|
||||
value = int(value)
|
||||
@ -87,7 +82,7 @@ def to_decimal(value):
|
||||
return value
|
||||
|
||||
|
||||
def fromDecimal(value):
|
||||
def from_decimal(value):
|
||||
"""
|
||||
Converts value to it's hex representation
|
||||
"""
|
||||
@ -99,10 +94,3 @@ def fromDecimal(value):
|
||||
|
||||
result = hex(value)
|
||||
return result
|
||||
|
||||
|
||||
def fromAscii(obj):
|
||||
"""
|
||||
Should be called to get hex representation (prefixed by 0x) of ascii string
|
||||
"""
|
||||
return "0x" + binascii.hexlify(obj.encode("ascii", "ignore")).decode("ascii", "ignore")
|
||||
|
||||
@ -1,14 +0,0 @@
|
||||
from __future__ import absolute_import
|
||||
import socket
|
||||
import contextlib
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def get_ipc_socket(ipc_path, timeout=0.1):
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
sock.connect(ipc_path)
|
||||
sock.settimeout(timeout)
|
||||
|
||||
yield sock
|
||||
|
||||
sock.close()
|
||||
@ -33,28 +33,9 @@ def is_boolean(value):
|
||||
return isinstance(value, bool)
|
||||
|
||||
|
||||
def is_Object(obj):
|
||||
"""
|
||||
Returns true if object is Objet, otherwise false
|
||||
"""
|
||||
def is_object(obj):
|
||||
return isinstance(obj, dict)
|
||||
|
||||
|
||||
def isArray(obj):
|
||||
"""
|
||||
Returns true if object is array, otherwise false
|
||||
"""
|
||||
def is_array(obj):
|
||||
return isinstance(obj, list)
|
||||
|
||||
|
||||
def isJson(string):
|
||||
"""
|
||||
Returns true if given string is valid json object
|
||||
"""
|
||||
try:
|
||||
decoded = json.loads(string)
|
||||
if decoded or decoded == {}:
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
return False
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
import web3.utils.encoding as encoding
|
||||
from web3.utils.encoding import (
|
||||
to_decimal,
|
||||
)
|
||||
from web3.utils.functional import (
|
||||
apply_formatters_to_return,
|
||||
)
|
||||
@ -23,7 +25,7 @@ class Version(object):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@property
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def network(self):
|
||||
return self.request_manager.request_blocking("net_version", [])
|
||||
|
||||
@ -31,7 +33,7 @@ class Version(object):
|
||||
raise NotImplementedError("Async calling has not been implemented")
|
||||
|
||||
@property
|
||||
@apply_formatters_to_return(encoding.toDecimal)
|
||||
@apply_formatters_to_return(to_decimal)
|
||||
def ethereum(self):
|
||||
return self.request_manager.request_blocking("eth_protocolVersion", [])
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user