def test_claim(self):

        # https://www.realitykeys.com/runkeeper/6206
        # https://www.realitykeys.com/api/v1/runkeeper/6206?accept_terms_of_service=current

        after_event = json.loads('{"no_pubkey": "", "comparison": null, "measurement": "total_distance", "activity_open_datetime": "2015-12-02 06:35:05", "settlement_date": "2015-12-03", "objection_period_secs": 0, "human_resolution_scheduled_datetime": null, "value": null, "machine_resolution_winner": "No", "id": 6206, "evaluation_method": null, "machine_resolution_value": "246.210454708", "is_user_authenticated": true, "objection_fee_satoshis_paid": 0, "objection_fee_satoshis_due": 1000000, "machine_resolution_scheduled_datetime": "2015-12-03 00:00:00", "user_id": "29908850", "goal": null, "created_datetime": "2015-12-02 06:35:05", "winner": "No", "user_profile": "edochan", "winner_value": "246.210454708", "source": "runkeeper", "yes_pubkey": "", "signature_v2": {"signed_hash": "6ce5105e4239c5ff401e46a4e660b0980298a15bd91ede79beac4ceb1b03939a", "base_unit": 1000000000000000000, "signed_value": "00000000000000000000000000000000000000000000000d58db4013f9be0800", "sig_der": "304502210083463358f3df9507b04d3db8ebaddf4cc36e50c97268a141282708f987d38d93022036a38b9fa72a16e8701478a1c39f766561bc9bce8fa4b5e9ab7b99ce685744d8", "ethereum_address": "6fde387af081c37d9ffa762b49d340e6ae213395", "fact_hash": "634ab403c50fec82f39e8c4057ea29105708967d386c7f58325a28db333bc418", "sig_r": "83463358f3df9507b04d3db8ebaddf4cc36e50c97268a141282708f987d38d93", "sig_s": "36a38b9fa72a16e8701478a1c39f766561bc9bce8fa4b5e9ab7b99ce685744d8", "pubkey": "02e577bc17badf301e14d86c33d76be5c3b82a0c416fc93cd124d612761191ec21", "sig_v": 28}, "activity_closed_datetime": null, "activity": "walking", "human_resolution_value": null, "user_name": ["edochan"], "winner_privkey": null}')

        sig_data = after_event['signature_v2']
        signed_hash = sig_data['signed_hash']
        rk_addr = sig_data['ethereum_address']
        event_hash = sig_data['fact_hash']
        result_value_hex = sig_data['signed_value']
        v = sig_data['sig_v']
        r = sig_data['sig_r']
        s = sig_data['sig_s']

        base_unit = sig_data['base_unit']

        self.c.settle(
            self.pledge_id,
            decode_hex(result_value_hex),
            v,
            decode_hex(r),
            decode_hex(s)
        )

        return
Example #2
0
def test_reward_uncles(db):
    """
    B0 B1 B2
    B0 Uncle

    We raise the block's coinbase account by Rb, the block reward,
    and also add uncle and nephew rewards
    """
    k, v, k2, v2 = accounts()
    blk0 = mkquickgenesis(db=db)
    local_coinbase = decode_hex('1' * 40)
    uncle_coinbase = decode_hex('2' * 40)
    chain = Chain(env=env(blk0.db), genesis=blk0)
    uncle = mine_on_chain(chain, blk0, coinbase=uncle_coinbase)
    assert uncle.get_balance(uncle_coinbase) == 1 * chain.env.config['BLOCK_REWARD']
    blk1 = mine_on_chain(chain, blk0, coinbase=local_coinbase)
    assert blk1.hash in chain
    assert uncle.hash in chain
    assert uncle.hash != blk1.hash
    assert chain.head == blk1
    assert chain.head.get_balance(local_coinbase) == 1 * chain.env.config['BLOCK_REWARD']
    assert chain.head.get_balance(uncle_coinbase) == 0
    # next block should reward uncles
    blk2 = mine_on_chain(chain, coinbase=local_coinbase)
    assert blk2.get_parent().prevhash == uncle.prevhash
    assert len(blk2.uncles) == 1
    assert blk2 == chain.head
    assert chain.head.get_balance(local_coinbase) == \
        2 * chain.env.config['BLOCK_REWARD'] + chain.env.config['NEPHEW_REWARD']
    assert chain.head.get_balance(uncle_coinbase) == chain.env.config['BLOCK_REWARD'] * 7 / 8
Example #3
0
def test_reverter():
    s = tester.state()
    c = s.abi_contract(reverter_code, endowment=10 ** 15)
    c.entry()
    assert s.block.get_storage_data(c.address, 8080) == 4040
    assert s.block.get_balance(decode_hex('0' * 39 + '7')) == 9
    assert s.block.get_storage_data(c.address, 8081) == 0
    assert s.block.get_balance(decode_hex('0' * 39 + '8')) == 0
Example #4
0
def get_blocks_from_textdump(data):
    if '\n' not in data:
        r = rlp.decode(decode_hex(data))
        if len(r[0]) != 3:
            blocks = [r]
        else:
            blocks = r
    else:
        blocks = [rlp.decode(decode_hex(ln)) for ln in data.split('\n')]
    return blocks
Example #5
0
    def test_allowances(self):

        # a
        # aa             ab
        # aaa  aab       aba
        # aaaa aaba aabb abaa

        genesis_hash = decode_hex("fca5e1a248b8fee34db137da5e38b41f95d11feb5a8fa192a150d8d5d8de1c59")

        null_hash = decode_hex("0000000000000000000000000000000000000000000000000000000000000000")
        # print encode_hex(null_hash)

        k0_addr = encode_hex(keys.privtoaddr(t.k0))
        k1_addr = encode_hex(keys.privtoaddr(t.k1))
        k2_addr = encode_hex(keys.privtoaddr(t.k2))

        contract_addr = encode_hex(keys.privtoaddr(t.k9))

        self.assertEqual(k1_addr, '7d577a597b2742b498cb5cf0c26cdcd726d39e6e')

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000)

        self.rc.transfer(k1_addr, 1000000, genesis_hash, sender=t.k0, startgas=200000)

        # self.s.block.timestamp = self.s.block.timestamp + 100
        # self.s = t.state()

        window_index = 4 # index of genesis hash in struct

        self.assertEqual(self.rc.balanceOf(keys.privtoaddr(t.k0), genesis_hash), 2100000000000000-1000000)
        self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 1000000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, k1_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)

        self.rc.approve(k2_addr, 500000, genesis_hash, sender=t.k0, startgas=200000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, k1_addr, 600000, genesis_hash, sender=t.k2, startgas=200000)


        self.mine()
        start_bal = self.rc.balanceOf(k0_addr, genesis_hash)

        self.rc.transferFrom(k0_addr, k1_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)
        #self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 1000000-500000)

        self.mine()

        self.assertEqual(self.rc.balanceOf(k1_addr, genesis_hash), 400000+1000000)
        self.assertEqual(self.rc.balanceOf(k0_addr, genesis_hash), start_bal - 400000)

        with self.assertRaises(TransactionFailed):
            self.rc.transferFrom(k0_addr, 400000, genesis_hash, sender=t.k2, startgas=200000)
