コード例 #1
0
def sign_block(block, key, randao_parent, vchash, skips):
    block.header.extra_data = \
        randao_parent + \
        utils.zpad(utils.encode_int(skips), 32) + \
        vchash
    for val in utils.ecsign(block.header.signing_hash, key):
        block.header.extra_data += utils.zpad(utils.encode_int(val), 32)
    return block
コード例 #2
0
    def run(self, sender=None, to=None, code=None, gas=None):
        sender = normalize_address(sender) if sender else normalize_address(zpad('sender', 20))
        to = normalize_address(to) if to else normalize_address(zpad('receiver', 20))
        code = scan_bin(code) if code else ''
        gas = scan_int(gas) if gas else 10000000000000

        msg = vm.Message(sender, to, gas=gas)
        ext = VMExt(self.state, Transaction(0, 0, 21000, b'', 0, b''))

        result, gas_remained, data = _apply_msg(ext, msg, code)
        return bytearray_to_bytestr(data) if result else None
コード例 #3
0
def test_block_18315_changes():
    pre = {}
    toadd = [
        [
            '0x0000000000000000000000000000000000000000000000000000000000000000',
            '0xf9e88bc2b3203e764fe67b4d0f4171b7756117c8'
        ],
        [
            '0x0000000000000000000000000000000000000000000000000000000000000001',
            '0x'
        ],
        [
            '0x0000000000000000000000000000000000000000000000000000000000000002',
            '0x'
        ],
    ]
    db = RefcountDB(EphemDB())
    db.logging = True
    NODES = 60
    t1 = pruning_trie.Trie(db)
    t2 = pruning_trie.Trie(db)
    db.ttl = NODES * 2
    c = 0
    for k, v in pre.items():
        triekey = utils.sha3(utils.zpad(k[2:].decode('hex'), 32))
        t1.update(triekey, rlp.encode(v[2:].decode('hex')))
        t2.update(triekey, rlp.encode(v[2:].decode('hex')))
        db.commit_refcount_changes(c)
        db.cleanup(c)
        c += 1
    sys.stderr.write('##############################\n')
    print(utils.encode_hex(t1.root_hash))
    print(t1.to_dict())
    for k, v in toadd:
        sys.stderr.write('kv: %s %s\n' % (k, v))
        triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32))
        if v == '0x':
            t1.delete(triekey)
        else:
            t1.update(triekey, rlp.encode(utils.decode_hex(v[2:])))
        db.commit_refcount_changes(c)
        db.cleanup(c)
        c += 1
    t1.clear_all()
    db.commit_refcount_changes(c)
    for i in range(db.ttl + 1):
        db.cleanup(c)
        c += 1
    t3 = pruning_trie.Trie(db)
    t3.root_hash = t2.root_hash
    print(t3.to_dict())
コード例 #4
0
def load_state(env, alloc):
    db = env.db
    state = SecureTrie(Trie(db, BLANK_ROOT))
    count = 0
    print("Start loading state from snapshot")
    for addr in alloc:
        print("[%d] loading account %s" % (count, addr))
        account = alloc[addr]
        acct = Account.blank_account(db, env.config['ACCOUNT_INITIAL_NONCE'])
        if len(account['storage']) > 0:
            t = SecureTrie(Trie(db, BLANK_ROOT))
            c = 0
            for k in account['storage']:
                v = account['storage'][k]
                enckey = zpad(decode_hex(k), 32)
                t.update(enckey, decode_hex(v))
                c += 1
                if c % 1000 and len(db.db_service.uncommitted) > 50000:
                    print("%d uncommitted. committing..." %
                          len(db.db_service.uncommitted))
                    db.commit()
            acct.storage = t.root_hash
        if account['nonce']:
            acct.nonce = int(account['nonce'])
        if account['balance']:
            acct.balance = int(account['balance'])
        if account['code']:
            acct.code = decode_hex(account['code'])
        state.update(decode_hex(addr), rlp.encode(acct))
        count += 1
    db.commit()
    return state
