コード例 #1
0
def to_bytes(primitive):

    if isinstance(primitive, str):
        return encoding.to_bytes(hexstr=primitive)

    if isinstance(primitive, int):
        if primitive < -(1 << 255) or primitive > (1 << 255):
            raise ValueError(f"int {primitive} out of range")

        value = ((1 << 256) + primitive) if primitive < 0 else primitive
    else:
        value = primitive

    encoded = encoding.to_bytes(primitive=value)
    return encoded
コード例 #2
0
ファイル: account.py プロジェクト: ytsheng/web3.py
 def sign(self,
          message=None,
          private_key=None,
          message_hexstr=None,
          message_text=None):
     '''
     @param private_key in bytes, str, or int.
         In Python 2, a bytes, unicode or str object will be interpreted as hexstr
         In Python 3, only a str object will be interpreted as hexstr
     '''
     msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text)
     msg_hash = self.hashMessage(msg_bytes)
     key_bytes = hexstr_if_str(to_bytes, private_key)
     key = self._keys.PrivateKey(key_bytes)
     (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash)
     (r_hex, s_hex, eth_signature_hex) = map(to_hex,
                                             (r, s, eth_signature_bytes))
     return AttributeDict({
         'message': msg_bytes,
         'messageHash': msg_hash,
         'r': r_hex,
         's': s_hex,
         'v': v,
         'signature': eth_signature_hex,
     })
コード例 #3
0
def test_eth_account_encrypt(acct, web3js_key, web3js_password):
    encrypted = acct.encrypt(web3js_key, web3js_password)

    assert encrypted['address'] == '2c7536e3605d9c16a7a3d7b1898e529396a65c23'
    assert encrypted['version'] == 3

    decrypted_key = acct.decrypt(encrypted, web3js_password)

    assert decrypted_key == to_bytes(hexstr=web3js_key)
コード例 #4
0
ファイル: test_accounts.py プロジェクト: ytsheng/web3.py
def test_eth_account_prepared_encrypt(web3, web3js_key, web3js_password):
    account = web3.eth.account.privateKeyToAccount(web3js_key)
    encrypted = account.encrypt(web3js_password)

    assert encrypted['address'] == '2c7536e3605d9c16a7a3d7b1898e529396a65c23'
    assert encrypted['version'] == 3

    decrypted_key = web3.eth.account.decrypt(encrypted, web3js_password)

    assert decrypted_key == to_bytes(hexstr=web3js_key)
コード例 #5
0
    def sha3(primitive=None, text=None, hexstr=None):
        if isinstance(primitive, (bytes, int, type(None))):
            input_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
            return keccak(input_bytes)

        raise TypeError(
            "You called sha3 with first arg %r and keywords %r. You must call it with one of "
            "these approaches: sha3(text='txt'), sha3(hexstr='0x747874'), "
            "sha3(b'\\x74\\x78\\x74'), or sha3(0x747874)." % (primitive, {
                'text': text,
                'hexstr': hexstr
            }))
コード例 #6
0
ファイル: main.py プロジェクト: syngraph/web3.py
    def sha3(primitive=None, text=None, hexstr=None):
        if isinstance(primitive, (bytes, int, type(None))):
            input_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
            return keccak(input_bytes)

        raise TypeError(
            "You called sha3 with first arg %r and keywords %r. You must call it with one of "
            "these approaches: sha3(text='txt'), sha3(hexstr='0x747874'), "
            "sha3(b'\\x74\\x78\\x74'), or sha3(0x747874)." % (
                primitive,
                {'text': text, 'hexstr': hexstr}
            )
        )
