Exemplo n.º 1
0
    def test_reveal_returns_entropy(self):
        assert self.c.commit(1, self.COW_HASH, value=self.DEPOSIT_COST) == [1]
        assert self.c.request_entropy(sender=tester.k1,
                                      value=self.ENTROPY_COST) == [0, 4]
        assert self.c.get_block(self.s.block.number + 1) == [0, 1, 0, 1]

        self.s.mine(2)

        COW_SEED = utils.big_endian_to_int(
            utils.sha3(
                utils.sha3(utils.zpad('cow', 32)) + utils.zpad('cow', 32)))
        COW_HASH_1 = utils.big_endian_to_int(
            utils.sha3(utils.int_to_big_endian(COW_SEED)))

        balance = self.s.block.get_balance(tester.a0)
        assert self.c.reveal(1, self.COW_INT) == [1]
        assert self.s.block.get_balance(
            tester.a0
        ) - balance == self.DEPOSIT_COST + self.ENTROPY_COST  # deposit return + payout of committer share

        assert self.c.get_block(1) == [COW_SEED, 1, 1, 1]

        # signed vs unsigned as introduced by tester.send
        assert self.c.get_entropy_ticket(0) == [
            int(tester.a1, 16), 1, 1, COW_HASH_1 - 2**256
        ]
        assert self.c.get_entropy(
            0, sender=tester.k1) == [1, COW_HASH_1 - 2**256]  # ready
Exemplo n.º 2
0
def test_genesis_hash():
    set_db()
    genesis = blocks.genesis()
    """
    cpp: https://github.com/ethereum/cpp-ethereum/libethereum/BlockInfo.cpp#L64
    h256() << sha3EmptyList << h160() << stateRoot << h256() << c_genesisDifficulty << 0 << 0 << 1000000 << 0 << (uint)0 << string() << sha3(bytes(1, 42));

    PoC5 etherpad: https://ethereum.etherpad.mozilla.org/11
    Genesis block is: ( B32(0, 0, ...), B32(sha3(B())), B20(0, 0, ...), B32(stateRoot), B32(0, 0, ...), P(2^22), P(0), P(0), P(1000000), P(0), P(0) << B() << B32(sha3(B(42))) )

    Genesis hash: 69a7356a245f9dc5b865475ada5ee4e89b18f93c06503a9db3b3630e88e9fb4e

    YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
    0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (), SHA3(42), (), ()

    Where 0256 refers to the parent and state and transaction root hashes, 
    a 256-bit hash which is all zeroes; 
    0160 refers to the coinbase address, 
    a 160-bit hash which is all zeroes; 
    2**22 refers to the difficulty; 
    0 refers to the timestamp (the Unix epoch); 
    () refers to the extradata and the sequences of both uncles and transactions, all empty. 
    SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
    and only byte is of value 42. 
    SHA3RLP() values refer to the hashes of the transaction and uncle lists in RLP, 
    both empty.
    The proof-of-concept series include a development premine, making the state root 
    hash some value stateRoot. The latest documentation should be consulted for 
    the value of the state root.
    """

    h256 = "\x00" * 32
    sr = CPP_PoC5_GENESIS_STATE_ROOT_HEX_HASH.decode('hex')
    genisi_block_defaults = [
        ["prevhash", "bin", h256],  # h256()
        ["uncles_hash", "bin",
         utils.sha3(rlp.encode([]))],  # sha3EmptyList
        ["coinbase", "addr", "0" * 40],  # h160()
        ["state_root", "trie_root", sr],  # stateRoot
        ["tx_list_root", "trie_root", h256],  # h256()
        ["difficulty", "int", 2**22],  # c_genesisDifficulty
        ["number", "int", 0],  # 0
        ["min_gas_price", "int", 0],  # 0
        ["gas_limit", "int", 1000000],  # 1000000
        ["gas_used", "int", 0],  # 0
        ["timestamp", "int", 0],  # 0
        ["extra_data", "bin", ""],  # ""
        ["nonce", "bin", utils.sha3(chr(42))],  # sha3(bytes(1, 42));
    ]

    cpp_genesis_block = rlp.decode(CPP_PoC5_GENESIS_HEX.decode('hex'))
    cpp_genesis_header = cpp_genesis_block[0]

    for i, (name, typ, genesis_default) in enumerate(genisi_block_defaults):
        # print name, repr(getattr(genesis, name)),  repr(genesis_default)
        assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
        assert getattr(genesis, name) == genesis_default
    assert genesis.hex_hash() == CPP_PoC5_GENESIS_HEX_HASH
Exemplo n.º 3
0
def test_genesis_hash(genesis_fixture):
    set_db()
    genesis = blocks.genesis()
    """
    YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
    0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (),
    SHA3(42), (), ()

    Where 0256 refers to the parent and state and transaction root hashes,
    a 256-bit hash which is all zeroes;
    0160 refers to the coinbase address,
    a 160-bit hash which is all zeroes;
    2**22 refers to the difficulty;
    0 refers to the timestamp (the Unix epoch);
    () refers to the extradata and the sequences of both uncles and
    transactions, all empty.
    SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
    and only byte is of value 42.
    SHA3RLP() values refer to the hashes of the transaction and uncle lists
    in RLP
    both empty.
    The proof-of-concept series include a development premine, making the state
    root hash some value stateRoot. The latest documentation should be
    consulted for the value of the state root.
    """

    h256 = '\00' * 32
    sr = genesis_fixture['genesis_state_root'].decode('hex')
    genesis_block_defaults = [
        ["prevhash", "bin", h256],  # h256()
        ["uncles_hash", "bin", utils.sha3(rlp.encode([]))],  # sha3EmptyList
        ["coinbase", "addr", "0" * 40],  # h160()
        ["state_root", "trie_root", sr],  # stateRoot
        ["tx_list_root", "trie_root", trie.BLANK_ROOT],  # h256()
        ["difficulty", "int", 2 ** 22],  # c_genesisDifficulty
        ["number", "int", 0],  # 0
        ["min_gas_price", "int", 0],  # 0
        ["gas_limit", "int", 10 ** 6],  # 10**6 for genesis
        ["gas_used", "int", 0],  # 0
        ["timestamp", "int", 0],  # 0
        ["extra_data", "bin", ""],  # ""
        ["nonce", "bin", utils.sha3(chr(42))],  # sha3(bytes(1, 42));
    ]

    cpp_genesis_block = rlp.decode(
        genesis_fixture['genesis_rlp_hex'].decode('hex'))
    cpp_genesis_header = cpp_genesis_block[0]

    for i, (name, typ, genesis_default) in enumerate(genesis_block_defaults):
        assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
        assert getattr(genesis, name) == genesis_default

    assert genesis.hex_hash() == genesis_fixture['genesis_hash']

    assert genesis.hex_hash() == utils.sha3(
        genesis_fixture['genesis_rlp_hex'].decode('hex')
    ).encode('hex')