コード例 #5
0
def mine(block_number, difficulty, mining_hash, start_nonce=0, rounds=1000):
    assert utils.is_numeric(start_nonce)
    cache = get_cache(block_number)
    nonce = start_nonce
    target = utils.zpad(
        utils.int_to_big_endian(2**256 // (difficulty or 1) - 1), 32)
    for i in range(1, rounds + 1):
        bin_nonce = utils.zpad(utils.int_to_big_endian((nonce + i) & TT64M1),
                               8)
        o = hashimoto_light(block_number, cache, mining_hash, bin_nonce)
        if o[b'result'] <= target:
            log.debug('nonce found: {}'.format(bin_nonce))
            assert len(bin_nonce) == 8
            assert len(o[b'mix digest']) == 32
            return bin_nonce, o[b'mix digest']
    return None, None
コード例 #6
0
    def decode_event(self, log_topics, log_data):
        """ Return a dictionary representation the log.

        Note:
            This function won't work with anonymous events.

        Args:
            log_topics (List[bin]): The log's indexed arguments.
            log_data (bin): The encoded non-indexed arguments.
        """
        # https://github.com/biblecoin/wiki/wiki/Biblecoin-Contract-ABI#function-selector-and-argument-encoding

        # topics[0]: keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")
        # If the event is declared as anonymous the topics[0] is not generated;
        if not len(log_topics) or log_topics[0] not in self.event_data:
            raise ValueError('Unknown log type')

        event_id_ = log_topics[0]

        event = self.event_data[event_id_]

        # data: abi_serialise(EVENT_NON_INDEXED_ARGS)
        # EVENT_NON_INDEXED_ARGS is the series of EVENT_ARGS that are not
        # indexed, abi_serialise is the ABI serialisation function used for
        # returning a series of typed values from a function.
        unindexed_types = [
            type_
            for type_, indexed in zip(event['types'], event['indexed'])
            if not indexed
        ]
        unindexed_args = decode_abi(unindexed_types, log_data)

        # topics[n]: EVENT_INDEXED_ARGS[n - 1]
        # EVENT_INDEXED_ARGS is the series of EVENT_ARGS that are indexed
        indexed_count = 1  # skip topics[0]

        result = {}
        for name, type_, indexed in zip(
                event['names'], event['types'], event['indexed']):
            if indexed:
                topic_bytes = utils.zpad(
                    utils.encode_int(log_topics[indexed_count]),
                    32,
                )
                indexed_count += 1
                value = decode_single(process_type(type_), topic_bytes)
            else:
                value = unindexed_args.pop(0)

            result[name] = value
        result['_event_type'] = utils.to_string(event['name'])

        return result
コード例 #7
0
def test_transaction(filename, testname, 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_homestead()
        assert config_fork_specific_validation(konfig, blknum, tx)
        assert tx.startgas >= tx.intrinsic_gas_used
        if tx.sender == null_address:
            assert tx.value == 0 and tx.gasprice == 0 and tx.nonce == 0
        o["sender"] = tx.sender
        o["transaction"] = {
            "data": '0x' * (len(tx.data) > 0) + encode_hex(tx.data),
            "gasLimit": str(tx.startgas),
            "gasPrice": str(tx.gasprice),
            "nonce": str(tx.nonce),
            "r":
            '0x' + encode_hex(utils.zpad(utils.int_to_big_endian(tx.r), 32)),
            "s":
            '0x' + encode_hex(utils.zpad(utils.int_to_big_endian(tx.s), 32)),
            "v": str(tx.v),
            "value": 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
        # print(tx.to_dict(), testdata)
        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 str_to_bytes(encode_hex(o.get("sender", ''))) == str_to_bytes(
            testdata.get("sender", ''))
コード例 #8
0
def test_abi_encode_single_int():
    assert abi.encode_single(['int', '256', []], -2 **
                             255) == (b'\x80' + b'\x00' * 31)
    assert abi.encode_single(
        ['int', '256', []], (b'\x80' + b'\x00' * 31)) == (b'\x80' + b'\x00' * 31)

    assert abi.encode_single(['int', '8', []], -128)[-1:] == b'\x80'
    with pytest.raises(abi.ValueOutOfBounds):
        assert abi.encode_single(['int', '8', []], -129)

    assert abi.encode_single(['int', '8', []], 127) == zpad(b'\x7f', 32)
    with pytest.raises(abi.ValueOutOfBounds):
        assert abi.encode_single(['int', '8', []], 128)
コード例 #9
0
def test_block_18503_changes():
    pre = {'0x0c': '0x29d33c02a200937995e632c4597b4dca8e503978'}
    toadd = [
        ['0x', '0x09'],
    ]
    db = RefcountDB(EphemDB())
    db.logging = True
    NODES = 60
    t1 = pruning_trie.Trie(db)
    t2 = pruning_trie.Trie(db)
    db.ttl = NODES * 2
    c = 0
    for k, v in pre.items():
        triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32))
        t1.update(triekey, rlp.encode(utils.decode_hex(v[2:])))
        t2.update(triekey, rlp.encode(utils.decode_hex(v[2:])))
        db.commit_refcount_changes(c)
        db.cleanup(c)
        c += 1
    print(utils.encode_hex(t1.root_hash))
    for k, v in toadd:
        sys.stderr.write('kv: %s %s\n' % (k, v))
        triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32))
        if v == '0x':
            t1.delete(triekey)
        else:
            t1.update(triekey, rlp.encode(utils.decode_hex(v[2:])))
        db.commit_refcount_changes(c)
        db.cleanup(c)
        c += 1
    t1.clear_all()
    db.commit_refcount_changes(c)
    for i in range(db.ttl + 1):
        db.cleanup(c)
        c += 1
    t3 = pruning_trie.Trie(db)
    t3.root_hash = t2.root_hash
    print(t3.to_dict())