コード例 #7
0
ファイル: main.py プロジェクト: maxgillett/web3.py
    def sha3(primitive=None, text=None, hexstr=None, encoding=None):
        if encoding is not None:
            warnings.warn(
                DeprecationWarning(
                    "The encoding keyword has been deprecated.  Please update your "
                    "code to use sha3(text='txt'), sha3(hexstr='0x747874'), "
                    "sha3(b'\\x74\\x78\\x74'), or sha3(0x747874)."))
        elif not isinstance(primitive, (bytes, int, type(None))):
            warnings.warn(
                DeprecationWarning(
                    "The first argument as a string has been deprecated. Please update your "
                    "code to use sha3(text='txt'), sha3(hexstr='0x747874'), "
                    "sha3(b'\\x74\\x78\\x74'), or sha3(0x747874)."))

        args = (arg for arg in (primitive, text, hexstr) if arg is not None)
        if len(list(args)) != 1:
            raise TypeError(
                "Only supply one positional arg, or the text, or hexstr keyword args. "
                "You supplied %r and %r" % (primitive, {
                    'text': text,
                    'hexstr': hexstr
                }))

        if isinstance(primitive, bytes) and bytes == str:
            # *shakes fist at python 2*
            # fall back to deprecated functionality
            pass
        elif isinstance(
                primitive,
            (bytes, int)) or text is not None or hexstr is not None:
            input_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
            return keccak(input_bytes)

        # handle deprecated cases
        if encoding in ('hex', None):
            return keccak(decode_hex(primitive))
        elif encoding == 'bytes':
            return keccak(primitive)
        elif encoding == 'utf8':
            return keccak(primitive.encode('utf8'))

        raise TypeError(
            "You called sha3 with first arg %r and keywords %r. You must call it with one of "
            "these approaches: sha3(text='txt'), sha3(hexstr='0x747874'), "
            "sha3(b'\\x74\\x78\\x74'), or sha3(0x747874)." % (primitive, {
                'encoding': encoding,
                'text': text,
                'hexstr': hexstr
            }))
コード例 #8
0
ファイル: account.py プロジェクト: syngraph/web3.py
 def sign(self, message=None, private_key=None, message_hexstr=None, message_text=None):
     '''
     @param private_key in bytes, str, or int.
     '''
     msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text)
     msg_hash = self.hashMessage(msg_bytes)
     key_bytes = HexBytes(private_key)
     key = self._keys.PrivateKey(key_bytes)
     (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash)
     return AttributeDict({
         'message': HexBytes(msg_bytes),
         'messageHash': msg_hash,
         'r': r,
         's': s,
         'v': v,
         'signature': HexBytes(eth_signature_bytes),
     })
コード例 #9
0
def get_public_key_from_address(web3, account):
    """

    :param web3:
    :param account:
    :return:
    """
    _hash = web3.sha3(text='verify signature.')
    signature = web3.personal.sign(_hash, account.address, account.password)
    signature = split_signature(web3, to_bytes(hexstr=signature))
    signature_vrs = Signature(signature.v % 27, big_endian_to_int(signature.r),
                              big_endian_to_int(signature.s))
    prefixed_hash = prepare_prefixed_hash(_hash)
    pub_key = KeyAPI.PublicKey.recover_from_msg_hash(
        prefixed_hash, KeyAPI.Signature(vrs=signature_vrs))
    assert pub_key.to_checksum_address() == account.address, \
        'recovered address does not match signing address.'
    return pub_key
コード例 #10
0
 def sign(self,
          message=None,
          private_key=None,
          message_hexstr=None,
          message_text=None):
     '''
     @param private_key in bytes, str, or int.
     '''
     msg_bytes = to_bytes(message, hexstr=message_hexstr, text=message_text)
     msg_hash = self.hashMessage(msg_bytes)
     key_bytes = HexBytes(private_key)
     key = self._keys.PrivateKey(key_bytes)
     (v, r, s, eth_signature_bytes) = sign_message_hash(key, msg_hash)
     return AttributeDict({
         'message': HexBytes(msg_bytes),
         'messageHash': msg_hash,
         'r': r,
         's': s,
         'v': v,
         'signature': HexBytes(eth_signature_bytes),
     })
コード例 #11
0
ファイル: test_hexbytes.py プロジェクト: pipermerriam/web3.py
def test_hexbytes_hexstr_to_bytes(hexstr):
    assert HexBytes(hexstr) == to_bytes(hexstr=hexstr)
コード例 #12
0
def test_hexbytes_hexstr_to_bytes(hexstr):
    assert HexBytes(hexstr) == to_bytes(hexstr=hexstr)
