示例#1
0
 def __init__(self, msgs):
     self.msgs = msgs
     self.raw_hashes = b''
     for m in msgs:
         self.raw_hashes += m.h
     self.h = Web3.sha3(self.raw_hashes)
示例#2
0
    def parse_insert_abi(abi):
        def parse_inputs(func_inputs):
            inputs = []
            params = []
            param_counter = 0
            for r in func_inputs:
                param_counter += 1
                type_ = r["type"]

                name_ = r["name"]
                if len(name_) == 0:
                    name_ = "param" + str(param_counter)

                if name_[0] != "_":
                    name_ = "_" + name_

                params.append({"type": r["type"], "name": name_})

                if "tuple" not in type_:
                    inputs.append(type_)
                else:
                    type_ = f"({parse_inputs(r['components'])[0]})" + type_[5:]
                    inputs.append(type_)

            return ",".join(inputs), params

        output = {}

        for func in abi:
            if func["type"] in ["constructor", "fallback"]:
                continue

            inputs, params = parse_inputs(func["inputs"])

            fname = f"{func['name']}({inputs})"

            sha3 = Web3.sha3(text=fname).hex()[:10]

            if sha3 in output:
                print("double declaration for the same hash! {}".format(fname))
                continue

            output[sha3] = {
                "name": func["name"],
                "folded_name": fname,
                "params": params,
            }

        for sha3, row in output.items():
            row["cooccurs"] = list(output.keys())
            insert_row = (
                sha3,
                row["name"],
                row["folded_name"],
                json.dumps(row["params"]),
                ",".join(row["cooccurs"]),
            )

            insert_row2 = (
                int(sha3, 16),
                row["name"],
                row["folded_name"],
                json.dumps(row["params"]),
            )

            test_hash, test_cooccurs = insert_row[0], insert_row[4]

            cursor.execute(
                "SELECT * from functions where hash=? and cooccurs=?",
                (test_hash, test_cooccurs),
            )
            results = cursor.fetchall()
            if len(results) == 0:
                print("inserting", sha3, row["folded_name"])
                cursor.execute("INSERT INTO functions VALUES (?, ?, ?, ?, ?)",
                               insert_row)
                conn.commit()

            cursor2.execute("SELECT * from functions where hash=?",
                            (insert_row2[0], ))
            results = cursor2.fetchall()
            if len(results) == 0:
                print("inserting2", sha3, row["folded_name"])
                cursor2.execute("INSERT INTO functions VALUES (?, ?, ?, ?)",
                                insert_row2)

                conn2.commit()
示例#3
0
def generate_selector(method_name_and_params):
    method_selector = Web3.sha3(text=method_name_and_params)[0:4].hex()
    return method_selector
示例#4
0
文件: didregistry.py 项目: jl789/H2O
    def register(self, did_source, url=None, ddo=None, did=None, key=None, account=None):
        """
        Register or update a DID on the block chain using the DIDRegistry smart contract

        :param did_source: DID to register/update, can be a 32 byte or hexstring
        :param url: URL of the resolved DID
        :param ddo: DDO string or DDO object to resolve too
        :param did: DID to resovlve too, can be a 32 byte value or 64 hex string
        :param key: Optional 32 byte key ( 64 char hex )
        :param account: instance of Account to use to register/update the DID
        """

        value_type = VALUE_TYPE_DID
        value = None

        did_source_id = did_to_id_bytes(did_source)

        if not did_source_id:
            raise ValueError('{} must be a valid DID to register'.format(did_source))

        if url:
            value_type = VALUE_TYPE_URL
            value = url
            if not urlparse(url):
                raise ValueError('Invalid URL {0} to register for DID {1}'.format(url, did_source))

        if ddo:
            value_type = VALUE_TYPE_DDO
            if isinstance(ddo, DDO):
                value = ddo.as_text()
            elif isinstance(ddo, str):
                value = ddo
            else:
                raise ValueError('Invalid DDO {0} to register for DID {1}'.format(ddo, did_source))

        if did:
            value_type = VALUE_TYPE_DID
            id_bytes = did_to_id_bytes(did)
            if not id_bytes:
                raise ValueError('Invalid DID {}'.format(did))

            if did_source_id == id_bytes:
                raise OceanDIDCircularReference('Cannot have the same DID that points to itself')

            value = re.sub('^0x', '', Web3.toHex(id_bytes))

        if isinstance(key, str):
            key = Web3.sha3(text=key)

        if key is None:
            key = Web3.toBytes(0)

        if not isinstance(key, bytes):
            raise ValueError('Invalid key value {}, must be bytes or string'.format(key))

        if account is None:
            raise ValueError('You must provide an account to use to register a DID')

        self.unlock_account(account)
        transaction = self.register_attribute(did_source_id, value_type, key, value, account.address)
        receipt = self.get_tx_receipt(transaction)
        return receipt