Exemplo n.º 4
0
def test_genesis_hash(genesis_fixture):
    set_db()
    genesis = blocks.genesis()
    """
    YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
    0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (),
    SHA3(42), (), ()

    Where 0256 refers to the parent and state and transaction root hashes,
    a 256-bit hash which is all zeroes;
    0160 refers to the coinbase address,
    a 160-bit hash which is all zeroes;
    2**22 refers to the difficulty;
    0 refers to the timestamp (the Unix epoch);
    () refers to the extradata and the sequences of both uncles and
    transactions, all empty.
    SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
    and only byte is of value 42.
    SHA3RLP() values refer to the hashes of the transaction and uncle lists
    in RLP
    both empty.
    The proof-of-concept series include a development premine, making the state
    root hash some value stateRoot. The latest documentation should be
    consulted for the value of the state root.
    """

    h256 = '\00' * 32
    sr = genesis_fixture['genesis_state_root'].decode('hex')
    genesis_block_defaults = [
        ["prevhash", "bin", h256],  # h256()
        ["uncles_hash", "bin",
         utils.sha3(rlp.encode([]))],  # sha3EmptyList
        ["coinbase", "addr", "0" * 40],  # h160()
        ["state_root", "trie_root", sr],  # stateRoot
        ["tx_list_root", "trie_root", trie.BLANK_ROOT],  # h256()
        ["difficulty", "int", 2**22],  # c_genesisDifficulty
        ["number", "int", 0],  # 0
        ["min_gas_price", "int", 0],  # 0
        ["gas_limit", "int", 10**6],  # 10**6 for genesis
        ["gas_used", "int", 0],  # 0
        ["timestamp", "int", 0],  # 0
        ["extra_data", "bin", ""],  # ""
        ["nonce", "bin", utils.sha3(chr(42))],  # sha3(bytes(1, 42));
    ]

    cpp_genesis_block = rlp.decode(
        genesis_fixture['genesis_rlp_hex'].decode('hex'))
    cpp_genesis_header = cpp_genesis_block[0]

    for i, (name, typ, genesis_default) in enumerate(genesis_block_defaults):
        assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
        assert getattr(genesis, name) == genesis_default

    assert genesis.hex_hash() == genesis_fixture['genesis_hash']

    assert genesis.hex_hash() == utils.sha3(
        genesis_fixture['genesis_rlp_hex'].decode('hex')).encode('hex')
Exemplo n.º 5
0
def test_genesis_hash():
    set_db()
    genesis = blocks.genesis()
    """
    cpp: https://github.com/ethereum/cpp-ethereum/libethereum/BlockInfo.cpp#L64
    h256() << sha3EmptyList << h160() << stateRoot << h256() << c_genesisDifficulty << 0 << 0 << 1000000 << 0 << (uint)0 << string() << sha3(bytes(1, 42));

    PoC5 etherpad: https://ethereum.etherpad.mozilla.org/11
    Genesis block is: ( B32(0, 0, ...), B32(sha3(B())), B20(0, 0, ...), B32(stateRoot), B32(0, 0, ...), P(2^22), P(0), P(0), P(1000000), P(0), P(0) << B() << B32(sha3(B(42))) )

    Genesis hash: 69a7356a245f9dc5b865475ada5ee4e89b18f93c06503a9db3b3630e88e9fb4e

    YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
    0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (), SHA3(42), (), ()

    Where 0256 refers to the parent and state and transaction root hashes, 
    a 256-bit hash which is all zeroes; 
    0160 refers to the coinbase address, 
    a 160-bit hash which is all zeroes; 
    2**22 refers to the difficulty; 
    0 refers to the timestamp (the Unix epoch); 
    () refers to the extradata and the sequences of both uncles and transactions, all empty. 
    SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
    and only byte is of value 42. 
    SHA3RLP() values refer to the hashes of the transaction and uncle lists in RLP, 
    both empty.
    The proof-of-concept series include a development premine, making the state root 
    hash some value stateRoot. The latest documentation should be consulted for 
    the value of the state root.
    """

    h256 = "\x00" * 32
    sr = CPP_PoC5_GENESIS_STATE_ROOT_HEX_HASH.decode('hex')
    genisi_block_defaults = [
        ["prevhash", "bin", h256],  # h256()
        ["uncles_hash", "bin", utils.sha3(rlp.encode([]))],  # sha3EmptyList
        ["coinbase", "addr", "0" * 40],  # h160()
        ["state_root", "trie_root", sr],  # stateRoot
        ["tx_list_root", "trie_root", h256],  # h256()
        ["difficulty", "int", 2 ** 22],  # c_genesisDifficulty
        ["number", "int", 0],  # 0
        ["min_gas_price", "int", 0],  # 0
        ["gas_limit", "int", 1000000],  # 1000000
        ["gas_used", "int", 0],  # 0
        ["timestamp", "int", 0],  # 0
        ["extra_data", "bin", ""],  # ""
        ["nonce", "bin", utils.sha3(chr(42))],  # sha3(bytes(1, 42));
    ]

    cpp_genesis_block = rlp.decode(CPP_PoC5_GENESIS_HEX.decode('hex'))
    cpp_genesis_header = cpp_genesis_block[0]

    for i, (name, typ, genesis_default) in enumerate(genisi_block_defaults):
        # print name, repr(getattr(genesis, name)),  repr(genesis_default)
        assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
        assert getattr(genesis, name) == genesis_default
    assert genesis.hex_hash() == CPP_PoC5_GENESIS_HEX_HASH
Exemplo n.º 6
0
def bad(n=21):
    # Build n levels
    t = trie.Trie(s.db)
    accum = ''
    for i in range(n):
        for j in range(1,16):
            k = accum + '%X'%j
            if len(k) % 2 != 0: k += '0'
            k = zpadr(k.decode('hex'))
            print k.encode('hex')
            t.update(k,utils.sha3('cow'))
        accum += '%X'%0
    k = zpadr(accum.decode('hex'))
    t.update(k,utils.sha3('cow'))
    return t
Exemplo n.º 7
0
def bad(n=21):
    # Build n levels
    t = trie.Trie(s.db)
    accum = ''
    for i in range(n):
        for j in range(1, 16):
            k = accum + '%X' % j
            if len(k) % 2 != 0: k += '0'
            k = zpadr(k.decode('hex'))
            print k.encode('hex')
            t.update(k, utils.sha3('cow'))
        accum += '%X' % 0
    k = zpadr(accum.decode('hex'))
    t.update(k, utils.sha3('cow'))
    return t
Exemplo n.º 8
0
def test_status():
    p = get_packeter()
    total_difficulty = 1000
    head_hash = utils.sha3('head')
    genesis_hash = utils.sha3('genesis')
    msg = p.dump_Status(total_difficulty, head_hash, genesis_hash)
    success, res = p.load_packet(msg)
    assert success
    _, _, cmd, data, remain = res
    assert cmd == 'Status'
    assert idec(data[0]) == packeter.Packeter.ETHEREUM_PROTOCOL_VERSION
    assert idec(data[1]) == packeter.Packeter.NETWORK_ID
    assert idec(data[2]) == total_difficulty
    assert data[3] == head_hash
    assert data[4] == genesis_hash
    return
Exemplo n.º 9
0
def create_default_config():
    config = ConfigParser.ConfigParser()
    # set some defaults, which may be overwritten
    config.add_section('network')
    config.set('network', 'listen_host', '0.0.0.0')
    config.set('network', 'listen_port', '30303')
    config.set('network', 'num_peers', '5')
    config.set('network', 'remote_port', '30303')
    config.set('network', 'remote_host', '')
    config.set('network', 'client_id', Packeter.CLIENT_ID)
    config.set('network', 'node_id', sha3(str(uuid.uuid1())).encode('hex'))

    config.add_section('api')
    config.set('api', 'listen_host', '127.0.0.1')
    config.set('api', 'listen_port', '30203')

    config.add_section('misc')
    config.set('misc', 'verbosity', '1')
    config.set('misc', 'config_file', None)
    config.set('misc', 'logging', None)
    config.set('misc', 'data_dir', data_dir.path)
    config.set('misc', 'mining', '10')

    config.add_section('wallet')
    config.set('wallet', 'coinbase', '0' * 40)

    return config