コード例 #10
0
def format_message(msg, kwargs, highlight, level):
    if 'memory' in kwargs:
        vm.log_vm_op.memory = '0x' + kwargs['memory']
    if 'storage' in kwargs:
        s = []
        storage = kwargs['storage']['storage']
        for k in sorted(storage.keys()):
            v = '0x' + encode_hex(zpad(int_to_big_endian(scan_int(storage[k])),32))
            k = '0x' + encode_hex(zpad(int_to_big_endian(scan_int(k)),32))
            s.append(k + ': ' + v)
        s = ','.join(s)
        vm.log_vm_op.storage = s

    return '{"pc":%s,"op":%s,"gas":"%s","gasCost":"%s","memory":"%s","stack":[%s],"storage":{%s},"depth":%s}' % (
        kwargs['pc'],
        kwargs['inst'],
        encode_int(int(kwargs['gas'])),
        encode_int(kwargs['gas_cost']),
        vm.log_vm_op.memory,
        ','.join(['"%s"' % encode_int(v) for v in kwargs['stack']]),
        vm.log_vm_op.storage,
        kwargs['depth']+1
    )
コード例 #11
0
    def encode_function_call(self, function_name, args):
        """ Return the encoded function call.

        Args:
            function_name (str): One of the existing functions described in the
                contract interface.
            args (List[object]): The function arguments that wll be encoded and
                used in the contract execution in the vm.

        Return:
            bin: The encoded function name and arguments so that it can be used
                 with the evm to execute a funcion call, the binary string follows
                 the Biblecoin Contract ABI.
        """
        if function_name not in self.function_data:
            raise ValueError('Unkown function {}'.format(function_name))

        description = self.function_data[function_name]

        function_selector = zpad(encode_int(description['prefix']), 4)
        arguments = encode_abi(description['encode_types'], args)

        return function_selector + arguments
コード例 #12
0
ファイル: specials.py プロジェクト: biblecoin/pybiblecoin
def proc_modexp(ext, msg):
    if not ext.post_metropolis_hardfork():
        return 1, msg.gas, []
    print('modexp proc', msg.gas)
    baselen = msg.data.extract32(0)
    explen = msg.data.extract32(32)
    modlen = msg.data.extract32(64)
    first_exp_bytes = msg.data.extract32(96 + baselen) >> (8 *
                                                           max(32 - explen, 0))
    bitlength = -1
    while first_exp_bytes:
        bitlength += 1
        first_exp_bytes >>= 1
    adjusted_explen = max(bitlength, 0) + 8 * max(explen - 32, 0)
    gas_cost = (mult_complexity(max(modlen, baselen)) *
                max(adjusted_explen, 1)) // opcodes.GMODEXPQUADDIVISOR
    print(baselen, explen, modlen, 'expected gas cost', gas_cost)
    if msg.gas < gas_cost:
        return 0, 0, []
    if baselen == 0:
        return 1, msg.gas - gas_cost, [0] * modlen
    if modlen == 0:
        return 1, msg.gas - gas_cost, []
    base = bytearray(baselen)
    msg.data.extract_copy(base, 0, 96, baselen)
    exp = bytearray(explen)
    msg.data.extract_copy(exp, 0, 96 + baselen, explen)
    mod = bytearray(modlen)
    msg.data.extract_copy(mod, 0, 96 + baselen + explen, modlen)
    if utils.big_endian_to_int(mod) == 0:
        return 1, msg.gas - gas_cost, [0] * modlen
    o = pow(utils.big_endian_to_int(base), utils.big_endian_to_int(exp),
            utils.big_endian_to_int(mod))
    return 1, msg.gas - \
        gas_cost, [
            safe_ord(x) for x in utils.zpad(
                utils.int_to_big_endian(o), modlen)]
コード例 #13
0
def encode_hex_from_int(x):
    return encode_hex(utils.zpad(utils.int_to_big_endian(x), 256))