コード例 #13
0
 def hashMessage(data=None, hexstr=None, text=None):
     message_bytes = to_bytes(data, hexstr=hexstr, text=text)
     recovery_hasher = compose(HexBytes, keccak, signature_wrapper)
     return recovery_hasher(message_bytes)
コード例 #14
0
ファイル: account.py プロジェクト: syngraph/web3.py
 def hashMessage(data=None, hexstr=None, text=None):
     message_bytes = to_bytes(data, hexstr=hexstr, text=text)
     recovery_hasher = compose(HexBytes, keccak, signature_wrapper)
     return recovery_hasher(message_bytes)
コード例 #15
0
        #addr = addr.lower()

    return w3.eth.contract(address=addr, abi=abi)


def get_topic(text):
    return to_hex(keccak(text=text))


def hb_to_hex(hexbytes):
    return to_hex(bytes(hexbytes))


w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
accounts = w3.eth.accounts

topic = get_topic('Transfer(address,address,uint256)')

opts = {'topics': [topic]}
filter = w3.eth.filter(opts)

while True:
    for log in filter.get_new_entries():
        from_account = decode_single('address', bytes(log['topics'][1]))
        to_account = decode_single('address', bytes(log['topics'][2]))
        value = decode_single('uint256', to_bytes(hexstr=log['data']))
        print('event => Transfer')
        print('  from  : {0}'.format(from_account))
        print('  to    : {0}'.format(to_account))
        print('  value : {0}'.format(value))
    time.sleep(2)
コード例 #16
0
ファイル: signing.py プロジェクト: ycdk/web3.py
def sign_message_hash(key, msg_hash):
    signature = key.sign_msg_hash(msg_hash)
    (v_raw, r, s) = signature.vrs
    v = to_eth_v(v_raw)
    eth_signature_bytes = to_bytes32(r) + to_bytes32(s) + to_bytes(v)
    return (v, r, s, eth_signature_bytes)
コード例 #17
0
def to_standard_signature_bytes(ethereum_signature_bytes):
    rs = ethereum_signature_bytes[:-1]
    v = to_int(ethereum_signature_bytes[-1])
    standard_v = to_standard_v(v)
    return rs + to_bytes(standard_v)
コード例 #18
0
ファイル: order_hash.py プロジェクト: blockchainexchange/BEX
def sha256_like_solidity(type_value_tuples):
    hex_string = add_0x_prefix(''.join(
        remove_0x_prefix(hex_encode_abi_type(abi_type, value))
        for abi_type, value in type_value_tuples))

    return add_0x_prefix(sha256(to_bytes(hexstr=hex_string)).hexdigest())
コード例 #19
0
ファイル: signing.py プロジェクト: ytsheng/web3.py
def sign_message_hash(key, msg_hash_hex):
    signature = key.sign_msg_hash(to_bytes(hexstr=msg_hash_hex))
    (v_standard, r, s) = signature.vrs
    v = v_standard + V_OFFSET
    eth_signature_bytes = b''.join(map(to_bytes, (r, s, v)))
    return (v, r, s, eth_signature_bytes)
コード例 #20
0
 def _recoveryMessageHash(data=None, hexstr=None, text=None):
     message_bytes = to_bytes(data, hexstr=hexstr, text=text)
     recovery_hasher = compose(to_hex, keccak, signature_wrapper)
     return recovery_hasher(message_bytes)
コード例 #21
0
ファイル: test_encoding.py プロジェクト: ytsheng/web3.py
def test_hexstr_if_str_valid_hex_py2(val, converter):
    if converter is to_decimal and to_bytes(hexstr=val) == b'':
        with pytest.raises(ValueError):
            hexstr_if_str(converter, val)
    else:
        assert hexstr_if_str(converter, val) == converter(hexstr=val)
コード例 #22
0
ファイル: test_encoding.py プロジェクト: ytsheng/web3.py
def test_text_if_str_passthrough_py2(val, converter):
    if converter is to_decimal and to_bytes(val) == b'':
        with pytest.raises(ValueError):
            text_if_str(converter, val)
    else:
        assert text_if_str(converter, val) == converter(val)