Exemplo n.º 10
0
    def before_feature(self, context, feature):
        '''
        .. note::

            `context.conf` is used instead of `context.config` because `config`
            is used internally in `context` by *behave*

        '''
        context.conf = conf = mock.MagicMock()
        node_id = sha3(str(uuid.uuid1())).encode('hex')
        tempdir = tempfile.mkdtemp()

        def get_side_effect(section, option):
            if section == 'network' and option == 'client_id':
                return 'client id'

            if section == 'network' and option == 'node_id':
                return node_id

            if section == 'wallet' and option == 'coinbase':
                return '0'*40

            if section == 'misc' and option == 'data_dir':
                return tempdir

        def getint_side_effect(section, option):
            if section == 'network' and option == 'listen_port':
                return 1234

            if section == 'network' and option == 'num_peers':
                return 10

        conf.get.side_effect = get_side_effect
        conf.getint.side_effect = getint_side_effect
Exemplo n.º 11
0
def test_status():
    p = get_packeter()
    total_difficulty = 1000
    head_hash = utils.sha3('head')
    genesis_hash = utils.sha3('genesis')
    msg = p.dump_Status(total_difficulty, head_hash, genesis_hash)
    success, res = p.load_packet(msg)
    assert success
    _, _, cmd, data, remain = res
    assert cmd == 'Status'
    assert idec(data[0]) == packeter.Packeter.ETHEREUM_PROTOCOL_VERSION
    assert idec(data[1]) == packeter.Packeter.NETWORK_ID
    assert idec(data[2]) == total_difficulty
    assert data[3] == head_hash
    assert data[4] == genesis_hash
    return
Exemplo n.º 12
0
def create_default_config():
    config = ConfigParser.ConfigParser()
    # set some defaults, which may be overwritten
    config.add_section('network')
    config.set('network', 'listen_host', '0.0.0.0')
    config.set('network', 'listen_port', '30303')
    config.set('network', 'num_peers', '5')
    config.set('network', 'remote_port', '30303')
    config.set('network', 'remote_host', '')
    config.set('network', 'client_id', Packeter.CLIENT_ID)
    config.set('network', 'node_id', sha3(str(uuid.uuid1())).encode('hex'))

    config.add_section('api')
    config.set('api', 'listen_host', '127.0.0.1')
    config.set('api', 'listen_port', '30203')

    config.add_section('misc')
    config.set('misc', 'verbosity', '1')
    config.set('misc', 'config_file', None)
    config.set('misc', 'logging', None)
    config.set('misc', 'data_dir', data_dir.path)
    config.set('misc', 'mining', '10')

    config.add_section('wallet')
    config.set('wallet', 'coinbase', '0' * 40)

    return config
Exemplo n.º 13
0
 def create_wrapper(msg):
     ext.set_balance(msg.sender, ext.get_balance(msg.sender) - msg.value)
     sender = msg.sender.decode('hex') if len(msg.sender) == 40 else msg.sender
     nonce = u.encode_int(ext._block.get_nonce(msg.sender))
     addr = u.sha3(rlp.encode([sender, nonce]))[12:].encode('hex')
     hexdata = msg.data.extract_all().encode('hex')
     apply_message_calls.append(dict(gasLimit=msg.gas, value=msg.value,
                                     destination='', data=hexdata))
     return 1, msg.gas, addr
Exemplo n.º 14
0
def _recv_Blocks(self, data):
    print("RECEIVED", len(data))
    for x in reversed(data):
        enc = rlp.encode(x)
        #tb = blocks.TransientBlock(enc)
        #print tb
        self.blk_counter += 1
        fh.write(enc.encode('hex') + '\n')  # LOG line
        h = utils.sha3(enc)
        print('received block %s %d' % (h.encode('hex'), self.blk_counter))
    request(self, h)
Exemplo n.º 15
0
def _recv_Blocks(self, data):
    print("RECEIVED", len(data))
    for x in reversed(data):
        enc = rlp.encode(x)
        #tb = blocks.TransientBlock(enc)
        #print tb
        self.blk_counter += 1
        fh.write(enc.encode('hex') + '\n') # LOG line
        h = utils.sha3(enc)
        print('received block %s %d' % (h.encode('hex'), self.blk_counter))
    request(self,h)
def push_content(content, title, genesis, root_contract, usr):
    key, addr = usr
    nonce = get_nonce(genesis, addr)
    content_hash = utils.sha3(content)
    # push a transaction with a title.  recover title from blockchain
    tx_push = transactions.Transaction(nonce, 0, 10**12, 10000, root_contract, serpent.encode_datalist([1, content_hash, title])).sign(key)
    ans = processblock.apply_tx(genesis, tx_push)

    f = open('data/%s'%content_hash.encode('hex'), 'w')
    f.write(content)
    f.close()

    return content_hash
Exemplo n.º 17
0
 def create_wrapper(msg):
     ext.set_balance(msg.sender, ext.get_balance(msg.sender) - msg.value)
     sender = msg.sender.decode('hex') if len(
         msg.sender) == 40 else msg.sender
     nonce = u.encode_int(ext._block.get_nonce(msg.sender))
     addr = u.sha3(rlp.encode([sender, nonce]))[12:].encode('hex')
     hexdata = msg.data.extract_all().encode('hex')
     apply_message_calls.append(
         dict(gasLimit=msg.gas,
              value=msg.value,
              destination='',
              data=hexdata))
     return 1, msg.gas, addr
Exemplo n.º 18
0
def deserialize_child(parent, rlpdata):
    """
    deserialization w/ replaying transactions
    """
    header_args, transaction_list, uncles = rlp.decode(rlpdata)
    assert len(header_args) == len(blocks.block_structure)
    kargs = dict(transaction_list=transaction_list, uncles=uncles)
    # Deserialize all properties
    for i, (name, typ, default) in enumerate(blocks.block_structure):
        kargs[name] = utils.decoders[typ](header_args[i])

    block = blocks.Block.init_from_parent(parent,
                                          kargs['coinbase'],
                                          extra_data=kargs['extra_data'],
                                          timestamp=kargs['timestamp'])
    block.finalize()  # this is the first potential state change
    # replay transactions
    for tx_lst_serialized, _state_root, _gas_used_encoded in transaction_list:

        tx = transactions.Transaction.create(tx_lst_serialized)
        logger.debug("data %r", tx.data)
        logger.debug('applying %r', tx)
        logger.debug('applying %r', tx.to_dict())
        logger.debug('block.gas_used before: %r', block.gas_used)
        success, output = processblock.apply_transaction(block, tx)
        logger.debug('block.gas_used after: %r', block.gas_used)
        logger.debug('success: %r', success)
        diff = utils.decode_int(_gas_used_encoded) - block.gas_used
        logger.debug("GAS_USED DIFF %r", diff)
        assert utils.decode_int(_gas_used_encoded) == block.gas_used
        assert _state_root.encode('hex') == block.state.root_hash.encode('hex')

    # checks
    assert block.prevhash == parent.hash
    assert block.tx_list_root == kargs['tx_list_root']
    assert block.gas_used == kargs['gas_used']
    assert block.gas_limit == kargs['gas_limit']
    assert block.timestamp == kargs['timestamp']
    assert block.difficulty == kargs['difficulty']
    assert block.number == kargs['number']
    assert block.extra_data == kargs['extra_data']
    assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash']
    assert block.state.root_hash.encode('hex') == kargs['state_root'].encode(
        'hex')

    block.uncles_hash = kargs['uncles_hash']
    block.nonce = kargs['nonce']
    block.min_gas_price = kargs['min_gas_price']

    return block