コード例 #14
0
ファイル: bloom.py プロジェクト: biblecoin/pybiblecoin
def b64(int_bloom):
    "returns b256"
    return utils.zpad(utils.int_to_big_endian(int_bloom), 256)
コード例 #15
0
def test_mcopy2():
    c = tester.Chain()
    contract = c.contract(mcopy_code_2, language='serpent')
    assert contract.mcopy_test() == \
        b''.join([utils.zpad(utils.int_to_big_endian(x), 32)
                  for x in [99, 111, 119]])
コード例 #16
0
ファイル: db.py プロジェクト: biblecoin/pybiblecoin
def sub1(b):
    v = utils.big_endian_to_int(b)
    return utils.zpad(utils.encode_int(v - 1), 4)
コード例 #17
0
def encode_single(typ, arg):  # pylint: disable=too-many-return-statements,too-many-branches,too-many-statements,too-many-locals
    """ Encode `arg` as `typ`.

    `arg` will be encoded in a best effort manner, were necessary the function
    will try to correctly define the underlying binary representation (ie.
    decoding a hex-encoded address/hash).

    Args:
        typ (Tuple[(str, int, list)]): A 3-tuple defining the `arg` type.

            The first element defines the type name.
            The second element defines the type length in bits.
            The third element defines if it's an array type.

            Together the first and second defines the elementary type, the third
            element must be present but is ignored.

            Valid type names are:
                - uint
                - int
                - bool
                - ufixed
                - fixed
                - string
                - bytes
                - hash
                - address

        arg (object): The object to be encoded, it must be a python object
            compatible with the `typ`.

    Raises:
        ValueError: when an invalid `typ` is supplied.
        ValueOutOfBounds: when `arg` cannot be encoded as `typ` because of the
            binary contraints.

    Note:
        This function don't work with array types, for that use the `enc`
        function.
    """
    base, sub, _ = typ

    if base == 'uint':
        sub = int(sub)

        if not (0 < sub <= 256 and sub % 8 == 0):
            raise ValueError(
                'invalid unsigned integer bit length {}'.format(sub))

        try:
            i = decint(arg, signed=False)
        except EncodingError:
            # arg is larger than 2**256
            raise ValueOutOfBounds(repr(arg))

        if not 0 <= i < 2 ** sub:
            raise ValueOutOfBounds(repr(arg))

        value_encoded = int_to_big_endian(i)
        return zpad(value_encoded, 32)

    if base == 'int':
        sub = int(sub)
        bits = sub - 1

        if not (0 < sub <= 256 and sub % 8 == 0):
            raise ValueError('invalid integer bit length {}'.format(sub))

        try:
            i = decint(arg, signed=True)
        except EncodingError:
            # arg is larger than 2**255
            raise ValueOutOfBounds(repr(arg))

        if not -2 ** bits <= i < 2 ** bits:
            raise ValueOutOfBounds(repr(arg))

        value = i % 2 ** 256  # convert negative to "equivalent" positive
        value_encoded = int_to_big_endian(value)
        return zpad(value_encoded, 32)

    if base == 'bool':
        if arg is True:
            value_encoded = int_to_big_endian(1)
        elif arg is False:
            value_encoded = int_to_big_endian(0)
        else:
            raise ValueError('%r is not bool' % arg)

        return zpad(value_encoded, 32)

    if base == 'ufixed':
        sub = str(sub)  # pylint: disable=redefined-variable-type

        high_str, low_str = sub.split('x')
        high = int(high_str)
        low = int(low_str)

        if not (0 < high + low <= 256 and high % 8 == 0 and low % 8 == 0):
            raise ValueError('invalid unsigned fixed length {}'.format(sub))

        if not 0 <= arg < 2 ** high:
            raise ValueOutOfBounds(repr(arg))

        float_point = arg * 2 ** low
        fixed_point = int(float_point)
        return zpad(int_to_big_endian(fixed_point), 32)

    if base == 'fixed':
        sub = str(sub)  # pylint: disable=redefined-variable-type

        high_str, low_str = sub.split('x')
        high = int(high_str)
        low = int(low_str)
        bits = high - 1

        if not (0 < high + low <= 256 and high % 8 == 0 and low % 8 == 0):
            raise ValueError('invalid unsigned fixed length {}'.format(sub))

        if not -2 ** bits <= arg < 2 ** bits:
            raise ValueOutOfBounds(repr(arg))

        float_point = arg * 2 ** low
        fixed_point = int(float_point)
        value = fixed_point % 2 ** 256
        return zpad(int_to_big_endian(value), 32)

    # Decimals
    if base == 'decimal':
        val_to_encode = int(arg * 10**int(sub))
        return zpad(encode_int(val_to_encode % 2**256), 32)

    if base == 'string':
        if isinstance(arg, utils.unicode):
            arg = arg.encode('utf8')
        else:
            try:
                arg.decode('utf8')
            except UnicodeDecodeError:
                raise ValueError('string must be utf8 encoded')

        if len(sub):  # fixed length
            if not 0 <= len(arg) <= int(sub):
                raise ValueError('invalid string length {}'.format(sub))

            if not 0 <= int(sub) <= 32:
                raise ValueError('invalid string length {}'.format(sub))

            return rzpad(arg, 32)

        if not 0 <= len(arg) < TT256:
            raise Exception('Integer invalid or out of range: %r' % arg)

        length_encoded = zpad(int_to_big_endian(len(arg)), 32)
        value_encoded = rzpad(arg, utils.ceil32(len(arg)))

        return length_encoded + value_encoded

    if base == 'bytes':
        if not is_string(arg):
            if isinstance(arg, str):
                arg = bytes(arg, 'utf8')
            else:
                raise EncodingError('Expecting string: %r' % arg)

        arg = utils.to_string(arg)  # py2: force unicode into str

        if len(sub):  # fixed length
            if not 0 <= len(arg) <= int(sub):
                raise ValueError('string must be utf8 encoded')

            if not 0 <= int(sub) <= 32:
                raise ValueError('string must be utf8 encoded')

            return rzpad(arg, 32)

        if not 0 <= len(arg) < TT256:
            raise Exception('Integer invalid or out of range: %r' % arg)

        length_encoded = zpad(int_to_big_endian(len(arg)), 32)
        value_encoded = rzpad(arg, utils.ceil32(len(arg)))

        return length_encoded + value_encoded

    if base == 'hash':
        if not (int(sub) and int(sub) <= 32):
            raise EncodingError('too long: %r' % arg)

        if is_numeric(arg):
            return zpad(encode_int(arg), 32)

        if len(arg) == int(sub):
            return zpad(arg, 32)

        if len(arg) == int(sub) * 2:
            return zpad(decode_hex(arg), 32)

        raise EncodingError('Could not parse hash: %r' % arg)

    if base == 'address':
        assert sub == ''

        if is_numeric(arg):
            return zpad(encode_int(arg), 32)

        if len(arg) == 20:
            return zpad(arg, 32)

        if len(arg) == 40:
            return zpad(decode_hex(arg), 32)

        if len(arg) == 42 and arg[:2] == '0x':
            return zpad(decode_hex(arg[2:]), 32)

        raise EncodingError('Could not parse address: %r' % arg)
    raise EncodingError('Unhandled type: %r %r' % (base, sub))