示例#5
0
def sign_practice(pt, et):
    value = hex(long(Web3.sha3(pt), 16) ^ long(Web3.sha3(et), 16))
    return value
示例#6
0
文件: contracts.py 项目: anathk/MAIAN
def predict_contract_address(accountAddress):

    nonce = int(MyGlobals.web3.eth.getTransactionCount(accountAddress))
    adr = Web3.sha3(rlp.encode([normalize_address(accountAddress), nonce]),
                    encoding='bytes')[-40:]
    return '0x' + adr
示例#7
0
def gen_eth_private_key() -> bytes:
    """
    Simple private key generation function. Not for production use.
    """
    return Web3.sha3(os.urandom(4096))
    def parse_insert_abi(abi):

        def parse_inputs(func_inputs):
            inputs = []
            params = []
            param_counter = 0
            for r in func_inputs:
                param_counter += 1
                type_ = r['type']

                name_ = r['name']
                if len(name_) == 0:
                    name_ = 'param'+str(param_counter)

                if name_[0] != '_':
                    name_ = '_'+name_

                params.append({'type': r['type'], 'name': name_})

                if 'tuple' not in type_:
                    inputs.append(type_)
                else:
                    type_ = f"({parse_inputs(r['components'])[0]})" + type_[5:]
                    inputs.append(type_)

            return ','.join(inputs), params

        output = {}

        for func in abi:      
            if func['type'] in ['constructor', 'fallback']:
                continue

            inputs, params = parse_inputs(func['inputs'])

            fname = f"{func['name']}({inputs})"

            sha3 = Web3.sha3(text=fname).hex()[:10]

            if sha3 in output:
                print("double declaration for the same hash! {}".format(fname))
                continue

            output[sha3] = {
                'name': func['name'],
                'folded_name': fname,
                'params': params,
            }

        for sha3, row in output.items():
            row['cooccurs'] = list(output.keys())
            insert_row = (
                    sha3,
                    row['name'],
                    row['folded_name'],
                    json.dumps(row['params']),
                    ','.join(row['cooccurs']))

            insert_row2 = (
                    int(sha3, 16),
                    row['name'],
                    row['folded_name'],
                    json.dumps(row['params']))

            test_hash, test_cooccurs = insert_row[0], insert_row[4]

            cursor.execute('SELECT * from functions where hash=? and cooccurs=?', (test_hash, test_cooccurs))
            results = cursor.fetchall()
            if len(results) == 0:
                print('inserting', sha3, row['folded_name'])
                cursor.execute('INSERT INTO functions VALUES (?, ?, ?, ?, ?)', insert_row)
                conn.commit()

            cursor2.execute('SELECT * from functions where hash=?', (insert_row2[0], ))
            results = cursor2.fetchall()
            if len(results) == 0:
                print('inserting2', sha3, row['folded_name'])
                cursor2.execute('INSERT INTO functions VALUES (?, ?, ?, ?)', insert_row2)

                conn2.commit()
示例#9
0
def test_sha3_raise_if_hexstr_and_text():
    with pytest.raises(TypeError):
        Web3.sha3(hexstr='0x', text='')
示例#10
0
def test_sha3_raise_if_no_args():
    with pytest.raises(TypeError):
        Web3.sha3()
示例#11
0
def test_sha3_raise_if_primitive_and(kwargs):
    # must not set more than one input
    with pytest.raises(TypeError):
        Web3.sha3('', **kwargs)
示例#12
0
def test_sha3_primitive(primitive, digest):
    assert Web3.sha3(primitive) == digest
示例#13
0
def test_sha3_primitive_invalid(primitive, exception):
    with pytest.raises(exception):
        Web3.sha3(primitive)
示例#14
0
文件: launcher.py 项目: jwang-a/CTF
def is_solved_checker(addr: str, web3: Web3) -> bool:
    result = web3.eth.call({
        "to": addr,
        "data": web3.sha3(text="isSolved()")[:4],
    })
    return int(result.hex(), 16) == 1
示例#15
0
 def to_address(hexstr) -> str:
     hashed = Web3.sha3(hexstr=hexstr)
     address = Web3.toHex(hashed[-20:])
     return address
示例#16
0
 def mk_logout_msg_signed(validator_index, epoch, validation_key):
     msg_hash = Web3.sha3(rlp.encode([validator_index, epoch]))
     signed = w3.eth.account.signHash(msg_hash, validation_key)
     sig = encode_int32(signed.v) + encode_int32(signed.r) + encode_int32(
         signed.s)
     return rlp.encode([validator_index, epoch, sig])