Exemplo n.º 19
0
def genesis_fixture():
    """
    Read genesis block from fixtures.
    """
    genesis_fixture = None
    with open('fixtures/genesishashestest.json', 'r') as f:
        genesis_fixture = json.load(f)
    assert genesis_fixture is not None, "Could not read genesishashtest.json from fixtures. Make sure you did 'git submodule init'!"
    # FIXME: assert that link is uptodate
    for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash', 'initial_alloc'):
        assert k in genesis_fixture
    assert utils.sha3(genesis_fixture['genesis_rlp_hex'].decode('hex')).encode('hex') ==\
        genesis_fixture['genesis_hash']
    return genesis_fixture
Exemplo n.º 20
0
def genesis_fixture():
    """
    Read genesis block from fixtures.
    """
    genesis_fixture = None
    with open('fixtures/genesishashestest.json', 'r') as f:
        genesis_fixture = json.load(f)
    assert genesis_fixture is not None, "Could not read genesishashtest.json from fixtures. Make sure you did 'git submodule init'!"
    # FIXME: assert that link is uptodate
    for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash', 'initial_alloc'):
        assert k in genesis_fixture
    assert utils.sha3(genesis_fixture['genesis_rlp_hex'].decode('hex')).encode('hex') ==\
        genesis_fixture['genesis_hash']
    return genesis_fixture
Exemplo n.º 21
0
def deserialize_child(parent, rlpdata):
    """
    deserialization w/ replaying transactions
    """
    header_args, transaction_list, uncles = rlp.decode(rlpdata)
    assert len(header_args) == len(blocks.block_structure)
    kargs = dict(transaction_list=transaction_list, uncles=uncles)
    # Deserialize all properties
    for i, (name, typ, default) in enumerate(blocks.block_structure):
        kargs[name] = utils.decoders[typ](header_args[i])

    block = blocks.Block.init_from_parent(parent, kargs['coinbase'],
                                          extra_data=kargs['extra_data'],
                                          timestamp=kargs['timestamp'])
    block.finalize()  # this is the first potential state change
    # replay transactions
    for tx_lst_serialized, _state_root, _gas_used_encoded in transaction_list:

        tx = transactions.Transaction.create(tx_lst_serialized)
        logger.debug("data %r", tx.data)
        logger.debug('applying %r', tx)
        logger.debug('applying %r', tx.to_dict())
        logger.debug('block.gas_used before: %r', block.gas_used)
        success, output = processblock.apply_transaction(block, tx)
        logger.debug('block.gas_used after: %r', block.gas_used)
        logger.debug('success: %r', success)
        diff = utils.decode_int(_gas_used_encoded) - block.gas_used
        logger.debug("GAS_USED DIFF %r", diff)
        assert utils.decode_int(_gas_used_encoded) == block.gas_used
        assert _state_root.encode('hex') == block.state.root_hash.encode('hex')

    # checks
    assert block.prevhash == parent.hash
    assert block.tx_list_root == kargs['tx_list_root']
    assert block.gas_used == kargs['gas_used']
    assert block.gas_limit == kargs['gas_limit']
    assert block.timestamp == kargs['timestamp']
    assert block.difficulty == kargs['difficulty']
    assert block.number == kargs['number']
    assert block.extra_data == kargs['extra_data']
    assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash']
    assert block.state.root_hash.encode(
        'hex') == kargs['state_root'].encode('hex')

    block.uncles_hash = kargs['uncles_hash']
    block.nonce = kargs['nonce']
    block.min_gas_price = kargs['min_gas_price']

    return block
Exemplo n.º 22
0
def push_content(content, title, genesis, root_contract, usr):
    key, addr = usr
    nonce = get_nonce(genesis, addr)
    content_hash = utils.sha3(content)
    # push a transaction with a title.  recover title from blockchain
    tx_push = transactions.Transaction(
        nonce, 0, 10**12, 10000, root_contract,
        serpent.encode_datalist([1, content_hash, title])).sign(key)
    ans = processblock.apply_tx(genesis, tx_push)

    f = open('data/%s' % content_hash.encode('hex'), 'w')
    f.write(content)
    f.close()

    return content_hash
Exemplo n.º 23
0
def _get_block_before_tx(txhash):
    tx, blk = chain_manager.index.get_transaction(txhash.decode('hex'))
    # get the state we had before this transaction
    test_blk = Block.init_from_parent(blk.get_parent(),
                                        blk.coinbase,
                                        extra_data=blk.extra_data,
                                        timestamp=blk.timestamp,
                                        uncles=blk.uncles)
    pre_state = test_blk.state_root
    for i in range(blk.transaction_count):
        tx_lst_serialized, sr, _ = blk.get_transaction(i)
        if utils.sha3(rlp.encode(tx_lst_serialized)) == tx.hash:
            break
        else:
            pre_state = sr
    test_blk.state.root_hash = pre_state
    return test_blk, tx
Exemplo n.º 24
0
def _get_block_before_tx(txhash):
    tx, blk, i = chain_manager.index.get_transaction(txhash.decode('hex'))
    # get the state we had before this transaction
    test_blk = Block.init_from_parent(blk.get_parent(),
                                      blk.coinbase,
                                      extra_data=blk.extra_data,
                                      timestamp=blk.timestamp,
                                      uncles=blk.uncles)
    pre_state = test_blk.state_root
    for i in range(blk.transaction_count):
        tx_lst_serialized, sr, _ = blk.get_transaction(i)
        if utils.sha3(rlp.encode(tx_lst_serialized)) == tx.hash:
            break
        else:
            pre_state = sr
    test_blk.state.root_hash = pre_state
    return test_blk, tx, i
Exemplo n.º 25
0
    def before_feature(self, context, feature):
        '''
        .. note::

            `context.conf` is used instead of `context.config` because `config`
            is used internally in `context` by *behave*

        '''
        context.conf = conf = mock.MagicMock()
        node_id = sha3(str(uuid.uuid1())).encode('hex')
        tempdir = tempfile.mkdtemp()

        def get_side_effect(section, option):
            if section == 'network' and option == 'client_id':
                return 'client id'

            if section == 'network' and option == 'listen_host':
                return '0.0.0.0'

            if section == 'network' and option == 'node_id':
                return node_id

            if section == 'wallet' and option == 'coinbase':
                return '0'*40

            if section == 'misc' and option == 'data_dir':
                return tempdir

        def getint_side_effect(section, option):
            if section == 'network' and option == 'listen_port':
                return 1234

            if section == 'network' and option == 'num_peers':
                return 10

        conf.get.side_effect = get_side_effect
        conf.getint.side_effect = getint_side_effect
Exemplo n.º 26
0
 def get_proposal_id(self, proposal):
     return big_endian_to_int(sha3(zpad(proposal, 32)))
Exemplo n.º 27
0
 def __init__(self, secret):
     self.key = utils.sha3(secret)
     self.address = utils.privtoaddr(self.key)
                                                     ) + [n % 256]