コード例 #18
0
ファイル: db.py プロジェクト: biblecoin/pybiblecoin
def add1(b):
    v = utils.big_endian_to_int(b)
    return utils.zpad(utils.encode_int(v + 1), 4)
コード例 #19
0
ファイル: config.py プロジェクト: biblecoin/pybiblecoin
from rlp.utils import decode_hex

from biblecoin import utils
from biblecoin.db import BaseDB, EphemDB
from biblecoin.child_dao_list import L as child_dao_list
import copy

default_config = dict(
    # Genesis block difficulty
    GENESIS_DIFFICULTY=131072,
    # Genesis block gas limit
    GENESIS_GAS_LIMIT=3141592,
    # Genesis block prevhash, coinbase, nonce
    GENESIS_PREVHASH=b'\x00' * 32,
    GENESIS_COINBASE=b'\x00' * 20,
    GENESIS_NONCE=utils.zpad(utils.encode_int(42), 8),
    GENESIS_MIXHASH=b'\x00' * 32,
    GENESIS_TIMESTAMP=0,
    GENESIS_EXTRA_DATA=b'',
    GENESIS_INITIAL_ALLOC={},
    # Minimum gas limit
    MIN_GAS_LIMIT=5000,
    MAX_GAS_LIMIT=2**63 - 1,
    # Gas limit adjustment algo:
    # block.gas_limit=block.parent.gas_limit * 1023/1024 +
    #                   (block.gas_used * 6 / 5) / 1024
    GASLIMIT_EMA_FACTOR=1024,
    GASLIMIT_ADJMAX_FACTOR=1024,
    BLOCK_GAS_LIMIT=4712388,
    BLKLIM_FACTOR_NOM=3,
    BLKLIM_FACTOR_DEN=2,