def address_from_publickey(publickey):
    hash = Web3.sha3(hexstr=Web3.toHex(publickey))
    address = Web3.toHex(hash[-20:])
    return address
示例#18
0
def test_sha3_hexstr(hexstr, digest):
    assert Web3.sha3(hexstr=hexstr) == digest
示例#19
0
 def method_id(method) -> str:
     return Web3.sha3(text=method)[0:4].hex()
示例#20
0
def encode_function_signature(func_name_with_types: str):
    """input example 'transfer(address,uint256)'"""
    return eth_utils.to_hex(Web3.sha3(text=func_name_with_types))[:10]
示例#21
0
def test_sha3_raise_if_hexstr_and_text():
    with pytest.raises(TypeError):
        Web3.sha3(hexstr='0x', text='')
def test_claimReward_with_settle_call(
    token_network: Contract,
    monitoring_service_external: Contract,
    user_deposit_contract: Contract,
    event_handler: Callable,
    monitor_data: Dict,
    ms_address: HexAddress,
    web3: Web3,
    with_settle: bool,
) -> None:
    A, B = monitor_data["participants"]
    channel_identifier = monitor_data["channel_identifier"]

    # wait until MS is allowed to monitor
    token_network.web3.testing.mine(monitor_data["first_allowed"] -
                                    web3.eth.blockNumber)

    # MS updates closed channel on behalf of B
    txn_hash = monitoring_service_external.functions.monitor(
        A,
        B,
        *monitor_data["balance_proof_B"],
        monitor_data["non_closing_signature"],
        REWARD_AMOUNT,
        token_network.address,
        monitor_data["reward_proof_signature"],
    ).call_and_transact({"from": ms_address})

    # claiming before settlement timeout must fail
    with pytest.raises(TransactionFailed, match="channel not settled yet"):
        monitoring_service_external.functions.claimReward(
            channel_identifier, token_network.address, A,
            B).call({"from": ms_address})

    # Settle channel after settle_timeout elapsed
    token_network.web3.testing.mine(4)
    if with_settle:
        token_network.functions.settleChannel(
            channel_identifier,
            B,  # participant_B
            10,  # participant_B_transferred_amount
            0,  # participant_B_locked_amount
            LOCKSROOT_OF_NO_LOCKS,  # participant_B_locksroot
            A,  # participant_A
            20,  # participant_A_transferred_amount
            0,  # participant_A_locked_amount
            LOCKSROOT_OF_NO_LOCKS,  # participant_A_locksroot
        ).call_and_transact()

    # Claim reward for MS
    monitoring_service_external.functions.claimReward(
        channel_identifier, token_network.address, A,
        B).call_and_transact({"from": ms_address})

    # Check REWARD_CLAIMED event
    reward_identifier = Web3.sha3(
        encode_single("uint256", channel_identifier) +
        Web3.toBytes(hexstr=token_network.address))
    ms_ev_handler = event_handler(monitoring_service_external)
    ms_ev_handler.assert_event(
        txn_hash,
        MonitoringServiceEvent.REWARD_CLAIMED,
        dict(ms_address=ms_address,
             amount=REWARD_AMOUNT,
             reward_identifier=reward_identifier),
    )

    # Check that MS balance has increased by claiming the reward
    ms_balance_after_reward = user_deposit_contract.functions.balances(
        ms_address).call()
    assert ms_balance_after_reward == REWARD_AMOUNT
示例#23
0
def test_sha3_raise_if_no_args():
    with pytest.raises(TypeError):
        Web3.sha3()