choice1 = 0x01
nonce1 = 0x01
ch1 = ''.join(map(chr, tobytearr(choice1, 32)))
no1 = ''.join(map(chr, tobytearr(nonce1, 32)))
print("Player one chooses {} which is: {}").format(choice1, choice[choice1])

k0_pub_addr_hex = utils.privtoaddr(tester.k0)

## Prepare and pad the address
k0_pub_addr = ''.join(map(chr, tobytearr(long(k0_pub_addr_hex, 16), 32)))

## Now use it for the commitment
s1 = ''.join([k0_pub_addr, ch1, no1])
comm1 = utils.sha3(s1)

choice2 = 0x02
nonce2 = 0x01
ch2 = ''.join(map(chr, tobytearr(choice2, 32)))
no2 = ''.join(map(chr, tobytearr(nonce2, 32)))
print("Player two chooses {} which is: {}\n").format(choice2, choice[choice2])

k1_pub_addr_hex = utils.privtoaddr(tester.k1)
#print(type(k1_pub_addr_hex))  ## This is an encoded hex string .. cannot be used directly

## Prepare and pad the address
k1_pub_addr = ''.join(map(chr, tobytearr(long(k1_pub_addr_hex, 16), 32)))

## Now use it for the commitment
s2 = ''.join([k1_pub_addr, ch2, no2])
Exemplo n.º 29
0
 def get_proposal_id(self, proposal):
     return big_endian_to_int(sha3(zpad(proposal, 32)))
Exemplo n.º 30
0
 def blkhash(n):
     if n >= ext.block_number or n < ext.block_number - 256:
         return ''
     else:
         return u.sha3(str(n))
Exemplo n.º 31
0
def step_impl(context):
    assert (context.ans == utils.sha3(context.msg))
Exemplo n.º 32
0
def step_impl(context):
    context.key = utils.sha3('cows')
    context.addr = utils.privtoaddr(context.key)
    context.gen = blocks.genesis({context.addr: 10**60})
Exemplo n.º 33
0
def hash_value(value):
    return utils.big_endian_to_int(utils.sha3(utils.zpad(value, 32)))
Exemplo n.º 34
0
def create_config():

    config = ConfigParser.ConfigParser()
    # set some defaults, which may be overwritten
    config.add_section('network')
    config.set('network', 'listen_host', '0.0.0.0')
    config.set('network', 'listen_port', '30303')
    config.set('network', 'num_peers', '5')
    config.set('network', 'remote_port', '30303')
    config.set('network', 'remote_host', '')
    config.set('network', 'client_id', Packeter.CLIENT_ID)
    config.set('network', 'node_id', sha3(str(uuid.uuid1())).encode('hex'))

    config.add_section('api')
    config.set('api', 'listen_host', '127.0.0.1')
    config.set('api', 'listen_port', '30203')

    config.add_section('misc')
    config.set('misc', 'verbosity', '1')
    config.set('misc', 'config_file', None)
    config.set('misc', 'logging', None)
    config.set('misc', 'data_dir', data_dir.path)
    config.set('misc', 'mining', '10')

    config.add_section('wallet')
    config.set('wallet', 'coinbase', '0' * 40)

    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage,  version=Packeter.CLIENT_ID)
    parser.add_option(
        "-l", "--listen",
        dest="listen_port",
        default=config.get('network', 'listen_port'),
        help="<port>  Listen on the given port for incoming"
        " connected (default: 30303).")
    parser.add_option(
        "-a", "--address",
        dest="coinbase",
        help="Set the coinbase (mining payout) address",
        default=config.get('wallet', 'coinbase'))
    parser.add_option(
        "-d", "--data_dir",
        dest="data_dir",
        help="<path>  Load database from path (default: %s)" % config.get(
            'misc', 'data_dir'),
        default=config.get('misc', 'data_dir'))
    parser.add_option(
        "-r", "--remote",
        dest="remote_host",
        help="<host> Connect to remote host"
        " (try: 54.201.28.117 or 54.204.10.41)")
    parser.add_option(
        "-p", "--port",
        dest="remote_port",
        default=config.get('network', 'remote_port'),
        help="<port> Connect to remote port (default: 30303)"
    )
    parser.add_option(
        "-v", "--verbose",
        dest="verbosity",
        default=config.get('misc', 'verbosity'),
        help="<0 - 3>  Set the log verbosity from 0 to 3 (default: 1)")
    parser.add_option(
        "-m", "--mining",
        dest="mining",
        default=config.get('misc', 'mining'),
        help="<0 - 100> Percent CPU used for mining 0==off (default: 10)")
    parser.add_option(
        "-L", "--logging",
        dest="logging",
        default=config.get('misc', 'logging'),
        help="<logger1:LEVEL,logger2:LEVEL> set the console log level for"
        " logger1, logger2, etc. Empty loggername means root-logger,"
        " e.g. 'pyethereum.wire:DEBUG,:INFO'. Overrides '-v'")
    parser.add_option(
        "-x", "--peers",
        dest="num_peers",
        default=config.get('network', 'num_peers'),
        help="<number> Attempt to connect to given number of peers"
        "(default: 5)")
    parser.add_option("-C", "--config",
                      dest="config_file",
                      help="read coniguration")

    (options, args) = parser.parse_args()

    # set network options
    for attr in ('listen_port', 'remote_host', 'remote_port', 'num_peers'):
        config.set('network', attr, getattr(
            options, attr) or config.get('network', attr))
    # set misc options
    for attr in ('verbosity', 'config_file', 'logging', 'data_dir', 'mining'):
        config.set(
            'misc', attr, getattr(options, attr) or config.get('misc', attr))

    # set wallet options
    for attr in ('coinbase',):
        config.set(
            'wallet', attr, getattr(options, attr) or config.get('wallet', attr))

    if len(args) != 0:
        parser.error("wrong number of arguments")
        sys.exit(1)

    if config.get('misc', 'config_file'):
        config.read(config.get('misc', 'config_file'))

    # set datadir
    if config.get('misc', 'data_dir'):
        data_dir.set(config.get('misc', 'data_dir'))

    # configure logging
    configure_logging(
        config.get('misc', 'logging') or '',
        verbosity=config.getint('misc', 'verbosity'))

    return config
Exemplo n.º 35
0
 def __init__(self, name, genesis=None):
     self.private_key = utils.sha3(name)
     self.addr = utils.privtoaddr(self.private_key)
     self.genesis = genesis or blocks.genesis({self.addr: self.START_BALANCE})
Exemplo n.º 36
0
 def __init__(self, secret):
     self.key = utils.sha3(secret)
     self.address = utils.privtoaddr(self.key)
Exemplo n.º 37
0
import serpent
from pyethereum import transactions, blocks, processblock, utils
import bitcoin

key = utils.sha3('aimfesidfd')
addr = utils.privtoaddr(key)


def pad32(n):
    if type(n) == str:
        h = n.encode('hex')
    else:
        h = "%02x" % n
    l = len(h)
    return "0" * (32 - l) + h


nargs = pad32(1)
d0 = pad32('hi')
print nargs, d0
msg_hash = utils.sha3(nargs + d0)
v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key)
pubkey = bitcoin.privkey_to_pubkey(key)
verified = bitcoin.ecdsa_raw_verify(msg_hash, (v, r, s), pubkey)

gen = blocks.genesis({addr: 10**18})

print serpent.compile_to_assembly(open("DAOist frame.se").read())
DAOcode = serpent.compile(open("DAOist frame.se").read())