Example #6
0
def run_ethash_test(params, mode):
    if 'header' not in params:
        b = blocks.genesis(db)
        b.nonce = decode_hex(params['nonce'])
        b.number = params.get('number', 0)
        header = b.header
        params['header'] = encode_hex(rlp.encode(b.header))
    else:
        header = blocks.BlockHeader(decode_hex(params['header']))
    header_hash = header.mining_hash
    cache_size = ethash.get_cache_size(header.number)
    full_size = ethash.get_full_size(header.number)
    seed = b'\x00' * 32
    for i in range(header.number // ethash_utils.EPOCH_LENGTH):
        seed = utils.sha3(seed)
    nonce = header.nonce
    assert len(nonce) == 8
    assert len(seed) == 32
    t1 = time.time()
    cache = ethash.mkcache(cache_size, seed)
    t2 = time.time()
    cache_hash = encode_hex(utils.sha3(ethash.serialize_cache(cache)))
    t6 = time.time()
    light_verify = ethash.hashimoto_light(full_size, cache, header_hash, nonce)
    t7 = time.time()
    # assert full_mine == light_mine
    out = {
        "seed": encode_hex(seed),
        "header_hash": encode_hex(header_hash),
        "nonce": encode_hex(nonce),
        "cache_size": cache_size,
        "full_size": full_size,
        "cache_hash": cache_hash,
        "mixhash": encode_hex(light_verify["mix digest"]),
        "result": encode_hex(light_verify["result"]),
    }
    if mode == FILL:
        header.mixhash = light_verify["mixhash"]
        params["header"] = encode_hex(rlp.encode(header))
        for k, v in list(out.items()):
            params[k] = v
        return params
    elif mode == VERIFY:
        should, actual = header.mixhash, light_verify['mixhash']
        assert should == actual, "Mismatch: mixhash %r %r" % (should, actual)
        for k, v in list(out.items()):
            assert params[k] == v, "Mismatch: " + k + ' %r %r' % (params[k], v)
    elif mode == TIME:
        return {
            "cache_gen": t2 - t1,
            "verification_time": t7 - t6
        }
def worker():
    while True:
        item = q.get()
        try:
            block_number = int(jsonArrayElements[int(item)]['block'])
            difficulty = int(jsonArrayElements[int(item)]['diff'])
            header_hash = decode_hex(jsonArrayElements[int(item)]['pow'])
            mixhash = decode_hex(jsonArrayElements[int(item)]['digest'])
            nonce = decode_hex(jsonArrayElements[int(item)]['nonce'])
            result = ethpow.check_pow(block_number, header_hash, mixhash, nonce, difficulty)
            print 'I:'+str(item)+' Nonce:'+ encode_hex(nonce)+'='+str(result)
        finally:
            q.task_done()
Example #8
0
def send(transaction):
    if "from" in transaction:
        addr = decode_hex(strip_0x(transaction['from']))
        sender = keys[accounts.index(addr)]
    else:
        sender = keys[0]

    if "value" in transaction:
        value = int(strip_0x(transaction['value']), 16)
    else:
        value = 0

    if "to" in transaction:
        to = strip_0x(transaction['to'])
    else:
        to = None

    if "data" in transaction:
        data = decode_hex(strip_0x(transaction['data']))
    else:
        data = ""

    if "gas" in transaction:
        gas = int(strip_0x(transaction['gas']), 16)
    else:
        gas = None

    # print("value: " + encode_hex(value))
    # print("to: " + to)
    # print("from: " + encode_hex(accounts[keys.index(sender)]))
    # print("data: " + encode_hex(data))
    # print("gas: " + str(gas))

    if isContract(transaction):
        estimated_cost = len(encode_hex(data)) / 2 * 200

        print("Adding contract...")
        print("Estimated gas cost: " + str(estimated_cost))

        if gas != None and estimated_cost > gas:
            print("* ")
            print("* WARNING: Estimated cost higher than sent gas: " + str(estimated_cost) + " > " + str(gas))
            print("* ")

        r = encode_hex(evm.evm(data, sender, value, gas))
    else:
        r = encode_hex(evm.send(sender, to, value, data, gas))

    r = "0x" + r
    return r
Example #9
0
def create_contract(ext, msg):
    #print('CREATING WITH GAS', msg.gas)
    sender = decode_hex(msg.sender) if len(msg.sender) == 40 else msg.sender
    if ext.tx_origin != msg.sender:
        ext._block.increment_nonce(msg.sender)
    nonce = utils.encode_int(ext._block.get_nonce(msg.sender) - 1)
    msg.to = mk_contract_address(sender, nonce)
    b = ext.get_balance(msg.to)
    if b > 0:
        ext.set_balance(msg.to, b)
        ext._block.set_nonce(msg.to, 0)
        ext._block.set_code(msg.to, b'')
        ext._block.reset_storage(msg.to)
    msg.is_create = True
    # assert not ext.get_code(msg.to)
    code = msg.data.extract_all()
    msg.data = vm.CallData([], 0, 0)
    res, gas, dat = _apply_msg(ext, msg, code)
    assert utils.is_numeric(gas)

    if res:
        if not len(dat):
            return 1, gas, msg.to
        gcost = len(dat) * opcodes.GCONTRACTBYTE
        if gas >= gcost:
            gas -= gcost
        else:
            dat = []
            #print('CONTRACT CREATION OOG', 'have', gas, 'want', gcost)
            log_msg.debug('CONTRACT CREATION OOG', have=gas, want=gcost)
        ext._block.set_code(msg.to, b''.join(map(ascii_chr, dat)))
        return 1, gas, msg.to
    else:
        return 0, gas, b''
Example #10
0
def eth_getTransactionCount(address, block_number="latest"):
    address = strip_0x(address)

    block_number = format_block_number(block_number)
    block = evm.blocks[block_number]

    return "0x" + int_to_hex(block.get_nonce(decode_hex(address)))
def run_test(filename, testname, testdata):
    testdata = fixture_to_bytes(testdata)

    try:
        rlpdata = decode_hex(testdata["rlp"][2:])
        print rlpdata.encode("hex")
        o = {}
        tx = rlp.decode(rlpdata, transactions.Transaction)
        o["sender"] = tx.sender
        o["transaction"] = {
            "data": b"0x" * (len(tx.data) > 0) + encode_hex(tx.data),
            "gasLimit": str_to_bytes(str(tx.startgas)),
            "gasPrice": str_to_bytes(str(tx.gasprice)),
            "nonce": str_to_bytes(str(tx.nonce)),
            "r": b"0x" + encode_hex(utils.zpad(utils.int_to_big_endian(tx.r), 32)),
            "s": b"0x" + encode_hex(utils.zpad(utils.int_to_big_endian(tx.s), 32)),
            "v": str_to_bytes(str(tx.v)),
            "value": str_to_bytes(str(tx.value)),
            "to": encode_hex(tx.to),
        }
    except:
        tx = None
    if "transaction" not in testdata:  # expected to fail
        assert tx is None
    else:
        assert set(o["transaction"].keys()) == set(testdata.get("transaction", dict()).keys())
        o.get("transaction", None) == testdata.get("transaction", None)
        assert encode_hex(o.get("sender", "")) == testdata.get("sender", "")
Example #12
0
def coerce_addr_to_bin(x):
    if is_numeric(x):
        return encode_hex(zpad(big_endian_int.serialize(x), 20))
    elif len(x) == 40 or len(x) == 0:
        return decode_hex(x)
    else:
        return zpad(x, 20)[-20:]
Example #13
0
def coerce_addr_to_bin(x):
    if is_numeric(x):
        return encode_hex(zpad(big_endian_int.serialize(x), 20))
    elif len(x) == 40 or len(x) == 0:
        return decode_hex(x)
    else:
        return zpad(x, 20)[-20:]
Example #14
0
def coerce_to_bytes(x):
    if is_numeric(x):
        return big_endian_int.serialize(x)
    elif len(x) == 40:
        return decode_hex(x)
    else:
        return x
Example #15
0
def test_pay_for_myself(web3, payment_forwarder, team_multisig, customer):
    """Pay for myself."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16)  # Customer ids are 128-bit UUID v4

    team_multisig_begin = web3.eth.getBalance(team_multisig)

    checksumbyte = keccak_256(decode_hex(format(customer_id,
                                                'x').zfill(32))).digest()[:1]
    payment_forwarder.transact({
        "value": value,
        "from": customer
    }).payForMyselfWithChecksum(customer_id, checksumbyte)
    team_multisig_end = web3.eth.getBalance(team_multisig)

    assert team_multisig_end - team_multisig_begin > 0
    assert payment_forwarder.call().totalTransferred() == value
    assert payment_forwarder.call().paymentsByCustomer(customer_id) == value
    assert payment_forwarder.call().customerCount() == 1

    # Check we properly generate an event
    events = payment_forwarder.pastEvents("PaymentForwarded").get()
    assert len(events) == 1
    e = events[-1]
    assert e["args"]["source"] == customer
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer
Example #16
0
def create_contract(ext, msg):
    #print('CREATING WITH GAS', msg.gas)
    sender = decode_hex(msg.sender) if len(msg.sender) == 40 else msg.sender
    if ext.tx_origin != msg.sender:
        ext._block.increment_nonce(msg.sender)
    nonce = utils.encode_int(ext._block.get_nonce(msg.sender) - 1)
    msg.to = mk_contract_address(sender, nonce)
    b = ext.get_balance(msg.to)
    if b > 0:
        ext.set_balance(msg.to, b)
        ext._block.set_nonce(msg.to, 0)
        ext._block.set_code(msg.to, b'')
        ext._block.reset_storage(msg.to)
    msg.is_create = True
    # assert not ext.get_code(msg.to)
    code = msg.data.extract_all()
    msg.data = vm.CallData([], 0, 0)
    res, gas, dat = _apply_msg(ext, msg, code)
    assert utils.is_numeric(gas)

    if res:
        if not len(dat):
            return 1, gas, msg.to
        gcost = len(dat) * opcodes.GCONTRACTBYTE
        if gas >= gcost:
            gas -= gcost
        else:
            dat = []
            #print('CONTRACT CREATION OOG', 'have', gas, 'want', gcost)
            log_msg.debug('CONTRACT CREATION OOG', have=gas, want=gcost)
        ext._block.set_code(msg.to, b''.join(map(ascii_chr, dat)))
        return 1, gas, msg.to
    else:
        return 0, gas, b''
Example #17
0
def coerce_to_bytes(x):
    if is_numeric(x):
        return big_endian_int.serialize(x)
    elif len(x) == 40:
        return decode_hex(x)
    else:
        return x
Example #18
0
def coerce_to_int(x):
    if is_numeric(x):
        return x
    elif len(x) == 40:
        return big_endian_to_int(decode_hex(x))
    else:
        return big_endian_to_int(x)
Example #19
0
def coerce_to_int(x):
    if is_numeric(x):
        return x
    elif len(x) == 40:
        return big_endian_to_int(decode_hex(x))
    else:
        return big_endian_to_int(x)
Example #20
0
def solc_parse_output(compiler_output):
    """ Parses the compiler output. """
    # At the moment some solc output like --hashes or -- gas will not output
    # json at all so if used with those arguments the logic here will break.
    # Perhaps solidity will slowly switch to a json only output and this comment
    # can eventually go away and we will not need to add more logic here at
    # all.
    result = yaml.safe_load(compiler_output)['contracts']

    if 'bin' in tuple(result.values())[0]:
        for value in result.values():
            value['bin_hex'] = value['bin']

            # decoding can fail if the compiled contract has unresolved symbols
            try:
                value['bin'] = decode_hex(value['bin_hex'])
            except (TypeError, ValueError):
                pass

    for json_data in ('abi', 'devdoc', 'userdoc'):
        # the values in the output can be configured through the
        # --combined-json flag, check that it's present in the first value and
        # assume all values are consistent
        if json_data not in tuple(result.values())[0]:
            continue

        for value in result.values():
            value[json_data] = yaml.safe_load(value[json_data])

    return result
Example #21
0
def solc_parse_output(compiler_output):
    """ Parses the compiler output. """
    result = yaml.safe_load(compiler_output)['contracts']

    if 'bin' in tuple(result.values())[0]:
        for value in result.values():
            value['bin_hex'] = value['bin']

            # decoding can fail if the compiled contract has unresolved symbols
            try:
                value['bin'] = decode_hex(value['bin_hex'])
            except TypeError:
                pass

    for json_data in ('abi', 'devdoc', 'userdoc'):
        # the values in the output can be configured through the
        # --combined-json flag, check that it's present in the first value and
        # assume all values are consistent
        if json_data not in tuple(result.values())[0]:
            continue

        for value in result.values():
            value[json_data] = yaml.safe_load(value[json_data])

    return result
Example #22
0
def decode_single(typ, data):
    try:
        base, sub, arrlist = typ
    except ValueError:
        base, sub, arrlist = process_type(typ)

    if is_hex_encoded_value(data):
        data = decode_hex(strip_0x_prefix(data))

    if base == 'address':
        return encode_hex(data[12:])
    elif base == 'hash':
        return data[32 - int(sub):]
    elif base == 'string' or base == 'bytes':
        if len(sub):
            return data[:int(sub)]
        else:
            l = big_endian_to_int(data[0:32])
            return data[32:][:l]
    elif base == 'uint':
        return big_endian_to_int(data)
    elif base == 'int':
        o = big_endian_to_int(data)
        return (o - 2**int(sub)) if o >= 2**(int(sub) - 1) else o
    elif base == 'ureal':
        high, low = [int(x) for x in sub.split('x')]
        return big_endian_to_int(data) * 1.0 / 2**low
    elif base == 'real':
        high, low = [int(x) for x in sub.split('x')]
        o = big_endian_to_int(data)
        i = (o - 2**(high + low)) if o >= 2**(high + low - 1) else o
        return (i * 1.0 / 2**low)
    elif base == 'bool':
        return bool(int(encode_hex(data), 16))
Example #23
0
def eth_getBalance(address, block_number="latest"):
    address = strip_0x(address)

    block_number = format_block_number(block_number)
    block = evm.blocks[block_number]

    return "0x" + int_to_hex(block.get_balance(decode_hex(address)))
    def setUp(self):

        s = t.state()

        code = open('sponsor.sol').read()
        self.c = t.state().abi_contract(code, language='solidity')

        self.alice_priv = t.k0
        self.alice_addr = utils.privtoaddr(self.alice_priv)
        self.bob_priv = t.k1
        self.bob_addr = utils.privtoaddr(self.bob_priv)

        # wget -qO- https://www.realitykeys.com/api/v1/runkeeper/new --post-data="user_id=29908850&activity=running&measurement=total_distance&comparison=ge&goal=4000&settlement_date=2015-12-23&objection_period_secs=604800&accept_terms_of_service=current&use_existing=1"

        before_event = json.loads('{"no_pubkey": "", "comparison": null, "measurement": "total_distance", "activity_open_datetime": "2015-12-02 06:35:05", "settlement_date": "2015-12-03", "objection_period_secs": 0, "human_resolution_scheduled_datetime": null, "value": null, "machine_resolution_winner": "No", "id": 6206, "evaluation_method": null, "machine_resolution_value": "246.210454708", "is_user_authenticated": true, "objection_fee_satoshis_paid": 0, "objection_fee_satoshis_due": 1000000, "machine_resolution_scheduled_datetime": "2015-12-03 00:00:00", "user_id": "29908850", "goal": null, "created_datetime": "2015-12-02 06:35:05", "winner": null, "user_profile": "edochan", "winner_value": null, "source": "runkeeper", "yes_pubkey": "", "signature_v2": {"signed_hash": null, "base_unit": 1000000000000000000, "signed_value": null, "sig_der": null, "ethereum_address": "6fde387af081c37d9ffa762b49d340e6ae213395", "fact_hash": "634ab403c50fec82f39e8c4057ea29105708967d386c7f58325a28db333bc418", "sig_r": null, "sig_s": null, "pubkey": "02e577bc17badf301e14d86c33d76be5c3b82a0c416fc93cd124d612761191ec21", "sig_v": null}, "activity_closed_datetime": null, "activity": "walking", "human_resolution_value": null, "user_name": ["edochan"], "winner_privkey": null}')

        sig_data = before_event['signature_v2']
        rk_addr = sig_data['ethereum_address']
        event_hash = sig_data['fact_hash']
        base_unit = sig_data['base_unit']

        # This happens to be the same as the base unit, but there is no deep meaning behind this.
        ETH_TO_WEI = 1000000000000000000000

        self.pledge_id = self.c.add_pledge(
            self.bob_addr, 
            decode_hex(event_hash), 
            base_unit,
            100, # You have to walk at least 100 meters before we pay
            int(0.01 * ETH_TO_WEI / 100), # We'll give you 0.01 eth per 100 meters (0.0001 eth per meter) after that
            rk_addr,
            sender=self.alice_priv,
            value=int(0.04 * ETH_TO_WEI), # We'll fund you 0.04 eth
        );
Example #25
0
def test_transaction(filename, testname, testdata):
    testdata = fixture_to_bytes(testdata)

    try:
        rlpdata = decode_hex(testdata["rlp"][2:])
        o = {}
        tx = rlp.decode(rlpdata, transactions.Transaction)
        blknum = int(testdata["blocknumber"])
        if blknum >= config.default_config["HOMESTEAD_FORK_BLKNUM"]:
            tx.check_low_s()
        o["sender"] = tx.sender
        o["transaction"] = {
            "data": b'0x' * (len(tx.data) > 0) + encode_hex(tx.data),
            "gasLimit": str_to_bytes(str(tx.startgas)),
            "gasPrice": str_to_bytes(str(tx.gasprice)),
            "nonce": str_to_bytes(str(tx.nonce)),
            "r": b'0x' + encode_hex(utils.zpad(utils.int_to_big_endian(tx.r), 32)),
            "s": b'0x' + encode_hex(utils.zpad(utils.int_to_big_endian(tx.s), 32)),
            "v": str_to_bytes(str(tx.v)),
            "value": str_to_bytes(str(tx.value)),
            "to": encode_hex(tx.to),
        }
    except Exception as e:
        tx = None
        sys.stderr.write(str(e))
    if 'transaction' not in testdata:  # expected to fail
        assert tx is None
    else:
        assert set(o['transaction'].keys()) == set(testdata.get("transaction", dict()).keys())
        o.get("transaction", None) == testdata.get("transaction", None)
        assert encode_hex(o.get("sender", '')) == testdata.get("sender", '')
Example #26
0
def test_pay_twice(web3, payment_forwarder, team_multisig, customer,
                   customer_2):
    """Pay for an address twice."""

    value = to_wei("1.0", "ether")
    customer_id = int(uuid.uuid4().hex, 16)  # Customer ids are 128-bit UUID v4

    team_multisig_begin = web3.eth.getBalance(team_multisig)
    # We pay from two distinct addresses on behalf of the same customer
    checksumbyte = keccak_256(
        decode_hex(format(customer_id, 'x').zfill(32)) +
        decode_hex(format(customer[2:]).zfill(40))).digest()[:1]
    payment_forwarder.transact({
        "value": value,
        "from": customer
    }).pay(customer_id, customer, checksumbyte)

    # Here we make sure the first checkummed investment was successful
    events = payment_forwarder.pastEvents("PaymentForwarded").get()
    assert len(events) == 1
    e = events[-1]
    assert e["args"]["source"] == customer
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer

    payment_forwarder.transact({
        "value": value,
        "from": customer_2
    }).payWithoutChecksum(customer_id, customer)
    team_multisig_end = web3.eth.getBalance(team_multisig)

    assert team_multisig_end - team_multisig_begin > 0
    assert payment_forwarder.call().totalTransferred() == 2 * value
    assert payment_forwarder.call().paymentsByCustomer(
        customer_id) == 2 * value
    assert payment_forwarder.call().paymentsByBenefactor(customer) == 2 * value
    assert payment_forwarder.call().customerCount() == 1

    # Check we properly generate an event
    events = payment_forwarder.pastEvents("PaymentForwarded").get()
    assert len(events) == 2
    e = events[-1]
    assert e["args"]["source"] == customer_2
    assert e["args"]["amount"] == value
    assert e["args"]["customerId"] == customer_id
    assert e["args"]["benefactor"] == customer
Example #27
0
def run_block_test(params):
    b = blocks.genesis(env, start_alloc=params["pre"])
    gbh = params["genesisBlockHeader"]
    b.bloom = utils.scanners['int256b'](gbh["bloom"])
    b.timestamp = utils.scanners['int'](gbh["timestamp"])
    b.nonce = utils.scanners['bin'](gbh["nonce"])
    b.extra_data = utils.scanners['bin'](gbh["extraData"])
    b.gas_limit = utils.scanners['int'](gbh["gasLimit"])
    b.gas_used = utils.scanners['int'](gbh["gasUsed"])
    b.coinbase = utils.scanners['addr'](decode_hex(gbh["coinbase"]))
    b.difficulty = utils.parse_int_or_hex(gbh["difficulty"])
    b.prevhash = utils.scanners['bin'](gbh["parentHash"])
    b.mixhash = utils.scanners['bin'](gbh["mixHash"])
    assert b.receipts.root_hash == \
        utils.scanners['bin'](gbh["receiptTrie"])
    assert b.transactions.root_hash == \
        utils.scanners['bin'](gbh["transactionsTrie"])
    assert utils.sha3rlp(b.uncles) == \
        utils.scanners['bin'](gbh["uncleHash"])
    h = encode_hex(b.state.root_hash)
    if h != str_to_bytes(gbh["stateRoot"]):
        raise Exception("state root mismatch")
    if b.hash != utils.scanners['bin'](gbh["hash"]):
        raise Exception("header hash mismatch")
    assert b.header.check_pow()
    blockmap = {b.hash: b}
    env.db.put(b.hash, rlp.encode(b))
    for blk in params["blocks"]:
        if 'blockHeader' not in blk:
            try:
                rlpdata = decode_hex(blk["rlp"][2:])
                blkparent = rlp.decode(
                    rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
                b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
                success = b2.validate_uncles()
            except (ValueError, TypeError, AttributeError, VerificationFailed,
                    DecodingError, DeserializationError, InvalidTransaction, KeyError):
                success = False
            assert not success
        else:
            rlpdata = decode_hex(blk["rlp"][2:])
            blkparent = rlp.decode(rlp.encode(rlp.decode(rlpdata)[0]), blocks.BlockHeader).prevhash
            b2 = rlp.decode(rlpdata, blocks.Block, parent=blockmap[blkparent], env=env)
            assert b2.validate_uncles()
            blockmap[b2.hash] = b2
            env.db.put(b2.hash, rlp.encode(b2))
Example #28
0
def test_get_privkey():
    import sys
    if len(sys.argv) > 2:
        privkey = get_privkey(sys.argv[1], sys.argv[2])
        print(privkey)
        from ethereum.utils import privtoaddr
        from rlp.utils import decode_hex
        print(privtoaddr(decode_hex(privkey)))
Example #29
0
def _decimal_to_bytes(i):
    if i is None or i == 0:
        return ""
    hex_basic = hex(int(i))[2:]
    hex_basic = hex_basic.replace("L", "")
    if len(hex_basic) % 2 == 1:
        hex_basic = "0{}".format(hex_basic)
    return decode_hex(hex_basic)
Example #30
0
def createRawTransaction(nonce, gasprice, startgas, to, value, data):
    nonce_ = int(
        nonce, 16) if isinstance(nonce, str) and '0x' in nonce else int(nonce)
    gasprice_ = int(gasprice, 16) if isinstance(
        gasprice, str) and '0x' in gasprice else int(gasprice)
    startgas_ = int(startgas, 16) if isinstance(
        startgas, str) and '0x' in startgas else int(startgas)
    value_ = int(
        value, 16) if isinstance(value, str) and '0x' in value else int(value)
    from rlp.utils import encode_hex, decode_hex
    to_ = decode_hex(
        to[2:]) if isinstance(to, str) and '0x' in to else decode_hex(to)
    data_ = decode_hex(data)
    rawTransaction = TransactionEx(nonce_, gasprice_, startgas_, to_, value_,
                                   data_)
    rlp_data = rawTransaction.unsigned
    return encode_hex(rlp_data)
    def setUp(self):
        DatabaseFixture.setUp(self)
        self.state = tester.state()
        gnt_addr = self.state.evm(decode_hex(TestGNT.INIT_HEX))
        self.state.mine()
        self.gnt = tester.ABIContract(self.state, TestGNT.ABI, gnt_addr)
        PaymentProcessor.TESTGNT_ADDR = gnt_addr
        self.privkey = tester.k1
        self.client = mock.MagicMock(spec=Client)
        self.client.get_peer_count.return_value = 0
        self.client.is_syncing.return_value = False
        self.client.get_transaction_count.side_effect = \
            lambda addr: self.state.block.get_nonce(decode_hex(addr[2:]))
        self.client.get_balance.side_effect = \
            lambda addr: self.state.block.get_balance(decode_hex(addr[2:]))

        def call(_from, to, data, **kw):
            # pyethereum does not have direct support for non-mutating calls.
            # The implemenation just copies the state and discards it after.
            # Here we apply real transaction, but with gas price 0.
            # We assume the transaction does not modify the state, but nonce
            # will be bumped no matter what.
            _from = _from[2:].decode('hex')
            data = data[2:].decode('hex')
            nonce = self.state.block.get_nonce(_from)
            value = kw.get('value', 0)
            tx = Transaction(nonce, 0, 100000, to, value, data)
            assert _from == tester.a1
            tx.sign(tester.k1)
            block = kw['block']
            assert block == 'pending'
            success, output = apply_transaction(self.state.block, tx)
            assert success
            return '0x' + output.encode('hex')

        def send(tx):
            success, _ = apply_transaction(self.state.block, tx)
            assert success  # What happens in real RPC eth_send?
            return '0x' + tx.hash.encode('hex')

        self.client.call.side_effect = call
        self.client.send.side_effect = send
        self.pp = PaymentProcessor(self.client, self.privkey)
        self.clock = Clock()
        self.pp._loopingCall.clock = self.clock
Example #32
0
def host_port_pubkey_from_uri(uri):
    b_node_uri_scheme = str_to_bytes(node_uri_scheme)
    b_uri = str_to_bytes(uri)
    assert b_uri.startswith(b_node_uri_scheme) and \
        b'@' in b_uri and b':' in b_uri, b_uri
    pubkey_hex, ip_port = b_uri[len(b_node_uri_scheme):].split(b'@')
    assert len(pubkey_hex) == 2 * 512 // 8
    ip, port = ip_port.split(b':')
    return ip, port, decode_hex(pubkey_hex)
Example #33
0
def parse_int_or_hex(s):
    if is_numeric(s):
        return s
    elif s[:2] in (b'0x', '0x'):
        s = to_string(s)
        tail = (b'0' if len(s) % 2 else b'') + s[2:]
        return big_endian_to_int(decode_hex(tail))
    else:
        return int(s)
Example #34
0
def parse_int_or_hex(s):
    if is_numeric(s):
        return s
    elif s[:2] in (b'0x', '0x'):
        s = to_string(s)
        tail = (b'0' if len(s) % 2 else b'') + s[2:]
        return big_endian_to_int(decode_hex(tail))
    else:
        return int(s)
Example #35
0
def genesis(db, start_alloc=GENESIS_INITIAL_ALLOC,
            difficulty=GENESIS_DIFFICULTY,
            **kwargs):
    """Build the genesis block."""
    # https://ethereum.etherpad.mozilla.org/11
    header = BlockHeader(
        prevhash=kwargs.get('prevhash', GENESIS_PREVHASH),
        uncles_hash=utils.sha3(rlp.encode([])),
        coinbase=kwargs.get('coinbase', GENESIS_COINBASE),
        state_root=trie.BLANK_ROOT,
        tx_list_root=trie.BLANK_ROOT,
        receipts_root=trie.BLANK_ROOT,
        bloom=0,
        difficulty=kwargs.get('difficulty', GENESIS_DIFFICULTY),
        number=0,
        gas_limit=kwargs.get('gas_limit', GENESIS_GAS_LIMIT),
        gas_used=0,
        timestamp=kwargs.get('timestamp', 0),
        extra_data=kwargs.get('extra_data', ''),
        mixhash=kwargs.get('mixhash', GENESIS_MIXHASH),
        nonce=kwargs.get('nonce', GENESIS_NONCE),
    )
    block = Block(header, [], [], db=db)
    for addr, data in start_alloc.items():
        if len(addr) == 40:
            addr = decode_hex(addr)
        assert len(addr) == 20
        if 'wei' in data:
            block.set_balance(addr, int(data['wei']))
        if 'balance' in data:
            block.set_balance(addr, int(data['balance']))
        if 'code' in data:
            block.set_code(addr, utils.scanners['bin'](data['code']))
        if 'nonce' in data:
            block.set_nonce(addr, int(data['nonce']))
        if 'storage' in data:
            for k, v in data['storage'].items():
                block.set_storage_data(addr, utils.big_endian_to_int(decode_hex(k[2:])),
                                       utils.big_endian_to_int(decode_hex(v[2:])))
    block.commit_state()
    block.state.db.commit()
    # genesis block has predefined state root (so no additional finalization
    # necessary)
    return block
Example #36
0
 def create_wrapper(msg):
     sender = decode_hex(msg.sender) if \
         len(msg.sender) == 40 else msg.sender
     nonce = utils.encode_int(ext._block.get_nonce(msg.sender))
     addr = utils.sha3(rlp.encode([sender, nonce]))[12:]
     hexdata = encode_hex(msg.data.extract_all())
     apply_message_calls.append(dict(gasLimit=to_string(msg.gas),
                                     value=to_string(msg.value),
                                     destination=b'', data=b'0x' + hexdata))
     return 1, msg.gas, addr
Example #37
0
 def create_wrapper(msg):
     sender = decode_hex(msg.sender) if \
         len(msg.sender) == 40 else msg.sender
     nonce = utils.encode_int(ext._block.get_nonce(msg.sender))
     addr = utils.sha3(rlp.encode([sender, nonce]))[12:]
     hexdata = encode_hex(msg.data.extract_all())
     apply_message_calls.append(dict(gasLimit=to_string(msg.gas),
                                     value=to_string(msg.value),
                                     destination=b'', data=b'0x' + hexdata))
     return 1, msg.gas, addr
Example #38
0
    def del_account(self, address):
        """Delete an account.

        :param address: the address of the account (binary or hex string)
        """
        if len(address) == 40:
            address = decode_hex(address)
        assert len(address) == 20
        self.commit_state()
        self.state.delete(address)
Example #39
0
def decode_filter(filter_dict, block):
    """Decodes a filter as expected by eth_newFilter or eth_getLogs to a :class:`Filter`."""
    if not isinstance(filter_dict, dict):
        raise Exception('Filter must be an object')
    address = filter_dict.get('address', None)
    if utils.is_string(address):
        addresses = [decode_hex(strip_0x(address))]
    elif isinstance(address, Iterable):
        addresses = [decode_hex(strip_0x(addr)) for addr in address]
    elif address is None:
        addresses = None
    else:
        raise Exception('Parameter must be address or list of addresses')
    if 'topics' in filter_dict:
        topics = []
        for topic in filter_dict['topics']:
            if topic is not None:
                topics.append(utils.big_endian_to_int(decode_hex(strip_0x(topic))))
            else:
                topics.append(None)
    else:
        topics = None

    from_block = filter_dict.get('fromBlock') or 'latest'
    to_block = filter_dict.get('toBlock') or 'latest'

    if from_block not in ('earliest', 'latest', 'pending'):
        from_block = decode_number(from_block)

    if to_block not in ('earliest', 'latest', 'pending'):
        to_block = decode_number(to_block)

    # check order
    block_id_dict = {
        'earliest': 0,
        'latest': block.number,
        'pending': block.number+1
    }
    range_ = [b if utils.is_numeric(b) else block_id_dict[b] for b in (from_block, to_block)]
    if range_[0] > range_[1]:
        raise Exception('fromBlock must be newer or equal to toBlock')

    return {"from_block": from_block, "to_block": to_block, "addresses": addresses, "topics": topics}
Example #40
0
def test_eip8_hello():
    peer = PeerMock()
    proto = P2PProtocol(peer, WiredService(BaseApp()))
    test_packet = Packet(cmd_id=1, payload=eip8_hello)
    proto._receive_hello(test_packet)
    assert peer.hello_received
    assert peer.remote_client_version == b"kneth/v0.91/plan9"
    assert peer.remote_hello_version == 22
    assert peer.remote_pubkey == decode_hex(
        'fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877'
    )
def test_eip8_key_derivation():
    responder = RLPxSession(ECCx(raw_privkey=eip8_values['key_b']),
                            ephemeral_privkey=eip8_values['eph_key_b'])
    responder.decode_authentication(eip8_handshakes[1]['auth'])
    ack = responder.create_auth_ack_message(nonce=eip8_values['nonce_b'])
    responder.encrypt_auth_ack_message(ack)

    responder.setup_cipher()
    want_aes_secret = decode_hex(
        b'80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487')
    want_mac_secret = decode_hex(
        b'2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98')
    assert responder.aes_secret == want_aes_secret
    assert responder.mac_secret == want_mac_secret

    responder.ingress_mac.update(b'foo')
    mac_digest = responder.ingress_mac.digest()
    want_mac_digest = decode_hex(
        b'0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5')
    assert mac_digest == want_mac_digest
Example #42
0
def do_test_bloom(test_logs):
    """
    The logs sections is a mapping between the blooms and their corresponding logentries.
    Each logentry has the format:
    address: The address of the logentry.
    data: The data of the logentry.
    topics: The topics of the logentry, given as an array of values.
    """
    for data in test_logs:
        address = data["address"]
        # Test via bloom
        b = bloom.bloom_insert(0, decode_hex(address))
        for t in data["topics"]:
            b = bloom.bloom_insert(b, decode_hex(t))
        # Test via Log
        topics = [decode_int_from_hex(x) for x in data["topics"]]
        log = pb.Log(decode_hex(address), topics, "")
        log_bloom = bloom.b64(bloom.bloom_from_list(log.bloomables()))
        assert encode_hex(log_bloom) == encode_hex_from_int(b)
        assert str_to_bytes(data["bloom"]) == encode_hex(log_bloom)
Example #43
0
def do_test_bloom(test_logs):
    """
    The logs sections is a mapping between the blooms and their corresponding logentries.
    Each logentry has the format:
    address: The address of the logentry.
    data: The data of the logentry.
    topics: The topics of the logentry, given as an array of values.
    """
    for data in test_logs:
        address = data['address']
        # Test via bloom
        b = bloom.bloom_insert(0, decode_hex(address))
        for t in data['topics']:
            b = bloom.bloom_insert(b, decode_hex(t))
        # Test via Log
        topics = [decode_int_from_hex(x) for x in data['topics']]
        log = Log(decode_hex(address), topics, '')
        log_bloom = bloom.b64(bloom.bloom_from_list(log.bloomables()))
        assert encode_hex(log_bloom) == encode_hex_from_int(b)
        assert data['bloom'] == encode_hex(log_bloom)
Example #44
0
    def __init__(self, nonce, gasprice, startgas, to, value, data, v=0, r=0, s=0):
        if len(to) == 40:
            to = decode_hex(to)
        assert len(to) == 20 or len(to) == 0
        super(Transaction, self).__init__(nonce, gasprice, startgas, to, value, data, v, r, s)
        self.logs = []

        if self.gasprice >= TT256 or self.startgas >= TT256 or \
                self.value >= TT256 or self.nonce >= TT256:
            raise InvalidTransaction("Values way too high!")

        log.debug('deserialized tx', tx=self.hash.encode('hex')[:8])
Example #45
0
 def __init__(self, app, transport):
     self.app = app
     self.transport = transport
     self.privkey = decode_hex(app.config['node']['privkey_hex'])
     self.pubkey = crypto.privtopub(self.privkey)
     self.nodes = LRUCache(2048)   # nodeid->Node,  fixme should be loaded
     self.this_node = Node(self.pubkey, self.transport.address)
     self.kademlia = KademliaProtocolAdapter(self.this_node, wire=self)
     this_enode = utils.host_port_pubkey_to_uri(self.app.config['discovery']['listen_host'],
                                                self.app.config['discovery']['listen_port'],
                                                self.pubkey)
     log.info('starting discovery proto', this_enode=this_enode)
Example #46
0
def run_genesis_test(params, mode):
    params = copy.deepcopy(params)
    if 'difficulty' not in params:
        params['difficulty'] = int_to_hex(2**34)
    if 'mixhash' not in params:
        params['mixhash'] = '0x' + '0' * 64
    if 'nonce' not in params:
        params['nonce'] = '0x0000000000000042'
    if 'timestamp' not in params:
        params['timestamp'] = int_to_hex(5000)
    if 'parentHash' not in params:
        params['parentHash'] = '0x' + '0' * 64
    if 'gasLimit' not in params:
        params['gasLimit'] = int_to_hex(5000)
    if 'extraData' not in params:
        params['extraData'] = '0x'
    if 'coinbase' not in params:
        params['coinbase'] = '0x' + '3' * 40
    x = time.time()
    b = blocks.genesis(
        EphemDB(),
        start_alloc=params['alloc'],
        difficulty=parse_int_or_hex(params['difficulty']),
        timestamp=parse_int_or_hex(params['timestamp']),
        extra_data=decode_hex(remove_0x_head(params['extraData'])),
        gas_limit=parse_int_or_hex(params['gasLimit']),
        mixhash=decode_hex(remove_0x_head(params['mixhash'])),
        prevhash=decode_hex(remove_0x_head(params['parentHash'])),
        coinbase=decode_hex(remove_0x_head(params['coinbase'])),
        nonce=decode_hex(remove_0x_head(params['nonce'])))
    assert b.difficulty == parse_int_or_hex(params['difficulty'])
    assert b.timestamp == parse_int_or_hex(params['timestamp'])
    assert b.extra_data == decode_hex(remove_0x_head(params['extraData']))
    assert b.gas_limit == parse_int_or_hex(params['gasLimit'])
    assert b.mixhash == decode_hex(remove_0x_head(params['mixhash']))
    assert b.prevhash == decode_hex(remove_0x_head(params['parentHash']))
    assert b.nonce == decode_hex(remove_0x_head(params['nonce']))
    print 9
    if mode == FILL:
        params['result'] = encode_hex(rlp.encode(b))
        return params
    elif mode == VERIFY:
        assert params['result'] == encode_hex(rlp.encode(b))
    elif mode == TIME:
        return {'creation': time.time() - x}
Example #47
0
def run_genesis_test(params, mode):
    params = copy.deepcopy(params)
    if 'difficulty' not in params:
        params['difficulty'] = int_to_hex(2 ** 34)
    if 'mixhash' not in params:
        params['mixhash'] = '0x' + '0' * 64
    if 'nonce' not in params:
        params['nonce'] = '0x0000000000000042'
    if 'timestamp' not in params:
        params['timestamp'] = int_to_hex(5000)
    if 'parentHash' not in params:
        params['parentHash'] = '0x' + '0' * 64
    if 'gasLimit' not in params:
        params['gasLimit'] = int_to_hex(5000)
    if 'extraData' not in params:
        params['extraData'] = '0x'
    if 'coinbase' not in params:
        params['coinbase'] = '0x' + '3' * 40
    x = time.time()
    b = blocks.genesis(EphemDB(), start_alloc=params['alloc'],
                       difficulty=parse_int_or_hex(params['difficulty']),
                       timestamp=parse_int_or_hex(params['timestamp']),
                       extra_data=decode_hex(remove_0x_head(params['extraData'])),
                       gas_limit=parse_int_or_hex(params['gasLimit']),
                       mixhash=decode_hex(remove_0x_head(params['mixhash'])),
                       prevhash=decode_hex(remove_0x_head(params['parentHash'])),
                       coinbase=decode_hex(remove_0x_head(params['coinbase'])),
                       nonce=decode_hex(remove_0x_head(params['nonce'])))
    assert b.difficulty == parse_int_or_hex(params['difficulty'])
    assert b.timestamp == parse_int_or_hex(params['timestamp'])
    assert b.extra_data == decode_hex(remove_0x_head(params['extraData']))
    assert b.gas_limit == parse_int_or_hex(params['gasLimit'])
    assert b.mixhash == decode_hex(remove_0x_head(params['mixhash']))
    assert b.prevhash == decode_hex(remove_0x_head(params['parentHash']))
    assert b.nonce == decode_hex(remove_0x_head(params['nonce']))
    print(9)
    if mode == FILL:
        params['result'] = encode_hex(rlp.encode(b))
        return params
    elif mode == VERIFY:
        assert params['result'] == encode_hex(rlp.encode(b))
    elif mode == TIME:
        return {
            'creation': time.time() - x
        }
Example #48
0
def deploy_contract_and_accounts(state,
                                 n_devs,
                                 start=1,
                                 end=2,
                                 deploy_contract=True):
    dev_keys = []
    dev_accounts = []

    milestone = int(math.log10(n_devs))
    notify_step = milestone - 2
    notify_value = 10**notify_step if notify_step > 0 else 1

    # create developer accounts and keys in fashion of testers
    for account_number in range(n_devs):
        if account_number % notify_value == 0:
            print "Account", account_number + 1, "out of", n_devs

        dev_keys.append(sha3('dev' + to_string(account_number)))
        dev_accounts.append(privtoaddr(dev_keys[-1]))

    # developer balances
    block = state.block

    for i in range(n_devs):
        if i % notify_value == 0:
            print "Balance", i + 1, "out of", n_devs

        addr, data = dev_accounts[i], {'wei': 10**24}
        if len(addr) == 40:
            addr = decode_hex(addr)
        assert len(addr) == 20
        block.set_balance(addr, parse_int_or_hex(data['wei']))

    block.commit_state()
    block.state.db.commit()

    dev_addresses = [ContractHelper.dev_address(a) for a in dev_accounts]

    # deploy the gnt contract with updated developer accounts
    if deploy_contract:
        contract, _, _ = deploy_gnt(state,
                                    tester.accounts[9],
                                    start,
                                    end,
                                    replacements=[(dev_addresses,
                                                   DEV_ADDR_REGEX)])
        alloc_addr = mk_contract_address(contract.address, 0)
        allocation = tester.ABIContract(state, ALLOC_ABI, alloc_addr)
    else:
        contract, allocation = None, None

    return contract, allocation, dev_keys, dev_accounts
Example #49
0
    def __init__(self, app):
        log.info('PeerManager init')
        WiredService.__init__(self, app)
        self.peers = []
        self.errors = PeerErrors() if self.config['log_disconnects'] else PeerErrorsBase()

        # setup nodeid based on privkey
        if 'id' not in self.config['p2p']:
            self.config['node']['id'] = crypto.privtopub(
                decode_hex(self.config['node']['privkey_hex']))

        self.listen_addr = (self.config['p2p']['listen_host'], self.config['p2p']['listen_port'])
        self.server = StreamServer(self.listen_addr, handle=self._on_new_connection)
Example #50
0
    def _set_acct_item(self, address, param, value):
        """Set a specific parameter of a specific account.

        :param address: the address of the account (binary or hex string)
        :param param: the requested parameter (`'nonce'`, `'balance'`,
                      `'storage'` or `'code'`)
        :param value: the new value
        """
        if len(address) == 40:
            address = decode_hex(address)
        assert len(address) == 20
        self.set_and_journal(param, address, value)
        self.set_and_journal('all', address, True)
Example #51
0
def normalize_address(x, allow_blank=False):
    if allow_blank and x == '':
        return ''
    if len(x) in (42, 50) and x[:2] == '0x':
        x = x[2:]
    if len(x) in (40, 48):
        x = decode_hex(x)
    if len(x) == 24:
        assert len(x) == 24 and sha3(x[:20])[:4] == x[-4:]
        x = x[:20]
    if len(x) != 20:
        raise Exception("Invalid address format: %r" % x)
    return x
Example #52
0
def normalize_address(x, allow_blank=False):
    if allow_blank and (x is None or x == ''):
        return ''
    if len(x) in (42, 50) and x[:2] == '0x':
        x = x[2:]
    if len(x) in (40, 48):
        x = decode_hex(x)
    if len(x) == 24:
        assert len(x) == 24 and sha3(x[:20])[:4] == x[-4:]
        x = x[:20]
    if len(x) != 20:
        raise Exception("Invalid address format: %r" % x)
    return x
Example #53
0
 def __init__(self, keystore, password=None, path=None):
     self.keystore = keystore
     try:
         self._address = decode_hex(self.keystore['address'])
     except KeyError:
         self._address = None
     self.locked = True
     if password is not None:
         self.unlock(password)
     if path is not None:
         self.path = os.path.abspath(path)
     else:
         self.path = None
Example #54
0
 def address(self):
     """The account's address or `None` if the address is not stored in the key file and cannot
     be reconstructed (because the account is locked)
     """
     if self._address:
         pass
     elif 'address' in self.keystore:
         self._address = decode_hex(self.keystore['address'])
     elif not self.locked:
         self._address = keys.privtoaddr(self.privkey)
     else:
         return None
     return self._address
Example #55
0
    def find(self, identifier):
        """Find an account by either its address, its id or its index as string.

        Example identifiers:

        - '9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address)
        - '0x9c0e0240776cfbe6fa1eb37e57721e1a88a563d1' (address with 0x prefix)
        - '01dd527b-f4a5-4b3c-9abb-6a8e7cd6722f' (UUID)
        - '3' (index)

        :param identifier: the accounts hex encoded, case insensitive address (with optional 0x
                           prefix), its UUID or its index (as string, >= 1) in
                           `account_service.accounts`
        :raises: :exc:`ValueError` if the identifier could not be interpreted
        :raises: :exc:`KeyError` if the identified account is not known to the account_service
        """
        try:
            uuid = UUID(identifier)
        except ValueError:
            pass
        else:
            return self.get_by_id(uuid.hex)

        try:
            index = int(identifier, 10)
        except ValueError:
            pass
        else:
            if index <= 0:
                raise ValueError('Index must be 1 or greater')
            try:
                return self.accounts[index - 1]
            except IndexError as e:
                raise KeyError(e.message)

        if identifier[:2] == '0x':
            identifier = identifier[2:]
        try:
            address = decode_hex(identifier)
        except TypeError:
            success = False
        else:
            if len(address) != 20:
                success = False
            else:
                return self[address]

        assert not success
        raise ValueError('Could not interpret account identifier')
Example #56
0
    def _get_logs(self, topics, event_name=None):
        """
        Get logs (events).

        topics: a list of topics to search for.
        event_name: the name of the event.
        """
        # Set the event topic to the event ID if the event name is specified.
        if event_name is None:
            event_topic = None
        else:
            event_topic = self._get_event_id_by_name(event_name)

        # Prepent the event type to the topics.
        topics = [event_topic] + topics
        # Encode topics to be sent to the Ethereum client.
        topics = [encode_api_data(topic, padding=32) for topic in topics]

        # Get logs from Ethereum client.
        logs = ethclient.get_logs(
            from_block='earliest',
            address=self.address,
            topics=topics,
        )

        # Decode logs using the contract ABI.
        decoded_logs = []
        for log in logs:
            logobj = processblock.Log(log['address'][2:], [
                big_endian_to_int(decode_hex(topic[2:]))
                for topic in log['topics']
            ], decode_hex(log['data'][2:]))
            decoded_log = self._contracttranslator.listen(logobj, noprint=True)
            decoded_logs.append(decoded_log)

        return decoded_logs
Example #57
0
def normalize_address(x, allow_blank=False):
    if is_numeric(x):
        return int_to_addr(x)
    if allow_blank and x in {'', b''}:
        return b''
    if len(x) in (42, 50) and x[:2] in {'0x', b'0x'}:
        x = x[2:]
    if len(x) in (40, 48):
        x = decode_hex(x)
    if len(x) == 24:
        assert len(x) == 24 and sha3(x[:20])[:4] == x[-4:]
        x = x[:20]
    if len(x) != 20:
        raise Exception("Invalid address format: %r" % x)
    return x
Example #58
0
def decode_keystore_json(jsondata, pw):
    # Get KDF function and parameters
    if "crypto" in jsondata:
        cryptdata = jsondata["crypto"]
    elif "Crypto" in jsondata:
        cryptdata = jsondata["Crypto"]
    else:
        raise Exception("JSON data must contain \"crypto\" object")
    kdfparams = cryptdata["kdfparams"]
    kdf = cryptdata["kdf"]
    if cryptdata["kdf"] not in kdfs:
        raise Exception("Hash algo %s not supported" % kdf)
    kdfeval = kdfs[kdf]["calc"]
    # Get cipher and parameters
    cipherparams = cryptdata["cipherparams"]
    cipher = cryptdata["cipher"]
    if cryptdata["cipher"] not in ciphers:
        raise Exception("Encryption algo %s not supported" % cipher)
    decrypt = ciphers[cipher]["decrypt"]
    # Compute the derived key
    derivedkey = kdfeval(pw, kdfparams)
    assert len(derivedkey) >= 32, \
        "Derived key must be at least 32 bytes long"
    # print(b'derivedkey: ' + encode_hex(derivedkey))
    enckey = derivedkey[:16]
    # print(b'enckey: ' + encode_hex(enckey))
    ctext = decode_hex(cryptdata["ciphertext"])
    # Decrypt the ciphertext
    o = decrypt(ctext, enckey, cipherparams)
    # Compare the provided MAC with a locally computed MAC
    # print(b'macdata: ' + encode_hex(derivedkey[16:32] + ctext))
    mac1 = sha3(derivedkey[16:32] + ctext)
    mac2 = decode_hex(cryptdata["mac"])
    if mac1 != mac2:
        raise ValueError("MAC mismatch. Password incorrect?")
    return o
Example #59
0
def solidity_resolve_address(hex_code, library_symbol, library_address):
    """ Change the bytecode to use the given library address.

    Args:
        hex_code (bin): The bytecode encoded in hexadecimal.
        library_name (str): The library that will be resolved.
        library_address (str): The address of the library.

    Returns:
        bin: The bytecode encoded in hexadecimal with the library references
            resolved.
    """
    if library_address.startswith('0x'):
        raise ValueError('Address should not contain the 0x prefix')

    try:
        decode_hex(library_address)
    except TypeError:
        raise ValueError('library_address contains invalid characters, it must be hex encoded.')

    if len(library_symbol) != 40 or len(library_address) != 40:
        raise ValueError('Address with wrong length')

    return hex_code.replace(library_symbol, library_address)