示例#24
0
def compose_sol_data(method_name_params, params):
    method_name_params = method_name_params.replace('uint,',
                                                    'uint256,').replace(
                                                        'uint)', 'uint256)')
    fn_selector = Web3.toHex(Web3.sha3(text=method_name_params))
    fn_selector = fn_selector[0:10]
    print('function: ', method_name_params, ', function selector: ',
          fn_selector)

    param_types = []
    argstr = method_name_params.split('(')[1].split(')')[0]
    if argstr.strip():
        methodParams = argstr.split(',')
        for i in range(len(methodParams)):
            param_types.append(methodParams[i])
    # print('param_types', param_types, 'len: ', len(param_types))
    print('params', params, 'len: ', len(params))
    if (len(param_types) != len(params)):
        print('!!!parameters number is wrong.')
        return

    params_list = []
    for i in range(len(param_types)):
        params_list.append((param_types[i], params[i]))

    # print('params_list: ', params_list)
    first_list = [fn_selector]
    second_list = {}

    for i in range(len(params_list)):
        item = params_list[i]
        p_type, p_value = item[0], item[1]
        if p_type in ('bytes', 'string'):
            str_len, str_txt = rlp(p_value)
            result = str_len + str_txt
            second_list[i] = result
            pass
        elif '[]' in p_type:
            pass
        else:
            pass

    first_list = []
    param_num = len(param_types)
    start_pos = param_num * 32
    last_len = 0
    for i in range(len(params_list)):
        item = params_list[i]
        p_type, p_value = item[0], item[1]
        if p_type in ('bytes', 'string') or '[]' in p_type:
            # print('last_len=', last_len)
            first_list.append(
                str(Web3.toHex(start_pos + last_len))[2:].zfill(64))  # 起始位置
            last_len += int(len(second_list[i]) / 2)
            # start_pos += last_len
        elif p_type == 'address':
            first_list.append(p_value.zfill(64))
        else:
            first_list.append(str(Web3.toHex(p_value))[2:].zfill(64))  # 固定类型的值

    # print(first_list)
    # print()
    # print(second_list.values())
    # print()
    first_list += second_list.values()
    result_str = ''
    for part in first_list:
        result_str += part
    # print('final data: ', fn_selector+result_str)
    return fn_selector + result_str
示例#25
0
def test_sha3_text(message, digest):
    assert Web3.sha3(text=message) == digest
示例#26
0
 def __init__(self, l, r):
     self.l = l
     self.r = r
     self.h = Web3.sha3(l.h + r.h)
示例#27
0
def test_sha3_hexstr(hexstr, digest):
    assert Web3.sha3(hexstr=hexstr) == digest
示例#28
0
def get_sha3(_txt):
    """
    Returns keccak sha256 hash
    """
    return Web3.sha3(text=_txt).hex()
示例#29
0
def test_sha3_primitive_invalid(primitive, exception):
    with pytest.raises(exception):
        Web3.sha3(primitive)
示例#30
0
文件: init.py 项目: tmierzwa/EtherDB
            print("Function: %s" % (input[0:10]))
        input = input[10:]
        for j in range(len(input) // 64):
            print("Arg[%d]: %s" % (j + 1, input[j * 64:(j + 1) * 64]))

    for log in rcpt['logs']:
        print('Event address: ', log['address'])
        for i, topic in enumerate(log['topics']):
            print('Event topic %d: %s' % (i, topic.hex()))
        for i in range(len(log['data']) // 64):
            print("Event arg %d: %s" % (i, log['data'][i * 64:(i + 1) * 64]))

    return tx


hash = Web3.sha3(
    text='createSaleAuction(uint256,uint256,uint256,uint256)').hex()[0:10]
print(hash)

start_timestamp = datetime.now()

address = '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d'
blockNum = 5272293
count = 0
while blockNum <= w3.eth.blockNumber and count <= 10:
    block = w3.eth.getBlock(blockNum)
    print("Block:  %d: %s, %d \n" %
          (blockNum, block.hash.hex(), len(block.transactions)))
    for i in range(len(block.transactions)):
        tx = w3.eth.getTransaction(block.transactions[i])
        if tx['to'] == address:
            print("Block: %d Tx: %d: From: %s, Value: %d" %
示例#31
0
def test_sha3_primitive(primitive, digest):
    assert Web3.sha3(primitive) == digest
示例#32
0
def calculate_submit_hash_from_group(vals):
    hash_sums = [Web3.toInt(hexstr=val) for val in vals]
    return Web3.toHex(Web3.toInt(Web3.sha3(sum(hash_sums) & (2**256 - 1))))
示例#33
0
def test_sha3_raise_if_primitive_and(kwargs):
    # must not set more than one input
    with pytest.raises(TypeError):
        Web3.sha3('', **kwargs)
示例#34
0
def public_key_to_address(pk):
    hash_ = Web3.sha3(hexstr=str(pk))
    return Web3.toChecksumAddress(Web3.toHex(hash_[-20:]))
示例#35
0
def sign_practice(pt, et):
    print Web3.sha3(pt)
    return hex(long(Web3.sha3(pt), 16) ^ long(Web3.sha3(et), 16))
示例#36
0
def eth_sign_hash_message(encoded_message):
    signature_prefix = '\x19Ethereum Signed Message:\n'
    return Web3.sha3(
        Web3.toBytes(text=signature_prefix) +
        Web3.toBytes(text=str(len(encoded_message))) + encoded_message, )
示例#37
0
def test_sha3_text(message, digest):
    assert Web3.sha3(text=message) == digest