DAOcontract = transactions.contract(0, 1, 10**12, 100, DAOcode)
def new_user(brain_pass):
    key = utils.sha3(brain_pass)
    addr = utils.privtoaddr(key)
    return key, addr
Exemplo n.º 39
0
def mk_acc(n):
    out={"priv":utils.sha3("brainwallet"+str(n))}
    out["pub"]=b.privtopub(out["priv"])
    out["addr"]=int(utils.privtoaddr(out["priv"]), 16)
    return(out)
Exemplo n.º 40
0
        tempfile.mktemp()
    cfg.set('misc', 'data_dir', data_dir)
    return cfg


### From here is pasted together from earlier version of pyetherem

import serpent
from pyethereum import transactions, blocks, processblock, utils

#processblock.print_debug = 1
from pyethereum import slogging
slogging.set_level('eth.tx', "DEBUG")

code = serpent.compile(namecoin_code)
key = utils.sha3('cow')
addr = utils.privtoaddr(key)
genesis = blocks.genesis(new_db(), {addr: 10**18})
tx1 = transactions.contract(nonce=0,
                            gasprice=10**12,
                            startgas=10000,
                            endowment=0,
                            code=code).sign(key)
result, contract = processblock.apply_transaction(genesis, tx1)
print genesis.to_dict()
tx2 = transactions.Transaction(nonce=1,
                               gasprice=10**12,
                               startgas=10000,
                               to=contract,
                               value=0,
                               data=serpent.encode_abi(0, 1, 45)).sign(key)
def mk_acc(n):
    out = {"priv": utils.sha3("brainwallet" + str(n))}
    out["pub"] = b.privtopub(out["priv"])
    out["addr"] = int(utils.privtoaddr(out["priv"]), 16)
    return (out)
Exemplo n.º 42
0
Arquivo: build.py Projeto: krl/zeroid
import serpent, json, random
from pyethereum import transactions, blocks, processblock,utils

NUM_ACCOUNTS=4

root_code = serpent.compile(open('zeroid.se').read())
root_key = utils.sha3('cow')
root_addr = utils.privtoaddr(root_key)

keys = {}

for x in range(NUM_ACCOUNTS):
  key  = utils.sha3(str(x+4))
  addr = utils.privtoaddr(key)
  keys[addr] = key

endowment = {root_addr: 10**18}

for x in keys:
  endowment[x] = 10**18

genesis = blocks.genesis(endowment)

tx1 = transactions.contract(0, 10**12, 100000, 0, root_code).sign(root_key)

result, contract = processblock.apply_transaction(genesis, tx1)

nonce=1

for address in keys:
Exemplo n.º 43
0
    fixtures 15.10.:f68067286ddb7245c2203b18135456de1fc4ed6a24a2d9014195faa7900025bf
    py poc6:        08436a4d33c77e6acf013e586a3333ad152f25d31df8b68749d85046810e1f4b
    fixtures 19.9,: 08436a4d33c77e6acf013e586a3333ad152f25d31df8b68749d85046810e1f4b
    """
    genesis = blocks.genesis(new_db())
    assert genesis.hex_hash() == genesis_fixture['genesis_hash']


if __name__ == '__main__':

    cpp_genesis_rlp_hex = 'f9012ff9012aa00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0c67c70f5d7d3049337d1dcc0503a249881120019a8e7322774dbfe57b463718ca056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b84000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0'
    cpp_genesis_rlp = cpp_genesis_rlp_hex.decode('hex')

    poc7_genesis_hash_hex = '955f36d073ccb026b78ab3424c15cf966a7563aa270413859f78702b9e8e22cb'
    cpp_genesis = rlp.decode(cpp_genesis_rlp)
    cpp_genesis_hash_hex = utils.sha3(rlp.encode(cpp_genesis[0])).encode('hex')

    cpp_header = cpp_genesis[0]
    cpp_header_hex = [x.encode('hex') for x in cpp_header]

    py_genesis = rlp.decode(blocks.genesis().serialize())
    py_genesis_hex_hash = blocks.genesis().hex_hash()
    py_header = py_genesis[0]
    py_header_hex = [x.encode('hex') for x in py_header]

    print 'py genesis hash hex', py_genesis_hex_hash
    print 'py state_root', py_header[blocks.block_structure_rev['state_root']
                                     [0]].encode('hex')
    print 'py genesis rlp', blocks.genesis().hex_serialize()

    assert len(py_header_hex) == len(cpp_header_hex)
Exemplo n.º 44
0
class Packeter(object):
    """
    Translates between the network and the local data
    https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-Wire-Protocol
    https://github.com/ethereum/cpp-ethereum/wiki/%C3%90%CE%9EVP2P-Networking

    """
    NETWORK_PROTOCOL_VERSION = 0
    ETHEREUM_PROTOCOL_VERSION = 32
    CLIENT_VERSION = 'Ethereum(py)/%s/%s' % (sys.platform, __version__)
    #the node s Unique Identifier and is the 512-bit hash that serves to identify the node.
    NODE_ID = sha3('')  # set in config
    NETWORK_ID = 0
    SYNCHRONIZATION_TOKEN = 0x22400891
    CAPABILITIES = ['eth']  # + ['shh']  ethereum protocol  whisper protocol

    cmd_map = dict((
        (0x00, 'Hello'),
        (0x01, 'Disconnect'),
        (0x02, 'Ping'),
        (0x03, 'Pong'),
        (0x04, 'GetPeers'),
        (0x05, 'Peers'),
        (0x10, 'Status'),
        (0x11, 'GetTransactions'),
        (0x12, 'Transactions'),
        (0x13, 'GetBlockHashes'),
        (0x14, 'BlockHashes'),
        (0x15, 'GetBlocks'),
        (0x16, 'Blocks'),
    ))
    cmd_map_by_name = dict((v, k) for k, v in cmd_map.items())

    disconnect_reasons_map = dict(
        (('Disconnect requested', 0x00), ('TCP sub-system error', 0x01),
         ('Bad protocol', 0x02), ('Useless peer', 0x03),
         ('Too many peers', 0x04), ('Already connected', 0x05),
         ('Wrong genesis block', 0x06), ('Incompatible network protocols',
                                         0x07), ('Client quitting', 0x08)))
    disconnect_reasons_map_by_id = \
        dict((v, k) for k, v in disconnect_reasons_map.items())

    def __init__(self):
        pass

    def configure(self, config):
        self.config = config
        self.CLIENT_VERSION = self.config.get('network', 'client_version') \
            or self.CLIENT_VERSION
        self.NODE_ID = self.config.get('network', 'node_id')

    @classmethod
    def load_packet(cls, packet):
        '''
        Though TCP provides a connection-oriented medium, Ethereum nodes
        communicate in terms of packets. These packets are formed as a 4-byte
        synchronisation token (0x22400891), a 4-byte "payload size", to be
        interpreted as a big-endian integer and finally an N-byte
        RLP-serialised data structure, where N is the aforementioned
        "payload size". To be clear, the payload size specifies the number of
        bytes in the packet ''following'' the first 8.

        :return: (success, result), where result should be None when fail,
        and (header, payload_len, cmd, data) when success
        '''
        header = idec(packet[:4])
        if header != cls.SYNCHRONIZATION_TOKEN:
            return False, 'check header failed, skipping message,'\
                'sync token was hex: %s' % hex(header)

        try:
            payload_len = idec(packet[4:8])
        except Exception as e:
            return False, str(e)

        if len(packet) < payload_len + 8:
            return False, 'Packet is broken'

        try:
            payload = lrlp_decode(packet[8:8 + payload_len])
        except Exception as e:
            return False, str(e)

        #logger.debug('load packet, cmd:%d %r', idec(payload[0]), Packeter.cmd_map.get(idec(payload[0]),'unknown'))
        if (not len(payload)) or (idec(payload[0]) not in cls.cmd_map):
            return False, 'check cmd %r failed' % idec(payload[0])

        cmd = Packeter.cmd_map.get(idec(payload[0]))
        remain = packet[8 + payload_len:]
        return True, (header, payload_len, cmd, payload[1:], remain)

    def load_cmd(self, packet):
        success, res = self.load_packet(packet)
        if not success:
            raise Exception(res)
        _, _, cmd, data, remain = res
        return cmd, data, remain

    @classmethod
    def dump_packet(cls, data):
        """
        4-byte synchronisation token, (0x22400891),
        a 4-byte "payload size", to be interpreted as a big-endian integer
        an N-byte RLP-serialised data structure
        """
        payload = rlp.encode(recursive_int_to_big_endian(data))

        packet = ienc4(cls.SYNCHRONIZATION_TOKEN)
        packet += ienc4(len(payload))
        packet += payload
        return packet

    def dump_Hello(self):
        """
        0x01 Hello: [0x01: P, protocolVersion: P, clientVersion: B, [cap0: B, cap1: B, ...], listenPort: P, id: B_64]

        protocolVersion: The underlying network protocol. 0
        clientVersion: The underlying client. A user-readable string.
        capN: A peer-network capability code, readable ASCII and 3 letters. Currently only "eth" and "shh" are known.
        listenPort: The port on which the peer is listening for an incoming connection.
        id: The identity and public key of the peer.
        """
        data = [
            self.cmd_map_by_name['Hello'], self.NETWORK_PROTOCOL_VERSION,
            self.CLIENT_VERSION, self.CAPABILITIES,
            self.config.getint('network', 'listen_port'), self.NODE_ID
        ]
        return self.dump_packet(data)

    def dump_Ping(self):
        data = [self.cmd_map_by_name['Ping']]
        return self.dump_packet(data)

    def dump_Pong(self):
        data = [self.cmd_map_by_name['Pong']]
        return self.dump_packet(data)

    def dump_Disconnect(self, reason=None):
        data = [self.cmd_map_by_name['Disconnect']]
        if reason:
            data.append(self.disconnect_reasons_map[reason])
        return self.dump_packet(data)

    def dump_GetPeers(self):
        data = [self.cmd_map_by_name['GetPeers']]
        return self.dump_packet(data)

    def dump_Peers(self, peers):
        '''
        :param peers: a sequence of (ip, port, pid)
        :return: None if no peers
        '''
        data = [self.cmd_map_by_name['Peers']]
        for ip, port, pid in peers:
            assert ip.count('.') == 3
            ip = ''.join(chr(int(x)) for x in ip.split('.'))
            data.append([ip, port, pid])
        return self.dump_packet(data)

    def dump_Status(self, total_difficulty, head_hash, genesis_hash):
        """
        0x10 Status: [0x10: P, protocolVersion: P, networkID: P, totalDifficulty: P, latestHash: B_32, genesisHash: B_32]

        protocolVersion: The version of the Ethereum protocol this peer implements. 30 at present.
        networkID: The network version of Ethereum for this peer. 0 for the official testnet.
        totalDifficulty: Total Difficulty of the best chain. Integer, as found in block header.
        latestHash: The hash of the block with the highest validated total difficulty.
        GenesisHash: The hash of the Genesis block.
        """
        data = [
            self.cmd_map_by_name['Status'],
            self.ETHEREUM_PROTOCOL_VERSION,
            self.NETWORK_ID,
            total_difficulty,  # chain head total difficulty,
            head_hash,  # chain head hash
            genesis_hash  # genesis hash
        ]
        return self.dump_packet(data)

    def dump_Transactions(self, transactions):
        data = [self.cmd_map_by_name['Transactions']] + transactions
        return self.dump_packet(data)

    def dump_GetTransactions(self):
        """
        [0x12, [nonce, receiving_address, value, ... ], ... ]
        Specify (a) transaction(s) that the peer should make sure is included
        on its transaction queue. The items in the list (following the first
        item 0x12) are transactions in the format described in the main
        Ethereum specification.
        """
        data = [self.cmd_map_by_name['GetTransactions']]
        return self.dump_packet(data)

    def dump_Blocks(self, blocks):
        blocks_as_lists = [rlp.decode(b.serialize()) for b in blocks]
        # FIXME, can we have a method to append rlp encoded data
        data = [self.cmd_map_by_name['Blocks']] + blocks_as_lists
        return self.dump_packet(data)

    def dump_GetBlockHashes(self, block_hash, max_blocks):
        """
        [0x17, [ hash : B_32, maxBlocks: P ]]
        Requests a BlockHashes message of at most maxBlocks entries, of block hashes from
        the blockchain, starting at the parent of block hash. Does not require the peer
        to give maxBlocks hashes - they could give somewhat fewer.
        """
        data = [self.cmd_map_by_name['GetBlockHashes'], block_hash, max_blocks]
        return self.dump_packet(data)

    def dump_BlockHashes(self, block_hashes):
        """
        [0x18, [ hash_0: B_32, hash_1: B_32, .... ]]
        Gives a series of hashes of blocks (each the child of the next). This implies that
        the blocks are ordered from youngest to oldest.
        """
        data = [self.cmd_map_by_name['BlockHashes']] + block_hashes
        return self.dump_packet(data)

    def dump_GetBlocks(self, block_hashes):
        """
        [0x19,[ hash_0: B_32, hash_1: B_32, .... ]]
        Requests a Blocks message detailing a number of blocks to be sent, each referred to
        by a hash. Note: Don't expect that the peer necessarily give you all these blocks
        in a single message - you might have to re-request them.
        """
        data = [self.cmd_map_by_name['GetBlocks']] + block_hashes
        return self.dump_packet(data)
Exemplo n.º 45
0
from pyethereum import utils

SZABO = 10**12
FINNEY = 10**15
ETHER = 10**18

DEFAULT_GAS = 10000
GAS_PRICE = 10 * SZABO

JSONRPC_URL = "http://192.168.59.103:8080"

MIN_MINING_BALANCE = 3 * ETHER
POLL_SLEEP = 5  # seconds

GENESIS_HASH = "0000000000000000000000000000000000000000000000000000000000000000"

DEFAULT_KEY = '0x' + utils.sha3("cow").encode('hex')  # part of the Genesis block
DEFAULT_ADDRESS = '0x' + utils.privtoaddr(DEFAULT_KEY[2:])  # cd2a3d9f938e13cd947ec05abc7fe734df8dd826

VM_NAME = "eth-json-rpc"
VM_CMD = "eth --json-rpc --mining on -v 4"
VM_IMAGE = "cptobvious/cpp-ethereum-develop"
Exemplo n.º 46
0
def accounts():
    k = u.sha3('cow')
    v = u.privtoaddr(k)
    k2 = u.sha3('horse')
    v2 = u.privtoaddr(k2)
    return k, v, k2, v2
Exemplo n.º 47
0
def new_config(data_dir=None):
    cfg = _get_default_config()
    if not data_dir:
        tempfile.mktemp()
    cfg.set('misc', 'data_dir', data_dir)
    return cfg


### From here is pasted together from earlier version of pyetherem

import serpent
from pyethereum import transactions, blocks, processblock, utils

#processblock.print_debug = 1
from pyethereum import slogging
slogging.set_level('eth.tx',"DEBUG")

code = serpent.compile(namecoin_code)
key = utils.sha3('cow')
addr = utils.privtoaddr(key)
genesis = blocks.genesis(new_db(), { addr: 10**18 })
tx1 = transactions.contract(nonce=0,gasprice=10**12,startgas=10000,endowment=0,code=code).sign(key)
result, contract = processblock.apply_transaction(genesis,tx1)
print genesis.to_dict()
tx2 = transactions.Transaction(nonce=1,gasprice=10**12,startgas=10000,to=contract,value=0,
                               data=serpent.encode_abi(0,1,45)).sign(key)
result, ans = processblock.apply_transaction(genesis,tx2)
serpent.decode_datalist(ans)
#print genesis.to_dict()
Exemplo n.º 48
0
def accounts():
    k = utils.sha3('cow')
    v = utils.privtoaddr(k)
    k2 = utils.sha3('horse')
    v2 = utils.privtoaddr(k2)
    return k, v, k2, v2
Exemplo n.º 49
0
import json
import requests
import sys
import time
from uuid import uuid4

from pyethereum import utils
import serpent

JSONRPC_URL = "http://127.0.0.1:8080"

DEFAULT_GAS = 10000
GAS_PRICE = 10 * 10**12

DEFAULT_KEY = '0x' + utils.sha3("cow").encode(
    'hex')  # part of the Genesis block
DEFAULT_ADDRESS = '0x' + utils.privtoaddr(
    DEFAULT_KEY[2:])  # cd2a3d9f938e13cd947ec05abc7fe734df8dd826
# FIXME using cow address doesn't work
DEFAULT_ADDRESS = '0x8928602aaee4d7cec275e0da580805f6949cfe98'


class ApiException(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message

    def __str__(self):
        return "code=%d, message=\"%s\"" % (self.code, self.message)

Exemplo n.º 50
0
tobytearr = lambda n, L: [] if L == 0 else tobytearr(n / 256, L - 1)+[n % 256]

choice1 = 0x01
nonce1 = 0x01
ch1 = ''.join(map(chr, tobytearr(choice1, 32)))
no1 = ''.join(map(chr, tobytearr(nonce1, 32)))
print("Player one chooses {} which is: {}").format(choice1, choice[choice1])

k0_pub_addr_hex = utils.privtoaddr(tester.k0)

## Prepare and pad the address 
k0_pub_addr  = ''.join(map(chr, tobytearr(long(k0_pub_addr_hex,16),32)))

## Now use it for the commitment
s1 = ''.join([k0_pub_addr, ch1, no1])
comm1 = utils.sha3(s1)

choice2 = 0x02
nonce2 = 0x01
ch2 = ''.join(map(chr, tobytearr(choice2, 32)))
no2 = ''.join(map(chr, tobytearr(nonce2, 32)))
print("Player two chooses {} which is: {}\n").format(choice2, choice[choice2])

k1_pub_addr_hex = utils.privtoaddr(tester.k1)
#print(type(k1_pub_addr_hex))  ## This is an encoded hex string .. cannot be used directly

## Prepare and pad the address 
k1_pub_addr  = ''.join(map(chr, tobytearr(long(k1_pub_addr_hex,16),32)))

## Now use it for the commitment
s2 = ''.join([k1_pub_addr, ch2, no2])
Exemplo n.º 51
0
def dbl_sha3(x):
    if isinstance(x, (int, long)):
        x = encode_int(x)
    return decode_int(utils.sha3(utils.sha3(x)))    
Exemplo n.º 52
0
import time
import serpent
from pyethereum import transactions, blocks, processblock, utils
import bitcoin

key = utils.sha3(
    'cow'
)  # generate private key using 'brain wallet' seed (should be high entropy)
addr = utils.privtoaddr(key)  # get address from private key

gen = blocks.genesis({addr: 10**60})

assembly = serpent.compile_to_assembly(open('tester.se').read())
print assembly
code = serpent.assemble(assembly)
print code

msg_hash = utils.sha3('heres a message')
v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key)
pub = bitcoin.privkey_to_pubkey(key)
verified = bitcoin.ecdsa_raw_verify(msg_hash, (v, r, s), pub)
print verified

tx_make_root = transactions.contract(0, 10, 10**30, 10**30, code).sign(key)
success, root_contract = processblock.apply_tx(gen, tx_make_root)

#tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([msg_hash, v, r, s])).sign(key)
#tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist(['hi', 'bye'])).sign(key)
tx_init_root = transactions.Transaction(
    1, 100, 10**40, root_contract, 0,
    serpent.encode_datalist([2, '139dcd5cc79e260272e05147c349ab5f2db3f102',
Exemplo n.º 53
0
def sha3(x):
    return decode_int(utils.sha3(x))
Exemplo n.º 54
0
 def blkhash(n):
     if n >= blk.number or n < blk.number - 256:
         return ''
     else:
         return u.sha3(str(n))
Exemplo n.º 55
0
 def blkhash(n):
     if n >= ext.block_number or n < ext.block_number - 256:
         return ''
     else:
         return u.sha3(str(n))
Exemplo n.º 56
0
import json
import requests
import sys
import time
from uuid import uuid4

from pyethereum import utils
import serpent

JSONRPC_URL = "http://127.0.0.1:8080"

DEFAULT_GAS = 10000
GAS_PRICE = 10 * 10 ** 12

DEFAULT_KEY = "0x" + utils.sha3("cow").encode("hex")  # part of the Genesis block
DEFAULT_ADDRESS = "0x" + utils.privtoaddr(DEFAULT_KEY[2:])  # cd2a3d9f938e13cd947ec05abc7fe734df8dd826
# FIXME using cow address doesn't work
DEFAULT_ADDRESS = "0x8928602aaee4d7cec275e0da580805f6949cfe98"


class ApiException(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message

    def __str__(self):
        return 'code=%d, message="%s"' % (self.code, self.message)


class Api(object):
    def __init__(self, jsonrpc_url=JSONRPC_URL):
Exemplo n.º 57
0
def default_node_id():
    return sha3(str(uuid.uuid1())).encode('hex')
Exemplo n.º 58
0

        
'''
import serpent
from pyethereum import transactions, blocks, processblock, utils
import time
import sys

#require command line args
if len(sys.argv) < 3:
    print("Usage: %s [price] [recipient: transcation success: 2, transcation deny: 3]  [sender: transcation success: 2, transcation deny: 3]" %sys.argv[0])
    sys.exit(1)

code = serpent.compile(escrow)
sender_key = utils.sha3('sender')
sender_addr = utils.privtoaddr(sender_key)
recipient_key = utils.sha3('recipient')
recipient_addr = utils.privtoaddr(recipient_key)
host_key = utils.sha3('host')
host_addr = utils.privtoaddr(host_key)

#initialize the block
genesis = blocks.genesis({sender_addr: 10**18, recipient_addr: 10**18, host_addr: 10**18})

#initialize the contract
tx1 = transactions.contract(0, 10**12, 10000, 0, code).sign(host_key)
result, contract = processblock.apply_transaction(genesis, tx1)

#execute escrow transaction
#nonce, gasprice, startgas, to, value, data
Exemplo n.º 59
0
def sha3(x):
    return decode_int(utils.sha3(x))